Compare commits

...
193 Commits
Author SHA1 Message Date
Ole André Vadla Ravnås f497a764b6 subprojects: Prepare for release 2025-01-13 22:20:39 +01:00
Ole André Vadla Ravnås 20b7856fae subprojects: Bump outdated 2025-01-13 22:18:02 +01:00
Ole André Vadla Ravnås f2a81c03e3 subprojects: Prepare for release 2025-01-10 02:04:08 +01:00
Ole André Vadla Ravnås 79b34b9772 subprojects: Bump outdated 2025-01-10 02:02:04 +01:00
Ole André Vadla Ravnås 2fb702ba80 subprojects: Bump outdated 2025-01-09 23:35:23 +01:00
Ole André Vadla Ravnås 262d8f91e5 submodules: Bump releng 2025-01-09 23:35:22 +01:00
Ole André Vadla Ravnås 7638290dcb agent: Exclude OS/arch symbols in version script
Newer toolchains, such as the default toolchain on FreeBSD 14.2,
don't like references to symbols that don't exist. Instead of
listing JNI_OnLoad, which is only defined for Android builds,
we use a separate version script for Android instead.
2025-01-09 23:34:01 +01:00
Ole André Vadla Ravnås 1e0f37faf6 subprojects: Prepare for release 2025-01-09 13:18:38 +01:00
Ole André Vadla Ravnås fb46efaa12 compiler: Bump @types/frida-gum 2025-01-09 13:16:05 +01:00
Ole André Vadla Ravnås bb4a906c16 subprojects: Bump outdated 2025-01-08 19:06:43 +01:00
Ole André Vadla Ravnås 34eff8e9d6 darwin: Fix iOS/tvOS compilation issues
By porting the remaining bits to the new Gum.Module API.
2025-01-06 16:37:55 +01:00
Ole André Vadla Ravnås f28e5d4493 subprojects: Bump outdated 2025-01-06 16:03:28 +01:00
Ole André Vadla Ravnås 6f3434b454 subprojects: Bump outdated 2025-01-06 01:11:39 +01:00
Ole André Vadla Ravnås 90c2420bae submodules: Bump releng 2025-01-06 01:11:38 +01:00
Ole André Vadla Ravnås 95394935cd Port to the new Gum.Module API 2025-01-06 01:09:07 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a2ffb76ff3 ncm: Cap datagram count to 16 for performance
The layout computation could end up working its way down from a very
high number. Though we probably should optimize the layout computation,
there's no point for now.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-17 23:38:37 +01:00
Ole André Vadla Ravnås c1472f9cb8 Create FUNDING.yml 2024-12-12 13:37:04 +01:00
Ole André Vadla Ravnås aabe70d041 subprojects: Bump outdated 2024-12-09 00:58:03 +01:00
Ole André Vadla Ravnås abc464bf49 subprojects: Prepare for release 2024-12-09 00:52:26 +01:00
Ole André Vadla Ravnås b6d7c7259f subprojects: Prepare for release 2024-12-09 00:32:18 +01:00
Ole André Vadla Ravnås 78750a4644 subprojects: Bump outdated 2024-12-09 00:28:54 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a68dc36d2d fruity: Boost NCM performance with multi-transfers
Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-08 22:45:07 +01:00
Ole André Vadla Ravnås de54b7e4cf subprojects: Bump outdated 2024-12-08 16:31:53 +01:00
Ole André Vadla Ravnås 1f292bb856 submodules: Bump releng 2024-12-08 16:31:52 +01:00
Ole André Vadla Ravnås 2025b7aaad fruity: Enable lwIP TCP timestamps and SACK
To align with the Linux IP stack's defaults.
2024-12-08 03:23:34 +01:00
Ole André Vadla Ravnås 534d860a42 meson: Bump lwIP TCP MSS to 4036
For better TCP tunnel performance.
2024-12-08 03:22:06 +01:00
Ole André Vadla Ravnås db28eb0e70 fruity: Fix crash on USB op creation during teardown 2024-12-08 03:20:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 8d0b735a75 fruity: Improve userspace NCM driver to perform batching
As we observed packet loss in bursty situations, and implementing
batching avoids it.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-08 01:55:38 +01:00
Ole André Vadla Ravnås 930776dcca compat: Create relative subproject symlinks
So the source tree can be moved without breaking things.
2024-12-07 16:08:52 +01:00
Ole André Vadla Ravnås 7a38663672 compat: Fix subproject symlink_to() error-handling 2024-12-07 15:55:22 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 3779ce9f64 vapi: Add SocketAddressUnion to libngtcp2.vapi
Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:24:13 +01:00
Ole André Vadla RavnåsandHåvard Sørbø b5065e275d fruity: Improve USB device handling on non-macOS
- Do not open a given USB device if kernel NCM is available, as opening
  may fail and won't actually do anything useful in the end.
- Throw when a kernel NCM interface lacks an IPv6 address, instead of
  silently degrading to legacy mode.
- Replace retry logic with a fixed 250 ms delay, applied when a device
  arrives after starting, or during a mode-switch.
- Change USB device configuration if needed.
- Wait for kernel NCM interface to be ready. For now this is limited to
  Linux systems with either NetworkManager or networkd.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:24 +01:00
Ole André Vadla RavnåsandHåvard Sørbø a682e51f37 fruity: Only assume jailed if connection refused
Bubble up all other errors.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:06 +01:00
Ole André Vadla RavnåsandHåvard Sørbø bdf120016a api: Avoid redundant writes to output files
Modify the output logic to skip writing to files if the contents remain
unchanged, preventing unnecessary file updates. This means quicker
incremental builds.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:23:00 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 61eb12f718 meson: Avoid parsing API multiple times
As Meson's custom_target() supports multiple outputs.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-12-05 15:22:54 +01:00
Ole André Vadla RavnåsandHåvard Sørbø e149f5e332 fruity: Avoid USB access in case of kernel NCM
So we won't run into permission issues, and avoid unneccessary work.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 23:04:10 +01:00
Ole André Vadla RavnåsandHåvard Sørbø ef4fa0de7d fruity: Account for frida-server bind() delay
Where we just opened the tunnel, but frida-server hasn't yet noticed the
new interface and had a chance to bind() on it. This means we should
wait a bit and try again. Otherwise we may end up falling back to
usbmuxd, and use a less desirable transport. And if we're really
unlucky, even that could fail, and we'd end up falling back to jailed
mode.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 22:02:47 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 1bd9d389b8 fruity: Fix direct channel reliability
Where we might establish the HostSession connection through usbmuxd, and
proceed to establish direct connections through the tunnel. This is
usually fine, except when an Apple service happens to bind to the same
port inside the tunnel. In that case we'd end up talking to that instead
of the broker port, which is listening on INADDR_ANY.

Kudos to @mrmacete for helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-26 19:43:42 +01:00
Ole André Vadla Ravnås b32408c607 device: Fix the constructor logic
Broken by the refactoring in 2790745.
2024-11-24 15:32:58 +01:00
Ole André Vadla Ravnås a8e01c2940 Fix some stylistic inconsistencies 2024-11-24 15:32:14 +01:00
Ole André Vadla Ravnås cd6366a4eb tests: Fix the HostSession suite 2024-11-24 00:58:28 +01:00
Ole André Vadla Ravnås 2c1cf1ec58 api: Add GIR attributes 2024-11-24 00:34:32 +01:00
Ole André Vadla Ravnås 279074501c api: Avoid exposing internal types 2024-11-24 00:33:17 +01:00
Ole André Vadla Ravnås 20cfd56a7a api: Generate a proper gir
- Needed types in frida-base included.
- Internal types omitted.
2024-11-23 23:54:20 +01:00
Ole André Vadla Ravnås d03bda5545 api: Omit APIs involving HostSession 2024-11-23 15:14:37 +01:00
Ole André Vadla Ravnås 951796196c api: Refactor generate.py to improve readability 2024-11-23 15:14:33 +01:00
Ole André Vadla Ravnås 312e38b2ec fruity: Improve TcpTunnelConnection teardown
So the VirtualNetworkStack is torn down right away upon the remote end
closing the connection, instead of once close() is called.

Also ensure any pending write operation is cancelled at that point.
2024-11-22 14:50:31 +01:00
Ole André Vadla Ravnås 36a8ffbb99 subprojects: Prepare for release 2024-11-14 00:30:38 +01:00
Ole André Vadla Ravnås aeb2c0f6e4 subprojects: Bump outdated 2024-11-14 00:28:54 +01:00
Ole André Vadla Ravnås d5591cc453 submodules: Bump releng 2024-11-14 00:28:54 +01:00
lx866 20f4df23a8 android: Revive injector's handling of shared libc ranges
So we still do the right thing if the target process' lowest libc.so
range is a shared mapping, for example:

    HNFRI:/ # grep libc.so /proc/22001/maps
    6e3e1cd000-6e3e2c7000 r--s 00000000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb6c2000-71eb6ff000 r--p 00000000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb6ff000-71eb781000 r-xp 0003d000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb781000-71eb786000 r--p 000bf000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so
    71eb786000-71eb787000 rw-p 000c3000 07:08 38 /apex/com.android.runtime/lib64/bionic/libc.so

Originally implemented in 5e8314f, but lost in the injector rewrite.
2024-11-14 00:21:58 +01:00
JunGe-Y 89033cd1e8 compat: Fix compilation when using non-UTF-8 locales (#1122) 2024-11-13 23:55:57 +01:00
Ole André Vadla Ravnås a027f5b08e fruity: Skip jailed fallback in case of timeout 2024-11-13 20:37:07 +01:00
Ole André Vadla Ravnås 848f4b52e1 fruity: Expect networked device to respond quickly
When connecting to its pairing service, it should be reasonable to
assume that the TCP connection set up completes within two seconds.

This improves the UX when a device has gone to sleep, and its mDNS
records haven't yet timed out.
2024-11-13 20:35:42 +01:00
Ole André Vadla Ravnås e0524ad90b network-stack: Add open_tcp_connection_with_timeout() 2024-11-13 20:28:09 +01:00
Ole André Vadla Ravnås 5ce8ce0531 fruity: Always try USB transport first
As a network transport may be slower (best-case) or unavailable
(worst-case).
2024-11-13 20:15:52 +01:00
Ole André Vadla Ravnås 8f04f2f677 fruity: Fix TcpTunnelConnection teardown logic
Where it turns out IOStream.close_async() may throw other errors than
just IOError. This is a bug in gio-2.0.vapi, but still, once fixed there
we still want to catch (and ignore) all errors.

Kudos to @mrmacete for helping track this one down.
2024-11-13 18:03:38 +01:00
Ole André Vadla RavnåsandHåvard Sørbø f0593c2aec fruity: Fix QuicTunnelConnection teardown logic
And improve the ngtcp2 bindings.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-13 16:32:04 +01:00
Ole André Vadla RavnåsandHåvard Sørbø ec582967e8 fruity: Fix hang when a USB op starts at teardown
Which would result in such transfers never completing, as our USB worker
is no longer processing libusb events.

Kudos to @mrmacete for helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-13 13:23:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 4fce1c4321 fruity: Gracefully close TunnelConnection
Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-06 13:39:42 +01:00
Ole André Vadla Ravnås 667c7491b5 fruity: Relax NCM interface presence check
One operational network interface is sufficient.
2024-11-06 10:47:39 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 85de7a01fb fruity: Add support for the TCP tunnel protocol
And use it by default, to match Apple's new behavior.

The FRIDA_FRUITY_TUNNEL_PROTOCOL environment variable can be used to
revert back to QUIC.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-11-06 10:47:03 +01:00
Ole André Vadla Ravnås 8fdff55b80 subprojects: Bump outdated 2024-11-06 10:21:11 +01:00
Ole André Vadla Ravnås a420358565 submodules: Bump releng 2024-11-06 10:21:10 +01:00
Ole André Vadla RavnåsandHåvard Sørbø 2457ac45f6 fruity: Fix edge-case in tunnel logic for older OS versions
When usbmuxd is not available, we would try to set up a tunnel
connection. This would then fail when the OS is too old for CoreDevice
support, and we would erroneously cache the Tunnel implementation in its
unopened state. This meant it could be used as if it was opened, causing
undefined behavior.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-28 15:01:40 +01:00
Ole André Vadla Ravnås e797e829d8 fruity: Fix CoreDevice UDID logic for modern devices 2024-10-26 08:54:27 +02:00
WorksButNotTested aa95167156 linux: Pick other temp dir when $TMPDIR is noexec 2024-10-21 22:40:47 +02:00
Ole André Vadla Ravnås 03d609c1a5 linux: Improve helpers Makefile to use internal Meson 2024-10-21 14:55:20 +02:00
Harry Gunnarsson 36619e51e7 linux: Support overriding config when building helpers 2024-10-21 14:55:20 +02:00
Harry Gunnarsson e2b462823c linux: Improve injector's MUSL compatibility
The loader string could look different on different platforms.
2024-10-21 14:32:52 +02:00
Andrew Werner e8ee891924 linux: Allocate stack for injector's remote calls
For some target programs it's not reasonable to assume that any hijacked
thread has a large stack. For example, in Go, stacks are often small and
are allocated on the heap. The injector bootstrap program uses kilobytes
of stack. In order to side-step this problem, this patch changes the
boostrapper to allocate an auxiliary stack for remote calls to use and,
for the bootstrapper and loader, uses it.

The calls to mmap and munmap don't use much stack, so they are fine.

Fixes #544.
2024-10-21 14:07:00 +02:00
Andrew Werner d0fe3a1ae9 linux: Rebuild helper bin files
This commit utilizes the containers created in [frida/docker-images#2]
to rebuild all the Linux injector helper binaries for all the
architectures. It uses a new script to rebuild them and hooks up CI to
rebuild them and make sure that they are all the same as what is checked
in. This should allow us to make changes to these binaries without any
pain and with the confidence that what is checked in matches the source.

[frida/docker-images#2]: https://github.com/frida/docker-images/pull/2
2024-10-20 17:09:55 +02:00
Ole André Vadla Ravnås b223fc4235 darwin: Update to the new RpcClient.call() API 2024-10-20 16:42:12 +02:00
Ole André Vadla Ravnås 5ad248a894 android: Update to the new RpcClient.call() API 2024-10-20 16:40:56 +02:00
Yoav ShaiandOle André Vadla Ravnås d774d0e064 gadget: Support loading assets from APK on Android
On Android, when apps have `extractNativeLibs` set to `false`, the
configuration and potentially script files for frida-gadget are not
extracted and cannot be read from the filesystem.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-20 16:40:15 +02:00
WorksButNotTested e11938c11f inject: Support binary data on stdin and stdout 2024-10-20 12:11:31 +02:00
WorksButNotTested fb0049af86 barebone: Support binary data in Script.post() 2024-10-20 12:11:31 +02:00
WorksButNotTested 2fe6922b25 rpc-client: Support binary data in call() 2024-10-20 12:11:31 +02:00
Ole André Vadla Ravnås c96d94f796 subprojects: Prepare for release 2024-10-14 15:32:15 +02:00
Ole André Vadla Ravnås a8b710bc54 subprojects: Bump outdated 2024-10-14 15:30:11 +02:00
Håvard SørbøandOle André Vadla Ravnås 2b0c4da879 fruity: Fix use-after-free in TcpConnection
The error callback might be called at a point where the PCB has already
been freed. This meant that us clearing its user data would result in a
use-after-free where a NULL pointer was written into the unknown.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:24:37 +00:00
Håvard SørbøandOle André Vadla Ravnås d0129614cd fruity: Fix DTXArgumentList.parse() GValue init
Where we were using the wrong setter when encountering an object. This
was caught by GLib's runtime checks, but this went unnoticed because we
usually build without them.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:22:41 +00:00
Håvard SørbøandOle André Vadla Ravnås 12348209da payload: Fix AddressSanitizer build regression
Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-14 13:19:56 +00:00
Ole André Vadla Ravnås 0451ce09b2 subprojects: Prepare for release 2024-10-11 11:18:27 +02:00
Ole André Vadla Ravnås 0fa9765871 subprojects: Bump outdated 2024-10-11 11:16:06 +02:00
ajwerner 71e1068150 ci: Download proper ndk version (#551)
We were relying on the version built into the image being correct. It is
now too new.
2024-10-11 11:13:44 +02:00
Francesco Tamagni 690cc30260 control-service: Fix null dereference on incoming connection (#1060) 2024-10-11 11:12:15 +02:00
Ole André Vadla Ravnås 557aefc898 subprojects: Prepare for release 2024-10-10 22:07:51 +02:00
Ole André Vadla Ravnås 088edc09d7 subprojects: Bump outdated 2024-10-10 22:06:52 +02:00
Ole André Vadla Ravnås 19f6a2f378 compiler: Bump @types/frida-gum 2024-10-10 21:30:42 +02:00
Ole André Vadla Ravnås 16c9035bca subprojects: Prepare for release 2024-10-10 20:18:24 +02:00
Ole André Vadla Ravnås fbb46912db subprojects: Bump outdated 2024-10-10 20:08:54 +02:00
Ole André Vadla Ravnås 11aa03695f submodules: Bump releng 2024-10-10 20:08:53 +02:00
Håvard SørbøandOle André Vadla Ravnås a23fba6ee9 fruity: Bail on iOS tunnel service versions pre-17
Instead of crashing.

Co-authored-by: Ole André Vadla Ravnås <[email protected]>
2024-10-10 18:02:07 +00:00
Ole André Vadla RavnåsandHåvard Sørbø 364bf65c59 control-service: Fix reliability on CoreDevice systems
Where having a single transport broker listening on all interfaces may
result in an early TCP RST when trying to communicate with it from
inside a tunnel. The exact cause of this is not known, but we have
confirmed that having one broker per dynamic interface/tunnel does
resolve the issue. We also observed that listening on all interfaces,
but restricted to IPv6, also avoids the issue.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 19:03:41 +02:00
Ole André Vadla RavnåsandHåvard Sørbø dcdfcf53d1 fruity: Fix USB mode parsing on iOS < 16
Where the mode is a 3 byte blob.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 18:46:44 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2698d7dd1d meson: Fix i/tvOS compilation with GLib as a subproject
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-10 18:45:28 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 208aec031c web-service: Close connections of removed dynamic interfaces
To avoid them sticking around until we run out of file-descriptors.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-08 13:15:10 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 03e70d26b7 socket: Transition GSource callbacks to Source.REMOVE
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-08 13:14:20 +02:00
Ole André Vadla Ravnås b22507ed32 meson: Disable Fruity and friends on FreeBSD
As we currently rely on a libusb API that only exists in our libusb.
2024-10-05 19:53:26 +00:00
Ole André Vadla Ravnås 1c4902e72d fruity: Use USB product string as transport name 2024-10-05 19:36:34 +00:00
Ole André Vadla RavnåsandHåvard Sørbø e5eaedaf85 fruity: Bubble up USB permission errors
Co-authored-by: Håvard Sørbø <[email protected]>
2024-10-05 19:36:31 +00:00
Ole André Vadla Ravnås 944380225a subprojects: Bump outdated 2024-10-05 17:24:56 +02:00
Ole André Vadla Ravnås f84f2887d2 submodules: Bump releng 2024-10-05 17:24:55 +02:00
Ole André Vadla Ravnås e67d513d06 subprojects: Bump outdated 2024-10-05 16:14:44 +02:00
Ole André Vadla Ravnås 558628ad5a submodules: Bump releng 2024-10-05 16:14:43 +02:00
Ole André Vadla Ravnås 9c27b7b453 subprojects: Bump outdated 2024-10-05 16:12:48 +02:00
Ole André Vadla Ravnås 441636acd1 submodules: Bump releng 2024-10-05 16:12:47 +02:00
Ole André Vadla Ravnås 3238e2268a network-stack: Fix racy TCP data loss upon peer closure
Where the closure resulted in us letting go of the PCB, and the recv()
logic would return early because the PCB was gone. At that point there
might still be data left in the RX buffer, but the application wouldn't
see it.
2024-10-03 10:45:36 +02:00
Ole André Vadla Ravnås 66099c705f network-stack: Handle abrupt disposal of TcpConnection
Where we would free the PCB TCB but fail to notify any live TcpIOSource
instances and blocked TcpInputStream.read() calls.
2024-09-20 19:06:33 +02:00
Ole André Vadla Ravnås ca8519cec7 network-stack: Fix race in TcpInputStream.read()
Where the notify::pending-io signal fires after the call to
is_readable() but before our signal handler is connected.
2024-09-20 19:01:04 +02:00
Ole André Vadla Ravnås 416d2ea388 subprojects: Prepare for release 2024-09-19 00:00:49 +02:00
Ole André Vadla Ravnås 02e83a6d4a subprojects: Bump outdated 2024-09-18 23:57:30 +02:00
Ole André Vadla Ravnås 539f359a1f fruity: Handle USB TunnelConnection dropping
Which happens on e.g. an iOS userspace reboot.
2024-09-18 23:49:56 +02:00
Ole André Vadla Ravnås 24dc7f4a3d fruity: Fix unreliable modeswitch activation
Where its Promise could be resolved more than once.
2024-09-18 23:14:35 +02:00
Ole André Vadla Ravnås f48ced3a4a subprojects: Prepare for release 2024-09-18 14:33:15 +02:00
Ole André Vadla Ravnås 54829052bd subprojects: Bump outdated 2024-09-18 14:31:38 +02:00
Ole André Vadla Ravnås 73abf705b1 submodules: Bump releng 2024-09-18 14:31:37 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7e21f5cb1d fruity: Advertise our RemoteXPC protocol support
Like macOS does, but with most of the properties omitted.

We do this to more closely mimic macOS' behavior, and to avoid an error
ending up in the syslog:

    Invalid or missing remote device connection version flags

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-18 14:30:21 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 24a1f79b02 fruity: Handle iDevice not paired with anyone
Where the pairVerify step fails early.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-18 14:25:55 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 2d990888d9 fruity: Fix teardown when using our NCM driver
Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-17 18:34:21 +02:00
Ole André Vadla Ravnås 0fd255d3a4 fruity: Fix error marshaling in find_tunnel() for non-macOS 2024-09-17 17:15:35 +02:00
Ole André Vadla Ravnås fc500a19d9 fruity: Fix a stylistic inconsistency 2024-09-17 17:12:12 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 7280bbdbf7 fruity: Reuse NCM peer when tunnel setup fails
Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-17 13:25:25 +02:00
Ole André Vadla Ravnås 9539981511 subprojects: Prepare for release 2024-09-06 22:59:50 +02:00
Ole André Vadla Ravnås 3005ab2aa5 subprojects: Bump outdated 2024-09-06 22:58:46 +02:00
Ole André Vadla Ravnås 140c5cf2cd subprojects: Prepare for release 2024-09-06 21:57:05 +02:00
Ole André Vadla Ravnås 6bb27c17e9 subprojects: Bump outdated 2024-09-06 21:54:47 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 0f2d9c8b40 network-stack: Fix deadlock in perform_on_lwip_thread()
Where in the case of already being on the lwIP thread, we would enqueue
the request and then perform whichever is the oldest pending request. So
when there was already one or more requests pending, we would perform
that request instead. Then next we would join() our request, assuming it
had completed, and end up deadlocking the lwIP thread.

Kudos to @mrmacete for reporting and helping track this one down.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-09-06 15:16:48 +02:00
Ole André Vadla Ravnås 5606120f6a subprojects: Bump outdated 2024-08-30 23:00:20 +02:00
ajwerner 2376f425a3 linux: Handle process gone when detaching (#543)
This is an attempt to handle the situation where the process has gone
away and we're shutting down. I've observed the system looping
attempting to move the state out of ATTACHED. It's possible that the
state machine here needs to be made more complex (ALREADY_ATTACHED is
misleading).

Informs #478.
2024-08-30 22:37:41 +02:00
Ole André Vadla Ravnås 1f9e24e1ea windows: Revive the system session 2024-08-26 12:26:25 +02:00
Ole André Vadla Ravnås 694118cccc subprojects: Bump outdated 2024-08-26 01:51:50 +02:00
Ole André Vadla Ravnås 9d51496124 submodules: Bump releng 2024-08-26 01:51:49 +02:00
Ole André Vadla Ravnås 27849af528 subprojects: Bump outdated 2024-08-25 23:54:37 +02:00
Ole André Vadla Ravnås 9df97f9e6b windows: Add support for arm64 2024-08-25 23:52:42 +02:00
Ole André Vadla Ravnås 79126f0065 subprojects: Bump outdated 2024-08-25 13:41:41 +02:00
Ole André Vadla Ravnås 4b0d1eab04 meson: Add frida-netif to the public frida-core
It's needed by ControlService.
2024-08-25 13:40:51 +02:00
Ole André Vadla Ravnås 31188db39a subprojects: Prepare for release 2024-08-22 15:40:45 +02:00
Ole André Vadla Ravnås de09ec42d5 subprojects: Bump outdated 2024-08-22 15:39:00 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 34c1548ced tunnel-connection: Ensure JSON request ends up in its own UDP packet
When opening the tunnel, it seems problematic if a datagram and stream
data end up in the same UDP packet. We make our dummy-datagram larger to
avoid this.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:35:07 +02:00
Ole André Vadla RavnåsandHåvard Sørbø b753294acb tunnel-connection: Wire up missing stream close logic
Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:35:00 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 498c9be83e tunnel-connection: Consistently avoid writes after connection is gone
Which would result in a crash.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:32:30 +02:00
Ole André Vadla RavnåsandHåvard Sørbø bbcbe91b3e network-stack: Handle perform_on_lwip_thread() from the lwIP thread
Instead of deadlocking.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-08-22 15:29:11 +02:00
Ole André Vadla Ravnås ce80773d21 subprojects: Prepare for release 2024-08-20 21:50:41 +02:00
Ole André Vadla Ravnås e06da4d410 subprojects: Bump outdated 2024-08-20 21:48:20 +02:00
Francesco Tamagni 120dc491c4 tunnel-interface-observer: Fix start() crash on i/tvOS
When SCDynamicStoreCopyKeyList() fails.
2024-08-20 21:12:49 +02:00
Ole André Vadla Ravnås 2ebec1addf subprojects: Prepare for release 2024-08-02 14:05:13 +02:00
Håvard Sørbø 6a1e373ba2 fruity: Make find_usbmux_device() non-throwing 2024-08-02 14:03:03 +02:00
Ole André Vadla Ravnås 100b7a63d7 fruity: Guard against lockdown open<->close loop 2024-08-02 14:03:03 +02:00
Håvard Sørbø b3f2d1e7cc fruity: Fix invalidation of closed lockdown client 2024-08-02 14:03:03 +02:00
Håvard Sørbø 313cdc89f8 lockdown-client: Bubble up CONNECTION_CLOSED error 2024-08-02 14:03:03 +02:00
Ole André Vadla Ravnås 3c8221dd55 subprojects: Bump outdated 2024-07-29 11:00:36 +02:00
Ole André Vadla Ravnås dca8509960 submodules: Bump releng 2024-07-29 11:00:36 +02:00
Ole André Vadla Ravnås 78ff6e5b08 subprojects: Prepare for release 2024-07-23 10:14:56 +02:00
Ole André Vadla Ravnås 6537809897 subprojects: Bump outdated 2024-07-23 10:11:56 +02:00
Ole André Vadla Ravnås ead2ff6701 submodules: Bump releng 2024-07-23 10:11:56 +02:00
xiofee d55232fe52 fruity: Fix crash when enumerating network interfaces on Windows (#538)
Some don't have a unicast address, and need to be ignored.
2024-07-23 10:11:26 +02:00
Ole André Vadla Ravnås dab3b91f9e subprojects: Prepare for release 2024-07-22 11:49:03 +02:00
Ole André Vadla Ravnås 71f7b2f16a subprojects: Bump outdated 2024-07-22 11:37:45 +02:00
Ole André Vadla Ravnås 4cf806641f submodules: Bump releng 2024-07-22 11:37:44 +02:00
Ole André Vadla Ravnås e34a533a35 fruity: Handle devices without tunnel support on non-macOS
In the portable CoreDevice backend.
2024-07-22 11:28:23 +02:00
Ole André Vadla Ravnås 6b56c88295 fruity: Use UsbmuxDevice from USB transport if present
So we can reach the loopback interface, and for better performance.
2024-07-19 23:10:15 +02:00
Ole André Vadla Ravnås d810111f1e fruity: Expose name from USB transport if present
It has a more descriptive name in case of UsbmuxTransport.
2024-07-19 23:09:42 +02:00
Ole André Vadla Ravnås 3d17ad39da subprojects: Prepare for release 2024-07-17 22:43:10 +02:00
Ole André Vadla Ravnås 429607e7e3 xpc-client: Wire up cancellable in request()
As we can't cancel the request itself, we have to cancel the connection.
2024-07-17 22:34:24 +02:00
Ole André Vadla Ravnås 6ef660718a subprojects: Bump outdated 2024-07-17 22:10:01 +02:00
Ole André Vadla Ravnås cf61fda141 subprojects: Prepare for release 2024-07-16 15:24:54 +02:00
Ole André Vadla Ravnås b272dda27d subprojects: Bump outdated 2024-07-16 15:20:35 +02:00
Ole André Vadla Ravnås 300d176e85 ci: Re-enable tests on macOS 2024-07-16 15:14:43 +02:00
Ole André Vadla Ravnås e7f045bbe9 darwin: Await ObjC init on macOS Sequoia and iOS 18
By making use of notifyObjCInit() if available.
2024-07-16 11:45:16 +02:00
Ole André Vadla Ravnås 0b6abfeb7c darwin: Handle dyld restart on macOS Sequoia and iOS 18 2024-07-16 11:12:02 +02:00
Ole André Vadla Ravnås c17c6e31bc tests: Avoid relying on executable name on Darwin 2024-07-16 11:06:55 +02:00
Ole André Vadla Ravnås 0825aab1d0 fruity: Improve CoreDevice pairing support
- Fix support for multiple pairing relationships.
- Keep the in-memory peer store up-to-date, so new pairing relationships
  don't require a process restart to be able to match them up with
  pairing services on the network.
2024-07-15 14:41:03 +02:00
Ole André Vadla Ravnås be65296610 ncm: Fix a stylistic inconsistency 2024-07-15 13:24:16 +02:00
Ole André Vadla Ravnås 0a6002a3ce ncm: Avoid using a broken kernel NCM driver
Where only one of the two network interfaces exist, i.e. the tethering
interface.
2024-07-15 13:03:49 +02:00
Ole André Vadla Ravnås a3deb22999 ncm: Detach all drivers before changing configuration
We would previously only try to detach for the data interface, which
makes no sense if that interface is on a different configuration.
2024-07-15 12:54:14 +02:00
Ole André Vadla Ravnås 5aeb800a7a subprojects: Prepare for release 2024-07-13 00:34:04 +02:00
Ole André Vadla Ravnås a01f5dcd3d subprojects: Bump outdated 2024-07-13 00:06:51 +02:00
Ole André Vadla Ravnås 23b15b5f4b ncm: Switch USB device configuration if needed 2024-07-12 15:31:43 +02:00
Ole André Vadla Ravnås f1fdd980aa fruity: Add support for networked devices on Windows
By making use of DnsServiceBrowse() if the OS supports it -- which means
Windows 10 and newer.
2024-07-12 15:29:15 +02:00
Ole André Vadla Ravnås 05a68332f6 network-stack: Fix TcpConnection use-after-free
When lwIP notifies us about the PCB being closed or an error, we must
clear its user data so any future callbacks don't end up using the
TcpConnection after it's gone.
2024-07-12 00:06:17 +02:00
Ole André Vadla Ravnås 13521724f7 fruity: Remove commented-out variable 2024-07-11 23:57:55 +02:00
Ole André Vadla Ravnås 6c700a511e fruity: Split out DnsPacketReader 2024-07-11 23:14:01 +02:00
Ole André Vadla Ravnås 02ccafe516 fruity: Move LinuxPairingBrowser to ResolveService
Which is simpler and avoids some roundtrips to systemd-resolved.
2024-07-11 23:09:08 +02:00
Ole André Vadla Ravnås fb672d7a0b ci: Move the macOS x86_64 job to macos-latest
As the macos-11 runner is gone.

Also skip running tests on macOS entirely for now, as a stopgap until
__CFInitialize() has been dealt with.
2024-07-11 15:13:14 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 81fbfe2ab5 fruity: Add support for networked devices on Linux
By making use of systemd-resolved for mDNS-SD lookups.

Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 3aef106ec2 fruity: Fix the LWIP.NetworkInterface bindings
Where we would end up passing in a copy of the struct and have e.g.
neighbor discovery timers make use of dangling pointers.
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 370f1836a7 dtx: Fix teardown of DTXConnection vs. DTXChannel
So channels never make use of the connection once it's gone.
2024-07-11 15:09:12 +02:00
Ole André Vadla RavnåsandHåvard Sørbø 70bb82bb5d fruity: Remove forgotten .pcap debug output
Co-authored-by: Håvard Sørbø <[email protected]>
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås dc43be94c5 buffer: Add BufferReader 2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås 7c7367b010 buffer: Add content validation to read_fixed_string()
To support parsing untrusted data.
2024-07-11 15:09:12 +02:00
Ole André Vadla Ravnås a9073c07eb buffer: Add content validation to read_string()
To support parsing untrusted data.
2024-07-11 15:09:12 +02:00
101 changed files with 5994 additions and 2464 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
github: frida
+41 -2
View File
@@ -18,7 +18,7 @@ jobs:
include:
- { id: windows-x86_64, runner: '"windows-latest"' }
- { id: windows-x86, runner: '"windows-latest"' }
- { id: macos-x86_64, runner: '"macos-11"' }
- { id: macos-x86_64, runner: '"macos-latest"' }
- { id: macos-arm64, runner: '"macos-latest"' }
- { id: linux-x86_64, runner: '"ubuntu-latest"' }
- { id: linux-x86, runner: '"ubuntu-latest"' }
@@ -68,7 +68,6 @@ jobs:
name: core-devkit-${{ matrix.id }}
path: build/src/devkit/
- name: Test
if: matrix.id != 'macos-arm64'
run: make test
cross:
@@ -151,6 +150,14 @@ jobs:
certificates-p12: ${{ secrets.APPLE_CERTIFICATES_P12 }}
certificates-password: ${{ secrets.APPLE_CERTIFICATES_PASSWORD }}
keychain-password: ${{ secrets.APPLE_KEYCHAIN_PASSWORD }}
- uses: nttld/setup-ndk@v1
if: startsWith(matrix.id, 'android-')
id: setup-ndk
with:
ndk-version: r25c
- name: Add NDK to env
if: startsWith(matrix.id, 'android-')
run: echo ANDROID_NDK_ROOT=${{ steps.setup-ndk.outputs.ndk-path }} >> $GITHUB_ENV
- name: Build
run: |
./configure --host=${{ matrix.id }} ${{ env.FRIDA_CORE_OPTIONS }}
@@ -234,3 +241,35 @@ jobs:
cp -a tests/frida-tests tests/labrats lib/agent/frida-agent.so /tmp/pkg/
tar -C /tmp/pkg -cf /tmp/runner.tar .
/opt/sabrelite/run.sh /tmp/runner.tar /opt/frida/frida-tests
# This job is used to check that the Linux helpers are built correctly for all
# supported architectures. We do this because the binary artifacts are checked
# in, and we want to ensure that they are up-to-date with respect to the source
# for all architectures.
check-linux-helpers:
strategy:
matrix:
arch: [x86, x86_64, arm, arm64, mips, mipsel, mips64, mips64el]
runs-on: ubuntu-latest
container: ghcr.io/frida/core-linux-helpers-${{ matrix.arch }}:latest
steps:
- name: Check out repo
uses: actions/checkout@v4
with:
submodules: recursive
- name: Build
run: |
./src/linux/helpers/rebuild.sh ${{ matrix.arch }}
- name: Check for unexpected changes
run: |
git config --global --add safe.directory "$(realpath .)"
status_output="$(git status --porcelain)"
if [ -n "$status_output" ]; then
echo "Unexpected changes detected:"
echo "$status_output"
echo "Diff:"
git diff
exit 1
else
echo "No unexpected changes detected."
fi
+52 -7
View File
@@ -4,6 +4,7 @@ import base64
from collections import OrderedDict
from dataclasses import dataclass, field
import itertools
import locale
import os
from pathlib import Path
import pickle
@@ -14,7 +15,7 @@ import subprocess
import sys
import tempfile
import traceback
from typing import Any, Literal, Mapping, Optional, Sequence
from typing import Any, Literal, Mapping, Optional, Sequence, Tuple
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -140,16 +141,19 @@ def setup(role: Role,
compat = set()
else:
summary = "enabled by user"
missing: list[MissingFeature] = []
if "native" in compat:
have_toolchain = True
other_label: Optional[str] = None
other_triplet: Optional[str] = None
extra_environ: dict[str, str] = {}
if host_os == "windows" and host_arch == "x86_64" and host_config == "mingw":
other_triplet = "i686-w64-mingw32"
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
other_label = "x86"
have_toolchain, other_triplet = detect_mingw_toolchain_for("x86")
elif host_os == "linux" and host_arch == "x86_64" and host_config is None:
other_label = "x86"
other_triplet = "i686-linux-gnu"
have_toolchain = shutil.which(other_triplet + "-gcc") is not None
if not have_toolchain:
@@ -173,7 +177,7 @@ def setup(role: Role,
if not have_toolchain:
if not auto_detect:
raise ToolchainNotFoundError(f"unable to locate toolchain for {other_triplet}")
summary = "disabled due to missing toolchain for {other_triplet}"
missing.append(MissingFeature(other_label, other_triplet))
if host_os == "windows" and host_arch == "x86_64" and have_toolchain:
group = OutputGroup("x86", other_triplet, extra_environ)
@@ -269,6 +273,28 @@ def setup(role: Role,
]
if "emulated" in compat:
if host_os == "windows" and host_arch == "arm64":
for kind, emulated_arch in [("modern", "x86_64"), ("legacy", "x86")]:
if host_config == "mingw":
found, emulated_triplet = detect_mingw_toolchain_for(emulated_arch)
if not found:
if not auto_detect:
raise ToolchainNotFoundError(f"unable to locate toolchain for {emulated_triplet}")
missing.append(MissingFeature(emulated_arch, emulated_triplet))
continue
else:
emulated_triplet = None
outputs[OutputGroup(emulated_arch, emulated_triplet, extra_environ)] = [
Output(identifier=f"helper_emulated_{kind}",
name=HELPER_FILE_WINDOWS.name.replace(".exe", f"-{emulated_arch}.exe"),
file=HELPER_FILE_WINDOWS,
target=HELPER_TARGET),
Output(identifier=f"agent_emulated_{kind}",
name=AGENT_FILE_WINDOWS.name.replace(".dll", f"-{emulated_arch}.dll"),
file=AGENT_FILE_WINDOWS,
target=AGENT_TARGET),
]
if host_os == "android" and host_arch in {"x86_64", "x86"}:
outputs[OutputGroup("arm")] = [
Output(identifier="agent_emulated_legacy",
@@ -290,6 +316,8 @@ def setup(role: Role,
state = State(role, builddir, top_builddir, frida_version, host_os, host_config, allowed_prebuilds, outputs)
serialized_state = base64.b64encode(pickle.dumps(state)).decode('ascii')
if missing:
summary = ", ".join([f"{m.label} disabled due to missing toolchain for {m.triplet}" for m in missing])
variable_names, output_names = zip(*[(output.identifier, output.name) \
for output in itertools.chain.from_iterable(outputs.values())])
print("ok")
@@ -349,6 +377,12 @@ class Output:
target: str
@dataclass
class MissingFeature:
label: str
triplet: str
def compile(privdir: Path, state: State):
releng_location = query_releng_location(state.role)
subprojects = detect_relevant_subprojects(releng_location)
@@ -367,7 +401,7 @@ def compile(privdir: Path, state: State):
**kwargs,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"encoding": "utf-8",
"encoding": locale.getpreferredencoding(),
}
else:
silenced_kwargs = kwargs
@@ -570,10 +604,10 @@ def grab_subprojects_from_parent(subprojects: dict[str, Path], releng_location:
continue
try:
subp_here.symlink_to(location, target_is_directory=True)
subp_here.symlink_to(Path("..") / ".." / name, target_is_directory=True)
continue
except OSError as e:
if not getattr(e, "winerror") == 1314:
if not getattr(e, "winerror", None) == 1314:
raise e
subprocess.run(["git", "worktree", "add", subp_here],
@@ -589,6 +623,12 @@ def configure_import_path(releng_location: Path):
sys.path.insert(0, str(releng_location.parent))
def detect_mingw_toolchain_for(arch: str) -> Tuple[bool, Optional[str]]:
triplet = MINGW_ARCHS.get(arch, arch) + "-w64-mingw32"
found = shutil.which(triplet + "-gcc") is not None
return (found, triplet)
STATE_FILENAME = "state.dat"
DEPFILE_FILENAME = "compat.deps"
@@ -616,6 +656,11 @@ MSVS_ENVVARS = {
"LIB",
}
MINGW_ARCHS = {
"x86": "i686",
"arm64": "aarch64",
}
if __name__ == "__main__":
main(sys.argv)
+3
View File
@@ -1,6 +1,8 @@
helper_modern = get_option('helper_modern')
helper_legacy = get_option('helper_legacy')
helper_compat = ''
helper_emulated_modern = get_option('helper_emulated_modern')
helper_emulated_legacy = get_option('helper_emulated_legacy')
helper_depends = []
agent_modern = get_option('agent_modern')
@@ -18,6 +20,7 @@ server_depends = []
no_overridden_compat_bits = \
helper_modern == 'auto' and helper_legacy == 'auto' \
and helper_emulated_modern == 'auto' and helper_emulated_legacy == 'auto' \
and agent_modern == 'auto' and agent_legacy == 'auto' \
and agent_emulated_modern == 'auto' and agent_emulated_legacy == 'auto'
+61 -32
View File
@@ -388,7 +388,7 @@ namespace Frida.Inject {
return false;
}
script_runner.on_stdin (line);
script_runner.on_stdin (line, null);
return true;
}
@@ -414,7 +414,12 @@ namespace Frida.Inject {
buf[n] = 0;
script_runner.on_stdin ((string) buf);
if (script_runner.terminal_mode == TerminalMode.BINARY) {
var bytes = new Bytes (buf[:n]);
script_runner.on_stdin ("", bytes);
} else {
script_runner.on_stdin ((string) buf, null);
}
return true;
}
@@ -549,7 +554,7 @@ namespace Frida.Inject {
var stage = new Json.Node.alloc ().init_string ("early");
try {
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, io_cancellable);
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, io_cancellable);
} catch (GLib.Error e) {
}
}
@@ -591,7 +596,7 @@ namespace Frida.Inject {
private async TerminalMode query_terminal_mode () {
Json.Node mode_value;
try {
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, io_cancellable);
mode_value = yield rpc_client.call ("getFridaTerminalMode", new Json.Node[] {}, null, io_cancellable);
} catch (GLib.Error e) {
return COOKED;
}
@@ -599,7 +604,14 @@ namespace Frida.Inject {
if (mode_value.get_value_type () != typeof (string))
return COOKED;
return (mode_value.get_string () == "raw") ? TerminalMode.RAW : TerminalMode.COOKED;
switch (mode_value.get_string ()) {
case "raw":
return TerminalMode.RAW;
case "binary":
return TerminalMode.BINARY;
default:
return TerminalMode.COOKED;
}
}
private void apply_terminal_mode (TerminalMode mode) throws Error {
@@ -632,10 +644,10 @@ namespace Frida.Inject {
}
#endif
public void on_stdin (string data) {
var data_value = new Json.Node.alloc ().init_string (data);
public void on_stdin (string str, Bytes? data) {
var str_value = new Json.Node.alloc ().init_string (str);
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { data_value }, io_cancellable);
rpc_client.call.begin ("onFridaStdin", new Json.Node[] { str_value }, data, io_cancellable);
}
private void on_script_file_changed (File file, File? other_file, FileMonitorEvent event_type) {
@@ -675,7 +687,7 @@ namespace Frida.Inject {
handled = try_handle_log_message (message);
break;
case "send":
handled = try_handle_stdout_message (message);
handled = try_handle_stdout_message (message, data);
break;
default:
handled = false;
@@ -722,20 +734,19 @@ namespace Frida.Inject {
*
* {"type":"send","payload":["frida:stdout","DATA"]}
*/
private bool try_handle_stdout_message (Json.Object message) {
private bool try_handle_stdout_message (Json.Object message, Bytes? data) {
var payload = message.get_member ("payload");
if (payload.get_node_type () != Json.NodeType.ARRAY)
return false;
var tuple = payload.get_array ();
if (tuple.get_length () != 2)
var tuple_len = tuple.get_length ();
if (tuple_len == 0)
return false;
var first_element = tuple.get_element (0);
if (first_element.get_value_type () != typeof (string))
var type = tuple.get_element (0).get_string ();
if (type == null)
return false;
var type = first_element.get_string ();
switch (type) {
case "frida:stdout":
case "frida:stderr":
@@ -744,31 +755,49 @@ namespace Frida.Inject {
return false;
}
var second_element = tuple.get_element (1);
if (second_element.get_value_type () != typeof (string))
return false;
var str = second_element.get_string ();
switch (type) {
case "frida:stdout":
stdout.write (str.data);
stdout.flush ();
return true;
case "frida:stderr":
stderr.write (str.data);
return true;
default:
if (tuple_len >= 2) {
var str = tuple.get_element (1).get_string ();
if (str == null)
return false;
switch (type) {
case "frida:stdout":
stdout.write (str.data);
stdout.flush ();
break;
case "frida:stderr":
stderr.write (str.data);
break;
default:
return false;
}
}
if (data != null) {
switch (type) {
case "frida:stdout":
stdout.write (data.get_data ());
stdout.flush ();
break;
case "frida:stderr":
stderr.write (data.get_data ());
break;
default:
return false;
}
}
return true;
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
script.post (json, null);
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
script.post (json, data);
}
}
private enum TerminalMode {
COOKED,
RAW
RAW,
BINARY
}
}
+15 -16
View File
@@ -1509,13 +1509,14 @@ namespace Frida.Agent {
}
public static NativeBridgeApi open () throws Error {
string? nb_mod = null;
string? vm_mod = null;
Gum.Process.enumerate_modules ((details) => {
if (/\/lib(64)?\/libnativebridge.so$/.match (details.path))
nb_mod = details.path;
else if (/^lib(art|dvm).so$/.match (details.name) && !/\/system\/fake-libs/.match (details.path))
vm_mod = details.path;
Gum.Module? nb_mod = null;
Gum.Module? vm_mod = null;
Gum.Process.enumerate_modules (module => {
unowned string path = module.path;
if (/\/lib(64)?\/libnativebridge.so$/.match (path))
nb_mod = module;
else if (/^lib(art|dvm).so$/.match (module.name) && !/\/system\/fake-libs/.match (path))
vm_mod = module;
bool carry_on = nb_mod == null || vm_mod == null;
return carry_on;
});
@@ -1530,29 +1531,27 @@ namespace Frida.Agent {
NBUnloadLibraryFunc? unload;
NBGetTrampolineFunc get_trampoline;
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibrary");;
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibrary");;
if (load != null) {
flavor = MODERN;
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod, "NativeBridgeLoadLibraryExt");
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name ("NativeBridgeLoadLibraryExt");
// XXX: NativeBridgeUnloadLibrary() is only a stub as of Android 11 w/ libndk_translation.so
unload = null;
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
"NativeBridgeGetTrampoline");
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name ("NativeBridgeGetTrampoline");
} else {
flavor = LEGACY;
load = (NBLoadLibraryFunc) Gum.Module.find_export_by_name (nb_mod,
"_ZN7android23NativeBridgeLoadLibraryEPKci");
load_ext = (NBLoadLibraryExtFunc) Gum.Module.find_export_by_name (nb_mod,
load = (NBLoadLibraryFunc) nb_mod.find_export_by_name ("_ZN7android23NativeBridgeLoadLibraryEPKci");
load_ext = (NBLoadLibraryExtFunc) nb_mod.find_export_by_name (
"_ZN7android26NativeBridgeLoadLibraryExtEPKciPNS_25native_bridge_namespace_tE");
// XXX: Unload implementation seems to be unreliable.
unload = null;
get_trampoline = (NBGetTrampolineFunc) Gum.Module.find_export_by_name (nb_mod,
get_trampoline = (NBGetTrampolineFunc) nb_mod.find_export_by_name (
"_ZN7android25NativeBridgeGetTrampolineEPvPKcS2_j");
}
if (load == null || get_trampoline == null)
throw new Error.NOT_SUPPORTED ("NativeBridge API is not available on this system");
var get_vms = (JNIGetCreatedJavaVMsFunc) Gum.Module.find_export_by_name (vm_mod, "JNI_GetCreatedJavaVMs");
var get_vms = (JNIGetCreatedJavaVMsFunc) vm_mod.find_export_by_name ("JNI_GetCreatedJavaVMs");
if (get_vms == null)
throw new Error.NOT_SUPPORTED ("Unable to locate Java VM");
+8
View File
@@ -0,0 +1,8 @@
{
global:
frida_agent_main;
JNI_OnLoad;
local:
*;
};
-1
View File
@@ -1,7 +1,6 @@
{
global:
frida_agent_main;
JNI_OnLoad;
local:
*;
+1 -1
View File
@@ -28,7 +28,7 @@ if host_os_family == 'windows'
elif host_os_family == 'darwin'
extra_link_args += '-Wl,-exported_symbol,_frida_agent_main'
else
symscript = 'frida-agent.version'
symscript = (host_os == 'android') ? 'frida-agent-android.version' : 'frida-agent.version'
extra_link_args += '-Wl,--version-script,' + meson.current_source_dir() / symscript
extra_link_depends += symscript
endif
+135 -9
View File
@@ -428,21 +428,28 @@ namespace Frida {
return *((double *) &bits);
}
public string read_string (size_t offset) {
public string read_string (size_t offset) throws Error {
string * start = (string *) get_pointer (offset, sizeof (char));
size_t max_length = size - offset;
string * val = (string *) get_pointer (offset, sizeof (char));
string * end = memchr (val, 0, max_length);
assert (end != null);
size_t size = end - val;
return val->substring (0, (long) size);
string * end = memchr (start, 0, max_length);
if (end == null)
throw new Error.PROTOCOL ("Missing null character");
size_t size = end - start;
string val = start->substring (0, (long) size);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
}
[CCode (cname = "memchr", cheader_filename = "string.h")]
private extern static string * memchr (string * s, int c, size_t n);
public string read_fixed_string (size_t offset, size_t size) {
string * val = (string *) get_pointer (offset, size);
return val->substring (0, (long) size);
public string read_fixed_string (size_t offset, size_t size) throws Error {
string * start = (string *) get_pointer (offset, size);
string val = start->substring (0, (long) size);
if (!val.validate ())
throw new Error.PROTOCOL ("Invalid UTF-8 string");
return val;
}
public unowned Buffer write_string (size_t offset, string val) {
@@ -458,4 +465,123 @@ namespace Frida {
return data + offset;
}
}
public class BufferReader {
public size_t available {
get {
return buffer.bytes.get_size () - offset;
}
}
private Buffer buffer;
private size_t offset = 0;
public BufferReader (Buffer buf) {
buffer = buf;
}
public uint64 read_pointer (size_t offset) throws Error {
var pointer_size = buffer.pointer_size;
check_available (pointer_size);
var ptr = buffer.read_pointer (offset);
offset += pointer_size;
return ptr;
}
public int8 read_int8 () throws Error {
check_available (sizeof (int8));
var val = buffer.read_int8 (offset);
offset += sizeof (int8);
return val;
}
public uint8 read_uint8 () throws Error {
check_available (sizeof (uint8));
var val = buffer.read_uint8 (offset);
offset += sizeof (uint8);
return val;
}
public int16 read_int16 () throws Error {
check_available (sizeof (int16));
var val = buffer.read_int16 (offset);
offset += sizeof (int16);
return val;
}
public uint16 read_uint16 () throws Error {
check_available (sizeof (uint16));
var val = buffer.read_uint16 (offset);
offset += sizeof (uint16);
return val;
}
public int32 read_int32 () throws Error {
check_available (sizeof (int32));
var val = buffer.read_int32 (offset);
offset += sizeof (int32);
return val;
}
public uint32 read_uint32 () throws Error {
check_available (sizeof (uint32));
var val = buffer.read_uint32 (offset);
offset += sizeof (uint32);
return val;
}
public int64 read_int64 () throws Error {
check_available (sizeof (int64));
var val = buffer.read_int64 (offset);
offset += sizeof (int64);
return val;
}
public uint64 read_uint64 () throws Error {
check_available (sizeof (uint64));
var val = buffer.read_uint64 (offset);
offset += sizeof (uint64);
return val;
}
public float read_float () throws Error {
check_available (sizeof (float));
var val = buffer.read_float (offset);
offset += sizeof (float);
return val;
}
public double read_double () throws Error {
check_available (sizeof (double));
var val = buffer.read_double (offset);
offset += sizeof (double);
return val;
}
public string read_string () throws Error {
check_available (1);
var val = buffer.read_string (offset);
offset += val.length + 1;
return val;
}
public string read_fixed_string (size_t size) throws Error {
check_available (size);
var val = buffer.read_fixed_string (offset, size);
offset += size;
return val;
}
public Bytes read_bytes (size_t size) throws Error {
check_available (size);
var val = buffer.bytes[offset:offset + size];
offset += size;
return val;
}
private void check_available (size_t n) throws Error {
if (available < n)
throw new Error.PROTOCOL ("Malformed buffer: truncated");
}
}
}
+4 -1
View File
@@ -43,14 +43,17 @@ if host_os_family == 'darwin'
]
endif
base_gir_name = f'FridaBase-@[email protected]'
base = static_library('frida-base-' + api_version, base_sources,
c_args: frida_component_cflags,
vala_args: [base_vala_args, '--pkg=libsoup-3.0'] + extra_vala_args,
vala_header: 'frida-base.h',
vala_gir: base_gir_name,
vala_vapi: f'frida-base-@[email protected]',
dependencies: [glib_dep, gobject_dep, gio_dep, libsoup_dep, nice_dep, usrsctp_dep, gee_dep, json_glib_dep, gum_dep, openssl_dep] + extra_deps,
install: true,
install_dir: [true, header_install_dir, true],
install_dir: [true, header_install_dir, true, false],
)
base_dep = declare_dependency(
+3 -3
View File
@@ -11,7 +11,7 @@ namespace Frida {
Object (peer: peer);
}
public async Json.Node call (string method, Json.Node[] args, Cancellable? cancellable) throws Error, IOError {
public async Json.Node call (string method, Json.Node[] args, Bytes? data, Cancellable? cancellable) throws Error, IOError {
string request_id = Uuid.string_random ();
var request = new Json.Builder ();
@@ -39,7 +39,7 @@ namespace Frida {
pending_responses[request_id] = pending;
try {
yield peer.post_rpc_message (raw_request, cancellable);
yield peer.post_rpc_message (raw_request, data, cancellable);
} catch (Error e) {
if (pending_responses.unset (request_id))
pending.complete_with_error (e);
@@ -158,6 +158,6 @@ namespace Frida {
}
public interface RpcPeer : Object {
public abstract async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError;
public abstract async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError;
}
}
+459 -369
View File
@@ -218,7 +218,7 @@ namespace Frida {
frida_source.set_callback (negotiate_connection.callback);
frida_source.attach (frida_context);
return false;
return Source.REMOVE;
});
dbus_source.attach (dbus_context);
yield;
@@ -235,7 +235,7 @@ namespace Frida {
}
public class WebService : Object {
public signal void incoming (IOStream connection, SocketAddress remote_address);
public signal void incoming (IOStream connection, SocketAddress remote_address, DynamicInterface? dynamic_iface);
public EndpointParameters endpoint_params {
get;
@@ -264,9 +264,9 @@ namespace Frida {
}
}
private Soup.Server? main_server;
private ConnectionHandler main_handler;
private SocketAddress? _listen_address;
private Gee.Map<string, Soup.Server> dynamic_interface_servers = new Gee.HashMap<string, Soup.Server> ();
private Gee.Map<string, ConnectionHandler> dynamic_interface_handlers = new Gee.HashMap<string, ConnectionHandler> ();
private Cancellable io_cancellable = new Cancellable ();
@@ -292,7 +292,7 @@ namespace Frida {
var start_request = new Promise<SocketAddress> ();
schedule_on_dbus_thread (() => {
handle_start_request.begin (start_request, cancellable);
return false;
return Source.REMOVE;
});
_listen_address = yield start_request.future.wait_async (cancellable);
@@ -303,19 +303,19 @@ namespace Frida {
SocketAddress effective_address = yield do_start (cancellable);
schedule_on_frida_thread (() => {
start_request.resolve (effective_address);
return false;
return Source.REMOVE;
});
} catch (GLib.Error e) {
GLib.Error start_error = e;
schedule_on_frida_thread (() => {
start_request.reject (start_error);
return false;
return Source.REMOVE;
});
}
}
private async SocketAddress do_start (Cancellable? cancellable) throws Error, IOError {
main_server = create_server ();
main_handler = make_connection_handler (null);
SocketAddress? first_effective_address = null;
SocketConnectable connectable = (flavor == CONTROL)
? parse_control_address (endpoint_params.address, endpoint_params.port)
@@ -334,14 +334,10 @@ namespace Frida {
SocketAddress? effective_address = null;
InetSocketAddress? inet_address = address as InetSocketAddress;
if (inet_address != null) {
effective_address = listen_on_inet_address (inet_address, main_server);
effective_address = main_handler.listen_on_inet_address (inet_address);
} else {
try {
main_server.listen (address, compute_listen_options ());
effective_address = address;
} catch (GLib.Error e) {
throw_listen_error (e);
}
main_handler.listen_on_socket_address (address);
effective_address = address;
}
if (first_effective_address == null)
@@ -360,85 +356,39 @@ namespace Frida {
return first_effective_address;
}
private void on_dynamic_interface_attached (string name, InetAddress ip) {
private void on_dynamic_interface_attached (DynamicInterface iface) {
unowned string name = iface.name;
uint16 port = endpoint_params.port;
if (port == 0)
port = (flavor == CONTROL) ? DEFAULT_CONTROL_PORT : DEFAULT_CLUSTER_PORT;
var server = create_server ();
var handler = make_connection_handler (iface);
try {
listen_on_inet_address (new InetSocketAddress (ip, port), server);
handler.listen_on_inet_address (new InetSocketAddress (iface.ip, port));
} catch (Error e) {
return;
}
dynamic_interface_servers[name] = server;
dynamic_interface_handlers[name] = handler;
}
private void on_dynamic_interface_detached (string name, InetAddress ip) {
Soup.Server server;
if (dynamic_interface_servers.unset (name, out server))
destroy_server (server);
private void on_dynamic_interface_detached (DynamicInterface iface) {
ConnectionHandler handler;
if (dynamic_interface_handlers.unset (iface.name, out handler))
handler.close ();
}
private Soup.Server create_server () {
var server = (Soup.Server) Object.new (typeof (Soup.Server),
"tls-certificate", endpoint_params.certificate);
server.add_websocket_handler ("/ws", endpoint_params.origin, null, on_websocket_opened);
if (endpoint_params.asset_root != null)
server.add_handler (null, on_asset_request);
return server;
private ConnectionHandler make_connection_handler (DynamicInterface? dynamic_iface) {
var handler = new ConnectionHandler (dynamic_iface, endpoint_params, on_port_conflict);
handler.incoming.connect (on_incoming_connection);
return handler;
}
private void destroy_server (Soup.Server server) {
if (endpoint_params.asset_root != null)
server.remove_handler ("/");
server.remove_handler ("/ws");
server.disconnect ();
}
private Soup.ServerListenOptions compute_listen_options () {
return (endpoint_params.certificate != null)
? Soup.ServerListenOptions.HTTPS
: 0;
}
private InetSocketAddress listen_on_inet_address (InetSocketAddress address, Soup.Server server) throws Error {
InetSocketAddress candidate_address = address;
uint16 start_port = address.get_port ();
uint16 candidate_port = start_port;
do {
try {
server.listen (candidate_address, compute_listen_options ());
return candidate_address;
} catch (GLib.Error e) {
if (e is IOError.ADDRESS_IN_USE && on_port_conflict == PICK_NEXT) {
candidate_port++;
if (candidate_port == start_port)
throw new Error.ADDRESS_IN_USE ("Unable to bind to any port");
if (candidate_port == 0)
candidate_port = 1024;
candidate_address = new InetSocketAddress (candidate_address.get_address (),
candidate_port);
} else {
throw_listen_error (e);
}
}
} while (true);
}
[NoReturn]
private static void throw_listen_error (GLib.Error e) throws Error {
if (e is IOError.ADDRESS_IN_USE)
throw new Error.ADDRESS_IN_USE ("%s", e.message);
if (e is IOError.PERMISSION_DENIED)
throw new Error.PERMISSION_DENIED ("%s", e.message);
throw new Error.NOT_SUPPORTED ("%s", e.message);
private void on_incoming_connection (ConnectionHandler handler, IOStream connection, SocketAddress remote_address) {
schedule_on_frida_thread (() => {
incoming (connection, remote_address, handler.dynamic_iface);
return Source.REMOVE;
});
}
public void stop () {
@@ -446,301 +396,22 @@ namespace Frida {
schedule_on_dbus_thread (() => {
do_stop ();
return false;
return Source.REMOVE;
});
}
private void do_stop () {
foreach (var server in dynamic_interface_servers.values)
destroy_server (server);
dynamic_interface_servers.clear ();
foreach (var handler in dynamic_interface_handlers.values)
handler.close ();
dynamic_interface_handlers.clear ();
if (dynamic_interface_observer != null) {
dynamic_interface_observer.interface_attached.disconnect (on_dynamic_interface_attached);
dynamic_interface_observer.interface_detached.disconnect (on_dynamic_interface_detached);
}
if (main_server != null)
destroy_server (main_server);
}
private void on_websocket_opened (Soup.Server server, Soup.ServerMessage msg, string path,
Soup.WebsocketConnection connection) {
var peer = new WebConnection (connection);
IOStream soup_stream = connection.get_io_stream ();
SocketConnection socket_stream;
soup_stream.get ("base-iostream", out socket_stream);
SocketAddress remote_address;
try {
remote_address = socket_stream.get_remote_address ();
} catch (GLib.Error e) {
assert_not_reached ();
}
schedule_on_frida_thread (() => {
incoming (peer, remote_address);
return false;
});
}
private void on_asset_request (Soup.Server server, Soup.ServerMessage msg, string path, HashTable<string, string>? query) {
msg.get_response_headers ().replace ("Server", "Frida/" + _version_string ());
unowned string method = msg.get_method ();
if (method != "GET" && method != "HEAD") {
msg.set_status (Soup.Status.METHOD_NOT_ALLOWED, null);
return;
}
File location = endpoint_params.asset_root.resolve_relative_path (path.next_char ());
msg.pause ();
handle_asset_request.begin (path, location, msg);
}
private async void handle_asset_request (string path, File file, Soup.ServerMessage msg) {
int priority = Priority.DEFAULT;
string attributes = FileAttribute.STANDARD_TYPE + "," + FileAttribute.STANDARD_SIZE;
FileInfo info;
FileInputStream? stream = null;
try {
info = yield file.query_info_async (attributes, FileQueryInfoFlags.NONE, priority, io_cancellable);
FileType type = info.get_file_type ();
if (type == DIRECTORY) {
if (!path.has_suffix ("/")) {
handle_misplaced_request (path + "/", msg);
return;
}
File index_file = file.get_child ("index.html");
try {
var index_info = yield index_file.query_info_async (attributes, FileQueryInfoFlags.NONE,
priority, io_cancellable);
file = index_file;
info = index_info;
type = index_info.get_file_type ();
} catch (GLib.Error e) {
}
}
if (type != DIRECTORY)
stream = yield file.read_async (priority, io_cancellable);
} catch (GLib.Error e) {
msg.set_status (Soup.Status.NOT_FOUND, null);
msg.unpause ();
return;
}
if (stream == null)
yield handle_directory_request (path, file, msg);
else
yield handle_file_request (file, info, stream, msg);
}
private async void handle_directory_request (string path, File file, Soup.ServerMessage msg) {
var listing = new StringBuilder.sized (1024);
string escaped_path = Markup.escape_text (path);
listing.append ("""<html>
<head><title>Index of %s</title></head>
<body>
<h1>Index of %s</h1><hr><pre>""".printf (escaped_path, escaped_path));
if (path != "/")
listing.append ("<a href=\"../\">../</a>");
listing.append_c ('\n');
string attributes =
FileAttribute.STANDARD_DISPLAY_NAME + "," +
FileAttribute.STANDARD_TYPE + "," +
FileAttribute.TIME_MODIFIED + "," +
FileAttribute.STANDARD_SIZE;
int priority = Priority.DEFAULT;
try {
var enumerator = yield file.enumerate_children_async (attributes, FileQueryInfoFlags.NONE, priority,
io_cancellable);
List<FileInfo> files = yield enumerator.next_files_async (int.MAX, priority, io_cancellable);
files.sort ((a, b) => {
bool a_is_dir = a.get_file_type () == DIRECTORY;
bool b_is_dir = b.get_file_type () == DIRECTORY;
if (a_is_dir == b_is_dir)
return strcmp (a.get_display_name (), b.get_display_name ());
else if (a_is_dir)
return -1;
else
return 1;
});
foreach (FileInfo info in files) {
string display_name = info.get_display_name ();
FileType type = info.get_file_type ();
DateTime modified = info.get_modification_date_time ().to_local ();
string link = Markup.escape_text (display_name);
if (type == DIRECTORY)
link += "/";
listing
.append ("<a href=\"")
.append (link)
.append ("\">")
.append (link)
.append ("</a>");
int padding_needed = 50 - link.length;
while (padding_needed > 0) {
listing.append_c (' ');
padding_needed--;
}
listing
.append_c (' ')
.append (modified.format ("%d-%b-%Y %H:%M"))
.append (" ");
string size_info;
if (type != DIRECTORY)
size_info = info.get_size ().to_string ();
else
size_info = "-";
listing.append_printf ("%8s\n", size_info);
}
} catch (GLib.Error e) {
msg.set_status (Soup.Status.NOT_FOUND, null);
msg.unpause ();
return;
}
listing.append ("</pre><hr></body>\n</html>");
msg.set_status (Soup.Status.OK, null);
if (msg.get_method () == "HEAD") {
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", "text/html");
headers.replace ("Content-Length", listing.len.to_string ());
} else {
msg.set_response ("text/html", Soup.MemoryUse.COPY, listing.str.data);
}
msg.unpause ();
}
private async void handle_file_request (File file, FileInfo info, FileInputStream stream, Soup.ServerMessage msg) {
msg.set_status (Soup.Status.OK, null);
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", guess_mime_type_for (file.get_path ()));
headers.replace ("Content-Length", info.get_size ().to_string ());
if (msg.get_method () == "HEAD") {
msg.unpause ();
return;
}
var body = msg.get_response_body ();
body.set_accumulate (false);
bool finished = false;
bool waiting = false;
ulong finished_handler = msg.finished.connect (() => {
finished = true;
if (waiting)
handle_file_request.callback ();
});
ulong write_handler = msg.wrote_body_data.connect (chunk => {
if (waiting)
handle_file_request.callback ();
});
try {
var buffer = new uint8[64 * 1024];
while (true) {
ssize_t n;
try {
n = yield stream.read_async (buffer, Priority.DEFAULT, io_cancellable);
} catch (IOError e) {
break;
}
if (n == 0 || finished)
break;
body.append_take (buffer[0:n]);
msg.unpause ();
waiting = true;
yield;
waiting = false;
if (finished)
break;
msg.pause ();
}
} finally {
msg.disconnect (write_handler);
msg.disconnect (finished_handler);
if (!finished)
msg.unpause ();
}
}
private void handle_misplaced_request (string redirect_uri, Soup.ServerMessage msg) {
msg.set_redirect (Soup.Status.MOVED_PERMANENTLY, redirect_uri);
string body = """<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>%s</center>
</body>
</html>""".printf ("Frida/" + _version_string ());
if (msg.get_method () == "HEAD") {
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", "text/html");
headers.replace ("Content-Length", body.length.to_string ());
} else {
msg.set_response ("text/html", Soup.MemoryUse.COPY, body.data);
}
msg.unpause ();
}
private static string guess_mime_type_for (string path) {
if (path.has_suffix (".html"))
return "text/html";
if (path.has_suffix (".js"))
return "text/javascript";
if (path.has_suffix (".json"))
return "application/json";
if (path.has_suffix (".css"))
return "text/css";
if (path.has_suffix (".jpeg") || path.has_suffix (".jpg"))
return "image/jpeg";
if (path.has_suffix (".png"))
return "image/png";
if (path.has_suffix (".gif"))
return "image/gif";
bool uncertain;
return ContentType.guess (path, null, out uncertain);
if (main_handler != null)
main_handler.close ();
}
private void schedule_on_frida_thread (owned SourceFunc function) {
@@ -758,6 +429,405 @@ namespace Frida {
source.set_callback ((owned) function);
source.attach (dbus_context);
}
private class ConnectionHandler : Object {
public signal void incoming (IOStream connection, SocketAddress remote_address);
public DynamicInterface? dynamic_iface {
get;
construct;
}
public EndpointParameters endpoint_params {
get;
construct;
}
public PortConflictBehavior on_port_conflict {
get;
construct;
default = FAIL;
}
private Soup.Server server;
private Gee.Set<WebConnection> connections = new Gee.HashSet<WebConnection> ();
private Cancellable io_cancellable = new Cancellable ();
public ConnectionHandler (DynamicInterface? dynamic_iface, EndpointParameters endpoint_params,
PortConflictBehavior on_port_conflict) {
Object (
dynamic_iface: dynamic_iface,
endpoint_params: endpoint_params,
on_port_conflict: on_port_conflict
);
}
construct {
server = (Soup.Server) Object.new (typeof (Soup.Server),
"tls-certificate", endpoint_params.certificate);
server.add_websocket_handler ("/ws", endpoint_params.origin, null, on_websocket_opened);
if (endpoint_params.asset_root != null)
server.add_handler (null, on_asset_request);
}
public void close () {
io_cancellable.cancel ();
if (endpoint_params.asset_root != null)
server.remove_handler ("/");
server.remove_handler ("/ws");
server.disconnect ();
foreach (var connection in connections.to_array ()) {
try {
connection.close (null);
} catch (IOError e) {
assert_not_reached ();
}
remove_connection (connection);
}
}
public InetSocketAddress listen_on_inet_address (InetSocketAddress address) throws Error {
InetSocketAddress candidate_address = address;
uint16 start_port = address.get_port ();
uint16 candidate_port = start_port;
do {
try {
server.listen (candidate_address, compute_listen_options ());
return candidate_address;
} catch (GLib.Error e) {
if (e is IOError.ADDRESS_IN_USE && on_port_conflict == PICK_NEXT) {
candidate_port++;
if (candidate_port == start_port)
throw new Error.ADDRESS_IN_USE ("Unable to bind to any port");
if (candidate_port == 0)
candidate_port = 1024;
candidate_address = new InetSocketAddress (candidate_address.get_address (),
candidate_port);
} else {
throw_listen_error (e);
}
}
} while (true);
}
public void listen_on_socket_address (SocketAddress address) throws Error {
try {
server.listen (address, compute_listen_options ());
} catch (GLib.Error e) {
throw_listen_error (e);
}
}
private Soup.ServerListenOptions compute_listen_options () {
return (endpoint_params.certificate != null)
? Soup.ServerListenOptions.HTTPS
: 0;
}
[NoReturn]
private static void throw_listen_error (GLib.Error e) throws Error {
if (e is IOError.ADDRESS_IN_USE)
throw new Error.ADDRESS_IN_USE ("%s", e.message);
if (e is IOError.PERMISSION_DENIED)
throw new Error.PERMISSION_DENIED ("%s", e.message);
throw new Error.NOT_SUPPORTED ("%s", e.message);
}
private void on_websocket_opened (Soup.Server server, Soup.ServerMessage msg, string path,
Soup.WebsocketConnection connection) {
var peer = new WebConnection (connection);
peer.websocket_closed.connect (on_websocket_closed);
connections.add (peer);
IOStream soup_stream = connection.get_io_stream ();
SocketConnection socket_stream;
soup_stream.get ("base-iostream", out socket_stream);
SocketAddress remote_address;
try {
remote_address = socket_stream.get_remote_address ();
} catch (GLib.Error e) {
assert_not_reached ();
}
incoming (peer, remote_address);
}
private void on_websocket_closed (WebConnection connection) {
remove_connection (connection);
}
private void remove_connection (WebConnection connection) {
connection.websocket_closed.disconnect (on_websocket_closed);
connections.remove (connection);
}
private void on_asset_request (Soup.Server server, Soup.ServerMessage msg, string path,
HashTable<string, string>? query) {
msg.get_response_headers ().replace ("Server", "Frida/" + _version_string ());
unowned string method = msg.get_method ();
if (method != "GET" && method != "HEAD") {
msg.set_status (Soup.Status.METHOD_NOT_ALLOWED, null);
return;
}
File location = endpoint_params.asset_root.resolve_relative_path (path.next_char ());
msg.pause ();
handle_asset_request.begin (path, location, msg);
}
private async void handle_asset_request (string path, File file, Soup.ServerMessage msg) {
int priority = Priority.DEFAULT;
string attributes = FileAttribute.STANDARD_TYPE + "," + FileAttribute.STANDARD_SIZE;
FileInfo info;
FileInputStream? stream = null;
try {
info = yield file.query_info_async (attributes, FileQueryInfoFlags.NONE, priority, io_cancellable);
FileType type = info.get_file_type ();
if (type == DIRECTORY) {
if (!path.has_suffix ("/")) {
handle_misplaced_request (path + "/", msg);
return;
}
File index_file = file.get_child ("index.html");
try {
var index_info = yield index_file.query_info_async (attributes,
FileQueryInfoFlags.NONE, priority, io_cancellable);
file = index_file;
info = index_info;
type = index_info.get_file_type ();
} catch (GLib.Error e) {
}
}
if (type != DIRECTORY)
stream = yield file.read_async (priority, io_cancellable);
} catch (GLib.Error e) {
msg.set_status (Soup.Status.NOT_FOUND, null);
msg.unpause ();
return;
}
if (stream == null)
yield handle_directory_request (path, file, msg);
else
yield handle_file_request (file, info, stream, msg);
}
private async void handle_directory_request (string path, File file, Soup.ServerMessage msg) {
var listing = new StringBuilder.sized (1024);
string escaped_path = Markup.escape_text (path);
listing.append ("""<html>
<head><title>Index of %s</title></head>
<body>
<h1>Index of %s</h1><hr><pre>""".printf (escaped_path, escaped_path));
if (path != "/")
listing.append ("<a href=\"../\">../</a>");
listing.append_c ('\n');
string attributes =
FileAttribute.STANDARD_DISPLAY_NAME + "," +
FileAttribute.STANDARD_TYPE + "," +
FileAttribute.TIME_MODIFIED + "," +
FileAttribute.STANDARD_SIZE;
int priority = Priority.DEFAULT;
try {
var enumerator = yield file.enumerate_children_async (attributes, FileQueryInfoFlags.NONE, priority,
io_cancellable);
List<FileInfo> files = yield enumerator.next_files_async (int.MAX, priority, io_cancellable);
files.sort ((a, b) => {
bool a_is_dir = a.get_file_type () == DIRECTORY;
bool b_is_dir = b.get_file_type () == DIRECTORY;
if (a_is_dir == b_is_dir)
return strcmp (a.get_display_name (), b.get_display_name ());
else if (a_is_dir)
return -1;
else
return 1;
});
foreach (FileInfo info in files) {
string display_name = info.get_display_name ();
FileType type = info.get_file_type ();
DateTime modified = info.get_modification_date_time ().to_local ();
string link = Markup.escape_text (display_name);
if (type == DIRECTORY)
link += "/";
listing
.append ("<a href=\"")
.append (link)
.append ("\">")
.append (link)
.append ("</a>");
int padding_needed = 50 - link.length;
while (padding_needed > 0) {
listing.append_c (' ');
padding_needed--;
}
listing
.append_c (' ')
.append (modified.format ("%d-%b-%Y %H:%M"))
.append (" ");
string size_info;
if (type != DIRECTORY)
size_info = info.get_size ().to_string ();
else
size_info = "-";
listing.append_printf ("%8s\n", size_info);
}
} catch (GLib.Error e) {
msg.set_status (Soup.Status.NOT_FOUND, null);
msg.unpause ();
return;
}
listing.append ("</pre><hr></body>\n</html>");
msg.set_status (Soup.Status.OK, null);
if (msg.get_method () == "HEAD") {
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", "text/html");
headers.replace ("Content-Length", listing.len.to_string ());
} else {
msg.set_response ("text/html", Soup.MemoryUse.COPY, listing.str.data);
}
msg.unpause ();
}
private async void handle_file_request (File file, FileInfo info, FileInputStream stream, Soup.ServerMessage msg) {
msg.set_status (Soup.Status.OK, null);
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", guess_mime_type_for (file.get_path ()));
headers.replace ("Content-Length", info.get_size ().to_string ());
if (msg.get_method () == "HEAD") {
msg.unpause ();
return;
}
var body = msg.get_response_body ();
body.set_accumulate (false);
bool finished = false;
bool waiting = false;
ulong finished_handler = msg.finished.connect (() => {
finished = true;
if (waiting)
handle_file_request.callback ();
});
ulong write_handler = msg.wrote_body_data.connect (chunk => {
if (waiting)
handle_file_request.callback ();
});
try {
var buffer = new uint8[64 * 1024];
while (true) {
ssize_t n;
try {
n = yield stream.read_async (buffer, Priority.DEFAULT, io_cancellable);
} catch (IOError e) {
break;
}
if (n == 0 || finished)
break;
body.append_take (buffer[0:n]);
msg.unpause ();
waiting = true;
yield;
waiting = false;
if (finished)
break;
msg.pause ();
}
} finally {
msg.disconnect (write_handler);
msg.disconnect (finished_handler);
if (!finished)
msg.unpause ();
}
}
private void handle_misplaced_request (string redirect_uri, Soup.ServerMessage msg) {
msg.set_redirect (Soup.Status.MOVED_PERMANENTLY, redirect_uri);
string body = """<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>%s</center>
</body>
</html>""".printf ("Frida/" + _version_string ());
if (msg.get_method () == "HEAD") {
var headers = msg.get_response_headers ();
headers.replace ("Content-Type", "text/html");
headers.replace ("Content-Length", body.length.to_string ());
} else {
msg.set_response ("text/html", Soup.MemoryUse.COPY, body.data);
}
msg.unpause ();
}
private static string guess_mime_type_for (string path) {
if (path.has_suffix (".html"))
return "text/html";
if (path.has_suffix (".js"))
return "text/javascript";
if (path.has_suffix (".json"))
return "application/json";
if (path.has_suffix (".css"))
return "text/css";
if (path.has_suffix (".jpeg") || path.has_suffix (".jpg"))
return "image/jpeg";
if (path.has_suffix (".png"))
return "image/png";
if (path.has_suffix (".gif"))
return "image/gif";
bool uncertain;
return ContentType.guess (path, null, out uncertain);
}
}
}
public enum WebServiceTransport {
@@ -776,15 +846,33 @@ namespace Frida {
}
public interface DynamicInterfaceObserver : Object {
public signal void interface_attached (string name, InetAddress ip);
public signal void interface_detached (string name, InetAddress ip);
public signal void interface_attached (DynamicInterface iface);
public signal void interface_detached (DynamicInterface iface);
public abstract void start ();
}
public class DynamicInterface : Object {
public string name {
get;
construct;
}
public InetAddress ip {
get;
construct;
}
public DynamicInterface (string name, InetAddress ip) {
Object (name: name, ip: ip);
}
}
public extern static unowned string _version_string ();
private class WebConnection : IOStream {
public signal void websocket_closed ();
public Soup.WebsocketConnection websocket {
get;
construct;
@@ -862,7 +950,7 @@ namespace Frida {
var source = new IdleSource ();
source.set_callback (() => {
do_close ();
return false;
return Source.REMOVE;
});
source.attach (main_context);
}
@@ -907,7 +995,7 @@ namespace Frida {
var source = new IdleSource ();
source.set_callback (() => {
process_send_queue ();
return false;
return Source.REMOVE;
});
source.attach (main_context);
}
@@ -950,6 +1038,8 @@ namespace Frida {
state = websocket.state;
recompute_pending_io_unlocked ();
}
websocket_closed ();
}
private void on_message (int type, Bytes message) {
+5
View File
@@ -13,6 +13,7 @@ namespace Frida {
public abstract unowned ObjectBuilder add_uint64_value (uint64 val);
public abstract unowned ObjectBuilder add_data_value (Bytes val);
public abstract unowned ObjectBuilder add_string_value (string val);
public abstract unowned ObjectBuilder add_uuid_value (uint8[] val);
public abstract unowned ObjectBuilder add_raw_value (Bytes val);
public abstract Bytes build ();
@@ -238,6 +239,10 @@ namespace Frida {
return this;
}
public unowned ObjectBuilder add_uuid_value (uint8[] val) {
assert_not_reached ();
}
public unowned ObjectBuilder add_raw_value (Bytes val) {
string uuid = Uuid.string_random ();
builder.add_string_value (uuid);
+9
View File
@@ -65,8 +65,17 @@ namespace Frida {
});
});
var cancel_source = new CancellableSource (cancellable);
cancel_source.set_callback (() => {
connection.cancel ();
return Source.REMOVE;
});
cancel_source.attach (main_context);
yield;
cancel_source.destroy ();
if (reply.type == Darwin.Xpc.Error.TYPE) {
var e = (Darwin.Xpc.Error) reply;
throw new Error.NOT_SUPPORTED ("%s", e.get_string (Darwin.Xpc.Error.KEY_DESCRIPTION));
+65 -12
View File
@@ -751,7 +751,7 @@ namespace Frida.Gadget {
string config_data;
try {
FileUtils.get_contents (config_path, out config_data);
load_asset_text (config_path, out config_data);
} catch (FileError e) {
if (e is FileError.NOENT)
return new Config ();
@@ -1226,7 +1226,7 @@ namespace Frida.Gadget {
private ScriptConfig load_config (string path) throws Error {
string data;
try {
FileUtils.get_contents (path, out data);
load_asset_text (path, out data);
} catch (FileError e) {
if (e is FileError.NOENT)
return new ScriptConfig ();
@@ -1349,9 +1349,9 @@ namespace Frida.Gadget {
try {
var path = this.path;
uint8[] contents;
Bytes contents;
try {
FileUtils.get_data (path, out contents);
load_asset_bytes (path, out contents);
} catch (FileError e) {
throw new Error.INVALID_ARGUMENT ("%s", e.message);
}
@@ -1360,11 +1360,10 @@ namespace Frida.Gadget {
options.name = Path.get_basename (path).split (".", 2)[0];
ScriptEngine.ScriptInstance instance;
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC) {
instance = yield engine.create_script (null, new Bytes (contents), options);
} else {
instance = yield engine.create_script ((string) contents, null, options);
}
if (contents.length > 0 && contents[0] == QUICKJS_BYTECODE_MAGIC)
instance = yield engine.create_script (null, contents, options);
else
instance = yield engine.create_script ((string) contents.get_data (), null, options);
if (id.handle != 0)
yield engine.destroy_script (id);
@@ -1381,7 +1380,7 @@ namespace Frida.Gadget {
var stage = new Json.Node.alloc ().init_string ((peek_state () == State.CREATED) ? "early" : "late");
try {
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null);
yield rpc_client.call ("init", new Json.Node[] { stage, parameters }, null, null);
} catch (GLib.Error e) {
}
}
@@ -1449,8 +1448,8 @@ namespace Frida.Gadget {
return true;
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
engine.post_to_script (id, json);
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
engine.post_to_script (id, json, data);
}
}
@@ -2076,6 +2075,60 @@ namespace Frida.Gadget {
}
#endif
private void load_asset_text (string filename, out string text) throws FileError {
Bytes raw_contents;
load_asset_bytes (filename, out raw_contents);
unowned string str = (string) raw_contents.get_data ();
if (!str.validate ())
throw new FileError.FAILED ("%s: invalid UTF-8", filename);
text = str;
}
private void load_asset_bytes (string filename, out Bytes bytes) throws FileError {
#if ANDROID
if (maybe_load_asset_bytes_from_apk (filename, out bytes))
return;
#endif
uint8[] data;
FileUtils.get_data (filename, out data);
bytes = new Bytes.take ((owned) data);
}
#if ANDROID
private bool maybe_load_asset_bytes_from_apk (string filename, out Bytes contents) throws FileError {
contents = null;
var tokens = filename.split ("!", 2);
if (tokens.length != 2 || !tokens[0].has_suffix (".apk"))
return false;
unowned string apk_path = tokens[0];
unowned string file_path = tokens[1];
var reader = Minizip.Reader.create ();
try {
if (reader.open_file (apk_path) != OK)
throw new FileError.FAILED ("Unable to open APK");
if (reader.locate_entry (file_path[1:], true) != OK)
throw new FileError.FAILED ("Unable to locate %s inside APK", file_path);
var size = reader.entry_save_buffer_length ();
var data = new uint8[size + 1];
if (reader.entry_save_buffer (data[:size]) != OK)
throw new FileError.FAILED ("Unable to extract %s from APK", file_path);
contents = new Bytes.take ((owned) data);
return true;
} finally {
reader.close ();
Minizip.Reader.destroy (ref reader);
}
}
#endif
private Json.Node make_empty_json_object () {
return new Json.Node.alloc ().init_object (new Json.Object ());
}
+5
View File
@@ -29,6 +29,11 @@ if host_os_family == 'darwin'
extra_link_args += '-Wl,-framework,Foundation'
endif
if host_os == 'android'
extra_vala_args += '--pkg=minizip'
platform_deps += minizip_dep
endif
if host_os_family == 'windows'
if host_toolchain != 'microsoft'
symfile = 'frida-gadget.symbols'
+14 -7
View File
@@ -1,6 +1,6 @@
public class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
#if IOS || TVOS
private Gee.Map<string, InetAddress> interfaces = new Gee.HashMap<string, InetAddress> ();
private Gee.Map<string, DynamicInterface> interfaces = new Gee.HashMap<string, DynamicInterface> ();
private Darwin.SystemConfiguration.DynamicStore? store;
private Darwin.GCD.DispatchQueue event_queue =
@@ -30,11 +30,16 @@ public class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
context.info = this;
store = new Darwin.SystemConfiguration.DynamicStore (null, CoreFoundation.String.make ("Frida"),
on_interfaces_changed_wrapper, context);
var pattern = CoreFoundation.String.make ("State:/Network/Interface/utun.*/IPv6");
var patterns = new CoreFoundation.Array (null, ((CoreFoundation.Type[]) &pattern)[:1]);
store.set_notification_keys (null, patterns);
store.set_dispatch_queue (event_queue);
handle_interface_changes (store.copy_key_list (pattern));
var initial_keys = store.copy_key_list (pattern);
if (initial_keys != null)
handle_interface_changes (initial_keys);
}
private static void on_interfaces_changed_wrapper (Darwin.SystemConfiguration.DynamicStore store,
@@ -57,9 +62,9 @@ public class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
foreach (var key in CFArray.wrap<CoreFoundation.String> (changed_keys)) {
string name = key.to_string ().split ("/")[3];
InetAddress? address = null;
var val = (CoreFoundation.Dictionary) store.copy_value (key);
if (val != null) {
InetAddress? address = null;
foreach (var raw_address in CFArray.wrap<CoreFoundation.String> (val[addresses_str])) {
var str = raw_address.to_string ();
bool is_reserved_ipv6_range = str.has_prefix ("fc") || str.has_prefix ("fd");
@@ -70,12 +75,14 @@ public class Frida.TunnelInterfaceObserver : Object, DynamicInterfaceObserver {
}
}
if (address != null && !interfaces.has_key (name)) {
interfaces[name] = address;
interface_attached (name, address);
var iface = new DynamicInterface (name, address);
interfaces[name] = iface;
interface_attached (iface);
}
} else {
if (interfaces.unset (name, out address))
interface_detached (name, address);
DynamicInterface iface;
if (interfaces.unset (name, out iface))
interface_detached (iface);
}
}
}
+19 -16
View File
@@ -53,15 +53,18 @@ namespace Frida {
private delegate ssize_t ReadFunc (int fd, void * buf, size_t count);
construct {
Gum.Module.enumerate_imports ("libart.so", imp => {
if (imp.name == "read") {
read_slot = (ReadFunc *) imp.slot;
return false;
}
return true;
});
if (read_slot != null)
old_read_impl = update_read_slot (on_read);
var art = Gum.Process.find_module_by_name ("libart.so");
if (art != null) {
art.enumerate_imports (imp => {
if (imp.name == "read") {
read_slot = (ReadFunc *) imp.slot;
return false;
}
return true;
});
if (read_slot != null)
old_read_impl = update_read_slot (on_read);
}
}
~ThreadCountCloaker () {
@@ -212,34 +215,34 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
var open_listener = new OpenDirListener (this);
listeners.add (open_listener);
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "opendir"), open_listener);
interceptor.attach ((void *) libc.find_export_by_name ("opendir"), open_listener);
var close_listener = new CloseDirListener (this);
listeners.add (close_listener);
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, "closedir"), close_listener);
interceptor.attach ((void *) libc.find_export_by_name ("closedir"), close_listener);
var readdir_impl = Gum.Module.find_export_by_name (libc, "readdir");
var readdir_impl = libc.find_export_by_name ("readdir");
var readdir_listener = new ReadDirListener (this, LEGACY);
listeners.add (readdir_listener);
interceptor.attach ((void *) readdir_impl, readdir_listener);
var readdir64_impl = Gum.Module.find_export_by_name (libc, "readdir64");
var readdir64_impl = libc.find_export_by_name ("readdir64");
if (readdir64_impl != 0 && readdir64_impl != readdir_impl) {
var listener = new ReadDirListener (this, MODERN);
listeners.add (listener);
interceptor.attach ((void *) readdir64_impl, listener);
}
var readdir_r_impl = Gum.Module.find_export_by_name (libc, "readdir_r");
var readdir_r_impl = libc.find_export_by_name ("readdir_r");
var readdir_r_listener = new ReadDirRListener (this, LEGACY);
listeners.add (readdir_r_listener);
interceptor.attach ((void *) readdir_r_impl, readdir_r_listener);
var readdir64_r_impl = Gum.Module.find_export_by_name (libc, "readdir64_r");
var readdir64_r_impl = libc.find_export_by_name ("readdir64_r");
if (readdir64_r_impl != 0 && readdir64_r_impl != readdir_r_impl) {
var listener = new ReadDirRListener (this, MODERN);
listeners.add (listener);
+4 -3
View File
@@ -32,16 +32,17 @@ namespace Frida {
unowned Gum.InvocationListener listener = this;
#if WINDOWS
interceptor.attach ((void *) Gum.Module.find_export_by_name ("kernel32.dll", "ExitProcess"), listener);
interceptor.attach ((void *) Gum.Process.find_module_by_name ("kernel32.dll").find_export_by_name ("ExitProcess"),
listener);
#else
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
const string[] apis = {
"exit",
"_exit",
"abort",
};
foreach (var symbol in apis) {
interceptor.attach ((void *) Gum.Module.find_export_by_name (libc, symbol), listener);
interceptor.attach ((void *) libc.find_export_by_name (symbol), listener);
}
#endif
}
+1 -1
View File
@@ -26,7 +26,7 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
var close = Gum.Module.find_export_by_name (Gum.Process.query_libc_name (), "close");
var close = Gum.Process.get_libc_module ().find_export_by_name ("close");
close_listener = new CloseListener (this);
interceptor.attach ((void *) close, close_listener);
}
+16 -10
View File
@@ -45,9 +45,9 @@ namespace Frida {
}
static construct {
unowned string libc = Gum.Process.query_libc_name ();
fork_impl = (void *) Gum.Module.find_export_by_name (libc, "fork");
vfork_impl = (void *) Gum.Module.find_export_by_name (libc, "vfork");
var libc = Gum.Process.get_libc_module ();
fork_impl = (void *) libc.find_export_by_name ("fork");
vfork_impl = (void *) libc.find_export_by_name ("vfork");
}
construct {
@@ -61,15 +61,21 @@ namespace Frida {
string cmdline;
FileUtils.get_contents ("/proc/self/cmdline", out cmdline);
if (cmdline == "zygote" || cmdline == "zygote64" || cmdline == "usap32" || cmdline == "usap64") {
var set_argv0 = (void *) Gum.Module.find_export_by_name ("libandroid_runtime.so", "_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
if (set_argv0 != null) {
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
var runtime = Gum.Process.find_module_by_name ("libandroid_runtime.so");
if (runtime != null) {
var set_argv0 = (void *) runtime.find_export_by_name ("_Z27android_os_Process_setArgV0P7_JNIEnvP8_jobjectP8_jstring");
if (set_argv0 != null) {
interceptor.attach (set_argv0, listener, (void *) HookId.SET_ARGV0);
child_recovery_behavior = DEFERRED_UNTIL_SET_ARGV0;
}
}
var setcontext = (void *) Gum.Module.find_export_by_name ("libselinux.so", "selinux_android_setcontext");
if (setcontext != null)
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
var selinux = Gum.Process.find_module_by_name ("libselinux.so");
if (selinux != null) {
var setcontext = (void *) selinux.find_export_by_name ("selinux_android_setcontext");
if (setcontext != null)
interceptor.attach (setcontext, listener, (void *) HookId.SET_CTX);
}
}
} catch (FileError e) {
}
+18
View File
@@ -25,6 +25,24 @@ frida_run_atexit_handlers (void)
{
}
# ifdef HAVE_ASAN
__attribute__ ((constructor)) static void
frida_init_memory (void)
{
asm volatile ("");
}
# ifndef HAVE_DARWIN
__attribute__ ((destructor)) static void
frida_deinit_memory (void)
{
asm volatile ("");
}
# endif
# endif
#else
#define FRIDA_SHIM_LOCK() gum_spinlock_acquire (&frida_shim_lock)
+3 -3
View File
@@ -420,7 +420,7 @@ namespace Frida {
var reason_value = new Json.Node.alloc ().init_string (reason.to_nick ());
try {
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null);
yield rpc_client.call ("dispose", new Json.Node[] { reason_value }, null, null);
} catch (GLib.Error e) {
}
@@ -467,10 +467,10 @@ namespace Frida {
this.debug_message (message);
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
if (script == null)
throw new Error.INVALID_OPERATION ("Script is destroyed");
script.post (json);
script.post (json, data);
}
}
}
+15 -12
View File
@@ -38,21 +38,24 @@ namespace Frida {
var interceptor = Gum.Interceptor.obtain ();
#if WINDOWS
var create_process_internal = Gum.Module.find_export_by_name ("kernelbase.dll", "CreateProcessInternalW");
if (create_process_internal == 0)
create_process_internal = Gum.Module.find_export_by_name ("kernel32.dll", "CreateProcessInternalW");
var kernelbase = Gum.Process.find_module_by_name ("kernelbase.dll");
var create_process_internal = (kernelbase != null) ? kernelbase.find_export_by_name ("CreateProcessInternalW") : 0;
if (create_process_internal == 0) {
create_process_internal = Gum.Process.find_module_by_name ("kernel32.dll")
.find_export_by_name ("CreateProcessInternalW");
}
assert (create_process_internal != 0);
interceptor.attach ((void *) create_process_internal, this);
#else
unowned string libc = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
#if DARWIN
posix_spawn = (PosixSpawnFunc) Gum.Module.find_export_by_name (libc, "posix_spawn");
posix_spawnattr_init = (PosixSpawnAttrInitFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_init");
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_destroy");
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_getflags");
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) Gum.Module.find_export_by_name (libc, "posix_spawnattr_setflags");
posix_spawn = (PosixSpawnFunc) libc.find_export_by_name ("posix_spawn");
posix_spawnattr_init = (PosixSpawnAttrInitFunc) libc.find_export_by_name ("posix_spawnattr_init");
posix_spawnattr_destroy = (PosixSpawnAttrDestroyFunc) libc.find_export_by_name ("posix_spawnattr_destroy");
posix_spawnattr_getflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_getflags");
posix_spawnattr_setflags = (PosixSpawnAttrSetFlagsFunc) libc.find_export_by_name ("posix_spawnattr_setflags");
execve = (void *) Gum.Module.find_export_by_name (libc, "execve");
execve = (void *) libc.find_export_by_name ("execve");
interceptor.attach ((void *) posix_spawn, this);
@@ -60,10 +63,10 @@ namespace Frida {
#else
Gum.Address execve = 0;
#if ANDROID
execve = Gum.Module.find_symbol_by_name (libc, "__execve");
execve = libc.find_symbol_by_name ("__execve");
#endif
if (execve == 0)
execve = Gum.Module.find_export_by_name (libc, "execve");
execve = libc.find_export_by_name ("execve");
interceptor.attach ((void *) execve, this);
#endif
#endif
+4 -3
View File
@@ -26,9 +26,10 @@ namespace Frida {
construct {
var interceptor = Gum.Interceptor.obtain ();
task_threads = (TaskThreadsFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "task_threads");
thread_suspend = (ThreadSuspendFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_suspend");
thread_resume = (ThreadResumeFunc) Gum.Module.find_export_by_name (LIBSYSTEM_KERNEL, "thread_resume");
var kernel = Gum.Process.find_module_by_name (LIBSYSTEM_KERNEL);
task_threads = (TaskThreadsFunc) kernel.find_export_by_name ("task_threads");
thread_suspend = (ThreadSuspendFunc) kernel.find_export_by_name ("thread_suspend");
thread_resume = (ThreadResumeFunc) kernel.find_export_by_name ("thread_resume");
interceptor.replace ((void *) task_threads, (void *) replacement_task_threads, this);
interceptor.replace ((void *) thread_suspend, (void *) replacement_thread_suspend, this);
+12 -4
View File
@@ -300,6 +300,7 @@ static gpointer
frida_find_vtable (void)
{
GumAddress result = 0;
GumModule * libunwind;
GumAddress export;
uint64_t address;
G_GNUC_UNUSED cs_err err;
@@ -309,11 +310,15 @@ frida_find_vtable (void)
size_t size;
const size_t max_size = 2048;
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "unw_init_local");
libunwind = gum_process_find_module_by_name (FRIDA_LIBUNWIND_PATH);
if (libunwind == NULL)
goto beach;
export = gum_module_find_export_by_name (libunwind, "unw_init_local");
if (export == 0)
export = gum_module_find_export_by_name (FRIDA_LIBUNWIND_PATH, "_Unwind_RaiseException");
export = gum_module_find_export_by_name (libunwind, "_Unwind_RaiseException");
if (export == 0)
return NULL;
goto beach;
export = gum_strip_code_address (export);
address = export;
@@ -340,7 +345,7 @@ frida_find_vtable (void)
GumMemoryRange bss_range;
bss_range.base_address = 0;
gum_module_enumerate_sections (FRIDA_LIBUNWIND_PATH, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
gum_module_enumerate_sections (libunwind, (GumFoundSectionFunc) frida_find_bss_range, &bss_range);
while (cs_disasm_iter (capstone, &code, &size, &address, insn))
{
@@ -404,6 +409,9 @@ frida_find_vtable (void)
cs_free (insn, 1);
cs_close (&capstone);
beach:
g_clear_object (&libunwind);
return GSIZE_TO_POINTER (result);
}
+1 -1
View File
@@ -21,7 +21,7 @@ namespace Frida {
var interceptor = Gum.Interceptor.obtain ();
dyld_find_unwind_sections = (DyldFindUnwindSectionsFunc)
Gum.Module.find_export_by_name (LIBDYLD, "_dyld_find_unwind_sections");
Gum.Process.find_module_by_name (LIBDYLD).find_export_by_name ("_dyld_find_unwind_sections");
interceptor.replace ((void *) dyld_find_unwind_sections, (void *) replacement_dyld_find_unwind_sections, this);
+9 -2
View File
@@ -97,7 +97,7 @@ if cc.sizeof('void *') == 8
else
host_cpu_mode = '32'
endif
host_docks_mobile_devices = host_os in ['windows', 'macos', 'linux', 'freebsd'] and host_cpu_mode == '64'
host_docks_mobile_devices = host_os in ['windows', 'macos', 'linux'] and host_cpu_mode == '64'
gumjs_archs = {
'x86': 'ia32',
'x86_64': 'x64',
@@ -347,6 +347,13 @@ else
gio_unix_dep = dependency('gio-unix-2.0')
endif
if host_os == 'android'
minizip_dep = dependency('minizip', required: false, default_options: [
'zlib=enabled',
'lzma=disabled',
])
endif
have_local_backend = get_option('local_backend').allowed()
have_fruity_backend = get_option('fruity_backend') \
.disable_auto_if(not host_docks_mobile_devices) \
@@ -474,7 +481,7 @@ if have_fruity_backend
'dns=disabled',
'arp=disabled',
'ethernet=enabled',
'tcp_mss=1360',
'tcp_mss=4036',
'tcp_snd_buf=65535',
'tcp_wnd=65535',
]
+14 -2
View File
@@ -68,13 +68,25 @@ option('compat',
option('helper_modern',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for use on modern systems'
description: 'Prebuilt frida-helper to embed for supporting modern targets'
)
option('helper_legacy',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for use on legacy systems'
description: 'Prebuilt frida-helper to embed for supporting legacy targets'
)
option('helper_emulated_modern',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for supporting modern emulated targets'
)
option('helper_emulated_legacy',
type: 'string',
value: 'auto',
description: 'Prebuilt frida-helper to embed for supporting legacy emulated targets'
)
option('agent_modern',
+1 -1
Submodule releng updated: 54cc29651c...79d6dfa3d6.
+116 -30
View File
@@ -1,36 +1,49 @@
from __future__ import annotations
import argparse
import os
from dataclasses import dataclass
from io import StringIO
from pathlib import Path
import re
import sys
from typing import List, Set
import xml.etree.ElementTree as ET
CORE_NAMESPACE = "http://www.gtk.org/introspection/core/1.0"
C_NAMESPACE = "http://www.gtk.org/introspection/c/1.0"
GLIB_NAMESPACE = "http://www.gtk.org/introspection/glib/1.0"
GIR_NAMESPACES = {
"": CORE_NAMESPACE,
"c": C_NAMESPACE,
"glib": GLIB_NAMESPACE,
}
CORE_TAG_FIELD = f"{{{CORE_NAMESPACE}}}field"
CORE_TAG_CONSTRUCTOR = f"{{{CORE_NAMESPACE}}}constructor"
CORE_TAG_METHOD = f"{{{CORE_NAMESPACE}}}method"
def main():
parser = argparse.ArgumentParser(description="Generate refined Frida API definitions")
parser.add_argument('--output', dest='output_type', choices=['bundle', 'header', 'gir', 'vapi', 'vapi-stamp'], default='bundle')
parser.add_argument('api_version', metavar='api-version', type=str)
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_gir', metavar='/path/to/Frida-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_vapi', metavar='/path/to/frida-core.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('core_header', metavar='/path/to/frida-core.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_header', metavar='/path/to/frida-base.h', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_gir', metavar='/path/to/FridaBase-x.y.gir', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('base_vapi', metavar='/path/to/frida-base.vapi', type=argparse.FileType('r', encoding='utf-8'))
parser.add_argument('output_dir', metavar='/output/dir')
args = parser.parse_args()
output_type = args.output_type
api_version = args.api_version
core_header = args.core_header.read()
core_gir = args.core_gir.read()
core_vapi = args.core_vapi.read()
core_header = args.core_header.read()
base_vapi = args.base_vapi.read()
base_header = args.base_header.read()
base_gir = args.base_gir.read()
base_vapi = args.base_vapi.read()
output_dir = Path(args.output_dir)
if output_type == 'gir':
(output_dir / f"Frida-{api_version}.gir").write_text(core_gir, encoding='utf-8')
return
if output_type == 'vapi-stamp':
(output_dir / f"frida-core-{api_version}.vapi.stamp").write_bytes(b"")
return
@@ -45,30 +58,36 @@ def main():
toplevel_sources = []
src_dir = Path(__file__).parent.parent.resolve()
for name in toplevel_names:
with open(src_dir / name, 'r', encoding='utf-8') as f:
toplevel_sources.append(f.read())
toplevel_sources.append((src_dir / name).read_text(encoding='utf-8'))
toplevel_code = "\n".join(toplevel_sources)
enable_header = False
enable_gir = False
enable_vapi = False
if output_type == 'bundle':
enable_header = True
enable_gir = True
enable_vapi = True
elif output_type == 'header':
enable_header = True
elif output_type == 'gir':
enable_gir = True
elif output_type == 'vapi':
enable_vapi = True
api = parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header)
api = parse_api(api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi)
if enable_header:
emit_header(api, output_dir)
if enable_gir:
emit_gir(api, core_gir, base_gir, output_dir)
if enable_vapi:
emit_vapi(api, output_dir)
def emit_header(api, output_dir):
with open(output_dir / 'frida-core.h', 'w', encoding='utf-8') as output_header_file:
with OutputFile(output_dir / 'frida-core.h') as output_header_file:
output_header_file.write("#ifndef __FRIDA_CORE_H__\n#define __FRIDA_CORE_H__\n\n")
output_header_file.write("#include <glib.h>\n#include <glib-object.h>\n#include <gio/gio.h>\n#include <json-glib/json-glib.h>\n")
@@ -79,7 +98,6 @@ def emit_header(api, output_dir):
output_header_file.write("\ntypedef struct _%s %s;" % (object_type.c_name, object_type.c_name))
if object_type.c_iface_definition is not None:
output_header_file.write("\ntypedef struct _%sIface %sIface;" % (object_type.c_name, object_type.c_name))
output_header_file.write("\ntypedef struct _FridaHostSession FridaHostSession;")
for enum in api.enum_types:
output_header_file.write("\n\n" + enum.c_definition)
@@ -150,8 +168,61 @@ def emit_header(api, output_dir):
output_header_file.write("\n\n#endif\n")
def emit_gir(api: ApiSpec, core_gir: str, base_gir: str, output_dir: Path) -> str:
ET.register_namespace("", CORE_NAMESPACE)
ET.register_namespace("c", C_NAMESPACE)
ET.register_namespace("glib", GLIB_NAMESPACE)
core_tree = ET.ElementTree(ET.fromstring(core_gir))
base_tree = ET.ElementTree(ET.fromstring(base_gir))
core_root = core_tree.getroot()
base_root = base_tree.getroot()
merged_root = ET.Element(core_root.tag, core_root.attrib)
for elem in core_root.findall("include", GIR_NAMESPACES):
name = elem.get("name")
if name in {"GLib", "GObject", "Gio"}:
merged_root.append(elem)
for tag in ["package", "c:include"]:
for elem in core_root.findall(tag, GIR_NAMESPACES):
merged_root.append(elem)
core_namespace = core_root.find("namespace", GIR_NAMESPACES)
merged_namespace = ET.SubElement(merged_root, core_namespace.tag, core_namespace.attrib)
object_type_names = {obj.name for obj in api.object_types}
enum_type_names = {enum.name for enum in api.enum_types}
error_type_names = {error.name for error in api.error_types}
def merge_and_transform_elements(tag_name: str, spec_set: Set[str]):
core_elements = filter_elements(core_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
base_elements = filter_elements(base_root.findall(f".//{tag_name}", GIR_NAMESPACES), spec_set)
for elem in core_elements + base_elements:
if tag_name == "class":
for child in list(elem):
if child.tag == CORE_TAG_FIELD or child.get("name").startswith("_"):
elem.remove(child)
merged_namespace.append(elem)
merge_and_transform_elements("class", object_type_names)
merge_and_transform_elements("interface", object_type_names)
merge_and_transform_elements("enumeration", enum_type_names | error_type_names)
ET.indent(merged_root, space=" ")
result = ET.tostring(merged_root,
encoding="unicode",
xml_declaration=True)
with OutputFile(output_dir / f"Frida-{api.version}.gir") as output_gir:
output_gir.write(result)
def filter_elements(elements: List[ET.Element], spec_set: Set[str]):
return [elem for elem in elements if elem.get("name") in spec_set]
def emit_vapi(api, output_dir):
with open(output_dir / "frida-core-{0}.vapi".format(api.version), "w", encoding='utf-8') as output_vapi_file:
with OutputFile(output_dir / f"frida-core-{api.version}.vapi") as output_vapi_file:
output_vapi_file.write("[CCode (cheader_filename = \"frida-core.h\", cprefix = \"Frida\", lower_case_cprefix = \"frida_\")]")
output_vapi_file.write("\nnamespace Frida {")
output_vapi_file.write("\n\tpublic static void init ();")
@@ -189,12 +260,12 @@ def emit_vapi(api, output_dir):
output_vapi_file.write("\n}\n")
with open(output_dir / "frida-core-{0}.deps".format(api.version), "w", encoding='utf-8') as output_deps_file:
with OutputFile(output_dir / f"frida-core-{api.version}.deps") as output_deps_file:
output_deps_file.write("glib-2.0\n")
output_deps_file.write("gobject-2.0\n")
output_deps_file.write("gio-2.0\n")
def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, base_header):
def parse_api(api_version, toplevel_code, core_header, core_vapi, base_header, base_vapi):
all_headers = core_header + "\n" + base_header
all_enum_names = [m.group(1) for m in re.finditer(r"^\t+public\s+enum\s+(\w+)\s+", toplevel_code + "\n" + base_vapi, re.MULTILINE)]
@@ -287,8 +358,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
method_cname_lc = object_type.c_name_lc + '_' + method_name
if method_cname_lc not in seen_cfunctions:
seen_cfunctions.add(method_cname_lc)
if method_name not in ('construct', 'construct_with_host_session', 'get_main_context', 'get_provider', 'get_session') \
and not (object_type.name in ("Session", "Script") and method_name == 'get_id'):
if method_name != 'construct':
if (object_type.c_name + '*') in m.group(0):
if method_name == 'new' or method_name.startswith('new_'):
object_type.c_constructors.append(method_cprototype)
@@ -362,8 +432,7 @@ def parse_api(api_version, toplevel_code, core_vapi, core_header, base_vapi, bas
current_object_type.vapi_signals.append(stripped_line)
elif "{ get" in stripped_line:
name = re.match(r".+?(\w+)\s+{", stripped_line).group(1)
if name not in ('main_context', 'provider', 'session'):
current_object_type.vapi_properties.append(stripped_line)
current_object_type.vapi_properties.append(stripped_line)
else:
m = re.match(r".+?(\w+)\s+\(", stripped_line)
if m is not None:
@@ -400,19 +469,19 @@ def function_is_public(name):
"negotiate_connection"
]
def parse_vala_object_types(source):
def parse_vala_object_types(source) -> List[ApiObjectType]:
return [ApiObjectType(m.group(2), m.group(1)) for m in re.finditer(r"^\t+public\s+(class|interface)\s+(\w+)\s+", source, re.MULTILINE)]
def parse_vapi_functions(vapi):
def parse_vapi_functions(vapi) -> List[ApiFunction]:
return [ApiFunction(m.group(1), m.group(0)) for m in re.finditer(r"^\tpublic static .+ (\w+) \(.+;", vapi, re.MULTILINE)]
@dataclass
class ApiSpec:
def __init__(self, version, object_types, functions, enum_types, error_types):
self.version = version
self.object_types = object_types
self.functions = functions
self.enum_types = enum_types
self.error_types = error_types
version: str
object_types: List[ApiObjectType]
functions: List[ApiFunction]
enum_types: List[ApiEnum]
error_types: List[ApiEnum]
class ApiEnum:
def __init__(self, name):
@@ -514,6 +583,23 @@ def fuzzysort(items, keys):
result.extend(remaining)
return result
class OutputFile:
def __init__(self, output_path):
self._output_path = output_path
self._io = StringIO()
def __enter__(self):
return self._io
def __exit__(self, *exc):
result = self._io.getvalue()
if self._output_path.exists():
existing_contents = self._output_path.read_text(encoding='utf-8')
if existing_contents == result:
return False
self._output_path.write_text(result, encoding='utf-8')
return False
if __name__ == '__main__':
main()
+13 -30
View File
@@ -2,54 +2,37 @@ generate_api = [python, files('generate.py')]
generate_api_args = [
api_version,
core_build_dir / 'frida-core.h',
core_build_dir / core_gir_name,
core_build_dir / 'frida-core.vapi',
core_build_dir / 'frida-core.h',
base_build_dir / f'frida-base-@[email protected]',
base_build_dir / 'frida-base.h',
base_build_dir / base_gir_name,
base_build_dir / f'frida-base-@[email protected]',
meson.current_build_dir(),
]
core_public_h = custom_target('frida-core-header',
input: [core, base],
output: ['frida-core.h'],
command: [
generate_api,
'--output=header',
generate_api_args,
],
install: true,
install_dir: header_install_dir,
)
core_public_gir = custom_target('frida-core-gir',
input: [core, base],
output: [core_gir_name],
command: [
generate_api,
'--output=gir',
generate_api_args,
],
install: true,
install_dir: girdir,
)
core_public_vapi = custom_target('frida-core-vapi',
core_api = custom_target('frida-core-api',
input: [core, base],
output: [
'frida-core.h',
core_gir_name,
f'frida-core-@[email protected]',
f'frida-core-@[email protected]',
],
command: [
generate_api,
'--output=vapi',
'--output=bundle',
generate_api_args,
],
install: true,
install_dir: vapidir,
install_dir: [header_install_dir, girdir, vapidir, vapidir],
)
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
core_public_h = core_api[0]
core_public_gir = core_api[1]
core_public_vapi = [core_api[2], core_api[3]]
core_public_vapi_stamp = custom_target('frida-core-vapi-stamp',
input: core_public_vapi,
output: f'frida-core-@[email protected]',
command: [
+3 -1
View File
@@ -420,7 +420,9 @@ namespace Frida {
public void post (string json, Bytes? data) {
var json_val = ctx.make_string (json);
invoke_void (dispatch_message_func, { json_val }, runtime_obj);
var data_val = (data != null) ? ctx.make_array_buffer (data.get_data ()) : QuickJS.Null;
invoke_void (dispatch_message_func, { json_val, data_val }, runtime_obj);
ctx.free_value (data_val);
ctx.free_value (json_val);
perform_pending_io ();
+2 -2
View File
@@ -275,7 +275,7 @@ namespace Frida {
new Json.Node.alloc ().init_string (entrypoint),
new Json.Node.alloc ().init_string (opts.source_maps.to_nick ()),
new Json.Node.alloc ().init_string (opts.compression.to_nick ()),
}, cancellable);
}, null, cancellable);
return bundle.get_string ();
}
@@ -288,7 +288,7 @@ namespace Frida {
new Json.Node.alloc ().init_string (entrypoint),
new Json.Node.alloc ().init_string (opts.source_maps.to_nick ()),
new Json.Node.alloc ().init_string (opts.compression.to_nick ()),
}, cancellable);
}, null, cancellable);
}
private static string compute_project_root (string entrypoint, CompilerOptions options) {
+9 -8
View File
@@ -17,7 +17,7 @@
"@rollup/plugin-node-resolve": "^14.1.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "^8.3.4",
"@types/frida-gum": "18.7.0",
"@types/frida-gum": "18.7.2",
"@types/glob": "^8.0.0",
"@types/node": "18.7.23",
"glob": "^8.0.3",
@@ -468,10 +468,11 @@
"dev": true
},
"node_modules/@types/frida-gum": {
"version": "18.7.0",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-18.7.0.tgz",
"integrity": "sha512-HhBomXE23fLDAWXEKi3BjJLrlH9wAv9IEQNfO/PaYHQNNbh0Bi06gx6JbXTspVpbqlbVqkWAuU7n6HaS9B6yXA==",
"dev": true
"version": "18.7.2",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-18.7.2.tgz",
"integrity": "sha512-nOxTk8n45nQlFQhSSXcnePrzjw6k6JMJMESZ8HlHhUiIQqvGI4RYa69FYdUbGoBRnITn8srEq5vn0dkVwO/ezQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/glob": {
"version": "8.0.0",
@@ -1465,9 +1466,9 @@
"dev": true
},
"@types/frida-gum": {
"version": "18.7.0",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-18.7.0.tgz",
"integrity": "sha512-HhBomXE23fLDAWXEKi3BjJLrlH9wAv9IEQNfO/PaYHQNNbh0Bi06gx6JbXTspVpbqlbVqkWAuU7n6HaS9B6yXA==",
"version": "18.7.2",
"resolved": "https://registry.npmjs.org/@types/frida-gum/-/frida-gum-18.7.2.tgz",
"integrity": "sha512-nOxTk8n45nQlFQhSSXcnePrzjw6k6JMJMESZ8HlHhUiIQqvGI4RYa69FYdUbGoBRnITn8srEq5vn0dkVwO/ezQ==",
"dev": true
},
"@types/glob": {
+1 -1
View File
@@ -17,7 +17,7 @@
"@rollup/plugin-node-resolve": "^14.1.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "^8.3.4",
"@types/frida-gum": "18.7.0",
"@types/frida-gum": "18.7.2",
"@types/glob": "^8.0.0",
"@types/node": "18.7.23",
"glob": "^8.0.3",
+290 -168
View File
@@ -1,11 +1,6 @@
namespace Frida {
#if HAVE_LOCAL_BACKEND
public class ControlService : Object {
public HostSession host_session {
get;
construct;
}
public EndpointParameters endpoint_params {
get;
construct;
@@ -16,24 +11,23 @@ namespace Frida {
construct;
}
private HostSession host_session;
private State state = STOPPED;
private WebService service;
private Gee.Map<DBusConnection, Peer> peers = new Gee.HashMap<DBusConnection, Peer> ();
private ConnectionHandler main_handler;
private Gee.Map<string, ConnectionHandler> dynamic_interface_handlers = new Gee.HashMap<string, ConnectionHandler> ();
private Gee.Set<ControlChannel> spawn_gaters = new Gee.HashSet<ControlChannel> ();
private Gee.Map<uint, PendingSpawn> pending_spawn = new Gee.HashMap<uint, PendingSpawn> ();
private Gee.Map<AgentSessionId?, AgentSessionEntry> sessions =
new Gee.HashMap<AgentSessionId?, AgentSessionEntry> (AgentSessionId.hash, AgentSessionId.equal);
private SocketService broker_service = new SocketService ();
#if !WINDOWS
private uint16 broker_port = 0;
#endif
private Gee.Map<string, Transport> transports = new Gee.HashMap<string, Transport> ();
private Cancellable io_cancellable = new Cancellable ();
private MainContext? main_context;
private enum State {
STOPPED,
STARTING,
@@ -44,43 +38,55 @@ namespace Frida {
public ControlService (EndpointParameters endpoint_params, ControlServiceOptions? options = null) {
ControlServiceOptions opts = (options != null) ? options : new ControlServiceOptions ();
HostSession host_session;
HostSession session;
#if WINDOWS
var tempdir = new TemporaryDirectory ();
host_session = new WindowsHostSession (new WindowsHelperProcess (tempdir), tempdir);
session = new WindowsHostSession (new WindowsHelperProcess (tempdir), tempdir);
#endif
#if DARWIN
host_session = new DarwinHostSession (new DarwinHelperBackend (), new TemporaryDirectory (),
session = new DarwinHostSession (new DarwinHelperBackend (), new TemporaryDirectory (),
opts.sysroot, opts.report_crashes);
#endif
#if LINUX
var tempdir = new TemporaryDirectory ();
host_session = new LinuxHostSession (new LinuxHelperProcess (tempdir), tempdir, opts.report_crashes);
session = new LinuxHostSession (new LinuxHelperProcess (tempdir), tempdir, opts.report_crashes);
#endif
#if FREEBSD
host_session = new FreebsdHostSession ();
session = new FreebsdHostSession ();
#endif
#if QNX
host_session = new QnxHostSession ();
session = new QnxHostSession ();
#endif
Object (
host_session: host_session,
endpoint_params: endpoint_params,
options: opts
);
assign_session (session);
}
public ControlService.with_host_session (HostSession host_session, EndpointParameters endpoint_params,
internal ControlService.with_host_session (HostSession host_session, EndpointParameters endpoint_params,
ControlServiceOptions? options = null) {
Object (
host_session: host_session,
endpoint_params: endpoint_params,
options: (options != null) ? options : new ControlServiceOptions ()
);
assign_session (host_session);
}
construct {
var iface_observer = new TunnelInterfaceObserver ();
iface_observer.interface_detached.connect (on_interface_detached);
service = new WebService (endpoint_params, WebServiceFlavor.CONTROL, PortConflictBehavior.FAIL, iface_observer);
main_handler = new ConnectionHandler (this, null);
}
private void assign_session (HostSession session) {
host_session = session;
host_session.spawn_added.connect (notify_spawn_added);
host_session.child_added.connect (notify_child_added);
host_session.child_removed.connect (notify_child_removed);
@@ -88,12 +94,6 @@ namespace Frida {
host_session.output.connect (notify_output);
host_session.agent_session_detached.connect (on_agent_session_detached);
host_session.uninjected.connect (notify_uninjected);
service = new WebService (endpoint_params, WebServiceFlavor.CONTROL, PortConflictBehavior.FAIL,
new TunnelInterfaceObserver ());
service.incoming.connect (on_server_connection);
broker_service.incoming.connect (on_broker_service_connection);
}
public async void start (Cancellable? cancellable = null) throws Error, IOError {
@@ -101,6 +101,10 @@ namespace Frida {
throw new Error.INVALID_OPERATION ("Invalid operation");
state = STARTING;
main_context = MainContext.ref_thread_default ();
service.incoming.connect (on_server_connection);
try {
yield service.start (cancellable);
@@ -132,21 +136,17 @@ namespace Frida {
throw new Error.INVALID_OPERATION ("Invalid operation");
state = STOPPING;
broker_service.stop ();
service.stop ();
service.incoming.disconnect (on_server_connection);
io_cancellable.cancel ();
transports.clear ();
service.stop ();
foreach (var peer in peers.values.to_array ()) {
try {
yield peer.close ();
} catch (IOError e) {
assert_not_reached ();
}
}
peers.clear ();
foreach (var handler in dynamic_interface_handlers.values.to_array ())
yield handler.close (cancellable);
dynamic_interface_handlers.clear ();
yield main_handler.close (cancellable);
var base_host_session = host_session as BaseDBusHostSession;
if (base_host_session != null)
@@ -176,7 +176,7 @@ namespace Frida {
}
}
private void on_server_connection (IOStream connection, SocketAddress remote_address) {
private void on_server_connection (IOStream connection, SocketAddress remote_address, DynamicInterface? dynamic_iface) {
#if IOS || TVOS
/*
* We defer the launchd injection until the first connection is established in order
@@ -187,50 +187,28 @@ namespace Frida {
darwin_host_session.activate_crash_reporter_integration ();
#endif
handle_server_connection.begin (connection);
ConnectionHandler handler;
unowned string iface_name = dynamic_iface?.name;
if (iface_name != null) {
handler = dynamic_interface_handlers[iface_name];
if (handler == null) {
handler = new ConnectionHandler (this, dynamic_iface);
dynamic_interface_handlers[iface_name] = handler;
}
} else {
handler = main_handler;
}
handler.handle_server_connection.begin (connection);
}
private async void handle_server_connection (IOStream raw_connection) throws GLib.Error {
var connection = yield new DBusConnection (raw_connection, null, DELAY_MESSAGE_PROCESSING, null, io_cancellable);
connection.on_closed.connect (on_connection_closed);
Peer peer;
AuthenticationService? auth_service = endpoint_params.auth_service;
if (auth_service != null)
peer = new AuthenticationChannel (this, connection, auth_service);
else
peer = setup_control_channel (connection);
peers[connection] = peer;
connection.start_message_processing ();
}
private void on_connection_closed (DBusConnection connection, bool remote_peer_vanished, GLib.Error? error) {
Peer peer;
if (peers.unset (connection, out peer))
peer.close.begin (io_cancellable);
}
private async void promote_authentication_channel (AuthenticationChannel channel) throws GLib.Error {
DBusConnection connection = channel.connection;
peers.unset (connection);
yield channel.close (io_cancellable);
peers[connection] = setup_control_channel (connection);
}
private void kick_authentication_channel (AuthenticationChannel channel) {
var source = new IdleSource ();
source.set_callback (() => {
channel.connection.close.begin (io_cancellable);
return false;
private void on_interface_detached (DynamicInterface iface) {
schedule_on_frida_thread (() => {
ConnectionHandler handler;
if (dynamic_interface_handlers.unset (iface.name, out handler))
handler.close.begin (io_cancellable);
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
}
private ControlChannel setup_control_channel (DBusConnection connection) {
return new ControlChannel (this, connection);
}
private async void teardown_control_channel (ControlChannel channel) {
@@ -259,8 +237,235 @@ namespace Frida {
}
}
private void schedule_on_frida_thread (owned SourceFunc function) {
assert (main_context != null);
var source = new IdleSource ();
source.set_callback ((owned) function);
source.attach (main_context);
}
private class ConnectionHandler : Object {
public weak ControlService parent {
get;
construct;
}
public DynamicInterface? dynamic_iface {
get;
construct;
}
public HostSession host_session {
get {
return parent.host_session;
}
}
private Gee.Map<DBusConnection, Peer> peers = new Gee.HashMap<DBusConnection, Peer> ();
private SocketService broker_service = new SocketService ();
#if !WINDOWS
private uint16 broker_port = 0;
#endif
private Gee.Map<string, Transport> transports = new Gee.HashMap<string, Transport> ();
private Cancellable io_cancellable = new Cancellable ();
public ConnectionHandler (ControlService parent, DynamicInterface? dynamic_iface) {
Object (parent: parent, dynamic_iface: dynamic_iface);
}
construct {
broker_service.incoming.connect (on_broker_service_connection);
}
public async void close (Cancellable? cancellable) throws IOError {
broker_service.incoming.disconnect (on_broker_service_connection);
io_cancellable.cancel ();
broker_service.stop ();
transports.clear ();
foreach (var peer in peers.values.to_array ())
yield peer.close (cancellable);
peers.clear ();
}
public Gee.Iterator<ControlChannel> all_control_channels () {
return (Gee.Iterator<ControlChannel>) peers.values.filter (peer => peer is ControlChannel);
}
public async void handle_server_connection (IOStream raw_connection) throws GLib.Error {
var connection = yield new DBusConnection (raw_connection, null, DELAY_MESSAGE_PROCESSING, null,
io_cancellable);
connection.on_closed.connect (on_connection_closed);
AuthenticationService? auth_service = parent.endpoint_params.auth_service;
peers[connection] = (auth_service != null)
? (Peer) new AuthenticationChannel (this, connection, auth_service)
: (Peer) new ControlChannel (this, connection);
connection.start_message_processing ();
}
private void on_connection_closed (DBusConnection connection, bool remote_peer_vanished, GLib.Error? error) {
Peer peer;
if (peers.unset (connection, out peer))
peer.close.begin (io_cancellable);
}
public async void promote_authentication_channel (AuthenticationChannel channel) throws GLib.Error {
DBusConnection connection = channel.connection;
peers.unset (connection);
yield channel.close (io_cancellable);
peers[connection] = new ControlChannel (this, connection);
}
public void kick_authentication_channel (AuthenticationChannel channel) {
var source = new IdleSource ();
source.set_callback (() => {
channel.connection.close.begin (io_cancellable);
return false;
});
source.attach (MainContext.get_thread_default ());
}
public async void teardown_control_channel (ControlChannel channel) {
yield parent.teardown_control_channel (channel);
}
public async void enable_spawn_gating (ControlChannel requester) throws GLib.Error {
yield parent.enable_spawn_gating (requester);
}
public async void disable_spawn_gating (ControlChannel requester) throws GLib.Error {
yield parent.disable_spawn_gating (requester);
}
public HostSpawnInfo[] enumerate_pending_spawn () {
return parent.enumerate_pending_spawn ();
}
public async void resume (uint pid, ControlChannel requester) throws GLib.Error {
yield parent.resume (pid, requester);
}
public async AgentSessionId attach (uint pid, HashTable<string, Variant> options, ControlChannel requester,
Cancellable? cancellable) throws Error, IOError {
return yield parent.attach (pid, options, requester, cancellable);
}
public async void reattach (AgentSessionId id, ControlChannel requester, Cancellable? cancellable)
throws Error, IOError {
yield parent.reattach (id, requester, cancellable);
}
public void open_tcp_transport (AgentSessionId id, Cancellable? cancellable, out uint16 port, out string token)
throws Error {
#if WINDOWS
throw new Error.NOT_SUPPORTED ("Not yet supported on Windows");
#else
var base_host_session = host_session as BaseDBusHostSession;
if (base_host_session == null)
throw new Error.NOT_SUPPORTED ("Not supported for remote host sessions");
if (!base_host_session.can_pass_file_descriptors_to_agent_session (id))
throw new Error.INVALID_ARGUMENT ("Not supported by this particular agent session");
if (broker_port == 0) {
try {
if (dynamic_iface != null) {
SocketAddress effective_address;
broker_service.add_address (
new InetSocketAddress (dynamic_iface.ip, 0),
STREAM,
TCP,
null,
out effective_address);
broker_port = ((InetSocketAddress) effective_address).get_port ();
} else {
broker_port = broker_service.add_any_inet_port (null);
}
} catch (GLib.Error e) {
throw new Error.NOT_SUPPORTED ("Unable to listen: %s", e.message);
}
broker_service.start ();
}
string transport_id = Uuid.string_random ();
var expiry_source = new TimeoutSource.seconds (20);
expiry_source.set_callback (() => {
transports.unset (transport_id);
return false;
});
expiry_source.attach (MainContext.get_thread_default ());
transports[transport_id] = new Transport (id, expiry_source);
port = broker_port;
token = transport_id;
#endif
}
private bool on_broker_service_connection (SocketConnection connection, Object? source_object) {
handle_broker_connection.begin (connection);
return true;
}
private async void handle_broker_connection (SocketConnection connection) throws GLib.Error {
var socket = connection.socket;
if (socket.get_family () != UNIX)
Tcp.enable_nodelay (socket);
const size_t uuid_length = 36;
var raw_token = new uint8[uuid_length + 1];
size_t bytes_read;
yield connection.input_stream.read_all_async (raw_token[0:uuid_length], Priority.DEFAULT, io_cancellable,
out bytes_read);
unowned string token = (string) raw_token;
Transport transport;
if (!transports.unset (token, out transport))
return;
transport.expiry_source.destroy ();
#if !WINDOWS
AgentSessionId session_id = transport.session_id;
var base_host_session = host_session as BaseDBusHostSession;
if (base_host_session == null)
throw new Error.NOT_SUPPORTED ("Not supported for remote host sessions");
AgentSessionProvider provider = base_host_session.obtain_session_provider (session_id);
yield provider.migrate (session_id, socket, io_cancellable);
#endif
}
private class Transport {
public AgentSessionId session_id;
public Source expiry_source;
public Transport (AgentSessionId session_id, Source expiry_source) {
this.session_id = session_id;
this.expiry_source = expiry_source;
}
}
}
private Gee.Iterator<ControlChannel> all_control_channels () {
return (Gee.Iterator<ControlChannel>) peers.values.filter (peer => peer is ControlChannel);
var channels = new Gee.ArrayList<ControlChannel> ();
channels.add_all_iterator (main_handler.all_control_channels ());
foreach (var handler in dynamic_interface_handlers.values)
channels.add_all_iterator (handler.all_control_channels ());
return channels.iterator ();
}
private async void enable_spawn_gating (ControlChannel requester) throws GLib.Error {
@@ -447,85 +652,12 @@ namespace Frida {
sessions.unset (entry.id);
}
private void open_tcp_transport (AgentSessionId id, Cancellable? cancellable, out uint16 port,
out string token) throws Error {
#if WINDOWS
throw new Error.NOT_SUPPORTED ("Not yet supported on Windows");
#else
var base_host_session = host_session as BaseDBusHostSession;
if (base_host_session == null)
throw new Error.NOT_SUPPORTED ("Not supported for remote host sessions");
if (!base_host_session.can_pass_file_descriptors_to_agent_session (id))
throw new Error.INVALID_ARGUMENT ("Not supported by this particular agent session");
if (broker_port == 0) {
try {
broker_port = broker_service.add_any_inet_port (null);
} catch (GLib.Error e) {
throw new Error.NOT_SUPPORTED ("Unable to listen: %s", e.message);
}
broker_service.start ();
}
string transport_id = Uuid.string_random ();
var expiry_source = new TimeoutSource.seconds (20);
expiry_source.set_callback (() => {
transports.unset (transport_id);
return false;
});
expiry_source.attach (MainContext.get_thread_default ());
transports[transport_id] = new Transport (id, expiry_source);
port = broker_port;
token = transport_id;
#endif
}
private bool on_broker_service_connection (SocketConnection connection, Object? source_object) {
handle_broker_connection.begin (connection);
return true;
}
private async void handle_broker_connection (SocketConnection connection) throws GLib.Error {
var socket = connection.socket;
if (socket.get_family () != UNIX)
Tcp.enable_nodelay (socket);
const size_t uuid_length = 36;
var raw_token = new uint8[uuid_length + 1];
size_t bytes_read;
yield connection.input_stream.read_all_async (raw_token[0:uuid_length], Priority.DEFAULT, io_cancellable,
out bytes_read);
unowned string token = (string) raw_token;
Transport transport;
if (!transports.unset (token, out transport))
return;
transport.expiry_source.destroy ();
#if !WINDOWS
AgentSessionId session_id = transport.session_id;
var base_host_session = host_session as BaseDBusHostSession;
if (base_host_session == null)
throw new Error.NOT_SUPPORTED ("Not supported for remote host sessions");
AgentSessionProvider provider = base_host_session.obtain_session_provider (session_id);
yield provider.migrate (session_id, socket, io_cancellable);
#endif
}
private interface Peer : Object {
public abstract async void close (Cancellable? cancellable = null) throws IOError;
}
private class AuthenticationChannel : Object, Peer, AuthenticationService {
public weak ControlService parent {
public weak ConnectionHandler parent {
get;
construct;
}
@@ -542,7 +674,7 @@ namespace Frida {
private Gee.Collection<uint> registrations = new Gee.ArrayList<uint> ();
public AuthenticationChannel (ControlService parent, DBusConnection connection, AuthenticationService service) {
public AuthenticationChannel (ConnectionHandler parent, DBusConnection connection, AuthenticationService service) {
Object (
parent: parent,
connection: connection,
@@ -582,7 +714,7 @@ namespace Frida {
}
private class ControlChannel : Object, Peer, HostSession, TransportBroker {
public weak ControlService parent {
public weak ConnectionHandler parent {
get;
construct;
}
@@ -600,7 +732,7 @@ namespace Frida {
private Gee.Set<uint> registrations = new Gee.HashSet<uint> ();
private TimeoutSource? ping_timer;
public ControlChannel (ControlService parent, DBusConnection connection) {
public ControlChannel (ConnectionHandler parent, DBusConnection connection) {
Object (parent: parent, connection: connection);
}
@@ -849,16 +981,6 @@ namespace Frida {
expiry_timer = null;
}
}
private class Transport {
public AgentSessionId session_id;
public Source expiry_source;
public Transport (AgentSessionId session_id, Source expiry_source) {
this.session_id = session_id;
this.expiry_source = expiry_source;
}
}
}
#else
public class ControlService : Object {
+7 -6
View File
@@ -933,27 +933,28 @@ namespace Frida {
}
public async void prepare_for_launch (string identifier, Cancellable? cancellable) throws Error, IOError {
yield call ("prepareForLaunch", new Json.Node[] { new Json.Node.alloc ().init_string (identifier) }, cancellable);
yield call ("prepareForLaunch", new Json.Node[] { new Json.Node.alloc ().init_string (identifier) }, null,
cancellable);
}
public async void cancel_launch (string identifier, Cancellable? cancellable) throws Error, IOError {
yield call ("cancelLaunch", new Json.Node[] { new Json.Node.alloc ().init_string (identifier) }, cancellable);
yield call ("cancelLaunch", new Json.Node[] { new Json.Node.alloc ().init_string (identifier) }, null, cancellable);
}
public async void enable_spawn_gating (Cancellable? cancellable) throws Error, IOError {
yield call ("enableSpawnGating", new Json.Node[] {}, cancellable);
yield call ("enableSpawnGating", new Json.Node[] {}, null, cancellable);
}
public async void disable_spawn_gating (Cancellable? cancellable) throws Error, IOError {
yield call ("disableSpawnGating", new Json.Node[] {}, cancellable);
yield call ("disableSpawnGating", new Json.Node[] {}, null, cancellable);
}
public async void claim_process (uint pid, Cancellable? cancellable) throws Error, IOError {
yield call ("claimProcess", new Json.Node[] { new Json.Node.alloc ().init_int (pid) }, cancellable);
yield call ("claimProcess", new Json.Node[] { new Json.Node.alloc ().init_int (pid) }, null, cancellable);
}
public async void unclaim_process (uint pid, Cancellable? cancellable) throws Error, IOError {
yield call ("unclaimProcess", new Json.Node[] { new Json.Node.alloc ().init_int (pid) }, cancellable);
yield call ("unclaimProcess", new Json.Node[] { new Json.Node.alloc ().init_int (pid) }, null, cancellable);
}
protected override void on_event (string type, Json.Array event) {
+37 -13
View File
@@ -183,6 +183,7 @@ struct _FridaSpawnInstance
GumAddress modern_entry_address;
/* V4+ */
GumAddress notify_objc_init;
GumAddress info_ptr_address;
/* V3- */
@@ -390,12 +391,12 @@ static void frida_spawn_instance_set_libc_initialized (FridaSpawnInstance * self
static kern_return_t frida_spawn_instance_create_dyld_data (FridaSpawnInstance * self);
static void frida_spawn_instance_destroy_dyld_data (FridaSpawnInstance * self);
#if defined (HAVE_IOS) || defined (HAVE_TVOS)
static gboolean frida_pick_ios_tvos_bootstrapper (const GumModuleDetails * details, gpointer user_data);
static gboolean frida_pick_ios_tvos_bootstrapper (GumModule * module, gpointer user_data);
#endif
static void frida_spawn_instance_unset_helpers (FridaSpawnInstance * self);
static void frida_spawn_instance_call_set_helpers (FridaSpawnInstance * self, GumDarwinUnifiedThreadState * state, mach_vm_address_t helpers);
static void frida_spawn_instance_call_dlopen (FridaSpawnInstance * self, GumDarwinUnifiedThreadState * state, mach_vm_address_t lib_name, int mode);
static gboolean frida_find_cf_initialize (const GumModuleDetails * details, gpointer user_data);
static gboolean frida_find_cf_initialize (GumModule * module, gpointer user_data);
static void frida_spawn_instance_call_cf_initialize (FridaSpawnInstance * self, GumDarwinUnifiedThreadState * state);
static void frida_spawn_instance_set_nth_breakpoint (FridaSpawnInstance * self, guint n, GumAddress break_at, FridaBreakpointRepeat repeat);
static void frida_spawn_instance_enable_nth_breakpoint (FridaSpawnInstance * self, guint n);
@@ -2030,6 +2031,10 @@ _frida_darwin_helper_backend_prepare_spawn_instance_for_injection (FridaDarwinHe
instance->dyld_flavor = (modern_entry_address != 0) ? FRIDA_DYLD_V4_PLUS : FRIDA_DYLD_V3_MINUS;
if (instance->dyld_flavor == FRIDA_DYLD_V4_PLUS)
{
instance->notify_objc_init = gum_darwin_module_resolve_symbol_address (dyld, "__ZN5dyld412RuntimeState14notifyObjCInitEPKNS_6LoaderE");
if (instance->notify_objc_init != 0)
modern_entry_address = instance->notify_objc_init;
instance->modern_entry_address = modern_entry_address;
legacy_entry_address = 0;
@@ -2108,7 +2113,12 @@ _frida_darwin_helper_backend_prepare_spawn_instance_for_injection (FridaDarwinHe
if (instance->dyld_flavor == FRIDA_DYLD_V4_PLUS)
{
GumAddress restart_with_dyld_in_cache = gum_darwin_module_resolve_symbol_address (dyld,
"__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPK15DyldSharedCachePv");
if (restart_with_dyld_in_cache == 0)
{
restart_with_dyld_in_cache = gum_darwin_module_resolve_symbol_address (dyld,
"__ZN5dyld422restartWithDyldInCacheEPKNS_10KernelArgsEPKN5dyld39MachOFileEPv");
}
if (restart_with_dyld_in_cache != 0)
frida_spawn_instance_set_nth_breakpoint (instance, i++, restart_with_dyld_in_cache, FRIDA_BREAKPOINT_REPEAT_NEVER);
}
@@ -3085,9 +3095,15 @@ frida_spawn_instance_handle_breakpoint (FridaSpawnInstance * self, FridaBreakpoi
if (self->dyld_flavor == FRIDA_DYLD_V4_PLUS)
{
if (pc == self->modern_entry_address)
self->breakpoint_phase = FRIDA_BREAKPOINT_SET_LIBDYLD_INITIALIZE_CALLER_BREAKPOINT;
{
self->breakpoint_phase = (pc == self->notify_objc_init)
? FRIDA_BREAKPOINT_LIBSYSTEM_INITIALIZED
: FRIDA_BREAKPOINT_SET_LIBDYLD_INITIALIZE_CALLER_BREAKPOINT;
}
else
{
return frida_spawn_instance_handle_dyld_restart (self);
}
}
else
{
@@ -3353,6 +3369,7 @@ frida_spawn_instance_handle_dyld_restart (FridaSpawnInstance * self)
GumAddress * info_ptr;
struct dyld_all_image_infos * info = NULL;
GumDarwinModule * dyld = NULL;
gssize delta;
info_ptr = (GumAddress *) gum_darwin_read (self->task, self->info_ptr_address, sizeof (GumAddress), NULL);
if (info_ptr == NULL)
@@ -3367,7 +3384,11 @@ frida_spawn_instance_handle_dyld_restart (FridaSpawnInstance * self)
if (dyld == NULL)
goto beach;
self->modern_entry_address = GUM_ADDRESS (info->dyldImageLoadAddress) + (self->modern_entry_address - self->dyld->base_address);
delta = (gssize) info->dyldImageLoadAddress - (gssize) self->dyld->base_address;
self->modern_entry_address += delta;
if (self->notify_objc_init != 0)
self->notify_objc_init += delta;
g_object_unref (self->dyld);
self->dyld = g_steal_pointer (&dyld);
@@ -3625,22 +3646,25 @@ frida_spawn_instance_destroy_dyld_data (FridaSpawnInstance * self)
#if defined (HAVE_IOS) || defined (HAVE_TVOS)
static gboolean
frida_pick_ios_tvos_bootstrapper (const GumModuleDetails * details, gpointer user_data)
frida_pick_ios_tvos_bootstrapper (GumModule * module, gpointer user_data)
{
FridaSpawnInstanceDyldData * data = user_data;
const gchar * path;
const gchar * candidates[] = {
"/usr/lib/substitute-inserter.dylib",
"/usr/lib/pspawn_payload-stg2.dylib"
};
guint i;
path = gum_module_get_path (module);
for (i = 0; i != G_N_ELEMENTS (candidates); i++)
{
const gchar * bootstrapper = candidates[i];
if (strcmp (details->path, bootstrapper) == 0)
if (strcmp (path, bootstrapper) == 0)
{
strcpy (data->bootstrapper, details->path);
strcpy (data->bootstrapper, path);
return FALSE;
}
}
@@ -3803,15 +3827,15 @@ frida_spawn_instance_call_dlopen (FridaSpawnInstance * self, GumDarwinUnifiedThr
}
static gboolean
frida_find_cf_initialize (const GumModuleDetails * details, gpointer user_data)
frida_find_cf_initialize (GumModule * module, gpointer user_data)
{
FridaSpawnInstance * self = user_data;
GumDarwinModule * core_foundation;
if (strcmp (details->path, CORE_FOUNDATION) != 0)
if (strcmp (gum_module_get_path (module), CORE_FOUNDATION) != 0)
return TRUE;
core_foundation = gum_darwin_module_new_from_memory (CORE_FOUNDATION, self->task, details->range->base_address,
core_foundation = gum_darwin_module_new_from_memory (CORE_FOUNDATION, self->task, gum_module_get_range (module)->base_address,
GUM_DARWIN_MODULE_FLAGS_NONE, NULL);
self->cf_initialize_address = gum_darwin_module_resolve_symbol_address (core_foundation, "___CFInitialize");
@@ -4270,7 +4294,7 @@ frida_agent_context_init_functions (FridaAgentContext * self, GumDarwinModuleRes
{
GumDarwinModule * module;
module = gum_darwin_module_resolver_find_module (resolver, "/usr/lib/system/libsystem_kernel.dylib");
module = gum_darwin_module_resolver_find_module_by_name (resolver, "/usr/lib/system/libsystem_kernel.dylib");
if (module == NULL)
goto no_libc;
FRIDA_AGENT_CONTEXT_RESOLVE (mach_task_self);
@@ -4280,7 +4304,7 @@ frida_agent_context_init_functions (FridaAgentContext * self, GumDarwinModuleRes
FRIDA_AGENT_CONTEXT_RESOLVE (mach_port_destroy);
FRIDA_AGENT_CONTEXT_RESOLVE (thread_terminate);
module = gum_darwin_module_resolver_find_module (resolver, "/usr/lib/system/libsystem_pthread.dylib");
module = gum_darwin_module_resolver_find_module_by_name (resolver, "/usr/lib/system/libsystem_pthread.dylib");
if (module == NULL)
goto no_libc;
FRIDA_AGENT_CONTEXT_TRY_RESOLVE (pthread_create_from_mach_thread);
@@ -4294,7 +4318,7 @@ frida_agent_context_init_functions (FridaAgentContext * self, GumDarwinModuleRes
if (mapper == NULL)
{
module = gum_darwin_module_resolver_find_module (resolver, "/usr/lib/system/libdyld.dylib");
module = gum_darwin_module_resolver_find_module_by_name (resolver, "/usr/lib/system/libdyld.dylib");
if (module == NULL)
goto no_libc;
FRIDA_AGENT_CONTEXT_RESOLVE (dlopen);
+4 -2
View File
@@ -151,10 +151,12 @@ frida_replacement_xpc_look_up_endpoint (const char * service_name, uint32_t type
static FridaXpcLookUpEndpointFunc
frida_find_xpc_look_up_endpoint_implementation (void)
{
GumModule * libxpc;
guint32 * cursor;
cursor = GSIZE_TO_POINTER (
gum_strip_code_address (gum_module_find_export_by_name ("/usr/lib/system/libxpc.dylib", "xpc_endpoint_create_bs_named")));
libxpc = gum_process_find_module_by_name ("/usr/lib/system/libxpc.dylib");
cursor = GSIZE_TO_POINTER (gum_strip_code_address (gum_module_find_export_by_name (libxpc, "xpc_endpoint_create_bs_named")));
g_object_unref (libxpc);
if (cursor == NULL)
return NULL;
+42 -18
View File
@@ -2,6 +2,7 @@ from pathlib import Path
import shutil
import subprocess
import sys
import struct
def main(argv):
@@ -27,29 +28,36 @@ def main(argv):
embedded_assets = []
if host_os == "windows":
for agent, flavor in [(agent_modern, "64"),
(agent_legacy, "32")]:
embedded_agent = priv_dir / f"frida-agent-{flavor}.dll"
embedded_dbghelp = priv_dir / f"dbghelp-{flavor}.dll"
embedded_symsrv = priv_dir / f"symsrv-{flavor}.dll"
pending_archs = {"arm64", "x86_64", "x86"}
for agent in {agent_modern, agent_legacy, agent_emulated_modern, agent_emulated_legacy}:
if agent is None:
continue
arch = detect_pefile_arch(agent)
embedded_agent = priv_dir / f"frida-agent-{arch}.dll"
embedded_dbghelp = priv_dir / f"dbghelp-{arch}.dll"
embedded_symsrv = priv_dir / f"symsrv-{arch}.dll"
if agent is not None:
shutil.copy(agent, embedded_agent)
shutil.copy(agent, embedded_agent)
if agent_dbghelp_prefix is not None:
shutil.copy(agent_dbghelp_prefix / flavor / "dbghelp.dll", embedded_dbghelp)
else:
embedded_dbghelp.write_bytes(b"")
if agent_symsrv_prefix is not None:
shutil.copy(agent_symsrv_prefix / flavor / "symsrv.dll", embedded_symsrv)
else:
embedded_symsrv.write_bytes(b"")
if agent_dbghelp_prefix is not None:
shutil.copy(agent_dbghelp_prefix / arch / "dbghelp.dll", embedded_dbghelp)
else:
for f in [embedded_agent, embedded_dbghelp, embedded_symsrv]:
f.write_bytes(b"")
embedded_dbghelp.write_bytes(b"")
if agent_symsrv_prefix is not None:
shutil.copy(agent_symsrv_prefix / arch / "symsrv.dll", embedded_symsrv)
else:
embedded_symsrv.write_bytes(b"")
embedded_assets += [embedded_agent, embedded_dbghelp, embedded_symsrv]
pending_archs.remove(arch)
for missing_arch in pending_archs:
embedded_agent = priv_dir / f"frida-agent-{missing_arch}.dll"
embedded_dbghelp = priv_dir / f"dbghelp-{missing_arch}.dll"
embedded_symsrv = priv_dir / f"symsrv-{missing_arch}.dll"
for asset in {embedded_agent, embedded_dbghelp, embedded_symsrv}:
asset.write_bytes(b"")
embedded_assets += [asset]
elif host_os in {"macos", "ios", "watchos", "tvos"}:
embedded_agent = priv_dir / "frida-agent.dylib"
if agent_modern is not None and agent_legacy is not None:
@@ -103,5 +111,21 @@ def pop_cmd_array_arg(args):
return result
def detect_pefile_arch(location):
with location.open(mode="rb") as pe:
pe.seek(0x3c)
e_lfanew, = struct.unpack("<I", pe.read(4))
pe.seek(e_lfanew + 4)
machine, = struct.unpack("<H", pe.read(2))
return PE_MACHINES[machine]
PE_MACHINES = {
0x014c: "x86",
0x8664: "x86_64",
0xaa64: "arm64",
}
if __name__ == "__main__":
main(sys.argv)
+37 -6
View File
@@ -2,6 +2,7 @@ from pathlib import Path
import shutil
import subprocess
import sys
import struct
def main(argv):
@@ -14,12 +15,28 @@ def main(argv):
output_dir = Path(args.pop(0))
priv_dir = Path(args.pop(0))
resource_config = args.pop(0)
helper_modern, helper_legacy = [Path(p) if p else None for p in args[:2]]
helper_modern, helper_legacy, \
helper_emulated_modern, helper_emulated_legacy \
= [Path(p) if p else None for p in args[:4]]
priv_dir.mkdir(exist_ok=True)
embedded_assets = []
if host_os in {"macos", "ios", "watchos", "tvos"}:
if host_os == "windows":
pending_archs = {"arm64", "x86_64", "x86"}
for helper in {helper_modern, helper_legacy, helper_emulated_modern, helper_emulated_legacy}:
if helper is None:
continue
arch = detect_pefile_arch(helper)
embedded_helper = priv_dir / f"frida-helper-{arch}.exe"
shutil.copy(helper, embedded_helper)
embedded_assets += [embedded_helper]
pending_archs.remove(arch)
for missing_arch in pending_archs:
embedded_helper = priv_dir / f"frida-helper-{missing_arch}.exe"
embedded_helper.write_bytes(b"")
embedded_assets += [embedded_helper]
elif host_os in {"macos", "ios", "watchos", "tvos"}:
embedded_helper = priv_dir / "frida-helper"
if helper_modern is not None and helper_legacy is not None:
@@ -34,10 +51,8 @@ def main(argv):
embedded_assets += [embedded_helper]
else:
exe_suffix = ".exe" if host_os == "windows" else ""
embedded_helper_modern = priv_dir / f"frida-helper-64{exe_suffix}"
embedded_helper_legacy = priv_dir / f"frida-helper-32{exe_suffix}"
embedded_helper_modern = priv_dir / f"frida-helper-64"
embedded_helper_legacy = priv_dir / f"frida-helper-32"
if helper_modern is not None:
shutil.copy(helper_modern, embedded_helper_modern)
@@ -74,5 +89,21 @@ def pop_cmd_array_arg(args):
return result
def detect_pefile_arch(location):
with location.open(mode="rb") as pe:
pe.seek(0x3c)
e_lfanew, = struct.unpack("<I", pe.read(4))
pe.seek(e_lfanew + 4)
machine, = struct.unpack("<H", pe.read(2))
return PE_MACHINES[machine]
PE_MACHINES = {
0x014c: "x86",
0x8664: "x86_64",
0xaa64: "arm64",
}
if __name__ == "__main__":
main(sys.argv)
+55 -89
View File
@@ -1,3 +1,4 @@
[CCode (gir_namespace = "Frida", gir_version = "1.0")]
namespace Frida {
public extern void init ();
public extern void init_with_runtime (Runtime runtime);
@@ -303,7 +304,7 @@ namespace Frida {
}
}
public void _release_device (Device device) {
internal void _release_device (Device device) {
var device_did_exist = devices.remove (device);
assert (device_did_exist);
}
@@ -524,18 +525,10 @@ namespace Frida {
}
}
public HostSessionProvider provider {
get;
construct;
}
public weak DeviceManager? manager {
get;
construct;
}
private string? _id;
private string? _name;
internal HostSessionProvider provider;
private unowned DeviceManager? manager;
private HostSessionOptions? host_session_options;
private Promise<HostSession>? host_session_request;
@@ -552,24 +545,26 @@ namespace Frida {
public delegate bool ProcessPredicate (Process process);
internal Device (DeviceManager? manager, HostSessionProvider provider, string? id = null, string? name = null,
internal Device (DeviceManager? mgr, HostSessionProvider prov, string? id = null, string? name = null,
HostSessionOptions? options = null) {
Object (
manager: manager,
provider: provider,
icon: provider.icon
);
Object (icon: prov.icon);
_id = id;
_name = name;
manager = mgr;
host_session_options = options;
assign_provider (prov);
}
construct {
_bus = new Bus (this);
}
private void assign_provider (HostSessionProvider prov) {
provider = prov;
provider.host_session_detached.connect (on_host_session_detached);
provider.agent_session_detached.connect (on_agent_session_detached);
_bus = new Bus (this);
}
public bool is_lost () {
@@ -1310,7 +1305,7 @@ namespace Frida {
throw new Error.INVALID_OPERATION ("Device is gone");
}
public async HostSession get_host_session (Cancellable? cancellable) throws Error, IOError {
internal async HostSession get_host_session (Cancellable? cancellable) throws Error, IOError {
while (host_session_request != null) {
try {
return yield host_session_request.future.wait_async (cancellable);
@@ -1338,16 +1333,6 @@ namespace Frida {
}
}
public HostSession get_host_session_sync (Cancellable? cancellable = null) throws Error, IOError {
return create<GetHostSessionTask> ().execute (cancellable);
}
private class GetHostSessionTask : DeviceTask<HostSession> {
protected override async HostSession perform_operation () throws Error, IOError {
return yield parent.get_host_session (cancellable);
}
}
private void on_host_session_detached (HostSession session) {
if (session != current_host_session)
return;
@@ -1462,7 +1447,7 @@ namespace Frida {
}
}
public async void _release_session (Session session, bool may_block, Cancellable? cancellable) throws IOError {
internal async void _release_session (Session session, bool may_block, Cancellable? cancellable) throws IOError {
AgentSessionId? session_id = null;
foreach (var entry in agent_sessions.entries) {
if (entry.value == session) {
@@ -2074,26 +2059,13 @@ namespace Frida {
construct;
}
public AgentSessionId id {
get;
construct;
}
public AgentSession session {
get {
return active_session;
}
}
public uint persist_timeout {
get;
construct;
}
public weak Device device {
get;
construct;
}
private AgentSessionId id;
private unowned Device device;
private State state = ATTACHED;
private Promise<bool> close_request;
@@ -2131,12 +2103,10 @@ namespace Frida {
}
internal Session (Device device, uint pid, AgentSessionId id, SessionOptions options) {
Object (
pid: pid,
id: id,
persist_timeout: options.persist_timeout,
device: device
);
Object (pid: pid, persist_timeout: options.persist_timeout);
this.id = id;
this.device = device;
}
public bool is_detached () {
@@ -2192,7 +2162,7 @@ namespace Frida {
uint last_tx_batch_id;
try {
yield session.resume (last_rx_batch_id, cancellable, out last_tx_batch_id);
yield active_session.resume (last_rx_batch_id, cancellable, out last_tx_batch_id);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2224,7 +2194,7 @@ namespace Frida {
check_open ();
try {
yield session.enable_child_gating (cancellable);
yield active_session.enable_child_gating (cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2244,7 +2214,7 @@ namespace Frida {
check_open ();
try {
yield session.disable_child_gating (cancellable);
yield active_session.disable_child_gating (cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2268,7 +2238,7 @@ namespace Frida {
AgentScriptId script_id;
try {
script_id = yield session.create_script (source, raw_options, cancellable);
script_id = yield active_session.create_script (source, raw_options, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2306,7 +2276,7 @@ namespace Frida {
AgentScriptId script_id;
try {
script_id = yield session.create_script_from_bytes (bytes.get_data (), raw_options,
script_id = yield active_session.create_script_from_bytes (bytes.get_data (), raw_options,
cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
@@ -2345,7 +2315,7 @@ namespace Frida {
uint8[] data;
try {
data = yield session.compile_script (source, raw_options, cancellable);
data = yield active_session.compile_script (source, raw_options, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2378,7 +2348,7 @@ namespace Frida {
uint8[] data;
try {
data = yield session.snapshot_script (embed_script, raw_options, cancellable);
data = yield active_session.snapshot_script (embed_script, raw_options, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2782,7 +2752,7 @@ namespace Frida {
PortalMembershipId membership_id;
try {
membership_id = yield session.join_portal (address, raw_options, cancellable);
membership_id = yield active_session.join_portal (address, raw_options, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -2944,7 +2914,7 @@ namespace Frida {
}
}
public void _release_script (AgentScriptId script_id) {
internal void _release_script (AgentScriptId script_id) {
var script_did_exist = scripts.unset (script_id);
assert (script_did_exist);
}
@@ -3010,7 +2980,7 @@ namespace Frida {
private async void close_session_and_peer_connection (Cancellable? cancellable) throws IOError {
try {
yield session.close (cancellable);
yield active_session.close (cancellable);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED) {
discard_peer_connection ();
@@ -3033,6 +3003,10 @@ namespace Frida {
}
#endif
public DBusConnection _get_connection () {
return ((DBusProxy) active_session).g_connection;
}
private T create<T> () {
return Object.new (typeof (T), parent: this);
}
@@ -3049,22 +3023,18 @@ namespace Frida {
public signal void destroyed ();
public signal void message (string json, Bytes? data);
public AgentScriptId id {
get;
construct;
}
public weak Session session {
get;
construct;
}
private AgentScriptId id;
private unowned Session session;
private Promise<bool> close_request;
private Gum.InspectorServer? inspector_server;
internal Script (Session session, AgentScriptId script_id) {
Object (id: script_id, session: session);
Object ();
this.id = script_id;
this.session = session;
}
public bool is_destroyed () {
@@ -3075,7 +3045,7 @@ namespace Frida {
check_open ();
try {
yield session.session.load_script (id, cancellable);
yield session.active_session.load_script (id, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -3111,7 +3081,7 @@ namespace Frida {
check_open ();
try {
yield session.session.eternalize_script (id, cancellable);
yield session.active_session.eternalize_script (id, cancellable);
yield _do_close (false, cancellable);
} catch (GLib.Error e) {
@@ -3162,7 +3132,7 @@ namespace Frida {
inspector_server.message.connect (on_debugger_message_from_frontend);
try {
yield session.session.enable_debugger (id, cancellable);
yield session.active_session.enable_debugger (id, cancellable);
} catch (GLib.Error e) {
inspector_server = null;
@@ -3176,7 +3146,7 @@ namespace Frida {
inspector_server = null;
try {
yield session.session.disable_debugger (id, cancellable);
yield session.active_session.disable_debugger (id, cancellable);
} catch (GLib.Error e) {
}
@@ -3210,7 +3180,7 @@ namespace Frida {
inspector_server = null;
try {
yield session.session.disable_debugger (id, cancellable);
yield session.active_session.disable_debugger (id, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -3264,7 +3234,7 @@ namespace Frida {
if (may_block) {
try {
yield parent.session.destroy_script (id, cancellable);
yield parent.active_session.destroy_script (id, cancellable);
} catch (GLib.Error e) {
}
}
@@ -3287,23 +3257,19 @@ namespace Frida {
}
public class PortalMembership : Object {
public uint id {
get;
construct;
}
public Session session {
get;
construct;
}
private uint id;
private Session session;
internal PortalMembership (Session session, PortalMembershipId membership_id) {
Object (id: membership_id.handle, session: session);
Object ();
this.id = membership_id.handle;
this.session = session;
}
public async void terminate (Cancellable? cancellable = null) throws Error, IOError {
try {
yield session.session.leave_portal (PortalMembershipId (id), cancellable);
yield session.active_session.leave_portal (PortalMembershipId (id), cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
+349 -168
View File
@@ -19,7 +19,7 @@ namespace Frida.Fruity {
return null;
var iface_stream = new DataInputStream (iface.read ());
string iface_name = iface_stream.read_line ();
if (iface_name != "NCM Control" && iface_name != "AppleUSBEthernet")
if (iface_name != "NCM Control")
return null;
var serial = File.new_build_filename (dev_path, "..", "..", "..", "serial");
@@ -27,7 +27,7 @@ namespace Frida.Fruity {
return null;
var serial_stream = new DataInputStream (serial.read ());
return serial_stream.read_line ();
return UsbDevice.udid_from_serial_number (serial_stream.read_line ());
} catch (GLib.Error e) {
throw new Error.NOT_SUPPORTED ("%s", e.message);
}
@@ -35,209 +35,390 @@ namespace Frida.Fruity {
}
public class LinuxPairingBrowser : Object, PairingBrowser {
private DBusConnection connection;
private AvahiServer server;
private AvahiServiceBrowser browser;
private Gee.List<PairingServiceDetails> current_batch = new Gee.ArrayList<PairingServiceDetails> ();
private Resolved.Manager? resolved;
private Source? timer;
private Cancellable io_cancellable = new Cancellable ();
construct {
start.begin ();
}
private const size_t IF_NAMESIZE = 16;
private async void start () {
public async void start (Cancellable? cancellable) throws IOError {
try {
connection = yield GLib.Bus.get (BusType.SYSTEM, io_cancellable);
var connection = yield GLib.Bus.get (BusType.SYSTEM, cancellable);
server = yield connection.get_proxy (AVAHI_SERVICE_NAME, "/", DO_NOT_LOAD_PROPERTIES, io_cancellable);
resolved = yield connection.get_proxy (Resolved.SERVICE_NAME, Resolved.SERVICE_PATH, DO_NOT_LOAD_PROPERTIES,
cancellable);
GLib.ObjectPath browser_path = yield server.service_browser_prepare (-1, INET6, PAIRING_REGTYPE,
PAIRING_DOMAIN, 0, io_cancellable);
browser = yield connection.get_proxy (AVAHI_SERVICE_NAME, browser_path, DO_NOT_LOAD_PROPERTIES,
io_cancellable);
browser.item_new.connect (on_item_new);
browser.all_for_now.connect (on_all_for_now);
yield browser.start (io_cancellable);
try {
yield resolve_services (MDNS_IPV6 | NO_NETWORK, cancellable);
schedule_next_poll ();
} catch (Error e) {
handle_poll_timer_tick.begin ();
}
} catch (GLib.Error e) {
printerr ("Oopsie: %s\n", e.message);
}
}
private void on_item_new (int interface_index, AvahiProtocol protocol, string name, string type, string domain, uint flags) {
char raw_interface_name[Linux.Network.INTERFACE_NAME_SIZE];
Linux.Network.if_indextoname (interface_index, (string) raw_interface_name);
unowned string interface_name = (string) raw_interface_name;
current_batch.add (new LinuxPairingServiceDetails (name, interface_index, interface_name, protocol, server));
public async void stop (Cancellable? cancellable) throws IOError {
if (timer != null) {
timer.destroy ();
timer = null;
}
io_cancellable.cancel ();
}
private void on_all_for_now () {
services_discovered (current_batch.to_array ());
current_batch.clear ();
private void schedule_next_poll () {
timer = new TimeoutSource.seconds (5);
timer.set_callback (() => {
timer = null;
handle_poll_timer_tick.begin ();
return Source.REMOVE;
});
timer.attach (MainContext.get_thread_default ());
}
private async void handle_poll_timer_tick () {
try {
yield resolve_services (MDNS_IPV6, io_cancellable);
schedule_next_poll ();
} catch (GLib.Error e) {
if (!(e is IOError.CANCELLED))
schedule_next_poll ();
}
}
private async void resolve_services (Resolved.Flags flags, Cancellable? cancellable) throws Error, IOError {
Resolved.RRItem[] items;
uint64 ptr_flags;
try {
yield resolved.resolve_record (Resolved.ANY_INTERFACE, PairingService.DNS_SD_NAME, DnsRecordClass.IN,
DnsRecordType.PTR, flags, cancellable, out items, out ptr_flags);
} catch (GLib.Error e) {
throw (Error) parse_error (e);
}
var promises = new Gee.ArrayQueue<Promise<PairingServiceDetails?>> ();
foreach (var item in items) {
var pr = new DnsPacketReader (new Bytes (item.data));
DnsPtrRecord ptr = pr.read_ptr ();
var promise = new Promise<PairingServiceDetails> ();
resolve_service.begin (ptr, item.ifindex, flags, cancellable, promise);
promises.offer (promise);
}
Promise<PairingServiceDetails?>? p;
while ((p = promises.poll ()) != null) {
try {
yield p.future.wait_async (cancellable);
} catch (Error e) {
}
}
}
private async void resolve_service (DnsPtrRecord ptr, int32 ifindex, Resolved.Flags flags, Cancellable? cancellable,
Promise<PairingServiceDetails?> promise) {
try {
PairingServiceDetails? service = yield do_resolve_service (ptr, ifindex, flags, cancellable);
promise.resolve (service);
} catch (GLib.Error e) {
promise.reject (e);
}
}
private async PairingServiceDetails? do_resolve_service (DnsPtrRecord ptr, int32 ifindex, Resolved.Flags flags,
Cancellable? cancellable) throws Error, IOError {
Resolved.SrvItem[] srv_items;
Variant txt_items;
string canonical_name;
string canonical_type;
string canonical_domain;
uint64 srv_flags;
try {
yield resolved.resolve_service (ifindex, "", "", ptr.name, Posix.AF_INET6, flags, cancellable,
out srv_items, out txt_items, out canonical_name, out canonical_type, out canonical_domain,
out srv_flags);
} catch (GLib.Error e) {
throw (Error) parse_error (e);
}
var txt_record = new Gee.ArrayList<string> ();
foreach (var raw_item in txt_items) {
string item = ((string *) raw_item.get_data ())->substring (0, (long) raw_item.get_size ());
if (!item.validate ())
throw new Error.PROTOCOL ("Invalid TXT item");
txt_record.add (item);
}
var meta = PairingServiceMetadata.from_txt_record (txt_record);
var ip = new InetAddress.from_bytes (srv_items[0].addresses[0].ip, IPV6);
var service = new PairingServiceDetails () {
identifier = meta.identifier,
auth_tag = meta.auth_tag,
endpoint = (InetSocketAddress) Object.new (typeof (InetSocketAddress),
address: ip,
port: srv_items[0].port,
scope_id: ip.get_is_link_local () ? ifindex : 0
),
interface_address = resolve_interface_address (ifindex),
};
service_discovered (service);
return service;
}
private static InetSocketAddress resolve_interface_address (int32 ifindex) throws Error {
char ifname_buf[IF_NAMESIZE];
unowned string? ifname = Linux.Network.if_indextoname (ifindex, (string) ifname_buf);
if (ifname == null)
throw new Error.INVALID_ARGUMENT ("Unable to resolve interface name");
Linux.Network.IfAddrs ifaddrs;
Linux.Network.getifaddrs (out ifaddrs);
for (unowned Linux.Network.IfAddrs candidate = ifaddrs; candidate != null; candidate = candidate.ifa_next) {
if (candidate.ifa_name != ifname)
continue;
if (candidate.ifa_addr.sa_family != Posix.AF_INET6)
continue;
return (InetSocketAddress)
SocketAddress.from_native ((void *) candidate.ifa_addr, sizeof (Posix.SockAddrIn6));
}
throw new Error.NOT_SUPPORTED ("Unable to resolve interface address");
}
private static GLib.Error parse_error (GLib.Error e) {
if (e is Error || e is IOError.CANCELLED)
return e;
return new Error.TRANSPORT ("%s", e.message);
}
}
private class LinuxPairingServiceDetails : Object, PairingServiceDetails {
public string name {
get { return _name; }
}
public uint interface_index {
get { return _interface_index; }
}
public string interface_name {
get { return _interface_name; }
}
private string _name;
private uint _interface_index;
private string _interface_name;
private AvahiProtocol protocol;
private AvahiServer server;
internal LinuxPairingServiceDetails (string name, uint interface_index, string interface_name, AvahiProtocol protocol,
AvahiServer server) {
_name = name;
_interface_index = interface_index;
_interface_name = interface_name;
this.protocol = protocol;
this.server = server;
}
public async Gee.List<PairingServiceHost> resolve (Cancellable? cancellable) throws Error, IOError {
AvahiServiceResolver resolver;
namespace Network {
public async void wait_until_interfaces_ready (Gee.Collection<string> interface_names, Cancellable? cancellable)
throws Error, IOError {
try {
GLib.ObjectPath path = yield server.service_resolver_prepare ((int) interface_index, protocol, name,
PAIRING_REGTYPE, PAIRING_DOMAIN, INET6, 0, cancellable);
DBusConnection connection = ((DBusProxy) server).get_connection ();
resolver = yield connection.get_proxy (AVAHI_SERVICE_NAME, path, DO_NOT_LOAD_PROPERTIES, cancellable);
} catch (GLib.Error e) {
throw new Error.NOT_SUPPORTED ("%s", e.message);
}
var connection = yield GLib.Bus.get (BusType.SYSTEM, cancellable);
var promise = new Promise<Gee.List<PairingServiceHost>> ();
var hosts = new Gee.ArrayList<PairingServiceHost> ();
resolver.found.connect ((interface_index, protocol, name, type, domain, host, address_protocol, address, port, txt,
flags) => {
var txt_record = new Gee.ArrayList<string> ();
var iter = new VariantIter (txt);
Variant? cur;
while ((cur = iter.next_value ()) != null) {
unowned string raw_val = (string) cur.get_data ();
string val = raw_val.make_valid ((ssize_t) cur.get_size ());
txt_record.add (val);
NetworkManager.Service? nm = null;
Networkd.Service? netd = null;
if (yield system_has_service (NetworkManager.SERVICE_NAME, connection, cancellable)) {
nm = yield connection.get_proxy (NetworkManager.SERVICE_NAME, NetworkManager.SERVICE_PATH,
DO_NOT_LOAD_PROPERTIES, cancellable);
} else if (yield system_has_service (Networkd.SERVICE_NAME, connection, cancellable)) {
netd = yield connection.get_proxy (Networkd.SERVICE_NAME, Networkd.SERVICE_PATH,
DO_NOT_LOAD_PROPERTIES, cancellable);
} else {
return;
}
hosts.add (new LinuxPairingServiceHost (
host,
new InetSocketAddress.from_string (address, port),
port,
txt_record));
var remaining = interface_names.size + 1;
if (!promise.future.ready)
promise.resolve (hosts);
});
resolver.failure.connect (error => {
if (!promise.future.ready)
promise.reject (new Error.NOT_SUPPORTED ("%s", error));
});
NotifyCompleteFunc on_complete = () => {
remaining--;
if (remaining == 0)
wait_until_interfaces_ready.callback ();
};
foreach (var name in interface_names) {
if (nm != null) {
NetworkManager.wait_until_interface_ready.begin (name, nm, connection, cancellable,
on_complete);
} else {
Networkd.wait_until_interface_ready.begin (name, netd, connection, cancellable,
on_complete);
}
}
var source = new IdleSource ();
source.set_callback (() => {
on_complete ();
return Source.REMOVE;
});
source.attach (MainContext.get_thread_default ());
yield;
} catch (GLib.Error e) {
}
}
private async bool system_has_service (string name, DBusConnection connection, Cancellable? cancellable) throws GLib.Error {
var v = yield connection.call (
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
"NameHasOwner",
new Variant.tuple ({ name }),
new VariantType.tuple ({ VariantType.BOOLEAN }),
DBusCallFlags.NONE, -1, cancellable);
bool has_owner;
v.get ("(b)", out has_owner);
return has_owner;
}
}
private delegate void NotifyCompleteFunc ();
namespace NetworkManager {
private async void wait_until_interface_ready (string name, Service service, DBusConnection connection,
Cancellable? cancellable, NotifyCompleteFunc on_complete) {
try {
yield resolver.start (cancellable);
string device_path = yield service.get_device_by_ip_iface (name);
Device device = yield connection.get_proxy (SERVICE_NAME, device_path, DBusProxyFlags.NONE, cancellable);
var device_proxy = (DBusProxy) device;
ulong handler = device_proxy.g_properties_changed.connect ((changed, invalidated) => {
if (changed.lookup_value ("StateReason", null) != null)
wait_until_interface_ready.callback ();
});
while (!cancellable.is_cancelled ()) {
uint32 state, reason;
device_proxy.get_cached_property ("StateReason").get ("(uu)", out state, out reason);
if (state == DEVICE_STATE_ACTIVATED)
break;
if (state == DEVICE_STATE_DISCONNECTED && reason != DEVICE_STATE_REASON_NONE)
break;
yield;
}
device_proxy.disconnect (handler);
} catch (GLib.Error e) {
throw new Error.NOT_SUPPORTED ("%s", e.message);
}
return yield promise.future.wait_async (cancellable);
on_complete ();
}
private const string SERVICE_NAME = "org.freedesktop.NetworkManager";
private const string SERVICE_PATH = "/org/freedesktop/NetworkManager";
[DBus (name = "org.freedesktop.NetworkManager")]
private interface Service : Object {
public abstract async string get_device_by_ip_iface (string iface) throws GLib.Error;
}
[DBus (name = "org.freedesktop.NetworkManager.Device")]
private interface Device : Object {
}
private const uint32 DEVICE_STATE_DISCONNECTED = 30;
private const uint32 DEVICE_STATE_ACTIVATED = 100;
private const uint32 DEVICE_STATE_REASON_NONE = 0;
}
namespace Networkd {
private async void wait_until_interface_ready (string name, Service service, DBusConnection connection,
Cancellable? cancellable, NotifyCompleteFunc on_complete) {
try {
int32 ifindex;
string link_path;
yield service.get_link_by_name (name, out ifindex, out link_path);
Link link = yield connection.get_proxy (SERVICE_NAME, link_path, DBusProxyFlags.NONE, cancellable);
var link_proxy = (DBusProxy) link;
ulong handler = link_proxy.g_properties_changed.connect ((changed, invalidated) => {
wait_until_interface_ready.callback ();
});
while (!cancellable.is_cancelled ()) {
string operational_state;
link_proxy.get_cached_property ("OperationalState").get ("s", out operational_state);
if (operational_state != "carrier")
break;
yield;
}
link_proxy.disconnect (handler);
} catch (GLib.Error e) {
}
on_complete ();
}
private const string SERVICE_NAME = "org.freedesktop.network1";
private const string SERVICE_PATH = "/org/freedesktop/network1";
[DBus (name = "org.freedesktop.network1.Manager")]
private interface Service : Object {
public abstract async void get_link_by_name (string name, out int32 ifindex, out string path) throws GLib.Error;
}
[DBus (name = "org.freedesktop.network1.Link")]
private interface Link : Object {
}
}
public class LinuxPairingServiceHost : Object, PairingServiceHost {
public string name {
get { return _name; }
namespace Resolved {
public const string SERVICE_NAME = "org.freedesktop.resolve1";
public const string SERVICE_PATH = "/org/freedesktop/resolve1";
public const int32 ANY_INTERFACE = 0;
[DBus (name = "org.freedesktop.resolve1.Manager")]
public interface Manager : Object {
public abstract async void resolve_record (int32 ifindex, string name, uint16 klass, uint16 type, uint64 flags,
Cancellable? cancellable, out RRItem[] items, out uint64 result_flags) throws GLib.Error;
public abstract async void resolve_service (int32 ifindex, string name, string type, string domain, int32 family,
uint64 flags, Cancellable? cancellable, out SrvItem[] srv_items,
[DBus (signature = "aay")] out Variant txt_items, out string canonical_name, out string canonical_type,
out string canonical_domain, out uint64 result_flags) throws GLib.Error;
}
public InetSocketAddress address {
get { return _address; }
[Flags]
public enum Flags {
DNS = 1 << 0,
LLMNR_IPV4 = 1 << 1,
LLMNR_IPV6 = 1 << 2,
MDNS_IPV4 = 1 << 3,
MDNS_IPV6 = 1 << 4,
NO_CNAME = 1 << 5,
NO_TXT = 1 << 6,
NO_ADDRESS = 1 << 7,
NO_SEARCH = 1 << 8,
AUTHENTICATED = 1 << 9,
NO_VALIDATE = 1 << 10,
NO_SYNTHESIZE = 1 << 11,
NO_CACHE = 1 << 12,
NO_ZONE = 1 << 13,
NO_TRUST_ANCHOR = 1 << 14,
NO_NETWORK = 1 << 15,
REQUIRE_PRIMARY = 1 << 16,
CLAMP_TTL = 1 << 17,
CONFIDENTIAL = 1 << 18,
SYNTHETIC = 1 << 19,
FROM_CACHE = 1 << 20,
FROM_ZONE = 1 << 21,
FROM_TRUST_ANCHOR = 1 << 22,
FROM_NETWORK = 1 << 23,
NO_STALE = 1 << 24,
RELAX_SINGLE_LABEL = 1 << 25,
}
public uint16 port {
get { return _port; }
public struct RRItem {
public int32 ifindex;
public uint16 klass;
public uint16 type;
public uint8[] data;
}
public Gee.List<string> txt_record {
get { return _txt_record; }
public struct SrvItem {
public uint16 priority;
public uint16 weight;
public uint16 port;
public string name;
public SrvAddress[] addresses;
public string canonical_name;
}
private string _name;
private InetSocketAddress _address;
private uint16 _port;
private Gee.List<string> _txt_record;
internal LinuxPairingServiceHost (string name, InetSocketAddress address, uint16 port, Gee.List<string> txt_record) {
_name = name;
_address = address;
_port = port;
_txt_record = txt_record;
public struct SrvAddress {
public int32 ifindex;
public int32 family;
public uint8[] ip;
}
public async Gee.List<InetSocketAddress> resolve (Cancellable? cancellable) throws Error, IOError {
var result = new Gee.ArrayList<InetSocketAddress> ();
result.add (address);
return result;
}
}
private const string AVAHI_SERVICE_NAME = "org.freedesktop.Avahi";
[DBus (name = "org.freedesktop.Avahi.Server2")]
private interface AvahiServer : Object {
public abstract async GLib.ObjectPath service_browser_prepare (int interface_index, AvahiProtocol protocol, string type,
string domain, uint flags, Cancellable? cancellable) throws GLib.Error;
public abstract async GLib.ObjectPath service_resolver_prepare (int interface_index, AvahiProtocol protocol, string name,
string type, string domain, AvahiProtocol aprotocol, AvahiLookupFlags flags, Cancellable? cancellable)
throws GLib.Error;
}
[DBus (name = "org.freedesktop.Avahi.ServiceBrowser")]
private interface AvahiServiceBrowser : Object {
public signal void item_new (int interface_index, AvahiProtocol protocol, string name, string type, string domain,
uint flags);
public signal void item_remove (int interface_index, AvahiProtocol protocol, string name, string type, string domain,
uint flags);
public signal void failure (string error);
public signal void all_for_now ();
public signal void cache_exhausted ();
public abstract async void start (Cancellable? cancellable) throws GLib.Error;
public abstract async void free (Cancellable? cancellable) throws GLib.Error;
}
[DBus (name = "org.freedesktop.Avahi.ServiceResolver")]
private interface AvahiServiceResolver : Object {
public signal void found (int interface_index, AvahiProtocol protocol, string name, string type, string domain, string host,
AvahiProtocol address_protocol, string address, uint16 port, [DBus (signature = "aay")] Variant txt, uint flags);
public signal void failure (string error);
public abstract async void start (Cancellable? cancellable) throws GLib.Error;
public abstract async void free (Cancellable? cancellable) throws GLib.Error;
}
private enum AvahiProtocol {
INET,
INET6,
UNSPEC = -1,
}
[Flags]
private enum AvahiLookupFlags {
USE_WIDE_AREA = 1,
USE_MULTICAST = 2,
NO_TXT = 4,
NO_ADDRESS = 8,
}
}
+10 -1
View File
@@ -211,7 +211,7 @@ namespace Frida.Fruity {
}
}
public async Tunnel? find_tunnel (Cancellable? cancellable) throws Error, IOError {
public async Tunnel? find_tunnel (UsbmuxDevice? device, Cancellable? cancellable) throws Error, IOError {
while (tunnel_request != null) {
try {
return yield tunnel_request.future.wait_async (cancellable);
@@ -246,6 +246,12 @@ namespace Frida.Fruity {
}
}
public int64 opened_at {
get {
return _opened_at;
}
}
public Darwin.Xpc.Uuid? assertion_identifier {
get {
return _assertion_identifier;
@@ -256,6 +262,7 @@ namespace Frida.Fruity {
private Darwin.Xpc.Uuid? _assertion_identifier;
private InetAddress? tunnel_device_address;
private DiscoveryService? _discovery;
private int64 _opened_at = -1;
public MacOSTunnel (XpcClient pairing_device) {
this.pairing_device = pairing_device;
@@ -275,6 +282,8 @@ namespace Frida.Fruity {
r.body.set_int64 ("flags", 0);
var response = yield pairing_device.request (r.message, cancellable);
_opened_at = get_monotonic_time ();
var reader = new XpcObjectReader (response);
reader.read_member ("response");
+150 -1
View File
@@ -2,8 +2,12 @@
#include "../windows/icon-helpers.h"
#include <setupapi.h>
#include <devguid.h>
#include <iphlpapi.h>
#include <setupapi.h>
#include <windns.h>
typedef struct _FridaPairingBrowserBackend FridaPairingBrowserBackend;
typedef struct _FridaMobileDeviceInfo FridaMobileDeviceInfo;
typedef struct _FridaImageDeviceInfo FridaImageDeviceInfo;
@@ -13,8 +17,18 @@ typedef struct _FridaFindImageDeviceContext FridaFindImageDeviceContext;
typedef struct _FridaDeviceInfo FridaDeviceInfo;
typedef struct _FridaDnsApi FridaDnsApi;
typedef gboolean (* FridaEnumerateDeviceFunc) (const FridaDeviceInfo * device_info, gpointer user_data);
struct _FridaPairingBrowserBackend
{
FridaFruityWindowsPairingBrowserResultCallback callback;
gpointer callback_target;
DNS_SERVICE_CANCEL browse_handle;
};
struct _FridaMobileDeviceInfo
{
WCHAR * location;
@@ -49,6 +63,14 @@ struct _FridaDeviceInfo
PSP_DEVINFO_DATA device_info_data;
};
struct _FridaDnsApi
{
DNS_STATUS (WINAPI * browse) (DNS_SERVICE_BROWSE_REQUEST * request, DNS_SERVICE_CANCEL * cancel);
DNS_STATUS (WINAPI * browse_cancel) (DNS_SERVICE_CANCEL * cancel_handle);
};
static void WINAPI frida_fruity_windows_pairing_browser_on_browse_results (void * query_context, DNS_QUERY_RESULT * query_results);
static FridaMobileDeviceInfo * find_mobile_device_by_udid (const WCHAR * udid);
static FridaImageDeviceInfo * find_image_device_by_location (const WCHAR * location);
@@ -68,8 +90,108 @@ static WCHAR * frida_read_registry_string (HKEY key, WCHAR * value_name);
static WCHAR * frida_read_registry_multi_string (HKEY key, WCHAR * value_name);
static gpointer frida_read_registry_value (HKEY key, WCHAR * value_name, DWORD expected_type);
static FridaDnsApi * frida_try_get_dns_api (void);
static GUID GUID_APPLE_USB = { 0xF0B32BE3, 0x6678, 0x4879, { 0x92, 0x30, 0x0E4, 0x38, 0x45, 0xD8, 0x05, 0xEE } };
void
_frida_fruity_windows_pairing_browser_enumerate_network_interfaces (FridaFruityWindowsPairingBrowserNetifFoundFunc func,
gpointer func_target)
{
IP_ADAPTER_ADDRESSES * adapters;
ULONG buffer_size, result;
IP_ADAPTER_ADDRESSES_LH * adapter;
if (frida_try_get_dns_api () == NULL)
return;
buffer_size = 32768;
adapters = g_malloc (buffer_size);
do
{
result = GetAdaptersAddresses (AF_INET6, 0, NULL, adapters, &buffer_size);
if (result != ERROR_BUFFER_OVERFLOW)
break;
adapters = g_realloc (adapters, buffer_size);
}
while (result == ERROR_BUFFER_OVERFLOW);
if (result != ERROR_SUCCESS)
goto beach;
for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
{
SOCKET_ADDRESS * raw_addr;
GInetSocketAddress * addr;
if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
continue;
if (adapter->FirstUnicastAddress == NULL)
continue;
raw_addr = &adapter->FirstUnicastAddress->Address;
addr = G_INET_SOCKET_ADDRESS (g_socket_address_new_from_native (raw_addr->lpSockaddr, raw_addr->iSockaddrLength));
func (adapter->IfIndex, adapter->AdapterName, addr, func_target);
}
beach:
g_free (adapters);
}
void *
_frida_fruity_windows_pairing_browser_monitor_create_backend (gulong interface_index,
FridaFruityWindowsPairingBrowserResultCallback callback, gpointer callback_target)
{
FridaPairingBrowserBackend * backend;
FridaDnsApi * api;
DNS_SERVICE_BROWSE_REQUEST r = { 0, };
api = frida_try_get_dns_api ();
if (api == NULL)
return NULL;
backend = g_slice_new0 (FridaPairingBrowserBackend);
backend->callback = callback;
backend->callback_target = callback_target;
r.Version = DNS_QUERY_REQUEST_VERSION2;
r.InterfaceIndex = interface_index;
r.QueryName = G_PASTE (L, FRIDA_FRUITY_PAIRING_SERVICE_DNS_SD_NAME);
r.pBrowseCallbackV2 = frida_fruity_windows_pairing_browser_on_browse_results;
r.pQueryContext = backend;
if (api->browse (&r, &backend->browse_handle) != DNS_REQUEST_PENDING)
{
g_slice_free (FridaPairingBrowserBackend, backend);
return NULL;
}
return backend;
}
void
_frida_fruity_windows_pairing_browser_monitor_destroy_backend (void * opaque_backend)
{
FridaPairingBrowserBackend * backend = opaque_backend;
if (backend == NULL)
return;
frida_try_get_dns_api ()->browse_cancel (&backend->browse_handle);
g_slice_free (FridaPairingBrowserBackend, backend);
}
static void WINAPI
frida_fruity_windows_pairing_browser_on_browse_results (void * query_context, DNS_QUERY_RESULT * query_results)
{
FridaPairingBrowserBackend * backend = query_context;
backend->callback (query_results, backend->callback_target);
}
void
_frida_fruity_usbmux_backend_extract_details_for_device (gint product_id, const char * udid, char ** name, GVariant ** icon,
GError ** error)
@@ -426,3 +548,30 @@ beach:
return buffer;
}
static FridaDnsApi *
frida_try_get_dns_api (void)
{
static gsize api_value = 0;
if (g_once_init_enter (&api_value))
{
HMODULE mod;
FARPROC browse;
FridaDnsApi * api = NULL;
mod = GetModuleHandleW (L"dnsapi.dll");
browse = GetProcAddress (mod, "DnsServiceBrowse");
if (browse != NULL)
{
api = g_slice_new (FridaDnsApi);
api->browse = (gpointer) browse;
api->browse_cancel = (gpointer) GetProcAddress (mod, "DnsServiceBrowseCancel");
}
g_once_init_leave (&api_value, GPOINTER_TO_SIZE (api) + 1);
}
return GSIZE_TO_POINTER (api_value - 1);
}
+102
View File
@@ -0,0 +1,102 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public class WindowsPairingBrowser : Object, PairingBrowser {
private Gee.Map<string, Monitor> monitors = new Gee.HashMap<string, Monitor> ();
private MainContext main_context = MainContext.ref_thread_default ();
public async void start (Cancellable? cancellable) throws IOError {
_enumerate_network_interfaces ((index, name, address) => {
var monitor = new Monitor (this, index, address);
monitors[name] = monitor;
});
}
public async void stop (Cancellable? cancellable) throws IOError {
monitors.clear ();
}
private void on_result (WinDns.QueryResult * result, InetSocketAddress interface_address) {
try {
PairingServiceDetails service = parse_result (result, interface_address);
var source = new IdleSource ();
source.set_callback (() => {
service_discovered (service);
return Source.REMOVE;
});
source.attach (main_context);
} catch (GLib.Error e) {
}
}
private static PairingServiceDetails parse_result (WinDns.QueryResult * res,
InetSocketAddress interface_address) throws GLib.Error {
PairingServiceMetadata? meta = null;
InetAddress? ip = null;
uint16 port = 0;
for (WinDns.Record * r = res->query_records; r != null; r = r->next) {
switch (r->type) {
case TEXT:
WinDns.TxtData * txt = &r->txt;
var txt_record = new Gee.ArrayList<string> ();
foreach (unowned string16 str in txt->strings)
txt_record.add (str.to_utf8 ());
meta = PairingServiceMetadata.from_txt_record (txt_record);
break;
case AAAA:
ip = new InetAddress.from_bytes (r->aaaa.ip.data, IPV6);
break;
case SRV:
port = r->srv.port;
break;
default:
break;
}
}
if (meta == null || ip == null || port == 0)
throw new Error.PROTOCOL ("Incomplete result");
return new PairingServiceDetails () {
identifier = meta.identifier,
auth_tag = meta.auth_tag,
endpoint = (InetSocketAddress) Object.new (typeof (InetSocketAddress),
address: ip,
port: port,
scope_id: ip.get_is_link_local () ? interface_address.get_scope_id () : 0
),
interface_address = interface_address,
};
}
private class Monitor {
private weak WindowsPairingBrowser parent;
private InetSocketAddress interface_address;
private void * backend;
public Monitor (WindowsPairingBrowser parent, ulong interface_index, InetSocketAddress interface_address) {
this.parent = parent;
this.interface_address = interface_address;
backend = _create_backend (interface_index, on_result);
}
~Monitor () {
_destroy_backend (backend);
}
private void on_result (void * result) {
parent.on_result (result, interface_address);
}
public extern static void * _create_backend (ulong interface_index, ResultCallback callback);
public extern static void _destroy_backend (void * backend);
}
public extern static void _enumerate_network_interfaces (NetifFoundFunc func);
public delegate void NetifFoundFunc (ulong index, string identifier, owned InetSocketAddress address);
public delegate void ResultCallback (void * result);
}
}
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public class DnsPacketReader {
private BufferReader reader;
public DnsPacketReader (Bytes packet) {
reader = new BufferReader (new Buffer (packet, BIG_ENDIAN));
}
public DnsPtrRecord read_ptr () throws Error {
var rr = read_record ();
if (rr.key.type != PTR)
throw new Error.PROTOCOL ("Expected a PTR record");
if (rr.key.klass != IN)
throw new Error.PROTOCOL ("Expected a PTR record of class IN");
var subreader = new DnsPacketReader (rr.data);
var name = subreader.read_name ();
return new DnsPtrRecord () {
key = rr.key,
ttl = rr.ttl,
data = rr.data,
name = name,
};
}
public DnsTxtRecord read_txt () throws Error {
var rr = read_record ();
if (rr.key.type != TXT)
throw new Error.PROTOCOL ("Expected a TXT record");
if (rr.key.klass != IN)
throw new Error.PROTOCOL ("Expected a TXT record of class IN");
var entries = new Gee.ArrayList<string> ();
var subreader = new DnsPacketReader (rr.data);
while (subreader.reader.available != 0) {
string text = subreader.read_string ();
entries.add (text);
}
return new DnsTxtRecord () {
key = rr.key,
ttl = rr.ttl,
data = rr.data,
entries = entries.to_array (),
};
}
public DnsAaaaRecord read_aaaa () throws Error {
var rr = read_record ();
if (rr.key.type != AAAA)
throw new Error.PROTOCOL ("Expected an AAAA record");
if (rr.key.klass != IN)
throw new Error.PROTOCOL ("Expected an AAAA record of class IN");
var subreader = new DnsPacketReader (rr.data);
var raw_address = subreader.reader.read_bytes (16);
var address = new InetAddress.from_bytes (raw_address.get_data (), IPV6);
return new DnsAaaaRecord () {
key = rr.key,
ttl = rr.ttl,
data = rr.data,
address = address,
};
}
public DnsSrvRecord read_srv () throws Error {
var rr = read_record ();
if (rr.key.type != SRV)
throw new Error.PROTOCOL ("Expected a SRV record");
if (rr.key.klass != IN)
throw new Error.PROTOCOL ("Expected a SRV record of class IN");
var subreader = new DnsPacketReader (rr.data);
var priority = subreader.reader.read_uint16 ();
var weight = subreader.reader.read_uint16 ();
var port = subreader.reader.read_uint16 ();
var name = subreader.read_name ();
return new DnsSrvRecord () {
key = rr.key,
ttl = rr.ttl,
data = rr.data,
priority = priority,
weight = weight,
port = port,
name = name,
};
}
public DnsResourceRecord read_record () throws Error {
var key = read_key ();
var ttl = reader.read_uint32 ();
var size = reader.read_uint16 ();
var data = reader.read_bytes (size);
return new DnsResourceRecord () {
key = key,
ttl = ttl,
data = data,
};
}
public DnsResourceKey read_key () throws Error {
var name = read_name ();
var type = reader.read_uint16 ();
var klass = reader.read_uint16 ();
return new DnsResourceKey () {
name = name,
type = type,
klass = klass,
};
}
public string read_name () throws Error {
var name = new StringBuilder.sized (256);
while (true) {
size_t size = reader.read_uint8 ();
if (size == 0)
break;
if (size > 63)
throw new Error.PROTOCOL ("Invalid DNS name length");
var label = reader.read_fixed_string (size);
if (name.len != 0)
name.append_c ('.');
name.append (label);
}
return name.str;
}
public string read_string () throws Error {
size_t size = reader.read_uint8 ();
return reader.read_fixed_string (size);
}
}
public class DnsPtrRecord : DnsResourceRecord {
public string name;
}
public class DnsTxtRecord : DnsResourceRecord {
public string[] entries;
}
public class DnsAaaaRecord : DnsResourceRecord {
public InetAddress address;
}
public class DnsSrvRecord : DnsResourceRecord {
public uint16 priority;
public uint16 weight;
public uint16 port;
public string name;
}
public class DnsResourceRecord {
public DnsResourceKey key;
public uint32 ttl;
public Bytes data;
}
public class DnsResourceKey {
public string name;
public DnsRecordType type;
public DnsRecordClass klass;
}
public enum DnsRecordType {
PTR = 12,
TXT = 16,
AAAA = 28,
SRV = 33,
}
public enum DnsRecordClass {
IN = 1,
}
}
+17 -4
View File
@@ -504,6 +504,14 @@ namespace Frida.Fruity {
process_incoming_fragments.begin ();
}
public override void dispose () {
foreach (var channel in channels.values)
channel.transport = null;
channels.clear ();
base.dispose ();
}
private async void close (Cancellable? cancellable) throws IOError {
io_cancellable.cancel ();
@@ -878,9 +886,9 @@ namespace Frida.Fruity {
construct;
}
public weak DTXTransport transport {
public weak DTXTransport? transport {
get;
construct;
set;
}
public State state {
@@ -903,7 +911,7 @@ namespace Frida.Fruity {
}
public override void dispose () {
transport.remove_channel (this);
close ();
base.dispose ();
}
@@ -915,6 +923,11 @@ namespace Frida.Fruity {
var error = new Error.TRANSPORT ("Channel closed");
foreach (var request in pending_responses.values.to_array ())
request.reject (error);
if (transport != null) {
transport.remove_channel (this);
transport = null;
}
}
public async NSObject? invoke (string method_name, DTXArgumentListBuilder? args, Cancellable? cancellable)
@@ -1103,7 +1116,7 @@ namespace Frida.Fruity {
NSObject? obj = NSKeyedArchive.decode (buf);
if (obj != null) {
var gval = Value (Type.from_instance (obj));
gval.set_boxed (obj);
gval.set_instance (obj);
elements += (owned) gval;
} else {
var gval = Value (typeof (NSObject));
+90 -19
View File
@@ -198,12 +198,15 @@ namespace Frida {
public async void close (Cancellable? cancellable) throws IOError {
if (remote_server_request != null) {
var server = yield try_get_remote_server (cancellable);
if (server != null) {
try {
yield server.connection.close (cancellable);
} catch (GLib.Error e) {
try {
var server = yield try_get_remote_server (cancellable);
if (server != null) {
try {
yield server.connection.close (cancellable);
} catch (GLib.Error e) {
}
}
} catch (Error e) {
}
}
@@ -968,7 +971,7 @@ namespace Frida {
var transport_broker = server.transport_broker;
if (transport_broker != null) {
try {
entry.connection = yield establish_direct_connection (transport_broker, remote_session_id, device,
entry.connection = yield establish_direct_connection (transport_broker, remote_session_id, server,
cancellable);
} catch (Error e) {
if (e is Error.NOT_SUPPORTED)
@@ -1052,11 +1055,13 @@ namespace Frida {
entry.close.begin (io_cancellable);
}
private async RemoteServer? try_get_remote_server (Cancellable? cancellable) throws IOError {
private async RemoteServer? try_get_remote_server (Cancellable? cancellable) throws Error, IOError {
try {
return yield get_remote_server (cancellable);
} catch (Error e) {
return null;
if (e is Error.SERVER_NOT_RUNNING)
return null;
throw e;
}
}
@@ -1082,10 +1087,9 @@ namespace Frida {
DBusConnection? connection = null;
try {
var stream = yield device.open_channel (
("tcp:%" + uint16.FORMAT_MODIFIER + "u").printf (DEFAULT_CONTROL_PORT),
cancellable);
var channel = yield connect_to_remote_server (cancellable);
IOStream stream = channel.stream;
WebServiceTransport transport = PLAIN;
string? origin = null;
@@ -1113,7 +1117,7 @@ namespace Frida {
if (connection.closed)
throw new Error.SERVER_NOT_RUNNING ("Unable to connect to remote frida-server");
var server = new RemoteServer (session, connection, flavor, transport_broker);
var server = new RemoteServer (flavor, session, connection, channel, device, transport_broker);
attach_remote_server (server);
current_remote_server = server;
last_server_check_timer = null;
@@ -1131,8 +1135,8 @@ namespace Frida {
last_server_check_timer = null;
last_server_check_error = null;
} else {
if (e is Error.SERVER_NOT_RUNNING) {
api_error = new Error.SERVER_NOT_RUNNING ("Unable to connect to remote frida-server");
if (e is Error) {
api_error = e;
} else if (connection != null) {
api_error = new Error.PROTOCOL ("Incompatible frida-server version");
} else {
@@ -1150,6 +1154,51 @@ namespace Frida {
}
}
private async Fruity.TcpChannel connect_to_remote_server (Cancellable? cancellable) throws Error, IOError {
var tunnel = yield device.find_tunnel (cancellable);
bool tunnel_recently_opened = tunnel != null && get_monotonic_time () - tunnel.opened_at < 1000000;
uint delays[] = { 0, 50, 250 };
uint max_attempts = tunnel_recently_opened ? delays.length : 1;
var main_context = MainContext.ref_thread_default ();
Error? pending_error = null;
for (uint attempts = 0; attempts != max_attempts; attempts++) {
uint delay = delays[attempts];
if (delay != 0) {
var timeout_source = new TimeoutSource (delay);
timeout_source.set_callback (connect_to_remote_server.callback);
timeout_source.attach (main_context);
var cancel_source = new CancellableSource (cancellable);
cancel_source.set_callback (connect_to_remote_server.callback);
cancel_source.attach (main_context);
yield;
cancel_source.destroy ();
timeout_source.destroy ();
if (cancellable.is_cancelled ())
break;
}
bool is_last_attempt = attempts == max_attempts - 1;
var open_flags = is_last_attempt
? Fruity.OpenTcpChannelFlags.ALLOW_ANY_TRANSPORT
: Fruity.OpenTcpChannelFlags.ALLOW_TUNNEL;
try {
return yield device.open_tcp_channel (DEFAULT_CONTROL_PORT.to_string (), open_flags, cancellable);
} catch (Error e) {
pending_error = e;
if (!(e is Error.SERVER_NOT_RUNNING))
break;
}
}
throw pending_error;
}
private void attach_remote_server (RemoteServer server) {
server.connection.on_closed.connect (on_remote_connection_closed);
@@ -1445,7 +1494,12 @@ namespace Frida {
}
}
private class RemoteServer : Object {
private class RemoteServer : Object, HostChannelProvider {
public Flavor flavor {
get;
construct;
}
public HostSession session {
get;
construct;
@@ -1456,7 +1510,12 @@ namespace Frida {
construct;
}
public Flavor flavor {
public Fruity.TcpChannel channel {
get;
construct;
}
public Fruity.Device device {
get;
construct;
}
@@ -1471,15 +1530,27 @@ namespace Frida {
set;
}
public RemoteServer (HostSession session, DBusConnection connection, Flavor flavor,
TransportBroker? transport_broker) {
public RemoteServer (Flavor flavor, HostSession session, DBusConnection connection, Fruity.TcpChannel channel,
Fruity.Device device, TransportBroker? transport_broker) {
Object (
flavor: flavor,
session: session,
connection: connection,
flavor: flavor,
channel: channel,
device: device,
transport_broker: transport_broker
);
}
public async IOStream open_channel (string address, Cancellable? cancellable) throws Error, IOError {
if (!address.has_prefix ("tcp:"))
throw new Error.NOT_SUPPORTED ("Unsupported channel address");
var flags = (channel.kind == TUNNEL)
? Fruity.OpenTcpChannelFlags.ALLOW_TUNNEL
: Fruity.OpenTcpChannelFlags.ALLOW_USBMUX;
var channel = yield device.open_tcp_channel (address[4:], flags, cancellable);
return channel.stream;
}
}
}
+3
View File
@@ -265,6 +265,8 @@ namespace Frida.Fruity {
}
private static LockdownError error_from_service (PlistServiceError e) {
if (e is PlistServiceError.CONNECTION_CLOSED)
return new LockdownError.CONNECTION_CLOSED ("%s", e.message);
return new LockdownError.PROTOCOL ("%s", e.message);
}
@@ -274,6 +276,7 @@ namespace Frida.Fruity {
}
public errordomain LockdownError {
CONNECTION_CLOSED,
INVALID_SERVICE,
NOT_PAIRED,
UNSUPPORTED,
+380 -135
View File
@@ -6,6 +6,11 @@ namespace Frida.Fruity {
construct;
}
public UsbNcmConfig config {
get;
construct;
}
public VirtualNetworkStack netstack {
get {
return _netstack;
@@ -18,33 +23,32 @@ namespace Frida.Fruity {
}
}
private uint8 data_iface;
private int data_altsetting;
private uint8 rx_address;
private uint8 tx_address;
private uint32 ntb_in_max_size;
private uint32 ntb_out_max_size;
private uint16 ndp_out_divisor;
private uint16 ndp_out_payload_remainder;
private uint16 ndp_out_alignment;
private uint16 ntb_out_max_datagrams;
private size_t max_in_transfers;
private size_t max_out_transfers;
private VirtualNetworkStack? _netstack;
private Gee.Queue<Bytes> pending_output = new Gee.ArrayQueue<Bytes> ();
private bool writing = false;
private uint16 next_outgoing_sequence = 1;
private InetAddress? _remote_ipv6_address;
private Cancellable io_cancellable = new Cancellable ();
private enum UsbDescriptorType {
INTERFACE = 0x04,
private const uint16 TRANSFER_HEADER_SIZE = 4 + 2 + 2 + 2 + 2;
private const size_t MAX_TRANSFER_MEMORY = 60 * 1518;
private enum CdcRequest {
GET_NTB_PARAMETERS = 0x80,
SET_NTB_INPUT_SIZE = 0x86,
}
private enum UsbCommSubclass {
NCM = 0x0d,
}
private enum UsbDataSubclass {
UNDEFINED = 0x00,
}
private enum UsbCdcDescriptorSubtype {
ETHERNET = 0x0f,
}
private const uint16 NTB_PARAMETERS_MIN_SIZE = 28;
private enum EtherType {
IPV6 = 0x86dd,
@@ -54,8 +58,9 @@ namespace Frida.Fruity {
UDP = 0x11,
}
public static async UsbNcmDriver open (UsbDevice device, Cancellable? cancellable = null) throws Error, IOError {
var driver = new UsbNcmDriver (device);
public static async UsbNcmDriver open (UsbDevice device, UsbNcmConfig config, Cancellable? cancellable = null)
throws Error, IOError {
var driver = new UsbNcmDriver (device, config);
try {
yield driver.init_async (Priority.DEFAULT, cancellable);
@@ -66,53 +71,15 @@ namespace Frida.Fruity {
return driver;
}
private UsbNcmDriver (UsbDevice device) {
Object (device: device);
private UsbNcmDriver (UsbDevice device, UsbNcmConfig config) {
Object (device: device, config: config);
}
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
unowned LibUSB.DeviceHandle handle = device.handle;
LibUSB.ConfigDescriptor config;
Usb.check (device.raw_device.get_active_config_descriptor (out config),
"Failed to get active USB config descriptor");
bool found_cdc_header = false;
bool found_data_interface = false;
uint8 mac_address_index = 0;
foreach (var iface in config.@interface) {
foreach (var setting in iface.altsetting) {
if (setting.bInterfaceClass == LibUSB.ClassCode.COMM &&
setting.bInterfaceSubClass == UsbCommSubclass.NCM) {
try {
parse_cdc_header (setting.extra, out mac_address_index);
found_cdc_header = true;
} catch (Error e) {
break;
}
} else if (setting.bInterfaceClass == LibUSB.ClassCode.DATA &&
setting.bInterfaceSubClass == UsbDataSubclass.UNDEFINED &&
setting.endpoint.length == 2) {
found_data_interface = true;
data_iface = setting.bInterfaceNumber;
data_altsetting = setting.bAlternateSetting;
foreach (var ep in setting.endpoint) {
if ((ep.bEndpointAddress & LibUSB.EndpointDirection.MASK) == LibUSB.EndpointDirection.IN)
rx_address = ep.bEndpointAddress;
else
tx_address = ep.bEndpointAddress;
}
}
}
}
if (!found_cdc_header || !found_data_interface)
throw_user_error ("No USB CDC-NCM interface found");
var language_id = yield device.query_default_language_id (cancellable);
uint8 mac_address[6];
string mac_address_str = yield device.read_string_descriptor (mac_address_index, device.default_language_id,
cancellable);
string mac_address_str = yield device.read_string_descriptor (config.mac_address_index, language_id, cancellable);
if (mac_address_str.length != 12)
throw new Error.PROTOCOL ("Invalid MAC address");
for (uint i = 0; i != 6; i++) {
@@ -121,13 +88,62 @@ namespace Frida.Fruity {
mac_address[i] = (uint8) v;
}
handle.detach_kernel_driver (data_iface);
unowned LibUSB.DeviceHandle handle = device.handle;
try {
Usb.check (handle.claim_interface (data_iface), "Failed to claim USB interface");
Usb.check (handle.claim_interface (config.ctrl_iface), "Failed to claim control interface");
Usb.check (handle.claim_interface (config.data_iface), "Failed to claim data interface");
} catch (Error e) {
throw_user_error (@"Unable to claim USB CDC-NCM interface ($(e.message))");
throw new Error.PERMISSION_DENIED ("%s",
make_user_error_message (@"Unable to claim USB CDC-NCM interface ($(e.message))"));
}
Usb.check (handle.set_interface_alt_setting (data_iface, data_altsetting),
uint8 raw_ntb_params[NTB_PARAMETERS_MIN_SIZE];
var raw_ntb_params_size = yield device.control_transfer (
LibUSB.RequestRecipient.INTERFACE | LibUSB.RequestType.CLASS | LibUSB.EndpointDirection.IN,
CdcRequest.GET_NTB_PARAMETERS,
0,
config.ctrl_iface,
raw_ntb_params,
1000,
cancellable);
if (raw_ntb_params_size < NTB_PARAMETERS_MIN_SIZE)
throw new Error.PROTOCOL ("Truncated NTB parameters response");
var ntb_params = new Buffer (new Bytes (raw_ntb_params[:raw_ntb_params_size]), LITTLE_ENDIAN);
uint32 device_ntb_in_max_size = ntb_params.read_uint32 (4);
ntb_in_max_size = uint32.min (device_ntb_in_max_size, 16384);
ntb_out_max_size = uint32.min (ntb_params.read_uint32 (16), 16384);
ndp_out_divisor = ntb_params.read_uint16 (20);
ndp_out_payload_remainder = ntb_params.read_uint16 (22);
ndp_out_alignment = ntb_params.read_uint16 (24);
ntb_out_max_datagrams = uint16.min (ntb_params.read_uint16 (26), 16);
if (ntb_in_max_size != device_ntb_in_max_size) {
var ntb_size_buf = new BufferBuilder (LITTLE_ENDIAN)
.append_uint32 (ntb_in_max_size)
.build ();
yield device.control_transfer (
LibUSB.RequestRecipient.INTERFACE | LibUSB.RequestType.CLASS | LibUSB.EndpointDirection.OUT,
CdcRequest.SET_NTB_INPUT_SIZE,
0,
config.ctrl_iface,
ntb_size_buf.get_data (),
1000,
cancellable);
}
var speed = device.raw_device.get_device_speed ();
if (speed >= LibUSB.Speed.SUPER) {
max_in_transfers = (5 * MAX_TRANSFER_MEMORY) / ntb_in_max_size;
max_out_transfers = (5 * MAX_TRANSFER_MEMORY) / ntb_out_max_size;
} else if (speed == LibUSB.Speed.HIGH) {
max_in_transfers = MAX_TRANSFER_MEMORY / ntb_in_max_size;
max_out_transfers = MAX_TRANSFER_MEMORY / ntb_out_max_size;
} else {
max_in_transfers = 4;
max_out_transfers = 4;
}
Usb.check (handle.set_interface_alt_setting (config.data_iface, config.data_altsetting),
"Failed to set USB interface alt setting");
_netstack = new VirtualNetworkStack (new Bytes (mac_address), null, 1500);
@@ -138,36 +154,46 @@ namespace Frida.Fruity {
return true;
}
[NoReturn]
private void throw_user_error (string message) throws Error {
#if WINDOWS
throw new Error.NOT_SUPPORTED ("%s; use https://zadig.akeo.ie to switch from Apple's official driver onto " +
"Microsoft's WinUSB driver, so libusb can access it", message);
#else
throw new Error.NOT_SUPPORTED ("%s", message);
#endif
}
public void close () {
io_cancellable.cancel ();
_netstack.stop ();
}
private async void process_incoming_datagrams () {
var data = new uint8[64 * 1024];
var pending = new Gee.ArrayQueue<Promise<Bytes>> ();
while (true) {
for (uint i = pending.size; i != max_in_transfers; i++) {
var request = transfer_next_input_batch ();
pending.offer (request);
}
try {
size_t n = yield device.bulk_transfer (rx_address, data, uint.MAX, io_cancellable);
handle_ncm_frame (data[:n]);
var frame = yield pending.poll ().future.wait_async (io_cancellable);
handle_ncm_frame (frame);
} catch (GLib.Error e) {
return;
}
}
}
private void handle_ncm_frame (uint8[] data) throws GLib.Error {
var input = new DataInputStream (new MemoryInputStream.from_data (data));
private Promise<Bytes> transfer_next_input_batch () {
var request = new Promise<Bytes> ();
do_transfer_input_batch.begin (request);
return request;
}
private async void do_transfer_input_batch (Promise<Bytes> request) {
var data = new uint8[ntb_in_max_size];
try {
size_t n = yield device.bulk_transfer (config.rx_address, data, uint.MAX, io_cancellable);
request.resolve (new Bytes (data[:n]));
} catch (GLib.Error e) {
request.reject (e);
}
}
private void handle_ncm_frame (Bytes frame) throws GLib.Error {
var input = new DataInputStream (new MemoryInputStream.from_bytes (frame));
input.byte_order = LITTLE_ENDIAN;
uint8 raw_signature[4 + 1];
@@ -215,47 +241,274 @@ namespace Frida.Fruity {
} while (ndp_index != 0);
}
private async void on_netif_outgoing_datagram (Bytes datagram) {
uint16 transfer_header_length = 12;
uint16 ndp_header_length = 16;
uint16 alignment_padding_length = 2;
private void on_netif_outgoing_datagram (Bytes datagram) {
pending_output.offer (datagram);
uint16 datagram_start_index = transfer_header_length + ndp_header_length + alignment_padding_length;
uint16 datagram_length = (uint16) datagram.length;
uint16 sentinel_start_index = 0;
uint16 sentinel_size = 0;
uint16 sequence = next_outgoing_sequence++;
uint16 block_length = datagram_start_index + datagram_length;
uint16 ndp_index = transfer_header_length;
uint16 next_ndp_index = 0;
uint16 alignment_padding_value = 0;
var frame = new BufferBuilder (LITTLE_ENDIAN)
.append_string ("NCMH", StringTerminator.NONE)
.append_uint16 (transfer_header_length)
.append_uint16 (sequence)
.append_uint16 (block_length)
.append_uint16 (ndp_index)
.append_string ("NCM0", StringTerminator.NONE)
.append_uint16 (ndp_header_length)
.append_uint16 (next_ndp_index)
.append_uint16 (datagram_start_index)
.append_uint16 (datagram_length)
.append_uint16 (sentinel_start_index)
.append_uint16 (sentinel_size)
.append_uint16 (alignment_padding_value)
.append_bytes (datagram)
.build ();
try {
yield device.bulk_transfer (tx_address, frame.get_data (), uint.MAX, io_cancellable);
} catch (GLib.Error e) {
if (!writing) {
writing = true;
var source = new IdleSource ();
source.set_callback (() => {
process_pending_output.begin ();
return false;
});
source.attach (MainContext.get_thread_default ());
}
}
private async void process_pending_output () {
try {
while (!pending_output.is_empty) {
var pending = new Gee.ArrayList<Promise<uint>> ();
do {
var request = transfer_next_output_batch ();
pending.add (request);
} while (pending.size < max_out_transfers && !pending_output.is_empty);
foreach (var request in pending)
yield request.future.wait_async (io_cancellable);
}
} catch (GLib.Error e) {
} finally {
writing = false;
}
}
private Promise<uint> transfer_next_output_batch () {
size_t num_datagrams = ntb_out_max_datagrams;
TransferLayout layout;
while ((layout = TransferLayout.compute (pending_output, num_datagrams, ndp_out_alignment,
ndp_out_divisor, ndp_out_payload_remainder)).size > ntb_out_max_size) {
num_datagrams--;
}
var batch = new Gee.ArrayList<Bytes> ();
for (var i = 0; i != layout.offsets.size; i++)
batch.add (pending_output.poll ());
var transfer = build_output_transfer (batch, layout, next_outgoing_sequence++);
var request = new Promise<uint> ();
do_transfer_output_batch.begin (transfer, request);
return request;
}
private async void do_transfer_output_batch (Bytes transfer, Promise<uint> request) {
try {
var size = yield device.bulk_transfer (config.tx_address, transfer.get_data (), uint.MAX, io_cancellable);
request.resolve ((uint) size);
} catch (GLib.Error e) {
request.reject (e);
}
}
private class TransferLayout {
public uint16 size;
public uint16 ndp_header_offset;
public uint16 ndp_header_size;
public Gee.List<uint16> offsets;
public static TransferLayout compute (Gee.Collection<Bytes> datagrams, size_t max_datagrams, size_t ndp_alignment,
size_t datagram_modulus, size_t datagram_remainder) {
size_t ndp_header_base_size = 4 + 2 + 2;
size_t ndp_entry_size = 2 + 2;
size_t ethernet_header_size = 14;
size_t ndp_header_offset = align (TRANSFER_HEADER_SIZE, ndp_alignment, 0);
size_t num_datagram_slots = size_t.min (datagrams.size, max_datagrams);
size_t ndp_header_size = ndp_header_base_size + ((num_datagram_slots + 1) * ndp_entry_size);
size_t current_transfer_size = ndp_header_offset + ndp_header_size;
var offsets = new Gee.ArrayList<uint16> ();
uint i = 0;
foreach (var datagram in datagrams) {
var size = (uint16) datagram.get_size ();
size_t start_offset =
align (current_transfer_size + ethernet_header_size, datagram_modulus, datagram_remainder);
size_t end_offset = start_offset + size;
if (end_offset > uint16.MAX)
break;
current_transfer_size = end_offset;
offsets.add ((uint16) start_offset);
i++;
if (i == max_datagrams)
break;
}
return new TransferLayout () {
size = (uint16) current_transfer_size,
ndp_header_offset = (uint16) ndp_header_offset,
ndp_header_size = (uint16) ndp_header_size,
offsets = offsets,
};
}
private static size_t align (size_t val, size_t modulus, size_t remainder) {
var delta = val % modulus;
if (delta != remainder)
return val + modulus - delta + remainder;
return val;
}
}
private static Bytes build_output_transfer (Gee.List<Bytes> datagrams, TransferLayout layout, uint16 sequence_number) {
var builder = new BufferBuilder (LITTLE_ENDIAN)
.append_string ("NCMH", StringTerminator.NONE)
.append_uint16 (TRANSFER_HEADER_SIZE)
.append_uint16 (sequence_number)
.append_uint16 (layout.size)
.append_uint16 (layout.ndp_header_offset);
uint16 next_ndp_index = 0;
builder
.seek (layout.ndp_header_offset)
.append_string ("NCM0", StringTerminator.NONE)
.append_uint16 (layout.ndp_header_size)
.append_uint16 (next_ndp_index);
int i;
i = 0;
foreach (var datagram in datagrams) {
builder
.append_uint16 (layout.offsets[i])
.append_uint16 ((uint16) datagram.get_size ());
i++;
}
i = 0;
foreach (var datagram in datagrams) {
builder
.seek (layout.offsets[i])
.append_bytes (datagram);
i++;
}
builder.seek (layout.size);
return builder.build ();
}
private static InetAddress? try_infer_remote_address_from_datagram (Bytes datagram) {
if (datagram.get_size () < 0x3e)
return null;
var buf = new Buffer (datagram, BIG_ENDIAN);
var ethertype = (EtherType) buf.read_uint16 (12);
if (ethertype != IPV6)
return null;
var next_header = (IPV6NextHeader) buf.read_uint8 (20);
if (next_header != UDP)
return null;
return new InetAddress.from_bytes (datagram[22:22 + 16].get_data (), IPV6);
}
}
internal class UsbNcmConfig {
public uint8 ctrl_iface;
public uint8 data_iface;
public int data_altsetting;
public uint8 rx_address;
public uint8 tx_address;
public uint8 mac_address_index;
private enum UsbDescriptorType {
INTERFACE = 0x04,
}
private enum UsbCommSubclass {
NCM = 0x0d,
}
private enum UsbDataSubclass {
UNDEFINED = 0x00,
}
private enum UsbCdcDescriptorSubtype {
ETHERNET = 0x0f,
}
public static UsbNcmConfig prepare (UsbDevice device, out bool device_configuration_changed) throws Error {
unowned LibUSB.Device raw_device = device.raw_device;
var dev_desc = LibUSB.DeviceDescriptor (raw_device);
LibUSB.ConfigDescriptor current_config;
Usb.check (raw_device.get_active_config_descriptor (out current_config), "Failed to get active config descriptor");
var config = new UsbNcmConfig ();
int desired_config_value = -1;
bool found_cdc_header = false;
bool found_data_interface = false;
for (uint8 config_value = dev_desc.bNumConfigurations; config_value != 0; config_value--) {
LibUSB.ConfigDescriptor config_desc;
Usb.check (raw_device.get_config_descriptor_by_value (config_value, out config_desc),
"Failed to get config descriptor");
foreach (var iface in config_desc.@interface) {
foreach (var setting in iface.altsetting) {
if (setting.bInterfaceClass == LibUSB.ClassCode.COMM &&
setting.bInterfaceSubClass == UsbCommSubclass.NCM) {
config.ctrl_iface = setting.bInterfaceNumber;
try {
parse_cdc_header (setting.extra, out config.mac_address_index);
found_cdc_header = true;
} catch (Error e) {
break;
}
} else if (setting.bInterfaceClass == LibUSB.ClassCode.DATA &&
setting.bInterfaceSubClass == UsbDataSubclass.UNDEFINED &&
setting.endpoint.length == 2) {
found_data_interface = true;
config.data_iface = setting.bInterfaceNumber;
config.data_altsetting = setting.bAlternateSetting;
foreach (var ep in setting.endpoint) {
if ((ep.bEndpointAddress & LibUSB.EndpointDirection.MASK) ==
LibUSB.EndpointDirection.IN) {
config.rx_address = ep.bEndpointAddress;
} else {
config.tx_address = ep.bEndpointAddress;
}
}
}
}
}
if (found_cdc_header || found_data_interface) {
desired_config_value = config_value;
break;
}
}
if (!found_cdc_header || !found_data_interface)
throw new Error.NOT_SUPPORTED ("%s", make_user_error_message ("No USB CDC-NCM interface found"));
if (current_config.bConfigurationValue != desired_config_value) {
unowned LibUSB.DeviceHandle handle = device.handle;
foreach (var iface in current_config.@interface) {
unowned LibUSB.InterfaceDescriptor setting = iface.altsetting[0];
var res = handle.kernel_driver_active (setting.bInterfaceNumber);
if (res == 1)
handle.detach_kernel_driver (setting.bInterfaceNumber);
}
Usb.check (handle.set_configuration (desired_config_value), "Failed to set configuration");
device_configuration_changed = true;
} else {
device_configuration_changed = false;
}
return config;
}
private static void parse_cdc_header (uint8[] header, out uint8 mac_address_index) throws Error {
var input = new DataInputStream (new MemoryInputStream.from_data (header));
input.set_byte_order (LITTLE_ENDIAN);
@@ -285,22 +538,14 @@ namespace Frida.Fruity {
throw new Error.PROTOCOL ("CDC Ethernet descriptor not found");
}
}
private static InetAddress? try_infer_remote_address_from_datagram (Bytes datagram) {
if (datagram.get_size () < 0x3e)
return null;
var buf = new Buffer (datagram, BIG_ENDIAN);
var ethertype = (EtherType) buf.read_uint16 (12);
if (ethertype != IPV6)
return null;
var next_header = (IPV6NextHeader) buf.read_uint8 (20);
if (next_header != UDP)
return null;
return new InetAddress.from_bytes (datagram[22:22 + 16].get_data (), IPV6);
}
private string make_user_error_message (string message) {
#if WINDOWS
return message + "; use https://zadig.akeo.ie to switch from Apple's official driver onto Microsoft's WinUSB " +
"driver, so libusb can access it";
#else
return message;
#endif
}
}
+80 -64
View File
@@ -11,6 +11,42 @@ namespace Frida.Fruity {
public abstract async IOStream open_tcp_connection (InetSocketAddress address, Cancellable? cancellable)
throws Error, IOError;
public async IOStream open_tcp_connection_with_timeout (InetSocketAddress address, uint timeout, Cancellable? cancellable)
throws Error, IOError {
bool timed_out = false;
var open_cancellable = new Cancellable ();
var main_context = MainContext.get_thread_default ();
var timeout_source = new TimeoutSource (timeout);
timeout_source.set_callback (() => {
timed_out = true;
open_cancellable.cancel ();
return Source.REMOVE;
});
timeout_source.attach (main_context);
var cancel_source = new CancellableSource (cancellable);
cancel_source.set_callback (() => {
open_cancellable.cancel ();
return Source.REMOVE;
});
cancel_source.attach (main_context);
try {
return yield open_tcp_connection (address, open_cancellable);
} catch (IOError e) {
assert (e is IOError.CANCELLED);
if (timed_out)
throw new Error.TIMED_OUT ("Networked Apple device is not responding");
throw e;
} finally {
timeout_source.destroy ();
cancel_source.destroy ();
}
}
public abstract UdpSocket create_udp_socket () throws Error;
}
@@ -147,6 +183,7 @@ namespace Frida.Fruity {
private State state = STARTED;
private Gee.Queue<Request> requests = new Gee.ArrayQueue<Request> ();
private unowned Thread<bool>? lwip_thread;
private LWIP.NetworkInterface handle;
private LWIP.IP6Address raw_ipv6_address;
@@ -154,8 +191,6 @@ namespace Frida.Fruity {
private MainContext main_context;
private DataOutputStream? pcap;
private enum State {
STARTED,
STOPPED
@@ -249,13 +284,11 @@ namespace Frida.Fruity {
public void handle_incoming_datagram (Bytes datagram) throws Error {
check_started ();
log_datagram (datagram);
check (perform_on_lwip_thread (() => {
var pbuf = LWIP.PacketBuffer.alloc (RAW, (uint16) datagram.get_size (), POOL);
pbuf.take (datagram.get_data ());
var err = handle.input (pbuf, handle);
var err = handle.input (pbuf, ref handle);
if (err == OK)
*((void **) &pbuf) = null;
@@ -282,10 +315,8 @@ namespace Frida.Fruity {
var datagram = new Bytes (packet[:pbuf.tot_len]);
schedule_on_frida_thread (() => {
if (state == STARTED) {
log_datagram (datagram);
if (state == STARTED)
outgoing_datagram (datagram);
}
return Source.REMOVE;
});
}
@@ -293,18 +324,29 @@ namespace Frida.Fruity {
internal LWIP.ErrorCode perform_on_lwip_thread (owned WorkFunc work) {
var req = new Request ((owned) work);
lock (requests)
requests.offer (req);
LWIP.Runtime.schedule (perform_next_request);
if (Thread.self<bool> () == lwip_thread) {
perform_request (req);
} else {
lock (requests)
requests.offer (req);
LWIP.Runtime.schedule (perform_next_request);
}
return req.join ();
}
private void perform_next_request () {
if (lwip_thread == null)
lwip_thread = Thread.self ();
Request req;
lock (requests)
req = requests.poll ();
perform_request (req);
}
private static void perform_request (Request req) {
LWIP.ErrorCode err = req.work ();
req.complete (err);
}
@@ -352,45 +394,6 @@ namespace Frida.Fruity {
source.attach (main_context);
}
private void log_datagram (Bytes datagram) {
lock (pcap) {
try {
if (pcap == null) {
char buf[40];
unowned string addr = raw_ipv6_address.to_string (buf);
var f = File.new_build_filename (Environment.get_user_special_dir (DESKTOP),
"vns-%s.pcap".printf (addr.replace (":", "")));
try {
f.delete ();
} catch (GLib.Error e) {
}
pcap = new DataOutputStream (f.create (REPLACE_DESTINATION));
pcap.set_byte_order (HOST_ENDIAN);
pcap.put_uint32 (0xa1b2c3d4U);
pcap.put_uint16 (2);
pcap.put_uint16 (4);
pcap.put_uint32 (0);
pcap.put_uint32 (0);
pcap.put_uint32 (16384);
pcap.put_uint32 ((ethernet_address != null) ? 1 : 229); // Ethernet or IPv6
pcap.flush ();
}
int64 timestamp = get_real_time ();
pcap.put_uint32 ((uint32) (timestamp / 1000000));
pcap.put_uint32 ((uint32) (timestamp % 1000000));
pcap.put_uint32 (datagram.length);
pcap.put_uint32 (datagram.length);
size_t written;
pcap.write_all (datagram.get_data (), out written);
pcap.flush ();
} catch (GLib.Error e) {
printerr ("%s\n", e.message);
assert_not_reached ();
}
}
}
private class TcpConnection : IOStream, AsyncInitable {
public VirtualNetworkStack netstack {
get;
@@ -515,8 +518,9 @@ namespace Frida.Fruity {
if (self != null)
self->on_error (err);
});
pcb.set_flags (TIMESTAMP | SACK);
pcb.nagle_disable ();
pcb.bind_netif (netstack.handle);
pcb.bind_netif (&netstack.handle);
var err = pcb.connect (ip6_address_from_inet_socket_address (address), address.get_port (), (user_data, pcb, err) => {
TcpConnection * self = user_data;
@@ -542,6 +546,14 @@ namespace Frida.Fruity {
pcb = null;
return OK;
});
_state = CLOSED;
update_events ();
}
private void detach_from_pcb () {
pcb.set_user_data (null);
pcb = null;
}
private void on_connect () {
@@ -561,7 +573,7 @@ namespace Frida.Fruity {
private void on_recv (owned LWIP.PacketBuffer? pbuf, LWIP.ErrorCode err) {
if (pbuf == null) {
pcb = null;
detach_from_pcb ();
schedule_on_frida_thread (() => {
_state = CLOSED;
update_events ();
@@ -584,14 +596,17 @@ namespace Frida.Fruity {
}
private void on_error (LWIP.ErrorCode err) {
pcb = null;
bool pcb_already_freed = err == ABRT;
if (pcb_already_freed)
pcb = null;
else
detach_from_pcb ();
schedule_on_frida_thread (() => {
_state = CLOSED;
update_events ();
if (!established.future.ready) {
if (!established.future.ready)
established.reject (parse_error (err));
}
return Source.REMOVE;
});
@@ -627,9 +642,6 @@ namespace Frida.Fruity {
ssize_t n = 0;
netstack.perform_on_lwip_thread (() => {
if (pcb == null)
return OK;
lock (state) {
n = ssize_t.min (buffer.length, rx_buf.len);
if (n == 0)
@@ -638,6 +650,9 @@ namespace Frida.Fruity {
rx_buf.remove_range (0, (uint) n);
}
if (pcb == null)
return OK;
size_t remainder = n;
while (remainder != 0) {
uint16 chunk = (uint16) size_t.min (remainder, uint16.MAX);
@@ -794,10 +809,12 @@ namespace Frida.Fruity {
});
}
mutex.lock ();
while (!done)
cond.wait (mutex);
mutex.unlock ();
if (!is_readable ()) {
mutex.lock ();
while (!done)
cond.wait (mutex);
mutex.unlock ();
}
if (cancellation_handler != 0)
cancellable.disconnect (cancellation_handler);
@@ -957,7 +974,6 @@ namespace Frida.Fruity {
}
}
//private VirtualNetworkStack? _netstack;
private unowned LWIP.UdpPcb? pcb;
private IOCondition events = OUT;
private Gee.Queue<Packet> rx_queue = new Gee.ArrayQueue<Packet> ();
@@ -972,7 +988,7 @@ namespace Frida.Fruity {
netstack.perform_on_lwip_thread (() => {
pcb = LWIP.UdpPcb.make (V6);
pcb.set_recv_callback (on_recv);
pcb.bind_netif (netstack.handle);
pcb.bind_netif (&netstack.handle);
return OK;
});
}
+245
View File
@@ -0,0 +1,245 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
public class OpackBuilder {
protected BufferBuilder builder = new BufferBuilder (LITTLE_ENDIAN);
private Gee.Deque<Scope> scopes = new Gee.ArrayQueue<Scope> ();
public OpackBuilder () {
push_scope (new Scope (ROOT));
}
public unowned OpackBuilder begin_dictionary () {
begin_value ();
size_t type_offset = builder.offset;
builder.append_uint8 (0x00);
push_scope (new CollectionScope (type_offset));
return this;
}
public unowned OpackBuilder set_member_name (string name) {
return add_string_value (name);
}
public unowned OpackBuilder end_dictionary () {
CollectionScope scope = pop_scope ();
size_t n = scope.num_values / 2;
if (n < 0xf) {
builder.write_uint8 (scope.type_offset, 0xe0 | n);
} else {
builder
.write_uint8 (scope.type_offset, 0xef)
.append_uint8 (0x03);
}
return this;
}
public unowned OpackBuilder add_string_value (string val) {
begin_value ();
size_t len = val.length;
if (len > uint32.MAX) {
builder
.append_uint8 (0x6f)
.append_string (val, StringTerminator.NUL);
return this;
}
if (len <= 0x20)
builder.append_uint8 ((uint8) (0x40 + len));
else if (len <= uint8.MAX)
builder.append_uint8 (0x61).append_uint8 ((uint8) len);
else if (len <= uint16.MAX)
builder.append_uint8 (0x62).append_uint16 ((uint16) len);
else if (len <= 0xffffff)
builder.append_uint8 (0x63).append_uint8 ((uint8) (len & 0xff)).append_uint16 ((uint16) (len >> 8));
else
builder.append_uint8 (0x64).append_uint32 ((uint32) len);
builder.append_string (val, StringTerminator.NONE);
return this;
}
public unowned OpackBuilder add_data_value (Bytes val) {
begin_value ();
size_t size = val.get_size ();
if (size <= 0x20)
builder.append_uint8 ((uint8) (0x70 + size));
else if (size <= uint8.MAX)
builder.append_uint8 (0x91).append_uint8 ((uint8) size);
else if (size <= uint16.MAX)
builder.append_uint8 (0x92).append_uint16 ((uint16) size);
else if (size <= 0xffffff)
builder.append_uint8 (0x93).append_uint8 ((uint8) (size & 0xff)).append_uint16 ((uint16) (size >> 8));
else
builder.append_uint8 (0x94).append_uint32 ((uint32) size);
builder.append_bytes (val);
return this;
}
private unowned OpackBuilder begin_value () {
peek_scope ().num_values++;
return this;
}
public Bytes build () {
return builder.build ();
}
private void push_scope (Scope scope) {
scopes.offer_tail (scope);
}
private Scope peek_scope () {
return scopes.peek_tail ();
}
private T pop_scope<T> () {
return (T) scopes.poll_tail ();
}
private class Scope {
public Kind kind;
public size_t num_values = 0;
public enum Kind {
ROOT,
COLLECTION,
}
public Scope (Kind kind) {
this.kind = kind;
}
}
private class CollectionScope : Scope {
public size_t type_offset;
public CollectionScope (size_t type_offset) {
base (COLLECTION);
this.type_offset = type_offset;
}
}
}
public class OpackParser {
private BufferReader reader;
[Flags]
private enum ValueFlags {
ALLOW_TERMINATOR = 1 << 0,
}
public static Variant parse (Bytes opack) throws Error {
var parser = new OpackParser (opack);
return parser.read_value ();
}
private OpackParser (Bytes opack) {
reader = new BufferReader (new Buffer (opack, LITTLE_ENDIAN));
}
private Variant? read_value (ValueFlags flags = 0) throws Error {
uint8 v = reader.read_uint8 ();
uint8 top = v >> 4;
uint8 bottom = v & 0b1111;
switch (top) {
case 0:
switch (bottom) {
case 3:
if ((flags & ValueFlags.ALLOW_TERMINATOR) == 0)
throw new Error.PROTOCOL ("Unexpected OPACK terminator");
return null;
}
throw new Error.NOT_SUPPORTED ("Unsupported OPACK type 0x%02x", v);
case 3:
switch (bottom) {
case 0: return (int64) reader.read_int8 ();
case 1: return (int64) reader.read_int16 ();
case 2: return (int64) reader.read_int32 ();
case 3: return (int64) reader.read_int64 ();
}
throw new Error.NOT_SUPPORTED ("Unsupported OPACK type 0x%02x", v);
case 4:
case 5:
case 6:
return read_string (v - 0x40);
case 7:
case 8:
case 9:
return read_data (v - 0x70);
case 0xe:
return read_dictionary (bottom);
default:
throw new Error.NOT_SUPPORTED ("Unsupported OPACK type 0x%02x", v);
}
}
private Variant read_string (size_t len) throws Error {
if (len == 0x2f)
return reader.read_string ();
len = read_variable_length (len);
return reader.read_fixed_string (len);
}
private Variant read_data (size_t len) throws Error {
len = read_variable_length (len);
var bytes = reader.read_bytes (len);
return Variant.new_from_data (new VariantType.array (VariantType.BYTE), bytes.get_data (), true, bytes);
}
private size_t read_variable_length (size_t len) throws Error {
if (len <= 0x20)
return len;
switch (len) {
case 0x21:
return reader.read_uint8 ();
case 0x22:
return reader.read_uint16 ();
case 0x23:
uint32 bottom = reader.read_uint8 ();
uint32 top = reader.read_uint16 ();
return top << 8 | bottom;
case 0x24:
return reader.read_uint32 ();
default:
throw new Error.NOT_SUPPORTED ("Unsupported OPACK length: 0x%zx", len);
}
}
private Variant read_dictionary (size_t n) throws Error {
var builder = new VariantBuilder (VariantType.VARDICT);
bool has_terminator = n == 0xf;
size_t i = 0;
while (true) {
if (!has_terminator && i == n)
break;
var key = read_value (has_terminator ? ValueFlags.ALLOW_TERMINATOR : 0);
if (key == null)
break;
if (!key.is_of_type (VariantType.STRING))
throw new Error.PROTOCOL ("Unsupported OPACK dictionary key type");
var val = read_value ();
builder.add_value (new Variant.dict_entry (key, new Variant.variant (val)));
i++;
}
return builder.end ();
}
}
}
+109 -66
View File
@@ -1,34 +1,32 @@
[CCode (gir_namespace = "FridaFruity", gir_version = "1.0")]
namespace Frida.Fruity {
internal sealed class UsbDevice : Object, AsyncInitable {
internal sealed class UsbDevice : Object {
public string udid {
get;
construct;
}
public LibUSB.Device? raw_device {
get {
return _raw_device;
}
}
public UsbDeviceBackend backend {
get;
construct;
}
public LibUSB.DeviceHandle? handle {
get {
return _handle;
}
}
public string udid {
get {
return _udid;
}
}
public uint16 default_language_id {
get {
return _default_language_id;
}
}
private LibUSB.Device? _raw_device;
private LibUSB.DeviceHandle? _handle;
private string _udid;
private uint16 _default_language_id;
private uint num_pending_operations;
private Promise<bool>? pending_operations_completed;
private enum AppleSpecificRequest {
GET_MODE = 0x45,
@@ -38,85 +36,95 @@ namespace Frida.Fruity {
private const string MODE_INITIAL_UNTETHERED = "3:3:3:0"; // => 5:3:3:0
private const string MODE_INITIAL_TETHERED = "4:4:3:4"; // => 5:4:3:4
public static async UsbDevice open (LibUSB.Device raw_device, Cancellable? cancellable = null) throws Error, IOError {
var device = new UsbDevice (raw_device);
public UsbDevice (LibUSB.Device raw_device, UsbDeviceBackend backend) throws Error {
char serial[LibUSB.DEVICE_STRING_BYTES_MAX + 1];
var res = raw_device.get_device_string (SERIAL_NUMBER, serial);
Usb.check (res, "Failed to get serial number");
serial[res] = '\0';
try {
yield device.init_async (Priority.DEFAULT, cancellable);
} catch (GLib.Error e) {
throw_api_error (e);
}
Object (
udid: udid_from_serial_number ((string) serial),
backend: backend
);
return device;
}
private UsbDevice (LibUSB.Device raw_device) {
Object ();
_raw_device = raw_device;
}
private async bool init_async (int io_priority, Cancellable? cancellable) throws Error, IOError {
public void ensure_open (Cancellable? cancellable = null) throws Error {
if (_handle != null)
return;
Usb.check (_raw_device.open (out _handle), "Failed to open USB device");
Bytes language_ids_response = yield read_string_descriptor_bytes (0, 0, cancellable);
if (language_ids_response.get_size () < sizeof (uint16))
throw new Error.PROTOCOL ("Invalid language IDs response");
Buffer language_ids = new Buffer (language_ids_response, LITTLE_ENDIAN);
_default_language_id = language_ids.read_uint16 (0);
var dev_desc = LibUSB.DeviceDescriptor (_raw_device);
string serial_number = yield read_string_descriptor (dev_desc.iSerialNumber, _default_language_id, cancellable);
_udid = udid_from_serial_number (serial_number);
return true;
}
public void close () {
public async void close (Cancellable? cancellable) throws IOError {
if (num_pending_operations != 0) {
pending_operations_completed = new Promise<bool> ();
try {
yield pending_operations_completed.future.wait_async (cancellable);
} catch (Error e) {
assert_not_reached ();
}
pending_operations_completed = null;
}
_handle = null;
_raw_device = null;
}
public async bool maybe_modeswitch (Cancellable? cancellable) throws Error, IOError {
var response = yield control_transfer (
uint8 current_mode[4];
var n = yield control_transfer (
LibUSB.RequestRecipient.DEVICE | LibUSB.RequestType.VENDOR | LibUSB.EndpointDirection.IN,
AppleSpecificRequest.GET_MODE,
0,
0,
4,
current_mode,
1000,
cancellable);
string mode = parse_mode (response);
string mode = parse_mode (current_mode[:n]);
bool is_initial_mode = mode == MODE_INITIAL_UNTETHERED || mode == MODE_INITIAL_TETHERED;
if (!is_initial_mode)
return false;
response = yield control_transfer (
uint8 set_mode_result[1];
var set_mode_result_size = yield control_transfer (
LibUSB.RequestRecipient.DEVICE | LibUSB.RequestType.VENDOR | LibUSB.EndpointDirection.IN,
AppleSpecificRequest.SET_MODE,
0,
3,
1,
set_mode_result,
1000,
cancellable);
if (response.get_size () != 1 || response[0] != 0x00)
if (set_mode_result_size != 1 || set_mode_result[0] != 0x00)
return false;
return true;
}
private static string parse_mode (Bytes mode) throws Error {
if (mode.get_size () != 4)
throw new Error.PROTOCOL ("Invalid mode response");
unowned uint8[] m = mode.get_data ();
return "%u:%u:%u:%u".printf (m[0], m[1], m[2], m[3]);
private static string parse_mode (uint8[] mode) throws Error {
var result = new StringBuilder.sized (7);
foreach (uint8 byte in mode) {
if (result.len != 0)
result.append_c (':');
result.append_printf ("%u", byte);
}
return result.str;
}
private static string udid_from_serial_number (string serial) {
public static string udid_from_serial_number (string serial) {
if (serial.length == 24)
return serial.substring (0, 8) + "-" + serial.substring (8);
return serial[:8] + "-" + serial[8:];
return serial;
}
public async uint16 query_default_language_id (Cancellable? cancellable) throws Error, IOError {
Bytes language_ids_response = yield read_string_descriptor_bytes (0, 0, cancellable);
if (language_ids_response.get_size () < sizeof (uint16))
throw new Error.PROTOCOL ("Invalid language IDs response");
Buffer language_ids = new Buffer (language_ids_response, LITTLE_ENDIAN);
return language_ids.read_uint16 (0);
}
public async string read_string_descriptor (uint8 index, uint16 language_id, Cancellable? cancellable)
throws Error, IOError {
var response = yield read_string_descriptor_bytes (index, language_id, cancellable);
@@ -141,16 +149,17 @@ namespace Frida.Fruity {
public async Bytes read_string_descriptor_bytes (uint8 index, uint16 language_id, Cancellable? cancellable)
throws Error, IOError {
var response = yield control_transfer (
uint8 response[1024];
var response_size = yield control_transfer (
LibUSB.RequestRecipient.DEVICE | LibUSB.RequestType.STANDARD | LibUSB.EndpointDirection.IN,
LibUSB.StandardRequest.GET_DESCRIPTOR,
(LibUSB.DescriptorType.STRING << 8) | index,
language_id,
1024,
response,
1000,
cancellable);
try {
var input = new DataInputStream (new MemoryInputStream.from_bytes (response));
var input = new DataInputStream (new MemoryInputStream.from_data (response[:response_size]));
input.byte_order = LITTLE_ENDIAN;
uint8 length = input.read_byte ();
@@ -161,25 +170,29 @@ namespace Frida.Fruity {
if (type != LibUSB.DescriptorType.STRING)
throw new Error.PROTOCOL ("Invalid string descriptor type");
size_t remainder = response.get_size () - 2;
size_t remainder = response_size - 2;
length -= 2;
if (length > remainder)
throw new Error.PROTOCOL ("Invalid string descriptor length");
return response[2:2 + length];
return new Bytes (response[2:2 + length]);
} catch (GLib.Error e) {
throw new Error.PROTOCOL ("%s", e.message);
}
}
public async Bytes control_transfer (uint8 request_type, uint8 request, uint16 val, uint16 index, uint16 length,
public async size_t control_transfer (uint8 request_type, uint8 request, uint16 val, uint16 index, uint8[] buffer,
uint timeout, Cancellable? cancellable) throws Error, IOError {
var transfer = new LibUSB.Transfer ();
var op = backend.allocate_usb_operation ();
unowned LibUSB.Transfer transfer = op.transfer;
var ready_closure = new TransferReadyClosure (control_transfer.callback);
var buffer = new uint8[sizeof (LibUSB.ControlSetup) + length];
LibUSB.Transfer.fill_control_setup (buffer, request_type, request, val, index, length);
transfer.fill_control_transfer (_handle, buffer, on_transfer_ready, ready_closure, timeout);
size_t control_setup_size = 8;
var transfer_buffer = new uint8[control_setup_size + buffer.length];
LibUSB.Transfer.fill_control_setup (transfer_buffer, request_type, request, val, index, (uint16) buffer.length);
if ((request_type & LibUSB.EndpointDirection.IN) == 0)
Memory.copy ((uint8 *) transfer_buffer + control_setup_size, buffer, buffer.length);
transfer.fill_control_transfer (_handle, transfer_buffer, on_transfer_ready, ready_closure, timeout);
var cancel_source = new CancellableSource (cancellable);
cancel_source.set_callback (() => {
@@ -190,19 +203,27 @@ namespace Frida.Fruity {
try {
Usb.check (transfer.submit (), "Failed to submit control transfer");
on_operation_started ();
yield;
on_operation_ended ();
} finally {
cancel_source.destroy ();
}
Usb.check_transfer (transfer.status, "Control transfer failed");
return new Bytes (((uint8[]) transfer.control_get_data ())[:transfer.actual_length]);
var n = transfer.actual_length;
if ((request_type & LibUSB.EndpointDirection.IN) != 0)
Memory.copy (buffer, transfer.control_get_data (), n);
return n;
}
public async size_t bulk_transfer (uint8 endpoint, uint8[] buffer, uint timeout, Cancellable? cancellable)
throws Error, IOError {
var transfer = new LibUSB.Transfer ();
var op = backend.allocate_usb_operation ();
unowned LibUSB.Transfer transfer = op.transfer;
var ready_closure = new TransferReadyClosure (bulk_transfer.callback);
transfer.fill_bulk_transfer (_handle, endpoint, buffer, on_transfer_ready, ready_closure, timeout);
@@ -216,7 +237,9 @@ namespace Frida.Fruity {
try {
Usb.check (transfer.submit (), "Failed to submit bulk transfer");
on_operation_started ();
yield;
on_operation_ended ();
} finally {
cancel_source.destroy ();
}
@@ -226,6 +249,16 @@ namespace Frida.Fruity {
return transfer.actual_length;
}
private void on_operation_started () {
num_pending_operations++;
}
private void on_operation_ended () {
num_pending_operations--;
if (num_pending_operations == 0 && pending_operations_completed != null)
pending_operations_completed.resolve (true);
}
private static void on_transfer_ready (LibUSB.Transfer transfer) {
TransferReadyClosure * closure = transfer.user_data;
closure->schedule ();
@@ -252,6 +285,16 @@ namespace Frida.Fruity {
}
}
internal interface UsbDeviceBackend : Object {
public abstract UsbOperation allocate_usb_operation () throws Error;
}
internal interface UsbOperation : Object {
public abstract LibUSB.Transfer transfer {
get;
}
}
namespace Usb {
internal static void check (LibUSB.Error error, string prefix) throws Error {
if (error >= LibUSB.Error.SUCCESS)
+840 -375
View File
File diff suppressed because it is too large. Load diff
+7 -4
View File
@@ -1335,10 +1335,11 @@ namespace Frida {
protected virtual void on_event (string type, Json.Array event) {
}
protected async Json.Node call (string method, Json.Node[] args, Cancellable? cancellable) throws Error, IOError {
protected async Json.Node call (string method, Json.Node[] args, Bytes? data, Cancellable? cancellable)
throws Error, IOError {
yield ensure_loaded (cancellable);
return yield rpc_client.call (method, args, cancellable);
return yield rpc_client.call (method, args, data, cancellable);
}
protected async void post (Json.Node message, Cancellable? cancellable) throws Error, IOError {
@@ -1508,9 +1509,11 @@ namespace Frida {
printerr ("%s\n", json);
}
private async void post_rpc_message (string json, Cancellable? cancellable) throws Error, IOError {
private async void post_rpc_message (string json, Bytes? data, Cancellable? cancellable) throws Error, IOError {
var has_data = data != null;
var data_param = has_data ? data.get_data () : new uint8[0];
try {
yield session.post_messages ({ AgentMessage (SCRIPT, script, json, false, {}) }, 0, cancellable);
yield session.post_messages ({ AgentMessage (SCRIPT, script, json, has_data, data_param) }, 0, cancellable);
} catch (GLib.Error e) {
throw_dbus_error (e);
}
+53 -14
View File
@@ -854,12 +854,12 @@ namespace Frida {
private static ProcMapsEntry? local_android_ld;
static construct {
string libc_name = Gum.Process.query_libc_name ();
var libc = Gum.Process.get_libc_module ();
uint local_pid = Posix.getpid ();
local_libc = ProcMapsEntry.find_by_path (local_pid, libc_name);
local_libc = ProcMapsEntry.find_by_path (local_pid, libc.path);
assert (local_libc != null);
mmap_offset = (uint64) (uintptr) Gum.Module.find_export_by_name (libc_name, "mmap") - local_libc.base_address;
munmap_offset = (uint64) (uintptr) Gum.Module.find_export_by_name (libc_name, "munmap") - local_libc.base_address;
mmap_offset = (uint64) (uintptr) libc.find_export_by_name ("mmap") - local_libc.base_address;
munmap_offset = (uint64) (uintptr) libc.find_export_by_name ("munmap") - local_libc.base_address;
try {
var program = new Gum.ElfModule.from_file ("/proc/self/exe");
@@ -1017,8 +1017,9 @@ namespace Frida {
establish_connection (launch, spec, bres, agent_ctrl, fallback_address, cancellable);
uint64 loader_base = (uintptr) bres.context.allocation_base;
var call_builder = new RemoteCallBuilder (loader_base, saved_regs);
GPRegs regs = saved_regs;
regs.stack_pointer = bres.allocated_stack.stack_root;
var call_builder = new RemoteCallBuilder (loader_base, regs);
call_builder.add_argument (loader_base + loader_layout.ctx_offset);
RemoteCall loader_call = call_builder.build (this);
RemoteCallResult loader_result = yield loader_call.execute (cancellable);
@@ -1076,8 +1077,10 @@ namespace Frida {
unowned uint8[] bootstrapper_code = Frida.Data.HelperBackend.get_bootstrapper_bin_blob ().data;
size_t bootstrapper_size = round_size_to_page_size (bootstrapper_code.length);
size_t stack_size = 64 * 1024;
uint64 allocation_base = 0;
size_t allocation_size = size_t.max (bootstrapper_size, loader_size);
size_t allocation_size = size_t.max (bootstrapper_size, loader_size) + stack_size;
uint64 remote_mmap = 0;
uint64 remote_munmap = 0;
@@ -1117,10 +1120,12 @@ namespace Frida {
Memory.copy (&bootstrap_ctx, output_context, output_context.length);
allocation_base = (uintptr) bootstrap_ctx.allocation_base;
code_swap.revert ();
}
result.allocated_stack.stack_base = (void *) (allocation_base + allocation_size - stack_size);
result.allocated_stack.stack_size = stack_size;
try {
write_memory (allocation_base, bootstrapper_code);
maybe_fixup_helper_code (allocation_base, bootstrapper_code);
@@ -1129,7 +1134,9 @@ namespace Frida {
HelperBootstrapStatus status = SUCCESS;
do {
var call_builder = new RemoteCallBuilder (code_start, saved_regs);
GPRegs regs = saved_regs;
regs.stack_pointer = result.allocated_stack.stack_root;
var call_builder = new RemoteCallBuilder (code_start, regs);
unowned uint8[] fallback_ld_data = fallback_ld.data;
unowned uint8[] fallback_libc_data = fallback_libc.data;
@@ -1416,14 +1423,28 @@ namespace Frida {
}
}
private struct AllocatedStack {
public void * stack_base;
public size_t stack_size;
public uint64 stack_root {
get {
return (uint64) stack_base + (uint64) stack_size;
}
}
}
private class BootstrapResult {
public HelperBootstrapContext context;
public HelperLibcApi libc;
public AllocatedStack allocated_stack;
public BootstrapResult clone () {
var res = new BootstrapResult ();
res.context = context;
res.libc = libc;
res.allocated_stack = allocated_stack;
return res;
}
}
@@ -1931,6 +1952,10 @@ namespace Frida {
try {
yield suspend (null);
close ();
} catch (Error e) {
// If the process is gone, then there's no point in retrying.
if (e is Error.PROCESS_NOT_FOUND)
attach_state = ALREADY_ATTACHED;
} catch (GLib.Error e) {
}
}
@@ -3306,10 +3331,18 @@ namespace Frida {
public static ProcMapsEntry? find_by_path (uint pid, string path) {
var iter = MapsIter.for_pid (pid);
#if ANDROID
unowned string libc_path = Gum.Process.get_libc_module ().path;
#endif
while (iter.next ()) {
string candidate_path = iter.path;
if (candidate_path == path)
if (candidate_path == path) {
#if ANDROID
if (candidate_path == libc_path && iter.flags[3] == 's')
continue;
#endif
return new ProcMapsEntry (iter.start_address, candidate_path, iter.identity);
}
}
return null;
@@ -3332,18 +3365,24 @@ namespace Frida {
}
}
public string identity {
public string flags {
owned get {
return info.fetch (3);
}
}
public string path {
public string identity {
owned get {
return info.fetch (4);
}
}
public string path {
owned get {
return info.fetch (5);
}
}
public static MapsIter for_pid (uint pid) {
return new MapsIter (pid);
}
@@ -3355,8 +3394,8 @@ namespace Frida {
return;
}
if (!/^([0-9a-f]+)-([0-9a-f]+) \S{4} [0-9a-f]+ ([0-9a-f]{2,}:[0-9a-f]{2,} \d+) +([^\n]+)$/m.match (contents,
0, out info)) {
if (!/^([0-9a-f]+)-([0-9a-f]+) (\S{4}) [0-9a-f]+ ([0-9a-f]{2,}:[0-9a-f]{2,} \d+) +([^\n]+)$/m.match (
contents, 0, out info)) {
assert_not_reached ();
}
}
+7 -10
View File
@@ -2,24 +2,21 @@ top_srcdir := ../../..
releng := $(top_srcdir)/releng
BUILDDIR ?= $(top_srcdir)/build
FRIDA_MONOREPO ?= $(top_srcdir)/..
MESON ?= $(releng)/meson/meson.py
ifdef FRIDA_HOST
host_os := $(shell echo $(FRIDA_HOST) | cut -f1 -d"-")
host_arch := $(shell echo $(FRIDA_HOST) | cut -f2 -d"-")
host_machine := $(FRIDA_HOST)
else
host_os := $(shell $(releng)/detect-os.sh)
host_arch := $(shell $(releng)/detect-arch.sh)
host_machine := $(shell basename $$(ls -1 $(BUILDDIR)/frida-linux-*.txt | tail -1) | cut -d"." -f1 | cut -d"-" -f2-)
endif
host_arch := $(shell echo $(host_machine) | cut -d"-" -f2)
crossfile := $(shell test -d "$(BUILDDIR)" \
&& echo "$(BUILDDIR)/frida-$(host_os)-$(host_arch).txt" \
|| echo $(FRIDA_MONOREPO)/build/frida*-$(host_os)-$(host_arch).txt)
crossfile := $(BUILDDIR)/frida-$(host_machine).txt
build: ext/linux/tools/include/nolibc/nolibc.h
rm -rf build
meson setup --cross-file $(crossfile) -Db_lto=true build
meson compile -C build
$(MESON) setup --cross-file $(crossfile) -Db_lto=true build
$(MESON) compile -C build
cp build/bootstrapper.bin bootstrapper-$(host_arch).bin
cp build/loader.bin loader-$(host_arch).bin
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6 -2
View File
@@ -550,7 +550,9 @@ frida_infer_rtld_flavor_from_filename (const char * name)
if (frida_str_has_prefix (name, "ld-uClibc"))
return FRIDA_RTLD_UCLIBC;
if (strcmp (name, "libc.so") == 0)
if (strcmp (name, "libc.so") == 0 ||
frida_str_has_prefix (name, "libc.musl") ||
frida_str_has_prefix (name, "ld-musl"))
return FRIDA_RTLD_MUSL;
if (strcmp (name, "ld-android.so") == 0)
@@ -607,7 +609,9 @@ frida_path_is_libc (const char * path, FridaRtldFlavor rtld_flavor)
else
name = path;
return frida_str_has_prefix (name, "libc.so");
return frida_str_has_prefix (name, "libc.so") ||
frida_str_has_prefix (name, "libc.musl") ||
frida_str_has_prefix (name, "ld-musl");
}
static ssize_t
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6 -1
View File
@@ -24,6 +24,10 @@ if host_machine.cpu_family() == 'arm'
extra_flags += '-marm'
endif
if host_machine.cpu_family() == 'x86'
extra_flags += '-fno-stack-protector'
endif
common_objcopy_flags = [
'-O', 'binary',
'-S',
@@ -53,9 +57,10 @@ extra_link_args = [
'-Wl,-T,' + helper_lds,
]
if host_machine.cpu_family() == 'arm'
extra_link_args += run_command('../../../../build/frida-android-arm-clang', '-print-libgcc-file-name', check: false).stdout().strip()
extra_link_args += run_command(cc, '-print-libgcc-file-name', check: false).stdout().strip()
endif
bootstrapper_sources = [
'bootstrapper.c',
'elf-parser.c',
-23
View File
@@ -303,26 +303,3 @@ index 78473d34e..f17e6f598 100644
+ mode = va_arg(args, /* mode_t */ unsigned int);
va_end(args);
}
diff --git a/tools/include/nolibc/types.h b/tools/include/nolibc/types.h
index fbbc0e68c..d003c368d 100644
--- a/tools/include/nolibc/types.h
+++ b/tools/include/nolibc/types.h
@@ -92,6 +92,8 @@
#define FD_SETIDXMASK (8 * sizeof(unsigned long))
#define FD_SETBITMASK (8 * sizeof(unsigned long)-1)
+#ifndef __mips__
+
/* for select() */
typedef struct {
unsigned long fds[(FD_SETSIZE + FD_SETBITMASK) / FD_SETIDXMASK];
@@ -131,6 +133,8 @@ typedef struct {
__set->fds[__idx] = 0; \
} while (0)
+#endif
+
/* for poll() */
#define POLLIN 0x0001
#define POLLPRI 0x0002
+100
View File
@@ -0,0 +1,100 @@
#!/bin/bash
# This script is responsible for building Frida helpers for various Linux
# architectures. It can build helpers for a single specified architecture on the
# local machine, or for supported architectures in a container. The script uses
# Docker containers to ensure consistent build environments for each
# architecture.
#
# Note that the expectation is that when running the build for a specific
# architecture that it be run from inside the relevant container. This script is
# used by CI.
set -euo pipefail
CURRENT_FILE="${BASH_SOURCE[0]}"
HELPERS_DIR="$(cd "$(dirname "$CURRENT_FILE")" && pwd)"
FRIDA_CORE_DIR="$(cd "$HELPERS_DIR/../../.." && pwd)"
RELENG_DIR="$FRIDA_CORE_DIR/releng"
BUILD_DIR="$FRIDA_CORE_DIR/build"
RELATIVE_TO_FRIDA_CORE_DIR=$(realpath --relative-to="$FRIDA_CORE_DIR" "$CURRENT_FILE")
TMP_MESON_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_MESON_DIR"' EXIT
CONTAINER_REGISTRY="${CONTAINER_REGISTRY:-ghcr.io/frida}"
main () {
if [ "$#" -eq 0 ]; then
build_arches_in_container
return
fi
if [ "$#" -gt 1 ]; then
echo >&2 "Error: Too many arguments"
usage
fi
build_arch "$1"
}
usage () {
echo >&2 "Usage: $0 [<arch>]"
echo >&2 "If no arch is specified, then all helpers will be built in the container."
exit 1
}
ARCHS=(
x86
x86_64
arm
arm64
mips
mipsel
mips64
mips64el
)
build_arch () {
ARCH=$1
if [ -z "$ARCH" ]; then
usage
fi
if ! printf '%s\n' "${ARCHS[@]}" | grep -qx "$ARCH"; then
echo >&2 "Error: Invalid architecture '$ARCH'"
echo >&2 "Supported architectures: ${ARCHS[*]}"
exit 1
fi
if [[ "$ARCH" == arm* ]]; then
export FRIDA_HOST=android-$ARCH
else
export FRIDA_HOST=linux-$ARCH
fi
EXTRA_FLAGS=()
if [ "$FRIDA_HOST" == "linux-x86" ]; then
EXTRA_FLAGS+=("--build=linux-x86")
export CC="gcc -m32" CXX="g++ -m32" STRIP="strip"
fi
cd "$FRIDA_CORE_DIR"
rm -rf "$BUILD_DIR"
# Note that $XTOOLS_HOST is set by the container.
./configure --host="$XTOOLS_HOST" "${EXTRA_FLAGS[@]}"
make -C src/linux/helpers
}
build_arches_in_container () {
for ARCH in "${ARCHS[@]}"; do
docker run -u "$(id -u):$(id -g)" \
-w /frida-core \
-i -t \
-v "$FRIDA_CORE_DIR:/frida-core" \
"$CONTAINER_REGISTRY/core-linux-helpers-$ARCH:latest" \
"/frida-core/$RELATIVE_TO_FRIDA_CORE_DIR" "$ARCH"
done
}
main "$@"
+10 -9
View File
@@ -894,7 +894,7 @@ namespace Frida {
var scope = options.scope;
var scope_node = new Json.Node.alloc ().init_string (scope.to_nick ());
Json.Node result = yield call ("getFrontmostApplication", new Json.Node[] { scope_node }, cancellable);
Json.Node result = yield call ("getFrontmostApplication", new Json.Node[] { scope_node }, null, cancellable);
if (result.get_node_type () == NULL)
return HostApplicationInfo.empty ();
@@ -920,7 +920,7 @@ namespace Frida {
var scope = options.scope;
var scope_node = new Json.Node.alloc ().init_string (scope.to_nick ());
Json.Node apps = yield call ("enumerateApplications", new Json.Node[] { identifiers_node, scope_node },
Json.Node apps = yield call ("enumerateApplications", new Json.Node[] { identifiers_node, scope_node }, null,
cancellable);
var items = apps.get_array ();
@@ -946,7 +946,7 @@ namespace Frida {
var package_name_node = new Json.Node.alloc ().init_string (package);
var uid_node = new Json.Node.alloc ().init_int (uid);
Json.Node name = yield call ("getProcessName", new Json.Node[] { package_name_node, uid_node }, cancellable);
Json.Node name = yield call ("getProcessName", new Json.Node[] { package_name_node, uid_node }, null, cancellable);
return name.get_string ();
}
@@ -960,7 +960,8 @@ namespace Frida {
var scope_node = new Json.Node.alloc ().init_string (scope.to_nick ());
Json.Node by_pid = yield call ("getProcessParameters", new Json.Node[] { pids_node, scope_node }, cancellable);
Json.Node by_pid = yield call ("getProcessParameters", new Json.Node[] { pids_node, scope_node }, null,
cancellable);
var result = new Gee.HashMap<uint, HashTable<string, Variant>> ();
by_pid.get_object ().foreach_member ((object, pid_str, parameters_node) => {
@@ -982,20 +983,20 @@ namespace Frida {
if (entrypoint is DefaultActivityEntrypoint) {
var activity_node = new Json.Node.alloc ().init_null ();
yield call ("startActivity", new Json.Node[] { package_node, activity_node, uid_node }, cancellable);
yield call ("startActivity", new Json.Node[] { package_node, activity_node, uid_node }, null, cancellable);
} else if (entrypoint is ActivityEntrypoint) {
var e = entrypoint as ActivityEntrypoint;
var activity_node = new Json.Node.alloc ().init_string (e.activity);
yield call ("startActivity", new Json.Node[] { package_node, activity_node, uid_node }, cancellable);
yield call ("startActivity", new Json.Node[] { package_node, activity_node, uid_node }, null, cancellable);
} else if (entrypoint is BroadcastReceiverEntrypoint) {
var e = entrypoint as BroadcastReceiverEntrypoint;
var receiver_node = new Json.Node.alloc ().init_string (e.receiver);
var action_node = new Json.Node.alloc ().init_string (e.action);
yield call ("sendBroadcast", new Json.Node[] { package_node, receiver_node, action_node, uid_node },
yield call ("sendBroadcast", new Json.Node[] { package_node, receiver_node, action_node, uid_node }, null,
cancellable);
} else {
assert_not_reached ();
@@ -1006,13 +1007,13 @@ namespace Frida {
var package_node = new Json.Node.alloc ().init_string (package);
var uid_node = new Json.Node.alloc ().init_int (uid);
yield call ("stopPackage", new Json.Node[] { package_node, uid_node }, cancellable);
yield call ("stopPackage", new Json.Node[] { package_node, uid_node }, null, cancellable);
}
public async bool try_stop_package_by_pid (uint pid, Cancellable? cancellable) throws Error, IOError {
var pid_node = new Json.Node.alloc ().init_int (pid);
Json.Node success = yield call ("tryStopPackageByPid", new Json.Node[] { pid_node }, cancellable);
Json.Node success = yield call ("tryStopPackageByPid", new Json.Node[] { pid_node }, null, cancellable);
return success.get_boolean ();
}
+52 -1
View File
@@ -3,6 +3,7 @@
#include <pwd.h>
#include <string.h>
#include <unistd.h>
#include <gio/gunixmounts.h>
typedef struct _FridaEnumerateProcessesOperation FridaEnumerateProcessesOperation;
@@ -13,6 +14,8 @@ struct _FridaEnumerateProcessesOperation
};
static void frida_collect_process_info (guint pid, FridaEnumerateProcessesOperation * op);
static gboolean frida_is_directory_noexec (const gchar * directory);
static gchar * frida_get_application_directory (void);
static gboolean frida_add_process_metadata (GHashTable * parameters, const gchar * proc_entry_name);
static GDateTime * frida_query_boot_time (void);
static GVariant * frida_uid_to_name (uid_t uid);
@@ -151,12 +154,60 @@ frida_system_kill (guint pid)
gchar *
frida_temporary_directory_get_system_tmp (void)
{
const gchar * tmp_dir;
#ifdef HAVE_ANDROID
if (getuid () == 0)
return g_strdup ("/data/local/tmp");
#endif
return g_strdup (g_get_tmp_dir ());
tmp_dir = g_get_tmp_dir ();
/*
* If the temporary directory resides on a file-system which is marked
* `noexec`, then we won't be able to write the frida-agent.so there and
* subsequently dlopen() it inside the target application as it will result in
* permission denied.
*
* The mounting of the temporary file-system as `noexec` is sometimes used as
* an added security measure on embedded systems where the functionality is
* fixed and we aren't expecting any interactive user sessions.
*
* Since our current process is executing, we know that it must reside on a
* file-system which is not mounted `noexec`. Whilst it is possible that it is
* mounted read-only, or there may be some other reason why it isn't suitable,
* we know that the temporary directory is definitely unusable. If both these
* locations are found to be unsuitable, then a future implementation may seek
* to validate an ordered list of potential locations.
*/
if (frida_is_directory_noexec (tmp_dir))
return frida_get_application_directory ();
else
return g_strdup (tmp_dir);
}
static gboolean
frida_is_directory_noexec (const gchar * directory)
{
gboolean is_noexec;
g_autoptr(GUnixMountEntry) entry;
gchar ** options;
entry = g_unix_mount_for (directory, NULL);
if (entry == NULL)
return FALSE;
options = g_strsplit (g_unix_mount_get_options (entry), ",", 0);
is_noexec = g_strv_contains ((const char * const *) options, "noexec");
g_strfreev (options);
return is_noexec;
}
static gchar *
frida_get_application_directory (void)
{
return g_path_get_dirname (gum_module_get_path (gum_process_get_main_module ()));
}
static gboolean
+26 -7
View File
@@ -44,6 +44,14 @@ if have_local_backend
'@INPUT0@',
]
if helper_emulated_modern == 'auto'
helper_emulated_modern = ''
endif
if helper_emulated_legacy == 'auto'
helper_emulated_legacy = ''
endif
if host_os_family == 'windows'
backend_sources += [
'windows' / 'windows-host-session.vala',
@@ -54,6 +62,7 @@ if have_local_backend
'windows' / 'frida-helper-process-glue.c',
'windows' / 'access-helpers.c',
]
backend_vala_args += '--pkg=frida-gum-windows-1.0'
helper_backend_sources = [
'windows' / 'frida-helper-backend.vala',
@@ -61,7 +70,10 @@ if have_local_backend
'windows' / 'frida-helper-types.vala',
'windows' / 'wait-handle-source.c',
]
helper_backend_vala_args = base_vala_args
helper_backend_vala_args = [
base_vala_args,
'--pkg=frida-gum-windows-1.0',
]
helper_backend = static_library('frida-helper-backend', helper_backend_sources,
vala_args: helper_backend_vala_args,
c_args: frida_component_cflags,
@@ -105,7 +117,7 @@ if have_local_backend
'frida-data-helper-process.c',
'frida-data-helper-process-blob' + resource_blob_extension,
],
command: embed_helper + [helper_modern, helper_legacy],
command: embed_helper + [helper_modern, helper_legacy, helper_emulated_modern, helper_emulated_legacy],
depends: helper_depends,
)
backend_sources += [helper_process_data]
@@ -177,6 +189,7 @@ if have_local_backend
helper_backend_vala_args,
gum_vala_args,
'--pkg=frida-gum-darwin-1.0',
'--pkg=gmodule-2.0',
'--pkg=gio-unix-2.0',
'--pkg=posix',
],
@@ -253,7 +266,7 @@ if have_local_backend
'frida-data-helper-process.c',
'frida-data-helper-process-blob' + resource_blob_extension,
],
command: embed_helper + [helper_modern, helper_legacy],
command: embed_helper + [helper_modern, helper_legacy, helper_emulated_modern, helper_emulated_legacy],
depends: helper_depends,
)
backend_sources += [helper_process_data]
@@ -406,7 +419,7 @@ if have_local_backend
'frida-data-helper-process.c',
'frida-data-helper-process-blob' + resource_blob_extension,
],
command: embed_helper + [helper_modern, helper_legacy],
command: embed_helper + [helper_modern, helper_legacy, helper_emulated_modern, helper_emulated_legacy],
depends: helper_depends,
)
backend_sources += [helper_process_data]
@@ -490,15 +503,19 @@ if have_fruity_backend
'fruity' / 'lldb.vala',
'fruity' / 'injector.vala',
'fruity' / 'usbmux.vala',
'fruity' / 'dns.vala',
'fruity' / 'keyed-archive.vala',
'fruity' / 'plist.vala',
'fruity' / 'plist-service.vala',
'fruity' / 'opack.vala',
'fruity' / 'network-stack.vala',
'fruity' / 'usb.vala',
'fruity' / 'ncm.vala',
]
if host_os == 'macos'
if host_os_family == 'windows'
backend_sources += 'fruity' / 'device-monitor-windows.vala'
elif host_os == 'macos'
backend_sources += 'fruity' / 'device-monitor-macos.vala'
elif host_os == 'linux'
backend_sources += 'fruity' / 'device-monitor-linux.vala'
@@ -521,7 +538,9 @@ if have_fruity_backend
'--pkg=lwip',
'--pkg=openssl',
]
if host_os_family == 'darwin'
if host_os_family == 'windows'
backend_vala_args += '--pkg=windows-windns'
elif host_os_family == 'darwin'
backend_vala_args += [
'--pkg=darwin-xnu',
'--pkg=darwin-xpc',
@@ -562,7 +581,7 @@ subdir('compiler')
core_sources = base_sources + backend_sources + compiler_sources
internal_libs = [base, pipe] + backend_libs
internal_libs = [base, netif, pipe] + backend_libs
internal_deps = [base_dep, netif_dep, pipe_dep]
if host_os_family == 'windows'
+161 -131
View File
@@ -2,6 +2,7 @@
#include <gio/gio.h>
#include <gum/gum.h>
#include <gum/arch-arm64/gumarm64writer.h>
#include <gum/arch-x86/gumx86writer.h>
#include <windows.h>
@@ -75,6 +76,7 @@ static void frida_propagate_open_process_error (guint32 pid, DWORD os_error, GEr
static gboolean frida_enable_debug_privilege (void);
static gboolean frida_remote_worker_context_init (FridaRemoteWorkerContext * rwc, FridaInjectionDetails * details, GError ** error);
static gsize frida_remote_worker_context_emit_payload (FridaRemoteWorkerContext * rwc, gpointer code);
static void frida_remote_worker_context_destroy (FridaRemoteWorkerContext * rwc, FridaInjectionDetails * details);
static gboolean frida_remote_worker_context_has_resolved_all_kernel32_functions (const FridaRemoteWorkerContext * rwc);
@@ -304,16 +306,169 @@ frida_remote_worker_context_init (FridaRemoteWorkerContext * rwc, FridaInjection
{
gpointer code;
guint code_size;
GumX86Writer cw;
const gchar * loadlibrary_failed = "loadlibrary_failed";
const gchar * skip_unload = "skip_unload";
const gchar * return_result = "return_result";
SIZE_T page_size, alloc_size;
DWORD old_protect;
gum_init ();
code = gum_alloc_n_pages (1, GUM_PAGE_RWX); /* Executable so debugger can be used to inspect code */
code_size = frida_remote_worker_context_emit_payload (rwc, code);
memset (rwc, 0, sizeof (FridaRemoteWorkerContext));
gum_module_enumerate_exports ("kernel32.dll", frida_remote_worker_context_collect_kernel32_export, rwc);
if (!frida_remote_worker_context_has_resolved_all_kernel32_functions (rwc))
goto failed_to_resolve_kernel32_functions;
StringCbCopyW (rwc->dll_path, sizeof (rwc->dll_path), details->dll_path);
StringCbCopyA (rwc->entrypoint_name, sizeof (rwc->entrypoint_name), details->entrypoint_name);
StringCbCopyA (rwc->entrypoint_data, sizeof (rwc->entrypoint_data), details->entrypoint_data);
page_size = gum_query_page_size ();
g_assert (code_size <= page_size);
alloc_size = page_size + sizeof (FridaRemoteWorkerContext);
rwc->entrypoint = VirtualAllocEx (details->process_handle, NULL, alloc_size, MEM_COMMIT, PAGE_READWRITE);
if (rwc->entrypoint == NULL)
goto virtual_alloc_ex_failed;
if (!WriteProcessMemory (details->process_handle, rwc->entrypoint, code, code_size, NULL))
goto write_process_memory_failed;
rwc->argument = GSIZE_TO_POINTER (GPOINTER_TO_SIZE (rwc->entrypoint) + page_size);
if (!WriteProcessMemory (details->process_handle, rwc->argument, rwc, sizeof (FridaRemoteWorkerContext), NULL))
goto write_process_memory_failed;
if (!VirtualProtectEx (details->process_handle, rwc->entrypoint, page_size, PAGE_EXECUTE_READ, &old_protect))
goto virtual_protect_ex_failed;
gum_free_pages (code);
return TRUE;
/* ERRORS */
failed_to_resolve_kernel32_functions:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error while resolving kernel32 functions");
goto error_common;
}
virtual_alloc_ex_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error allocating memory in target process (VirtualAllocEx returned 0x%08lx)",
GetLastError ());
goto error_common;
}
write_process_memory_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error writing to memory in target process (WriteProcessMemory returned 0x%08lx)",
GetLastError ());
goto error_common;
}
virtual_protect_ex_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error changing memory permission in target process (VirtualProtectEx returned 0x%08lx)",
GetLastError ());
goto error_common;
}
error_common:
{
frida_remote_worker_context_destroy (rwc, details);
gum_free_pages (code);
return FALSE;
}
}
#define EMIT_ARM64_LOAD(reg, field) \
gum_arm64_writer_put_ldr_reg_reg_offset (&cw, ARM64_REG_##reg, ARM64_REG_X20, G_STRUCT_OFFSET (FridaRemoteWorkerContext, field))
#define EMIT_ARM64_LOAD_ADDRESS_OF(reg, field) \
gum_arm64_writer_put_add_reg_reg_imm (&cw, ARM64_REG_##reg, ARM64_REG_X20, G_STRUCT_OFFSET (FridaRemoteWorkerContext, field))
#define EMIT_ARM64_MOVE(dstreg, srcreg) \
gum_arm64_writer_put_mov_reg_reg (&cw, ARM64_REG_##dstreg, ARM64_REG_##srcreg)
#define EMIT_ARM64_CALL(reg) \
gum_arm64_writer_put_blr_reg_no_auth (&cw, ARM64_REG_##reg)
static gsize
frida_remote_worker_context_emit_payload (FridaRemoteWorkerContext * rwc, gpointer code)
{
gsize code_size;
const gchar * loadlibrary_failed = "loadlibrary_failed";
const gchar * skip_unload = "skip_unload";
const gchar * return_result = "return_result";
#ifdef HAVE_ARM64
GumArm64Writer cw;
gum_arm64_writer_init (&cw, code);
gum_arm64_writer_put_push_reg_reg (&cw, ARM64_REG_FP, ARM64_REG_LR);
gum_arm64_writer_put_mov_reg_reg (&cw, ARM64_REG_FP, ARM64_REG_SP);
gum_arm64_writer_put_push_reg_reg (&cw, ARM64_REG_X19, ARM64_REG_X20);
/* x20 = (FridaRemoteWorkerContext *) lpParameter */
EMIT_ARM64_MOVE (X20, X0);
/* x19 = LoadLibrary (x20->dll_path) */
EMIT_ARM64_LOAD_ADDRESS_OF (X0, dll_path);
EMIT_ARM64_LOAD (X8, load_library_impl);
EMIT_ARM64_CALL (X8);
gum_arm64_writer_put_cbz_reg_label (&cw, ARM64_REG_X0, loadlibrary_failed);
EMIT_ARM64_MOVE (X19, X0);
/* x8 = GetProcAddress (x19, x20->entrypoint_name) */
EMIT_ARM64_MOVE (X0, X19);
EMIT_ARM64_LOAD_ADDRESS_OF (X1, entrypoint_name);
EMIT_ARM64_LOAD (X8, get_proc_address_impl);
EMIT_ARM64_CALL (X8);
EMIT_ARM64_MOVE (X8, X0);
/* x8 (x20->entrypoint_data, &x20->stay_resident, NULL) */
EMIT_ARM64_LOAD_ADDRESS_OF (X0, entrypoint_data);
EMIT_ARM64_LOAD_ADDRESS_OF (X1, stay_resident);
EMIT_ARM64_MOVE (X2, XZR);
EMIT_ARM64_CALL (X8);
/* if (!x20->stay_resident) { */
EMIT_ARM64_LOAD (X0, stay_resident);
gum_arm64_writer_put_cbnz_reg_label (&cw, ARM64_REG_X0, skip_unload);
/* FreeLibrary (xsi) */
EMIT_ARM64_MOVE (X0, X19);
EMIT_ARM64_LOAD (X8, free_library_impl);
EMIT_ARM64_CALL (X8);
/* } */
gum_arm64_writer_put_label (&cw, skip_unload);
/* result = ERROR_SUCCESS */
EMIT_ARM64_MOVE (X0, XZR);
gum_arm64_writer_put_b_label (&cw, return_result);
gum_arm64_writer_put_label (&cw, loadlibrary_failed);
/* result = GetLastError() */
EMIT_ARM64_LOAD (X8, get_last_error_impl);
EMIT_ARM64_CALL (X8);
gum_arm64_writer_put_label (&cw, return_result);
gum_arm64_writer_put_pop_reg_reg (&cw, ARM64_REG_X19, ARM64_REG_X20);
gum_arm64_writer_put_pop_reg_reg (&cw, ARM64_REG_FP, ARM64_REG_LR);
gum_arm64_writer_put_ret (&cw);
gum_arm64_writer_flush (&cw);
code_size = gum_arm64_writer_offset (&cw);
gum_arm64_writer_clear (&cw);
#else
GumX86Writer cw;
gum_x86_writer_init (&cw, code);
/* Will clobber these */
@@ -393,80 +548,9 @@ frida_remote_worker_context_init (FridaRemoteWorkerContext * rwc, FridaInjection
gum_x86_writer_flush (&cw);
code_size = gum_x86_writer_offset (&cw);
gum_x86_writer_clear (&cw);
#endif
memset (rwc, 0, sizeof (FridaRemoteWorkerContext));
gum_module_enumerate_exports ("kernel32.dll", frida_remote_worker_context_collect_kernel32_export, rwc);
if (!frida_remote_worker_context_has_resolved_all_kernel32_functions (rwc))
goto failed_to_resolve_kernel32_functions;
StringCbCopyW (rwc->dll_path, sizeof (rwc->dll_path), details->dll_path);
StringCbCopyA (rwc->entrypoint_name, sizeof (rwc->entrypoint_name), details->entrypoint_name);
StringCbCopyA (rwc->entrypoint_data, sizeof (rwc->entrypoint_data), details->entrypoint_data);
page_size = gum_query_page_size ();
g_assert (code_size <= page_size);
alloc_size = page_size + sizeof (FridaRemoteWorkerContext);
rwc->entrypoint = VirtualAllocEx (details->process_handle, NULL, alloc_size, MEM_COMMIT, PAGE_READWRITE);
if (rwc->entrypoint == NULL)
goto virtual_alloc_ex_failed;
if (!WriteProcessMemory (details->process_handle, rwc->entrypoint, code, code_size, NULL))
goto write_process_memory_failed;
rwc->argument = GSIZE_TO_POINTER (GPOINTER_TO_SIZE (rwc->entrypoint) + page_size);
if (!WriteProcessMemory (details->process_handle, rwc->argument, rwc, sizeof (FridaRemoteWorkerContext), NULL))
goto write_process_memory_failed;
if (!VirtualProtectEx (details->process_handle, rwc->entrypoint, page_size, PAGE_EXECUTE_READ, &old_protect))
goto virtual_protect_ex_failed;
gum_free_pages (code);
return TRUE;
/* ERRORS */
failed_to_resolve_kernel32_functions:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error while resolving kernel32 functions");
goto error_common;
}
virtual_alloc_ex_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error allocating memory in target process (VirtualAllocEx returned 0x%08lx)",
GetLastError ());
goto error_common;
}
write_process_memory_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error writing to memory in target process (WriteProcessMemory returned 0x%08lx)",
GetLastError ());
goto error_common;
}
virtual_protect_ex_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error changing memory permission in target process (VirtualProtectEx returned 0x%08lx)",
GetLastError ());
goto error_common;
}
error_common:
{
frida_remote_worker_context_destroy (rwc, details);
gum_free_pages (code);
return FALSE;
}
return code_size;
}
static void
@@ -508,60 +592,6 @@ frida_remote_worker_context_collect_kernel32_export (const GumExportDetails * de
return TRUE;
}
gboolean
frida_windows_system_is_x64 (void)
{
static gboolean initialized = FALSE;
static gboolean system_is_x64;
if (!initialized)
{
SYSTEM_INFO si;
GetNativeSystemInfo (&si);
system_is_x64 = si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64;
initialized = TRUE;
}
return system_is_x64;
}
gboolean
frida_windows_process_is_x64 (guint32 pid, GError ** error)
{
HANDLE process_handle;
BOOL is_wow64, success;
if (!frida_windows_system_is_x64 ())
return FALSE;
process_handle = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
if (process_handle == NULL)
goto open_failed;
success = IsWow64Process (process_handle, &is_wow64);
CloseHandle (process_handle);
if (!success)
goto query_failed;
return !is_wow64;
open_failed:
{
frida_propagate_open_process_error (pid, GetLastError (), error);
return FALSE;
}
query_failed:
{
g_set_error (error,
FRIDA_ERROR,
FRIDA_ERROR_NOT_SUPPORTED,
"Unexpected error while interrogating process with pid %u (IsWow64Process failed)",
pid);
return FALSE;
}
}
static gboolean
frida_file_exists_and_is_readable (const WCHAR * filename)
{
+27 -9
View File
@@ -49,7 +49,7 @@ namespace Frida {
public async void inject_library_file (uint pid, PathTemplate path_template, string entrypoint, string data,
string[] dependencies, uint id, Cancellable? cancellable) throws Error {
string path = path_template.expand (WindowsProcess.is_x64 (pid) ? "64" : "32");
string path = path_template.expand (arch_name_from_pid (pid));
string target_dependent_path;
if (level == ELEVATED) {
@@ -101,6 +101,32 @@ namespace Frida {
protected extern static void _free_inject_instance (void * inject_instance, out bool is_resident);
}
public unowned string arch_name_from_pid (uint pid) throws Error {
switch (cpu_type_from_pid (pid)) {
case Gum.CpuType.IA32:
return "x86";
case Gum.CpuType.AMD64:
return "x86_64";
case Gum.CpuType.ARM64:
return "arm64";
default:
assert_not_reached ();
}
}
public Gum.CpuType cpu_type_from_pid (uint pid) throws Error {
try {
return Gum.Windows.cpu_type_from_pid (pid);
} catch (Gum.Error e) {
if (e is Gum.Error.NOT_FOUND)
throw new Error.PROCESS_NOT_FOUND ("Unable to find process with pid %u", pid);
else if (e is Gum.Error.PERMISSION_DENIED)
throw new Error.PERMISSION_DENIED ("Unable to access process with pid %u", pid);
else
throw new Error.NOT_SUPPORTED ("%s", e.message);
}
}
private class AssetDirectory {
public File file {
get;
@@ -206,14 +232,6 @@ namespace Frida {
}
}
namespace WindowsSystem {
public extern static bool is_x64 ();
}
namespace WindowsProcess {
public extern static bool is_x64 (uint32 pid) throws Error;
}
namespace WaitHandleSource {
public extern Source create (void * handle, bool owns_handle);
}
+33 -24
View File
@@ -57,9 +57,7 @@ namespace Frida {
string[] dependencies, uint id, Cancellable? cancellable) throws Error, IOError {
bool permission_denied = false;
try {
unowned string local_arch = sizeof (void *) == 8 ? "64" : "32";
unowned string remote_arch = WindowsProcess.is_x64 (pid) ? "64" : "32";
if (remote_arch == local_arch) {
if (cpu_type_from_pid (pid) == Gum.NATIVE_CPU) {
yield inprocess_backend.inject_library_file (pid, path_template, entrypoint, data, dependencies,
id, cancellable);
return;
@@ -172,15 +170,11 @@ namespace Frida {
Error? error = null;
try {
string native_helper_path = WindowsSystem.is_x64 ()
? resource_store.helper64.path
: resource_store.helper32.path;
string level_str = (level == PrivilegeLevel.ELEVATED) ? "ELEVATED" : "NORMAL";
void * process = spawn (native_helper_path,
void * process = spawn (resource_store.native_helper.path,
"MANAGER %s %s".printf (level_str, transport.remote_address),
level);
instance = new HelperInstance (resource_store.helper32, resource_store.helper64, transport,
stream_request, process);
instance = new HelperInstance (resource_store.helpers, transport, stream_request, process);
} catch (Error e) {
error = e;
}
@@ -247,8 +241,7 @@ namespace Frida {
}
}
private TemporaryFile helper32;
private TemporaryFile helper64;
private Gee.Collection<TemporaryFile> helpers;
private PipeTransport transport;
private Future<IOStream> stream_request;
private DBusConnection connection;
@@ -257,10 +250,9 @@ namespace Frida {
private Gee.Set<uint> injectee_ids = new Gee.HashSet<uint> ();
public HelperInstance (TemporaryFile helper32, TemporaryFile helper64, PipeTransport transport,
Future<IOStream> stream_request, void * process) {
this.helper32 = helper32;
this.helper64 = helper64;
public HelperInstance (Gee.Collection<TemporaryFile> helpers, PipeTransport transport, Future<IOStream> stream_request,
void * process) {
this.helpers = helpers;
this.transport = transport;
this.stream_request = stream_request;
this.process = process;
@@ -375,26 +367,43 @@ namespace Frida {
}
private class ResourceStore {
public TemporaryFile helper32 {
public TemporaryFile native_helper {
get;
private set;
}
public TemporaryFile helper64 {
public Gee.Collection<TemporaryFile> helpers {
get;
private set;
default = new Gee.ArrayList<TemporaryFile> ();
}
public ResourceStore (TemporaryDirectory tempdir) throws Error {
var blob32 = Frida.Data.Helper.get_frida_helper_32_exe_blob ();
helper32 = new TemporaryFile.from_stream ("frida-helper-32.exe",
new MemoryInputStream.from_data (blob32.data, null),
tempdir);
var helper_arm64 = add_helper ("arm64", Frida.Data.Helper.get_frida_helper_arm64_exe_blob (), tempdir);
var helper_x86_64 = add_helper ("x86_64", Frida.Data.Helper.get_frida_helper_x86_64_exe_blob (), tempdir);
var helper_x86 = add_helper ("x86", Frida.Data.Helper.get_frida_helper_x86_exe_blob (), tempdir);
var blob64 = Frida.Data.Helper.get_frida_helper_64_exe_blob ();
helper64 = new TemporaryFile.from_stream ("frida-helper-64.exe",
new MemoryInputStream.from_data (blob64.data, null),
switch (Gum.Windows.query_native_cpu_type ()) {
case ARM64:
native_helper = helper_arm64;
break;
case AMD64:
native_helper = helper_x86_64;
break;
case IA32:
native_helper = helper_x86;
break;
default:
assert_not_reached ();
}
}
private TemporaryFile add_helper (string name, Frida.Data.Helper.Blob blob, TemporaryDirectory tempdir) throws Error {
var file = new TemporaryFile.from_stream (@"frida-helper-$name.exe",
new MemoryInputStream.from_data (blob.data, null),
tempdir);
helpers.add (file);
return file;
}
}
}
+75 -102
View File
@@ -2,10 +2,12 @@
#include <windows.h>
#if GLIB_SIZEOF_VOID_P == 8
# define FRIDA_HELPER_SERVICE_ARCH "64"
#if defined (HAVE_ARM64)
# define FRIDA_HELPER_SERVICE_ARCH "arm64"
#elif GLIB_SIZEOF_VOID_P == 8
# define FRIDA_HELPER_SERVICE_ARCH "x86_64"
#else
# define FRIDA_HELPER_SERVICE_ARCH "32"
# define FRIDA_HELPER_SERVICE_ARCH "x86"
#endif
#define STANDALONE_JOIN_TIMEOUT_MSEC (5 * 1000)
@@ -17,25 +19,23 @@ struct _FridaServiceContext
gchar * service_basename;
SC_HANDLE scm;
SC_HANDLE service32;
SC_HANDLE service64;
HANDLE standalone32;
HANDLE standalone64;
GQueue system_services;
GQueue standalone_services;
};
static void WINAPI frida_managed_helper_service_main (DWORD argc, WCHAR ** argv);
static DWORD WINAPI frida_managed_helper_service_handle_control_code (DWORD control, DWORD event_type, void * event_data, void * context);
static void frida_managed_helper_service_report_status (DWORD current_state, DWORD exit_code, DWORD wait_hint);
static gboolean frida_register_and_start_services (FridaServiceContext * self);
static gboolean frida_register_and_start_services (FridaServiceContext * self, gchar ** archs, gint archs_length);
static void frida_stop_and_unregister_services (FridaServiceContext * self);
static gboolean frida_spawn_standalone_services (FridaServiceContext * self);
static gboolean frida_spawn_standalone_services (FridaServiceContext * self, gchar ** archs, gint archs_length);
static gboolean frida_join_standalone_services (FridaServiceContext * self);
static void frida_kill_standalone_services (FridaServiceContext * self);
static void frida_release_standalone_services (FridaServiceContext * self);
static gboolean frida_register_services (FridaServiceContext * self);
static gboolean frida_register_services (FridaServiceContext * self, gchar ** archs, gint archs_length);
static gboolean frida_unregister_services (FridaServiceContext * self);
static gboolean frida_start_services (FridaServiceContext * self);
static gboolean frida_stop_services (FridaServiceContext * self);
@@ -59,7 +59,7 @@ static WCHAR * frida_managed_helper_service_name = NULL;
static SERVICE_STATUS_HANDLE frida_managed_helper_service_status_handle = NULL;
void *
frida_helper_manager_start_services (const char * service_basename, FridaPrivilegeLevel level)
frida_helper_manager_start_services (const char * service_basename, gchar ** archs, gint archs_length, FridaPrivilegeLevel level)
{
FridaServiceContext * self;
@@ -72,7 +72,7 @@ frida_helper_manager_start_services (const char * service_basename, FridaPrivile
{
frida_unregister_stale_services (self);
if (!frida_register_and_start_services (self))
if (!frida_register_and_start_services (self, archs, archs_length))
{
CloseServiceHandle (self->scm);
self->scm = NULL;
@@ -81,7 +81,7 @@ frida_helper_manager_start_services (const char * service_basename, FridaPrivile
if (self->scm == NULL)
{
if (!frida_spawn_standalone_services (self))
if (!frida_spawn_standalone_services (self, archs, archs_length))
{
frida_service_context_free (self);
self = NULL;
@@ -138,15 +138,16 @@ char *
frida_helper_service_derive_filename_for_suffix (const char * suffix)
{
WCHAR filename_utf16[MAX_PATH + 1] = { 0, };
gchar * name, * tmp;
gchar * name, * tail, * tmp;
glong len;
GetModuleFileNameW (NULL, filename_utf16, MAX_PATH);
name = g_utf16_to_utf8 (filename_utf16, -1, NULL, &len, NULL);
if (g_str_has_suffix (name, "-32.exe") || g_str_has_suffix (name, "-64.exe"))
tail = strrchr (name, '-');
if (tail != NULL)
{
name[len - 6] = '\0';
tail[1] = '\0';
tmp = g_strconcat (name, suffix, ".exe", NULL);
g_free (name);
name = tmp;
@@ -293,9 +294,9 @@ frida_managed_helper_service_report_status (DWORD current_state, DWORD exit_code
}
static gboolean
frida_register_and_start_services (FridaServiceContext * self)
frida_register_and_start_services (FridaServiceContext * self, gchar ** archs, gint archs_length)
{
if (!frida_register_services (self))
if (!frida_register_services (self, archs, archs_length))
return FALSE;
if (!frida_start_services (self))
@@ -315,44 +316,35 @@ frida_stop_and_unregister_services (FridaServiceContext * self)
}
static gboolean
frida_spawn_standalone_services (FridaServiceContext * self)
frida_spawn_standalone_services (FridaServiceContext * self, gchar ** archs, gint archs_length)
{
HANDLE standalone32, standalone64;
gint i;
standalone32 = frida_spawn_standalone_service (self, "32");
if (standalone32 == NULL)
return FALSE;
if (frida_windows_system_is_x64 ())
for (i = 0; i != archs_length; i++)
{
standalone64 = frida_spawn_standalone_service (self, "64");
if (standalone64 == NULL)
{
frida_kill_standalone_service (self, standalone32);
CloseHandle (standalone32);
return FALSE;
}
HANDLE service = frida_spawn_standalone_service (self, archs[i]);
if (service == NULL)
goto unable_to_spawn;
g_queue_push_tail (&self->standalone_services, service);
}
else
{
standalone64 = NULL;
}
self->standalone32 = standalone32;
self->standalone64 = standalone64;
return TRUE;
unable_to_spawn:
{
frida_kill_standalone_services (self);
return FALSE;
}
}
static gboolean
frida_join_standalone_services (FridaServiceContext * self)
{
gboolean success = TRUE;
GList * cur;
if (frida_windows_system_is_x64 ())
success &= frida_join_standalone_service (self, self->standalone64);
success &= frida_join_standalone_service (self, self->standalone32);
for (cur = self->standalone_services.head; cur != NULL; cur = cur->next)
success &= frida_join_standalone_service (self, cur->data);
if (success)
frida_release_standalone_services (self);
@@ -363,10 +355,10 @@ frida_join_standalone_services (FridaServiceContext * self)
static void
frida_kill_standalone_services (FridaServiceContext * self)
{
if (frida_windows_system_is_x64 ())
frida_kill_standalone_service (self, self->standalone64);
GList * cur;
frida_kill_standalone_service (self, self->standalone32);
for (cur = self->standalone_services.head; cur != NULL; cur = cur->next)
frida_kill_standalone_service (self, cur->data);
frida_release_standalone_services (self);
}
@@ -374,94 +366,77 @@ frida_kill_standalone_services (FridaServiceContext * self)
static void
frida_release_standalone_services (FridaServiceContext * self)
{
if (frida_windows_system_is_x64 ())
{
g_assert (self->standalone64 != NULL);
CloseHandle (self->standalone64);
self->standalone64 = NULL;
}
HANDLE service;
g_assert (self->standalone32 != NULL);
CloseHandle (self->standalone32);
self->standalone32 = NULL;
while ((service = g_queue_pop_tail (&self->standalone_services)) != NULL)
CloseHandle (service);
}
static gboolean
frida_register_services (FridaServiceContext * self)
frida_register_services (FridaServiceContext * self, gchar ** archs, gint archs_length)
{
SC_HANDLE service32, service64;
gint i;
service32 = frida_register_service (self, "32");
if (service32 == NULL)
return FALSE;
if (frida_windows_system_is_x64 ())
for (i = 0; i != archs_length; i++)
{
service64 = frida_register_service (self, "64");
if (service64 == NULL)
{
frida_unregister_service (self, service32);
CloseServiceHandle (service32);
return FALSE;
}
SC_HANDLE service = frida_register_service (self, archs[i]);
if (service == NULL)
goto unable_to_register;
g_queue_push_tail (&self->system_services, service);
}
else
{
service64 = NULL;
}
self->service32 = service32;
self->service64 = service64;
return TRUE;
unable_to_register:
{
frida_unregister_services (self);
return FALSE;
}
}
static gboolean
frida_unregister_services (FridaServiceContext * self)
{
gboolean success = TRUE;
SC_HANDLE service;
if (frida_windows_system_is_x64 ())
while ((service = g_queue_pop_tail (&self->system_services)) != NULL)
{
success &= frida_unregister_service (self, self->service64);
CloseServiceHandle (self->service64);
self->service64 = NULL;
success &= frida_unregister_service (self, service);
CloseServiceHandle (service);
}
success &= frida_unregister_service (self, self->service32);
CloseServiceHandle (self->service32);
self->service32 = NULL;
return success;
}
static gboolean
frida_start_services (FridaServiceContext * self)
{
if (!frida_start_service (self, self->service32))
return FALSE;
GList * cur;
if (frida_windows_system_is_x64 ())
for (cur = self->system_services.head; cur != NULL; cur = cur->next)
{
if (!frida_start_service (self, self->service64))
{
frida_stop_service (self, self->service32);
return FALSE;
}
if (!frida_start_service (self, cur->data))
goto unable_to_start;
}
return TRUE;
unable_to_start:
{
frida_stop_services (self);
return FALSE;
}
}
static gboolean
frida_stop_services (FridaServiceContext * self)
{
gboolean success = TRUE;
GList * cur;
if (frida_windows_system_is_x64 ())
success &= frida_stop_service (self, self->service64);
success &= frida_stop_service (self, self->service32);
for (cur = self->system_services.head; cur != NULL; cur = cur->next)
success &= frida_stop_service (self, cur->data);
return success;
}
@@ -480,7 +455,7 @@ frida_register_service (FridaServiceContext * self, const gchar * suffix)
servicename_utf8 = g_strconcat (self->service_basename, suffix, NULL);
servicename = g_utf8_to_utf16 (servicename_utf8, -1, NULL, NULL, NULL);
displayname_utf8 = g_strdup_printf ("Frida %s-bit helper (%s)", suffix, servicename_utf8);
displayname_utf8 = g_strdup_printf ("Frida %s helper (%s)", suffix, servicename_utf8);
displayname = g_utf8_to_utf16 (displayname_utf8, -1, NULL, NULL, NULL);
filename_utf8 = frida_helper_service_derive_filename_for_suffix (suffix);
@@ -714,6 +689,7 @@ frida_service_context_new (const gchar * service_basename)
self = g_slice_new0 (FridaServiceContext);
self->service_basename = g_strdup (service_basename);
g_queue_init (&self->standalone_services);
return self;
}
@@ -721,11 +697,8 @@ frida_service_context_new (const gchar * service_basename)
static void
frida_service_context_free (FridaServiceContext * self)
{
g_assert (self->standalone64 == NULL);
g_assert (self->standalone32 == NULL);
g_assert (self->service64 == NULL);
g_assert (self->service32 == NULL);
g_assert (g_queue_is_empty (&self->system_services));
g_assert (g_queue_is_empty (&self->standalone_services));
if (self->scm != NULL)
CloseServiceHandle (self->scm);
+2 -1
View File
@@ -5,7 +5,8 @@
G_BEGIN_DECLS
G_GNUC_INTERNAL void * frida_helper_manager_start_services (const char * service_basename, FridaPrivilegeLevel level);
G_GNUC_INTERNAL void * frida_helper_manager_start_services (const char * service_basename, gchar ** archs, gint archs_length,
FridaPrivilegeLevel level);
G_GNUC_INTERNAL void frida_helper_manager_stop_services (void * context);
G_GNUC_INTERNAL char * frida_helper_service_derive_basename (void);
+26 -29
View File
@@ -60,8 +60,7 @@ namespace Frida {
private DBusConnection connection;
private uint registration_id;
private ServiceConnection helper32;
private ServiceConnection? helper64;
private Gee.Collection<ServiceConnection> helpers = new Gee.ArrayList<ServiceConnection> ();
private void * context;
public HelperManager (string parent_address, PrivilegeLevel level) {
@@ -98,18 +97,23 @@ namespace Frida {
private async void start () {
try {
helper32 = new ServiceConnection (HelperService.derive_svcname_for_suffix ("32"));
if (WindowsSystem.is_x64 ())
helper64 = new ServiceConnection (HelperService.derive_svcname_for_suffix ("64"));
var archs = new Gee.ArrayList<string> ();
if (Gum.Windows.query_native_cpu_type () == ARM64)
archs.add ("arm64");
if (Gum.Windows.query_native_cpu_type () != IA32)
archs.add ("x86_64");
archs.add ("x86");
context = start_services (HelperService.derive_basename (), level);
foreach (string arch in archs) {
var helper = new ServiceConnection (HelperService.derive_svcname_for_suffix (arch));
helpers.add (helper);
}
yield helper32.open ();
helper32.proxy.uninjected.connect (on_uninjected);
context = start_services (HelperService.derive_basename (), archs.to_array (), level);
if (helper64 != null) {
yield helper64.open ();
helper64.proxy.uninjected.connect (on_uninjected);
foreach (var helper in helpers) {
yield helper.open ();
helper.proxy.uninjected.connect (on_uninjected);
}
var stream_request = Pipe.open (parent_address, null);
@@ -130,20 +134,14 @@ namespace Frida {
}
public async void stop (Cancellable? cancellable) throws Error, IOError {
if (helper64 != null) {
foreach (var helper in helpers) {
try {
yield helper64.proxy.stop (cancellable);
yield helper.proxy.stop (cancellable);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED)
throw (IOError) e;
}
}
try {
yield helper32.proxy.stop (cancellable);
} catch (GLib.Error e) {
if (e is IOError.CANCELLED)
throw (IOError) e;
}
Timeout.add (20, () => {
shutdown.begin ();
@@ -158,13 +156,14 @@ namespace Frida {
public async void inject_library_file (uint pid, PathTemplate path_template, string entrypoint, string data,
string[] dependencies, uint id, Cancellable? cancellable) throws Error, IOError {
try {
if (helper64 != null && yield helper64.proxy.can_handle_target (pid, cancellable)) {
yield helper64.proxy.inject_library_file (pid, path_template, entrypoint, data, dependencies, id,
cancellable);
} else {
yield helper32.proxy.inject_library_file (pid, path_template, entrypoint, data, dependencies, id,
cancellable);
foreach (var helper in helpers) {
if (yield helper.proxy.can_handle_target (pid, cancellable)) {
yield helper.proxy.inject_library_file (pid, path_template, entrypoint, data, dependencies,
id, cancellable);
return;
}
}
throw new Error.NOT_SUPPORTED ("Missing helper able to handle the given target");
} catch (GLib.Error e) {
throw_dbus_error (e);
}
@@ -210,7 +209,7 @@ namespace Frida {
}
}
private extern static void * start_services (string service_basename, PrivilegeLevel level);
private extern static void * start_services (string service_basename, string[] archs, PrivilegeLevel level);
private extern static void stop_services (void * context);
}
@@ -286,9 +285,7 @@ namespace Frida {
}
public async bool can_handle_target (uint pid, Cancellable? cancellable) throws Error, IOError {
uint local_arch = sizeof (void *) == 8 ? 64 : 32;
uint remote_arch = WindowsProcess.is_x64 (pid) ? 64 : 32;
return local_arch == remote_arch;
return cpu_type_from_pid (pid) == Gum.NATIVE_CPU;
}
public async void inject_library_file (uint pid, PathTemplate path_template, string entrypoint, string data,
+32 -14
View File
@@ -113,21 +113,23 @@ namespace Frida {
injector = new Winjector (helper, false, tempdir);
injector.uninjected.connect (on_uninjected);
var blob32 = Frida.Data.Agent.get_frida_agent_32_dll_blob ();
var blob64 = Frida.Data.Agent.get_frida_agent_64_dll_blob ();
var dbghelp32 = Frida.Data.Agent.get_dbghelp_32_dll_blob ();
var dbghelp64 = Frida.Data.Agent.get_dbghelp_64_dll_blob ();
var symsrv32 = Frida.Data.Agent.get_symsrv_32_dll_blob ();
var symsrv64 = Frida.Data.Agent.get_symsrv_64_dll_blob ();
agent = new AgentDescriptor (PathTemplate ("<arch>\\frida-agent.dll"),
new Bytes.static (blob32.data),
new Bytes.static (blob64.data),
new Bytes.static (Frida.Data.Agent.get_frida_agent_arm64_dll_blob ().data),
new Bytes.static (Frida.Data.Agent.get_frida_agent_x86_64_dll_blob ().data),
new Bytes.static (Frida.Data.Agent.get_frida_agent_x86_dll_blob ().data),
new AgentResource[] {
new AgentResource ("32\\dbghelp.dll", new Bytes.static (dbghelp32.data), tempdir),
new AgentResource ("32\\symsrv.dll", new Bytes.static (symsrv32.data), tempdir),
new AgentResource ("64\\dbghelp.dll", new Bytes.static (dbghelp64.data), tempdir),
new AgentResource ("64\\symsrv.dll", new Bytes.static (symsrv64.data), tempdir)
new AgentResource ("arm64\\dbghelp.dll",
new Bytes.static (Frida.Data.Agent.get_dbghelp_arm64_dll_blob ().data), tempdir),
new AgentResource ("arm64\\symsrv.dll",
new Bytes.static (Frida.Data.Agent.get_symsrv_arm64_dll_blob ().data), tempdir),
new AgentResource ("x86_64\\dbghelp.dll",
new Bytes.static (Frida.Data.Agent.get_dbghelp_x86_64_dll_blob ().data), tempdir),
new AgentResource ("x86_64\\symsrv.dll",
new Bytes.static (Frida.Data.Agent.get_symsrv_x86_64_dll_blob ().data), tempdir),
new AgentResource ("x86\\dbghelp.dll",
new Bytes.static (Frida.Data.Agent.get_dbghelp_x86_dll_blob ().data), tempdir),
new AgentResource ("x86\\symsrv.dll",
new Bytes.static (Frida.Data.Agent.get_symsrv_x86_dll_blob ().data), tempdir),
},
tempdir
);
@@ -164,7 +166,23 @@ namespace Frida {
protected override async AgentSessionProvider create_system_session_provider (Cancellable? cancellable,
out DBusConnection connection) throws Error, IOError {
var path_template = agent.get_path_template ();
var agent_path = path_template.expand (sizeof (void *) == 8 ? "64" : "32");
unowned string arch;
switch (Gum.NATIVE_CPU) {
case ARM64:
arch = "arm64";
break;
case AMD64:
arch = "x86_64";
break;
case IA32:
arch = "x86";
break;
default:
assert_not_reached ();
}
var agent_path = path_template.expand (arch);
system_session_container = yield AgentContainer.create (agent_path, cancellable);
+5 -4
View File
@@ -142,11 +142,12 @@ namespace Frida {
private PathTemplate? cached_path_template;
public AgentDescriptor (PathTemplate name_template, Bytes dll32, Bytes dll64, AgentResource[] dependencies,
TemporaryDirectory? tempdir = null) {
public AgentDescriptor (PathTemplate name_template, Bytes dll_arm64, Bytes dll_x86_64, Bytes dll_x86,
AgentResource[] dependencies, TemporaryDirectory? tempdir = null) {
var agents = new Gee.ArrayList<AgentResource> ();
agents.add (new AgentResource (name_template.expand ("32"), dll32, tempdir));
agents.add (new AgentResource (name_template.expand ("64"), dll64, tempdir));
agents.add (new AgentResource (name_template.expand ("arm64"), dll_arm64, tempdir));
agents.add (new AgentResource (name_template.expand ("x86_64"), dll_x86_64, tempdir));
agents.add (new AgentResource (name_template.expand ("x86"), dll_x86, tempdir));
Object (
name_template: name_template,
+1 -1
View File
@@ -1,6 +1,6 @@
[wrap-git]
url = https://github.com/frida/frida-gum.git
revision = 16.4.2
revision = 16.6.2
depth = 1
[provide]
+1 -1
View File
@@ -1,6 +1,6 @@
[wrap-git]
url = https://github.com/frida/libusb.git
revision = be4d8ec1012f35ff6ce9474ed8d7c3ec4182ac55
revision = ffff4bdfe8faa38cecfad5aab106cae923502d55
depth = 1
[provide]
+1 -1
View File
@@ -1,6 +1,6 @@
[wrap-git]
url = https://github.com/frida/lwip.git
revision = 9f64c40cac2e77eddf6b3913961fdd056d307716
revision = 2b3efb7862866904f67dc369c9147f527a2982ca
depth = 1
[provide]
+2 -4
View File
@@ -72,10 +72,8 @@ frida_test_process_backend_filename_of (void * handle)
image_count = _dyld_image_count ();
for (image_idx = 0; image_idx != image_count; image_idx++)
{
const gchar * image_path = _dyld_get_image_name (image_idx);
if (g_str_has_suffix (image_path, "/frida-tests"))
return g_strdup (image_path);
if (_dyld_get_image_header (image_idx)->filetype == MH_EXECUTE)
return g_strdup (_dyld_get_image_name (image_idx));
}
g_assert_not_reached ();
+2 -2
View File
@@ -113,7 +113,7 @@ namespace Frida.HostSessionTest {
"execvp",
"execve",
};
if (Gum.Module.find_export_by_name (null, "execvpe") != 0) {
if (Gum.Module.find_global_export_by_name ("execvpe") != 0) {
exec_symbol_names += "execvpe";
}
foreach (var fork_symbol_name in fork_symbol_names) {
@@ -1140,7 +1140,7 @@ namespace Frida.HostSessionTest {
if (strategy == PEER) {
yield session.setup_peer_connection ();
peer_connection = ((DBusProxy) session.session).g_connection;
peer_connection = session._get_connection ();
bool disrupting = false;
var main_context = MainContext.ref_thread_default ();
filter_id = peer_connection.add_filter ((conn, message, incoming) => {
+37
View File
@@ -18,7 +18,10 @@ namespace NGTcp2 {
[CCode (cname = "ngtcp2_conn_read_pkt")]
public int read_packet (Path path, PacketInfo * pi, uint8[] pkt, Timestamp ts);
public ssize_t write_connection_close (Path * path, PacketInfo * pi, uint8[] dest, ConnectionError error, Timestamp ts);
public int open_bidi_stream (out int64 stream_id, void * stream_user_data);
public int shutdown_stream (uint32 flags, int64 stream_id, uint64 app_error_code);
public ssize_t write_stream (Path * path, PacketInfo * pi, uint8[] dest, ssize_t * pdatalen, WriteStreamFlags flags,
int64 stream_id, uint8[]? data, Timestamp ts);
@@ -87,6 +90,26 @@ namespace NGTcp2 {
public uint8 data[MAX_CIDLEN];
}
[CCode (cname = "ngtcp2_ccerr", has_destroy_function = false)]
public struct ConnectionError {
[CCode (cname = "ngtcp2_ccerr_set_application_error")]
public ConnectionError.application (uint64 error_code, uint8[]? reason = null);
public ConnectionErrorType type;
public uint64 error_code;
public uint64 frame_type;
[CCode (array_length_cname = "reasonlen")]
public uint8[]? reason;
}
[CCode (cname = "ngtcp2_ccerr_type", cprefix = "NGTCP2_CCERR_TYPE_", has_type_id = false)]
public enum ConnectionErrorType {
TRANSPORT,
APPLICATION,
VERSION_NEGOTIATION,
IDLE_CLOSE,
}
[CCode (cname = "ngtcp2_connection_id_status_type", cprefix = "NGTCP2_CONNECTION_ID_STATUS_TYPE_", has_type_id = false)]
public enum ConnectionIdStatusType {
ACTIVATE,
@@ -149,6 +172,13 @@ namespace NGTcp2 {
FIN,
}
[Flags]
[CCode (cname = "uint32_t", cprefix = "NGTCP2_WRITE_DATAGRAM_FLAG_", has_type_id = false)]
public enum WriteDatagramFlags {
NONE,
MORE,
}
[CCode (cname = "NGTCP2_MAX_CIDLEN")]
public const size_t MAX_CIDLEN;
[CCode (cname = "NGTCP2_MIN_INITIAL_DCIDLEN")]
@@ -174,6 +204,13 @@ namespace NGTcp2 {
public struct InternetPort : uint16 {
}
[CCode (cname = "ngtcp2_sockaddr_union", has_destroy_function = false)]
public struct SocketAddressUnion {
public SocketAddress sa;
public SocketAddressInternet in;
public SocketAddressInternet6 in6;
}
[CCode (cname = "ngtcp2_sockaddr", has_destroy_function = false)]
public struct SocketAddress {
public SocketAddressFamily sa_family;
+28 -8
View File
@@ -33,7 +33,7 @@ namespace LWIP {
public void ip6_addr_set_state (int8 addr_index, IP6AddressState state);
[CCode (cname = "netif_input")]
public static ErrorCode default_input_handler (PacketBuffer pbuf, NetworkInterface netif);
public static ErrorCode default_input_handler (PacketBuffer pbuf, ref NetworkInterface netif);
public IP6Address ip6_addr[IPV6_NUM_ADDRESSES];
@@ -56,16 +56,16 @@ namespace LWIP {
}
[CCode (cname = "netif_init_fn", has_target = false)]
public delegate ErrorCode NetworkInterfaceInitFunc (NetworkInterface netif);
public delegate ErrorCode NetworkInterfaceInitFunc (ref NetworkInterface netif);
[CCode (cname = "netif_input_fn", has_target = false)]
public delegate ErrorCode NetworkInterfaceInputFunc (PacketBuffer pbuf, NetworkInterface netif);
public delegate ErrorCode NetworkInterfaceInputFunc (PacketBuffer pbuf, ref NetworkInterface netif);
[CCode (cname = "netif_linkoutput_fn", has_target = false)]
public delegate ErrorCode NetworkInterfaceLinkOutputFunc (NetworkInterface netif, PacketBuffer pbuf);
public delegate ErrorCode NetworkInterfaceLinkOutputFunc (ref NetworkInterface netif, PacketBuffer pbuf);
[CCode (cname = "netif_output_ip6_fn", has_target = false)]
public delegate ErrorCode NetworkInterfaceOutputIP6Func (NetworkInterface netif, PacketBuffer pbuf, IP6Address address);
public delegate ErrorCode NetworkInterfaceOutputIP6Func (ref NetworkInterface netif, PacketBuffer pbuf, IP6Address address);
[Flags]
[CCode (cheader_filename = "lwip/netif.h", cprefix = "NETIF_FLAG_")]
@@ -85,7 +85,7 @@ namespace LWIP {
namespace IPv6 {
[CCode (cheader_filename = "lwip/ethip6.h", cname = "ethip6_output")]
public ErrorCode output (NetworkInterface netif, PacketBuffer pbuf, IP6Address address);
public ErrorCode output (ref NetworkInterface netif, PacketBuffer pbuf, IP6Address address);
}
}
@@ -189,6 +189,8 @@ namespace LWIP {
[CCode (cname = "tcp_err")]
public void set_error_callback (ErrorFunc f);
public void set_flags (Flags flags);
public void nagle_disable ();
public void nagle_enable ();
@@ -196,7 +198,7 @@ namespace LWIP {
public ErrorCode close ();
public ErrorCode shutdown (bool shut_rx, bool shut_tx);
public void bind_netif (NetworkInterface? netif);
public void bind_netif (NetworkInterface * netif);
public ErrorCode connect (IP6Address address, uint16 port, ConnectedFunc connected);
@@ -221,6 +223,24 @@ namespace LWIP {
[CCode (cname = "tcp_connected_fn", has_target = false)]
public delegate ErrorCode ConnectedFunc (void * user_data, TcpPcb pcb, ErrorCode err);
[Flags]
[CCode (cname = "tcpflags_t", cprefix = "TF_", has_type_id = false)]
public enum Flags {
ACK_DELAY,
ACK_NOW,
INFR,
CLOSEPEND,
RXCLOSED,
FIN,
NODELAY,
NAGLEMEMERR,
WND_SCALE,
BACKLOGPEND,
TIMESTAMP,
RTO,
SACK,
}
[Flags]
[CCode (cname = "u8_t", cprefix = "TCP_WRITE_FLAG_", has_type_id = false)]
public enum WriteFlags {
@@ -241,7 +261,7 @@ namespace LWIP {
public void set_recv_callback (RecvFunc f);
public ErrorCode bind (IP6Address? ipaddr = null, uint16 port = 0);
public void bind_netif (NetworkInterface? netif);
public void bind_netif (NetworkInterface * netif);
public ErrorCode connect (IP6Address ipaddr, uint16 port);
+48
View File
@@ -1,3 +1,51 @@
[CCode (cprefix = "", gir_namespace = "Minizip", gir_version = "1.0", lower_case_cprefix = "mz_")]
namespace Minizip {
[SimpleType]
[CCode (cheader_filename = "minizip/mz_strm.h,minizip/mz_zip.h,minizip/mz_zip_rw.h", cname = "gpointer", cprefix = "mz_zip_reader_",
has_destroy_function = false)]
public struct Reader {
public static Reader create (out Reader stream = null);
[CCode (cname = "mz_zip_reader_delete")]
public static void destroy (ref Reader stream);
public Status open_file (string path);
public Status close ();
public Status locate_entry (string filename, bool ignore_case);
public Status entry_save_file (string path);
public Status entry_save_buffer (uint8[] buf);
public int32 entry_save_buffer_length ();
}
[CCode (cheader_filename = "minizip/mz.h", cname = "int32_t", cprefix = "MZ_", has_type_id = false)]
public enum Status {
OK,
STREAM_ERROR,
DATA_ERROR,
MEM_ERROR,
BUF_ERROR,
VERSION_ERROR,
END_OF_LIST,
END_OF_STREAM,
PARAM_ERROR,
FORMAT_ERROR,
INTERNAL_ERROR,
CRC_ERROR,
CRYPT_ERROR,
EXIST_ERROR,
PASSWORD_ERROR,
SUPPORT_ERROR,
HASH_ERROR,
OPEN_ERROR,
CLOSE_ERROR,
SEEK_ERROR,
TELL_ERROR,
READ_ERROR,
WRITE_ERROR,
SIGN_ERROR,
SYMLINK_ERROR,
}
}
+44
View File
@@ -21,11 +21,16 @@ namespace OpenSSL {
public void set_connect_state ();
public void set_accept_state ();
public int set_cipher_list (string str);
public int set_alpn_protos (uint8[] protos);
public void set_psk_client_callback (PskClientCallback callback);
public void set_quic_transport_version (int version);
}
[CCode (has_target = false)]
public delegate uint PskClientCallback (SSL ssl, string? hint, char[] identity, uint8[] psk);
[Compact]
[CCode (cname = "SSL_METHOD", cprefix = "SSL_METHOD_", free_function = "")]
public class SSLMethod {
@@ -384,6 +389,44 @@ namespace OpenSSL {
public class MessageDigest {
public static MessageDigest fetch (LibraryContext? ctx, string algorithm, string? properties = null);
}
[Compact]
[CCode (cname = "EVP_MAC_CTX", cprefix = "EVP_MAC_CTX_")]
public class MessageAuthCodeContext {
public MessageAuthCodeContext (MessageAuthCode mac);
[CCode (cname = "EVP_MAC_init")]
public int init (uint8[] key, [CCode (array_length = false)] Param[]? params = null);
[CCode (cname = "EVP_MAC_update")]
public int update (uint8[] data);
[CCode (cname = "EVP_MAC_final")]
public int final ([CCode (array_length_pos = 2)] uint8[]? outdata, out size_t outlen);
}
[Compact]
[CCode (cname = "EVP_MAC", cprefix = "EVP_MAC_")]
public class MessageAuthCode {
public static MessageAuthCode fetch (LibraryContext? ctx, string algorithm, string? properties = null);
}
[CCode (cheader_filename = "openssl/core_names.h", lower_case_cprefix = "OSSL_MAC_PARAM_")]
namespace MessageAuthParameter {
public const string KEY;
public const string IV;
public const string CUSTOM;
public const string SALT;
public const string XOF;
public const string DIGEST_NOINIT;
public const string DIGEST_ONESHOT;
public const string C_ROUNDS;
public const string D_ROUNDS;
public const string CIPHER;
public const string DIGEST;
public const string PROPERTIES;
public const string SIZE;
public const string BLOCK_SIZE;
public const string TLS_DATA_SIZE;
}
}
[Compact]
@@ -426,6 +469,7 @@ namespace OpenSSL {
public const string sha256;
public const string sha384;
public const string sha512;
public const string siphash;
public const string chacha20_poly1305;
}
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more