mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
13
Commits
v5.0.1
..
4b1ca5a490
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b1ca5a490 | ||
|
|
483a12cd3c | ||
|
|
416e83f36e | ||
|
|
4b9d371357 | ||
|
|
c710547cc8 | ||
|
|
4bb0d6ecd1 | ||
|
|
0e1280ef7f | ||
|
|
6eb1925ec3 | ||
|
|
59e705510e | ||
|
|
c548022068 | ||
|
|
6a43b3437a | ||
|
|
8cd4c54c07 | ||
|
|
3796cca9a1 |
No files matched your search
@@ -93,3 +93,44 @@ jobs:
|
||||
path: dist/JuiceAgent_*.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
build-linux:
|
||||
name: Build (Linux, GCC)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Install build tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
build-essential cmake ninja-build
|
||||
|
||||
- name: Configure
|
||||
run: |
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cmake --build build
|
||||
|
||||
echo "compiler: $(command -v g++)"
|
||||
echo "target: $(gcc -dumpmachine)"
|
||||
|
||||
echo "--- build/bin ---"
|
||||
ls -1 build/bin
|
||||
|
||||
- name: Package release tarball
|
||||
run: ./script/package.sh
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: JuiceAgent-linux-x64
|
||||
path: dist/JuiceAgent_*.tar.gz
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "ptrace-inject-cpp"]
|
||||
path = ptrace-inject-cpp
|
||||
url = https://github.com/xiaozhou233/ptrace-inject-cpp
|
||||
@@ -0,0 +1,222 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for AI coding agents (and humans) working in this repository.
|
||||
|
||||
## Project at a glance
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM (even with `DisableAttachMechanism=true`, no `-javaagent`),
|
||||
loads a JAR and calls an entry point, and exposes native APIs to
|
||||
redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
Four binaries:
|
||||
|
||||
| Target | Output | Role |
|
||||
| --- | --- | --- |
|
||||
| `injector` | `injector.exe` | CLI driver: loads `libinject.dll` and injects `libloader.dll` into a target PID |
|
||||
| `libinject` | `libinject.dll` | Reflective DLL injector (exports `inject`, plus JNI bindings) |
|
||||
| `libloader` | `libloader.dll` | **Reflectively loaded** into the target JVM. Attaches to the JVM, reads `config.toml`, registers the embedded JuiceAgent-API jar, bootstraps the agent |
|
||||
| `libagent` | `libagent.dll` | The JVMTI agent. Registers `ClassFileLoadHook` and implements the native side of the JuiceAgent-API |
|
||||
|
||||
## Toolchain
|
||||
|
||||
- Windows x64, MinGW-w64 GCC (the maintainer uses [w64devkit](https://github.com/skeeto/w64devkit)), Ninja, CMake 3.15+
|
||||
- C++20
|
||||
- JDK 17+ for the Java side. `--enable-native-access=ALL-UNNAMED` is required from
|
||||
JDK 22 on to keep `System.load` warning-free (a future JDK will deny native
|
||||
access without it).
|
||||
|
||||
## Build
|
||||
|
||||
```powershell
|
||||
cmake --preset release # or: --preset debug
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
Binaries land in `build/bin`.
|
||||
|
||||
Alternatively, without presets:
|
||||
|
||||
```powershell
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
Integration tests live in `tests/`. They are plain `main()` programs (not JUnit)
|
||||
that `System.load("resources/libagent.dll")` and call `JuiceAgent.init("")`.
|
||||
Two of them need the `injection` module compiled into `out/production/injection`.
|
||||
|
||||
Build first, then:
|
||||
|
||||
```powershell
|
||||
pwsh tests/run-tests.ps1
|
||||
# or point it at a specific JDK:
|
||||
pwsh tests/run-tests.ps1 -JdkHome "C:\Program Files\Zulu\zulu-25"
|
||||
```
|
||||
|
||||
The runner compiles the modules, refreshes `tests/resources` from `build/bin`
|
||||
(via `tests/copy-bin.bat`), compiles the tests, then runs every test and
|
||||
**asserts on its output**.
|
||||
|
||||
> Running the tests rebuilds the tracked file `tests/injection.jar`. After a local
|
||||
> run, restore it with `git checkout -- tests/injection.jar` before committing.
|
||||
|
||||
## Release
|
||||
|
||||
1. Bump `Version.txt` (`Major` / `Minor` / `Patch`).
|
||||
2. Add `docs/update/vX.Y.Z.md` (bilingual release notes) and an entry in
|
||||
`docs/update/CHANGELOG.md`.
|
||||
3. Commit the docs, then commit `Version X.Y.Z`, then tag `vX.Y.Z`.
|
||||
4. Build the package and attach it to a GitHub Release:
|
||||
|
||||
```powershell
|
||||
cmake -P script/package.cmake # -> dist/JuiceAgent_vX.Y.Z_x64.zip
|
||||
```
|
||||
|
||||
(`script/package.bat` wraps this but ends with `pause`.)
|
||||
|
||||
On Linux, `script/package.sh` packs `injector`, `libloader.so` and
|
||||
`libagent.so` into `dist/JuiceAgent_vX.Y.Z_x64_linux.tar.gz`:
|
||||
|
||||
```bash
|
||||
./script/package.sh
|
||||
```
|
||||
|
||||
`tests/`, `build/`, `dist/` and `*.log` are gitignored; `dist/*.zip` and
|
||||
`dist/*.tar.gz` are **not** committed.
|
||||
|
||||
## Hard rules (each of these was learned by breaking the build or a target JVM)
|
||||
|
||||
### 1. `libloader` must never throw a C++ exception
|
||||
|
||||
`libloader.dll` is loaded by a **reflective loader (manual mapping)**, so its
|
||||
unwind tables are never registered with the OS. A C++ exception thrown inside it
|
||||
**cannot be unwound or caught** - it crashes the target JVM with
|
||||
`EXCEPTION_ILLEGAL_INSTRUCTION` (a `try/catch` there is useless, not a fix).
|
||||
|
||||
- The `loader` target is compiled with `-fno-exceptions` (and
|
||||
`SPDLOG_NO_EXCEPTIONS`) on purpose: any exception-capable code fails the build.
|
||||
- Report problems with `spdlog` + an early `return`, never with `throw`.
|
||||
- This also means library code that can throw (`toml::parse_file`,
|
||||
`std::filesystem`, allocations) must be used in a non-throwing way. toml++
|
||||
switches to the non-throwing `toml::parse_result` API automatically when
|
||||
exceptions are disabled.
|
||||
|
||||
### 2. Config reads are non-throwing
|
||||
|
||||
`includes/JuiceAgent/Config.hpp` intentionally has **no throwing getters**. Use:
|
||||
|
||||
```cpp
|
||||
if (!cfg.contains("JarLoader.Mode")) { spdlog::error("Missing key: JarLoader.Mode"); return; }
|
||||
const std::string mode = cfg.get<std::string>("JarLoader.Mode", "");
|
||||
```
|
||||
|
||||
For required values, check `contains()` first and then `get(path, default)`.
|
||||
|
||||
### 3. Config schema changes are a coordinated edit
|
||||
|
||||
The current schema is v2 (`CONFIG_VERSION` in `includes/JuiceAgent/JuiceAgent.hpp`).
|
||||
It is validated at load time, so a mismatch makes the loader refuse to start.
|
||||
Changing the schema requires updating, together:
|
||||
|
||||
- `CONFIG_VERSION`
|
||||
- `docs/config.md`
|
||||
- the three `examples/*/config.toml`
|
||||
- the config block in `README.md` **and** `README_ZH.md`
|
||||
|
||||
### 4. Keep the MinGW runtime out of the shipped DLLs
|
||||
|
||||
Do not introduce a dependency on `libstdc++-6.dll` / `libgcc_s_seh-1.dll` /
|
||||
`libwinpthread-1.dll`. A DLL that needs them can pick up an incompatible copy
|
||||
from elsewhere on the machine and fail to load (`UnsatisfiedLinkError: The
|
||||
specified procedure could not be found`). w64devkit links the runtime statically;
|
||||
CI passes `-static-libgcc -static-libstdc++` to match.
|
||||
|
||||
### 5. Tests assert on output, not exit codes
|
||||
|
||||
The test programs print diagnostics and **still exit 0** when a step fails. Match
|
||||
an expected marker (e.g. `Bytes: 399`, `Modified!`, `Injection Invoked!`) -
|
||||
checking `$LASTEXITCODE` alone will silently pass broken builds.
|
||||
|
||||
Notes when adding tests:
|
||||
|
||||
- `GetClassBytesByName` only resolves **already loaded** classes; load the target
|
||||
first (`Class.forName("Target")`).
|
||||
- Tests that print to stderr make Windows PowerShell 5.1 unhappy; the runner sets
|
||||
`$ErrorActionPreference = "Continue"` and relies on explicit checks.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/injector injector.exe
|
||||
src/libinject libinject.dll (reflective injector)
|
||||
src/libloader libloader.dll (runs in the target; exception-free)
|
||||
src/libagent libagent.dll (JVMTI agent)
|
||||
services/ IService implementations, self-registered via JUICEAGENT_REGISTER_SERVICE
|
||||
includes/eventbus.hpp typed EventBus
|
||||
includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION)
|
||||
includes/toml++ vendored
|
||||
includes/spdlog vendored
|
||||
tests/ integration tests + run-tests.ps1 + copy-bin.bat
|
||||
docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog)
|
||||
examples/ runnable end-to-end examples (each has config.toml + HowToUse)
|
||||
script/ package.cmake / package.bat
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
### Services and the event bus
|
||||
|
||||
A service derives from `IService` (`src/libagent/includes/services/base.hpp`) and
|
||||
self-registers at file scope:
|
||||
|
||||
```cpp
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::MyService)
|
||||
```
|
||||
|
||||
Subscribe with the typed bus - there is no `EventId` and no `void*` casting:
|
||||
|
||||
```cpp
|
||||
listen<MyService, EventLoaded>(&MyService::onLoaded); // append
|
||||
listenFront<MyService, EventLoaded>(&MyService::onLoaded); // run before others
|
||||
```
|
||||
|
||||
Publish with `EventBus::getInstance().post(event)`. Call `unlistenAll()` in
|
||||
`onShutdown()`.
|
||||
|
||||
### Commit messages
|
||||
|
||||
`Type: subject`, then `- component: detail` bullets. Types used here:
|
||||
`Feat`, `BugFix`, `Refactor`, `Docs`, `CI`, and `Version X.Y.Z` for the release
|
||||
commit.
|
||||
|
||||
### Docs
|
||||
|
||||
`README.md` and `README_ZH.md` are kept in sync; keep both updated. Prose docs
|
||||
live in `docs/` (English). Release notes and the changelog live in `docs/update/`.
|
||||
|
||||
### Line endings
|
||||
|
||||
Tracked text files are **LF in the index, CRLF in the working tree** (no
|
||||
`.gitattributes`). When creating files, write CRLF to avoid noisy diffs.
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/ci.yml` has two jobs:
|
||||
|
||||
- `build-and-test` on `windows-latest`: JDK 25 (Temurin) + MinGW-w64 (MSYS2) +
|
||||
Ninja, then `configure -> build -> tests -> package`, uploading
|
||||
`dist/JuiceAgent_*.zip` as an artifact (14-day retention).
|
||||
- `build-linux` on `ubuntu-latest`: GCC + Ninja, then
|
||||
`configure -> build -> package` only — the integration tests are Windows-only —
|
||||
uploading `dist/JuiceAgent_*.tar.gz`.
|
||||
|
||||
CI-specific notes:
|
||||
|
||||
- It builds with `-static-libgcc -static-libstdc++` and also copies any remaining
|
||||
non-system imported DLLs next to the binaries (see rule 4).
|
||||
- The workflow prints the DLL import list - useful when a load error appears.
|
||||
- GitHub's unauthenticated REST API is limited to 60 requests/hour, so avoid
|
||||
polling workflow status in a loop; install `gh` or use a token instead.
|
||||
+16
-3
@@ -10,13 +10,26 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
|
||||
if(WIN32)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
endif()
|
||||
|
||||
# libraries
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
if (WIN32)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
else()
|
||||
set(PTRACE_INJECT_BUILD_CLI OFF CACHE BOOL "" FORCE)
|
||||
set(PTRACE_INJECT_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
|
||||
add_subdirectory(ptrace-inject-cpp)
|
||||
endif()
|
||||
|
||||
# modules
|
||||
add_subdirectory(${SRC_DIR}/libloader)
|
||||
add_subdirectory(${SRC_DIR}/injector)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
if(WIN32)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
endif()
|
||||
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
@@ -0,0 +1,403 @@
|
||||
# Quick Start for Agents
|
||||
|
||||
This guide tells an **agent** how to set up a JuiceAgent injection for a user:
|
||||
ask the right questions, generate the files, run the injection, and verify it.
|
||||
|
||||
Work through the steps in order. The result is a self-contained runtime
|
||||
directory called `app`, plus a short report to the user.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- Only inject into a JVM that the user owns or is authorized to test. If that is
|
||||
unclear, stop and ask before doing anything else.
|
||||
- Do not modify the JuiceAgent native sources. Configuration and payload changes
|
||||
cover almost every request.
|
||||
- Keep every file in one runtime directory: `config.toml`, both JARs and the
|
||||
four binaries. Relative paths only behave predictably when they sit next to
|
||||
each other (see [Step 4](#step-4--write-configtoml)).
|
||||
- Never guess a PID. Confirm it with the user or read it from the process list.
|
||||
|
||||
## Project overview
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM even when `DisableAttachMechanism=true` and without a
|
||||
`-javaagent` flag, loads a JAR and calls an entry point, and exposes native APIs
|
||||
to redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
## Step 1 — Check the environment (do this yourself, do not ask the user)
|
||||
|
||||
**1.1 JDK.** `javac`, `jar` and `jps` ship with the JDK, so a full JDK is
|
||||
required — a bare JRE is not enough.
|
||||
|
||||
```
|
||||
java -version
|
||||
```
|
||||
|
||||
If the JDK is missing or older than 1.8, ask the user to install JDK 1.8 or
|
||||
higher.
|
||||
|
||||
**1.2 JuiceAgent binaries.** When built from source they are in `build/bin`
|
||||
(release archives put them wherever they were extracted):
|
||||
|
||||
```
|
||||
ls build/bin
|
||||
```
|
||||
|
||||
Expected files:
|
||||
|
||||
```
|
||||
injector.exe libinject.dll libloader.dll libagent.dll
|
||||
```
|
||||
|
||||
If they are missing, ask the user to pick one of:
|
||||
|
||||
- **Method 1 (recommended):** download the latest release from
|
||||
https://github.com/xiaozhou233/JuiceAgent/releases/latest
|
||||
- **Method 2:** build from source — see the "How To Build" section of `README.md`
|
||||
|
||||
**1.3 Create the runtime directory.** Copy the four files into one directory and
|
||||
call it `app` for the rest of this guide. A complete `app` looks like:
|
||||
|
||||
```
|
||||
app/
|
||||
├─ injector.exe libinject.dll libloader.dll libagent.dll
|
||||
├─ config.toml # Step 4
|
||||
├─ payload.jar # Step 3 (Q3)
|
||||
├─ injection/ # Step 3 (Q5), dependency JARs; BuiltIn mode only
|
||||
├─ src/ # payload source, if you generate it
|
||||
└─ build/ # compiler output, one subdirectory per artifact
|
||||
├─ target/ # demo target classes
|
||||
└─ payload/ # payload classes
|
||||
```
|
||||
|
||||
## Step 2 — Gather requirements (ask the user)
|
||||
|
||||
Ask these six questions and translate them into the user's language. Each
|
||||
answer maps to a concrete decision, so do not skip any of them.
|
||||
|
||||
| # | Question | Decides |
|
||||
| --- | --- | --- |
|
||||
| Q1 | Which process do you want to inject into? (PID / process name / start a demo target — recommended) | the target and its working directory |
|
||||
| Q2 | Is the target a standard, unmodified JVM? | whether injection will work at all |
|
||||
| Q3 | What should the injected code do? (verify the link / your own code / modify bytecode) | the payload JAR, entry class and method |
|
||||
| Q4 | Does the payload need JuiceAgent-API? (yes / no / don't know) | `JarLoader.Mode` |
|
||||
| Q5 | Does the payload depend on other libraries? (yes / no) | `JarLoader.InjectionDir` |
|
||||
| Q6 | How should the injection be triggered? (`injector.exe` / JNI JavaInjector) | the commands in Step 5 |
|
||||
|
||||
## Step 3 — Apply the answers
|
||||
|
||||
### Q1 — Target process
|
||||
|
||||
- **PID:** remember it for Step 5.
|
||||
- **Process name:** resolve it to a PID with `jps -l`. Every JVM appears as
|
||||
`java.exe`, so match the main class or JAR path in the `jps -l` output, or use
|
||||
`Get-Process <name>` on Windows.
|
||||
- **Start a demo target (recommended when the user has no target):** write
|
||||
`app/target.java`:
|
||||
|
||||
```java
|
||||
import java.lang.management.ManagementFactory;
|
||||
|
||||
public class target {
|
||||
public static void main(String[] args) {
|
||||
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||
try {
|
||||
while (true) {
|
||||
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Compile and run it, **with `app` as the working directory**:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/target app/target.java
|
||||
```
|
||||
|
||||
```powershell
|
||||
Start-Process -FilePath java -ArgumentList "-cp","build/target","target" -WorkingDirectory "<path-to-app>"
|
||||
```
|
||||
|
||||
The target prints its PID every second; `jps -l` also lists it.
|
||||
|
||||
> Starting the target with `app` as its working directory is not cosmetic. See
|
||||
> [Step 4](#step-4--write-configtoml) for why the working directory decides which
|
||||
> `config.toml` the injected loader finds.
|
||||
|
||||
### Q2 — Standard JVM
|
||||
|
||||
- **Standard JVM / `DisableAttachMechanism=true`:** continue — JuiceAgent is
|
||||
designed for exactly this case.
|
||||
- **Custom or modified JVM:** continue, but warn the user that JuiceAgent is
|
||||
only tested against a regular JVM and may not work.
|
||||
|
||||
### Q3 — Payload
|
||||
|
||||
**Verify the link.** Write `app/src/Main.java`:
|
||||
|
||||
```java
|
||||
public class Main {
|
||||
public static void run() {
|
||||
System.out.println("[Demo] Injection succeeded! Hello from JuiceAgent.");
|
||||
System.out.println("[Demo] Current thread: " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Build it into `app/payload.jar`. Each artifact gets its own output directory, so
|
||||
packaging the payload never picks up the demo target's classes:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/payload app/src/Main.java
|
||||
jar --create --file app/payload.jar -C app/build/payload .
|
||||
```
|
||||
|
||||
The class name `Main` and method name `run` are needed in Step 4.
|
||||
|
||||
**Own code.** Ask the user for the payload JAR and record its fully qualified
|
||||
entry class and method. The entry method must be `public`, `static` and take no
|
||||
arguments (the project documents this as `public static void`; the return value
|
||||
is ignored). It is resolved by reflection, so a non-public, non-static or
|
||||
parameterized method is only reported as a failure at invocation time — the JAR
|
||||
itself still loads.
|
||||
|
||||
**Modify bytecode.** Point the user at `examples/retransform-class`. Payloads
|
||||
that redefine or retransform classes use JuiceAgent-API, so Q4 must resolve to
|
||||
`BuiltIn`.
|
||||
|
||||
### Q4 — JuiceAgent-API
|
||||
|
||||
| Answer | `JarLoader.Mode` |
|
||||
| --- | --- |
|
||||
| Yes | `BuiltIn` |
|
||||
| No | `CustomJar` |
|
||||
| I don't know | `BuiltIn` |
|
||||
|
||||
`BuiltIn` (recommended) runs in two stages, and **both stages read
|
||||
`config.toml` from the runtime directory**:
|
||||
|
||||
1. `libloader` extracts the embedded JuiceAgent-API JAR into `%TEMP%`, adds it
|
||||
to the system class loader and calls `JuiceAgentBootstrap.start`, which loads
|
||||
`libagent.dll` (from `JuiceAgentNativeLibraryPath`) and initializes the JVMTI
|
||||
agent.
|
||||
2. The agent's `JarLoaderService` reads the `JarLoader.*` keys again, then the
|
||||
`JarLoader` module adds every `*.jar` in `InjectionDir` to the system class
|
||||
loader, loads `JarPath` and invokes `EntryClass.EntryMethod`.
|
||||
|
||||
`Enabled` and `InjectionDir` are used in `BuiltIn` mode only. Omitting a key
|
||||
silently falls back to a default, which is a common source of confusion:
|
||||
`InjectionDir` defaults to `./injection`, `JarPath` to `./Entry.jar`,
|
||||
`EntryClass` to `Example.Main` and `EntryMethod` to `start`.
|
||||
|
||||
`CustomJar` skips JuiceAgent-API and `libagent.dll` entirely: `libloader` adds
|
||||
`JarPath` itself to the system class loader and invokes the entry method. In this
|
||||
mode `Enabled` and `InjectionDir` are ignored, so any library the payload needs
|
||||
must be bundled inside the payload JAR (or already on the target's classpath).
|
||||
|
||||
### Q5 — Other libraries
|
||||
|
||||
- **Yes:** create `app/injection/` and copy the dependency JARs into it. Every
|
||||
`*.jar` there is loaded before the payload (`BuiltIn` mode only).
|
||||
- **No:** still create the empty directory if the config references it, or drop
|
||||
`InjectionDir` from the config.
|
||||
|
||||
### Q6 — Injection way
|
||||
|
||||
- **`injector.exe`:** nothing to prepare, continue to Step 4.
|
||||
- **JNI JavaInjector:** copy the whole `examples/inject-via-java-api/injector`
|
||||
directory to `app/injector/`, then build it:
|
||||
|
||||
```
|
||||
app\injector\build.bat
|
||||
```
|
||||
|
||||
That directory ships a prebuilt `JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar`;
|
||||
`build.bat` merges the example's `JavaInjector.class` into it and sets the main
|
||||
class, so keep the JAR in place.
|
||||
|
||||
## Step 4 — Write config.toml
|
||||
|
||||
The file must be named exactly `config.toml` and placed in the directory that
|
||||
`libloader` treats as the **runtime directory** (see the table below). Do not
|
||||
rename it and do not scatter it across directories.
|
||||
|
||||
```toml
|
||||
# See docs/config.md for more information:
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
# BuiltIn: use the built-in jar loader (recommended; supports JuiceAgent-API)
|
||||
# CustomJar: load the JAR directly, without JuiceAgent-API
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
|
||||
# Q4
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# BuiltIn mode only; Q5
|
||||
InjectionDir = "./injection"
|
||||
|
||||
# Q3
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
- `Version` must stay `2`. A mismatch makes the loader refuse to start.
|
||||
- `JuiceAgentNativeLibraryPath = ""` means "`libagent.dll` in the runtime
|
||||
directory". Change it to an absolute path only if `libagent.dll` lives
|
||||
elsewhere.
|
||||
- `Mode = "CustomJar"` requires `JarPath`, `EntryClass` and `EntryMethod`
|
||||
(there are no defaults in that mode); `Enabled` and `InjectionDir` are unused.
|
||||
- Paths starting with `./` are resolved against the runtime directory; absolute
|
||||
paths are used as-is.
|
||||
|
||||
### Which directory is the runtime directory?
|
||||
|
||||
This is where most failed setups go wrong: `libloader` does not take the config
|
||||
directory from the `injector.exe` command line.
|
||||
|
||||
| How you inject | Directory `config.toml` is read from |
|
||||
| --- | --- |
|
||||
| Interactive `injector.exe` (type the PID) | the **injector process's** current directory — so `cd app` first |
|
||||
| `injector.exe <pid> <libloader.dll> [libinject.dll]` | the **target JVM's** current directory (no directory is passed) |
|
||||
| JavaInjector (JNI) | the `config_path` you enter; an empty value falls back to the target JVM's working directory |
|
||||
|
||||
Consequences:
|
||||
|
||||
- With the argument form, `config.toml` **and** every `./` path inside it
|
||||
(`JarPath`, `InjectionDir`, `libagent.dll`) resolve against the target JVM's
|
||||
working directory.
|
||||
- If the user cannot control the target's working directory, use absolute paths
|
||||
in `config.toml` — including `JuiceAgentNativeLibraryPath`.
|
||||
- JNI injection is the most predictable option, because the config directory is
|
||||
passed explicitly.
|
||||
|
||||
## Step 5 — Run the injection
|
||||
|
||||
### 5.1 Use `injector.exe`
|
||||
|
||||
```
|
||||
cd app
|
||||
```
|
||||
|
||||
`cd app` matters: `injector.exe` loads `libinject.dll` **by name from the
|
||||
current directory**, and in interactive mode the current directory is also the
|
||||
runtime directory.
|
||||
|
||||
**Interactive:**
|
||||
|
||||
```
|
||||
.\injector.exe
|
||||
```
|
||||
|
||||
It prints the `jps -l` output, then `Input PID:`. Type the PID of the target JVM
|
||||
and press Enter.
|
||||
|
||||
> The program always ends with `Press any key to exit...` and waits for stdin.
|
||||
> If you drive it from a script, feed it a newline after the PID and do not wait
|
||||
> for the process to exit on its own.
|
||||
|
||||
**With arguments:**
|
||||
|
||||
```
|
||||
.\injector.exe <PID> "<path-to-app>\libloader.dll" "<path-to-app>\libinject.dll"
|
||||
```
|
||||
|
||||
The third argument is the path to **`libinject.dll`**, not a config directory.
|
||||
Omit it to let `injector.exe` load `libinject.dll` from the current directory.
|
||||
Remember that this form reads `config.toml` from the *target's* working
|
||||
directory (Step 4).
|
||||
|
||||
### 5.2 Use JNI JavaInjector
|
||||
|
||||
Run it from `app`, because the example loads `./libinject.dll`:
|
||||
|
||||
```
|
||||
java -cp injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar JavaInjector
|
||||
```
|
||||
|
||||
```
|
||||
PID: 1234
|
||||
Dll: <path-to-app>\libloader.dll
|
||||
config_path: <path-to-app>
|
||||
```
|
||||
|
||||
Enter the target PID, the path to `libloader.dll`, and the directory containing
|
||||
`config.toml`. Leaving `config_path` empty behaves like the argument form above:
|
||||
the runtime directory falls back to the **target JVM's** working directory, so
|
||||
always pass the directory explicitly.
|
||||
|
||||
## Step 6 — Verify
|
||||
|
||||
Verification has two independent sources. Do not confuse them: the
|
||||
`[JuiceAgent JarLoader]` progress lines are printed to the **target's stdout**,
|
||||
while the diagnostic logs are written to **files**.
|
||||
|
||||
**1. Target stdout** — this is the user-visible proof:
|
||||
|
||||
```
|
||||
[JuiceAgent API] RuntimeDir : <the directory actually used>
|
||||
[JuiceAgent JarLoader] Loading entry jar: ...
|
||||
[JuiceAgent JarLoader] Resolving class: Main
|
||||
[JuiceAgent JarLoader] Invoking method: Main.run
|
||||
[JuiceAgent JarLoader] Entry method invoked successfully.
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
```
|
||||
|
||||
The `[JuiceAgent API]` banner prints the effective runtime directory and the
|
||||
native library path, which is the fastest way to confirm the Step 4 rules.
|
||||
|
||||
**2. Log files** — two files are written **relative to the target JVM's working
|
||||
directory** and truncated on every injection:
|
||||
|
||||
| File | Look for |
|
||||
| --- | --- |
|
||||
| `libloader.log` | `DllMain: DLL_PROCESS_ATTACH, runtime_dir:` and `[PreLoad] Runtime directory:` |
|
||||
| `libagent.log` | `[JuiceAgent] Added JVMTI capabilities`, `[JarLoaderService] Loaded jar:`, and `JNI Exception occurred at:` when the payload itself throws |
|
||||
|
||||
If the target has no console (a service or a detached window), the stdout
|
||||
markers are invisible — verify through the log files instead.
|
||||
|
||||
Report the outcome to the user, including the exact `app` path, the injection
|
||||
command used, and the observed output.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
| --- | --- |
|
||||
| Injection reports success but nothing happens | `config.toml` is not in the directory `libloader` actually used — see Step 4 |
|
||||
| `RuntimeDir :` in the banner is not `app` | The runtime directory fell back to the target JVM's working directory — see Step 4 |
|
||||
| `[JuiceAgent API] JuiceAgent library not found at: <path>` | `libagent.dll` could not be resolved — set an absolute `JuiceAgentNativeLibraryPath`, or fix the runtime directory |
|
||||
| `Failed to load injector library` / error 2 | `injector.exe` was not started from `app`, and no `libinject.dll` path was passed |
|
||||
| `Failed to open DLL file` | The `libloader.dll` path is wrong |
|
||||
| `libloader.log` / `libagent.log` seem missing | They are written in the target JVM's working directory, not your shell's |
|
||||
| Loader refuses to start | `[JuiceAgent] Version` is not `2` |
|
||||
| `Missing required config key: JarLoader.Mode` | `JarLoader.Mode` was omitted |
|
||||
| Errors about missing `JarPath` / `EntryClass` / `EntryMethod` | `Mode = "CustomJar"` requires all three |
|
||||
| `Failed to load jar: ...\Entry.jar` | `JarPath` was omitted and the default was used |
|
||||
| The JAR loads but the entry call fails | The method is not `public static` with no parameters, or `EntryClass` is not fully qualified |
|
||||
| `JNI Exception occurred at: CallStaticVoidMethod failed` | The payload threw — read the stack trace printed next to it |
|
||||
| The injected process hangs for ~30 s, then `Failed to attach to JVM!` | The target process is not a JVM (the loader retries 30 × 1 s before giving up) |
|
||||
| `jps` does not list the target | The target is 32-bit (JuiceAgent ships x64 only) or runs with different privileges |
|
||||
| Injection fails on an elevated target | Run `injector.exe` elevated too |
|
||||
| Antivirus flags the binaries | Expected false positive — see `docs/Antivirus-False-Positive.md` |
|
||||
| Native-access warning on JDK 22+ | The payload loads a native library; the target JVM needs `--enable-native-access=ALL-UNNAMED` |
|
||||
|
||||
## Done checklist
|
||||
|
||||
- [ ] A JDK 1.8+ with `javac`, `jar` and `jps` is available
|
||||
- [ ] `app/` contains all four JuiceAgent binaries
|
||||
- [ ] The payload JAR exists and its entry method is `public static` and takes no arguments
|
||||
- [ ] `config.toml` is in the directory `libloader` actually uses (Step 4), `Version = 2`, and every key matches the Q3–Q5 answers
|
||||
- [ ] The injection command reported success
|
||||
- [ ] The `[JuiceAgent API]` banner shows the expected `RuntimeDir`, and the payload output appears with no errors in the logs
|
||||
@@ -4,6 +4,11 @@
|
||||
|
||||
JuiceAgent is an advanced JVMTI-based injection framework for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation. It injects into a running JVM process even when `DisableAttachMechanism=true`, without requiring `-javaagent` startup arguments or the attach mechanism.
|
||||
|
||||
Two platforms are supported:
|
||||
|
||||
- **Windows x64** — reflective DLL injection (`injector.exe` + `libinject.dll`).
|
||||
- **Linux x64** — `ptrace` attach plus a remote `dlopen` call that makes the target JVM load `libloader.so` itself.
|
||||
|
||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||
|
||||
> **Tips**: Some antivirus software may flag JuiceAgent as malware. See [Antivirus False Positive Notice](docs/Antivirus-False-Positive.md) for details.
|
||||
@@ -14,6 +19,13 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ Group: 1103504356
|
||||
|
||||
> **New to JuiceAgent?** You do not have to wire up the injection by hand. A
|
||||
> coding agent such as OpenCode can do it for you: open this repository in the
|
||||
> agent and ask it to read [`QuickStartForAgents.md`](QuickStartForAgents.md) and
|
||||
> follow it. That guide covers the whole process — environment check, requirement
|
||||
> gathering, `config.toml`, injection and verification — and is written to be
|
||||
> executed by an agent. Simply tell the agent:
|
||||
> "Read `QuickStartForAgents.md` and follow it to inject my JAR."
|
||||
|
||||

|
||||

|
||||
@@ -25,7 +37,7 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -40,6 +52,7 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||
- [Features](#features)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Linux Support](#linux-support)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [Examples](#examples)
|
||||
- [How To Build](#how-to-build)
|
||||
@@ -69,6 +82,14 @@ With JuiceAgent, developers can:
|
||||
|
||||
The `JuiceAgent-API` jar is embedded in the native binaries, so no separate download is required.
|
||||
|
||||
On Linux the pipeline is the same, only the injection step changes. The injector
|
||||
attaches to the target process with `ptrace`, saves its registers, and performs a
|
||||
remote `dlopen` so the JVM loads `libloader.so` in-process (no `LD_PRELOAD`, no
|
||||
`-javaagent`). `libloader.so` then starts from an ELF constructor, resolves its
|
||||
runtime directory (`JuiceAgent_ConfigPath`, or `$HOME/.juiceagent` by default),
|
||||
and drives the agent exactly like the Windows loader. See
|
||||
[Linux Support](#linux-support).
|
||||
|
||||
## Features
|
||||
|
||||
- Load external JARs into the Bootstrap or System ClassLoader
|
||||
@@ -83,10 +104,10 @@ The `JuiceAgent-API` jar is embedded in the native binaries, so no separate down
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/libloader` — `libloader.dll`. Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll`. The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/injector` — `injector.exe`. Command-line driver that loads `libinject.dll` and injects `libloader.dll` into the target process.
|
||||
- `src/libinject` — `libinject.dll`. Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||
- `src/libloader` — `libloader.dll` (Windows) / `libloader.so` (Linux). Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll` (Windows) / `libagent.so` (Linux). The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/injector` — `injector.exe` (Windows) / `injector` (Linux). Command-line driver that loads the loader into the target process.
|
||||
- `src/libinject` — `libinject.dll` (Windows only). Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -96,6 +117,10 @@ The `JuiceAgent-API` jar is embedded in the native binaries, so no separate down
|
||||
|
||||
Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
||||
|
||||
> **Linux users**: Linux builds are **not** attached to GitHub Releases. Download
|
||||
> them from the [Jenkins job](https://jenkins.xiaozhou233.cn/job/JuiceAgent/)
|
||||
> instead — see [Linux Support](#linux-support).
|
||||
|
||||
Extract the ZIP file to a directory:
|
||||
|
||||
- YourDir
|
||||
@@ -174,6 +199,73 @@ See [Inject](docs/Inject.md)
|
||||
|
||||
The target JVM will load the specified JAR and execute the specified entry class and method.
|
||||
|
||||
## Linux Support
|
||||
|
||||
JuiceAgent also works on Linux x64. Instead of reflective DLL injection, the
|
||||
Linux injector uses `ptrace` to attach to the target process and then performs a
|
||||
**remote `dlopen`**: it saves the thread state, makes the target call
|
||||
`dlopen("libloader.so", RTLD_NOW)`, restores the state and detaches. The JVM
|
||||
therefore loads the loader itself — no `LD_PRELOAD` and no `-javaagent` — and the
|
||||
rest of the pipeline is identical to Windows.
|
||||
|
||||
### Download
|
||||
|
||||
Linux builds are **not** published on GitHub Releases. Download the latest
|
||||
successful build from the Jenkins job:
|
||||
|
||||
```text
|
||||
https://jenkins.xiaozhou233.cn/job/JuiceAgent/
|
||||
```
|
||||
|
||||
Grab the build artifact (`JuiceAgent_vX.Y.Z_x64_linux.tar.gz`) from the most
|
||||
recent successful build, then extract `injector`, `libloader.so` and
|
||||
`libagent.so` from it.
|
||||
|
||||
### Components
|
||||
|
||||
- `libloader.so` — loaded into the target JVM, starts from an ELF constructor.
|
||||
- `libagent.so` — the JVMTI agent. This is the default
|
||||
`JuiceAgentNativeLibraryPath` on Linux (instead of `libagent.dll`).
|
||||
- `injector` — attaches to the target PID and performs the remote `dlopen`.
|
||||
|
||||
### Configuration location
|
||||
|
||||
On Linux the loader does **not** look in the current working directory. It
|
||||
resolves the runtime directory in this order:
|
||||
|
||||
1. `JuiceAgent_ConfigPath` — if the environment variable is set and non-empty, it
|
||||
is used as-is.
|
||||
2. `$HOME/.juiceagent` — the default; created automatically if it does not exist.
|
||||
|
||||
`config.toml` is read from that directory. The schema is identical to Windows
|
||||
and relative paths (`JarPath`, `InjectionDir`, ...) are resolved against it, so a
|
||||
typical layout is:
|
||||
|
||||
```text
|
||||
~/.juiceagent/
|
||||
├── config.toml
|
||||
├── MyCustomJar.jar
|
||||
└── injection/
|
||||
└── Dependencies.jar
|
||||
```
|
||||
|
||||
To point the loader at another directory:
|
||||
|
||||
```bash
|
||||
export JuiceAgent_ConfigPath=/opt/juiceagent
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- Run the injector as the same user as the target JVM (or as `root`), and make
|
||||
sure `ptrace` is permitted. If injection fails with `EPERM`, check
|
||||
`/proc/sys/kernel/yama/ptrace_scope`.
|
||||
- The target JVM and the loader must both be x64.
|
||||
|
||||
> **Note**: The Linux injector binary is not open source yet. The `injector`
|
||||
> target in this repository is a placeholder that only prints a notice; the
|
||||
> loader and the agent are fully open source and build from this tree.
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
The following native functions are exposed to Java through the `cn.xiaozhou233.juiceagent.api.JuiceAgent` class (see the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) project for the Java API definition):
|
||||
@@ -203,7 +295,7 @@ The following native functions are exposed to Java through the `cn.xiaozhou233.j
|
||||
### Requirements
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- MinGW-w64 (Windows) or GCC/Clang (Linux)
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
@@ -227,7 +319,9 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
The generated binaries will be placed in `build/bin`.
|
||||
The generated binaries will be placed in `build/bin`. On Linux this produces
|
||||
`libloader.so`, `libagent.so` and `injector`; on Windows the `.dll` / `.exe`
|
||||
equivalents.
|
||||
|
||||
## Full Disclaimer
|
||||
|
||||
|
||||
+73
-7
@@ -6,6 +6,11 @@
|
||||
|
||||
JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加载、字节码变换和运行时 JVM 插桩。它可以在 `DisableAttachMechanism=true` 的情况下注入到正在运行的 JVM 进程中,无需 `-javaagent` 启动参数,也无需使用 attach 机制。
|
||||
|
||||
目前支持两个平台:
|
||||
|
||||
- **Windows x64**——反射式 DLL 注入(`injector.exe` + `libinject.dll`)。
|
||||
- **Linux x64**——通过 `ptrace` 附加目标进程,再用一次远程 `dlopen` 让目标 JVM 自己加载 `libloader.so`。
|
||||
|
||||
**警告**:本项目仍处于实验阶段,不建议用于生产环境。使用风险自负。
|
||||
|
||||
> **提示**:部分杀毒软件可能将 JuiceAgent 误报为恶意软件。详情见[杀毒软件误报说明](docs/Antivirus-False-Positive.md)。
|
||||
@@ -16,6 +21,9 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ 群:1103504356
|
||||
|
||||
> **不知道该怎么用?** 不必手动折腾注入流程:用支持读写文件和执行命令的 AI Agent(例如 OpenCode)即可。在本仓库中打开 Agent,让它先阅读 [`QuickStartForAgents.md`](QuickStartForAgents.md) 并照着执行——该文档覆盖了完整流程(环境检查、需求确认、`config.toml`、注入与验证),并且是专门写给 Agent 执行的。你只需要告诉它:
|
||||
> "请阅读 `QuickStartForAgents.md`,并照着里面的步骤把我的 JAR 注入到目标 JVM。"
|
||||
|
||||

|
||||

|
||||

|
||||
@@ -26,7 +34,7 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
@@ -41,6 +49,7 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||
- [特性](#特性)
|
||||
- [项目结构](#项目结构)
|
||||
- [快速开始](#快速开始)
|
||||
- [Linux 支持](#linux-支持)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [示例](#示例)
|
||||
- [如何构建](#如何构建)
|
||||
@@ -70,6 +79,8 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
`JuiceAgent-API` jar 内嵌于原生二进制中,无需单独下载。
|
||||
|
||||
Linux 上的流程与此相同,只有注入这一步不同。注入器通过 `ptrace` 附加到目标进程,保存线程状态,发起一次远程 `dlopen` 让 JVM 在自身进程内加载 `libloader.so`(无需 `LD_PRELOAD`,也无需 `-javaagent`)。随后 `libloader.so` 从 ELF constructor 启动,解析运行时目录(`JuiceAgent_ConfigPath`,默认 `$HOME/.juiceagent`),之后与 Windows 加载器完全一致地驱动 agent。详见 [Linux 支持](#linux-支持)。
|
||||
|
||||
## 特性
|
||||
|
||||
- 将外部 JAR 加载到 Bootstrap 或 System ClassLoader
|
||||
@@ -84,10 +95,10 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
## 项目结构
|
||||
|
||||
- `src/libloader` — `libloader.dll`。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||
- `src/libagent` — `libagent.dll`。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||
- `src/injector` — `injector.exe`。命令行驱动,加载 `libinject.dll` 并将 `libloader.dll` 注入到目标进程。
|
||||
- `src/libinject` — `libinject.dll`。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||
- `src/libloader` — `libloader.dll`(Windows)/ `libloader.so`(Linux)。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||
- `src/libagent` — `libagent.dll`(Windows)/ `libagent.so`(Linux)。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||
- `src/injector` — `injector.exe`(Windows)/ `injector`(Linux)。命令行驱动,将加载器注入到目标进程。
|
||||
- `src/libinject` — `libinject.dll`(仅 Windows)。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -97,6 +108,10 @@ JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
从 [releases](https://github.com/xiaozhou233/JuiceAgent/releases) 页面下载 `JuiceAgent_vx.x.x_x64.zip`。
|
||||
|
||||
> **Linux 用户注意**:Linux 构建**不会**发布在 GitHub Release 上,请从
|
||||
> [Jenkins](https://jenkins.xiaozhou233.cn/job/JuiceAgent/) 下载,详见
|
||||
> [Linux 支持](#linux-支持)。
|
||||
|
||||
解压 ZIP 到一个目录:
|
||||
|
||||
- YourDir
|
||||
@@ -175,6 +190,57 @@ Input PID:
|
||||
|
||||
目标 JVM 将加载指定的 JAR 并执行指定的入口类和入口方法。
|
||||
|
||||
## Linux 支持
|
||||
|
||||
JuiceAgent 同样支持 Linux x64。与反射式 DLL 注入不同,Linux 注入器使用 `ptrace` 附加目标进程,然后执行一次**远程 `dlopen`**:保存线程状态,让目标进程调用 `dlopen("libloader.so", RTLD_NOW)`,恢复状态并 detach。这样由 JVM 自己加载加载器——无需 `LD_PRELOAD`,也无需 `-javaagent`——其后的流程与 Windows 完全一致。
|
||||
|
||||
### 下载
|
||||
|
||||
Linux 构建**不会**发布在 GitHub Release 上,请从 Jenkins 任务下载最新一次成功的构建:
|
||||
|
||||
```text
|
||||
https://jenkins.xiaozhou233.cn/job/JuiceAgent/
|
||||
```
|
||||
|
||||
选择最近一次成功的构建,下载其产物(`JuiceAgent_vX.Y.Z_x64_linux.tar.gz`),从中解出
|
||||
`injector`、`libloader.so` 和 `libagent.so`。
|
||||
|
||||
### 组件
|
||||
|
||||
- `libloader.so` —— 加载进目标 JVM,从 ELF constructor 启动。
|
||||
- `libagent.so` —— JVMTI agent。在 Linux 上它是 `JuiceAgentNativeLibraryPath` 的默认值(而不是 `libagent.dll`)。
|
||||
- `injector` —— 附加到目标 PID 并执行远程 `dlopen`。
|
||||
|
||||
### 配置位置
|
||||
|
||||
Linux 上加载器**不会**在当前工作目录中查找配置,而是按以下顺序确定运行时目录:
|
||||
|
||||
1. `JuiceAgent_ConfigPath` —— 环境变量存在且非空时直接使用。
|
||||
2. `$HOME/.juiceagent` —— 默认值,目录不存在时会自动创建。
|
||||
|
||||
`config.toml` 从该目录读取,配置结构(schema)与 Windows 完全一致,相对路径(`JarPath`、`InjectionDir` 等)也以该目录为基准解析。典型目录结构:
|
||||
|
||||
```text
|
||||
~/.juiceagent/
|
||||
├── config.toml
|
||||
├── MyCustomJar.jar
|
||||
└── injection/
|
||||
└── Dependencies.jar
|
||||
```
|
||||
|
||||
如需指定其他目录:
|
||||
|
||||
```bash
|
||||
export JuiceAgent_ConfigPath=/opt/juiceagent
|
||||
```
|
||||
|
||||
### 环境要求
|
||||
|
||||
- 以与目标 JVM 相同的用户(或 `root`)运行注入器,并确保允许 `ptrace`。如果注入失败并返回 `EPERM`,请检查 `/proc/sys/kernel/yama/ptrace_scope`。
|
||||
- 目标 JVM 与加载器都必须是 x64。
|
||||
|
||||
> **注意**:Linux 注入器二进制目前尚未开源。本仓库中的 `injector` 目标只是一个占位程序,仅打印提示信息;加载器与 agent 完全开源,可直接从本仓库构建。
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
以下原生函数通过 `cn.xiaozhou233.juiceagent.api.JuiceAgent` 类暴露给 Java(Java API 定义见 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目):
|
||||
@@ -204,7 +270,7 @@ Input PID:
|
||||
### 环境要求
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- MinGW-w64(Windows)或 GCC/Clang(Linux)
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
@@ -228,7 +294,7 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
生成的二进制文件将放在 `build/bin` 中。
|
||||
生成的二进制文件将放在 `build/bin` 中。Linux 下会生成 `libloader.so`、`libagent.so` 和 `injector`;Windows 下为对应的 `.dll` / `.exe`。
|
||||
|
||||
## 完整免责声明
|
||||
|
||||
|
||||
@@ -3,5 +3,5 @@ out/
|
||||
|
||||
# Do not ignore root build artifacts:
|
||||
!new_target.class
|
||||
!playload.jar
|
||||
!payload.jar
|
||||
!target.jar
|
||||
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | Injection config |
|
||||
| `build.bat` | Build script |
|
||||
| `run.bat` | Run target JVM |
|
||||
| `playload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `payload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
|
||||
| `playload/` | Payload source |
|
||||
| `payload/` | Payload source |
|
||||
| `target/` | Target source |
|
||||
| `new_target/` | Modified copy of target source |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
This example injects `playload.jar` into a running JVM. The payload reads
|
||||
This example injects `payload.jar` into a running JVM. The payload reads
|
||||
`new_target.class` from its own JAR and calls
|
||||
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
|
||||
`target` class on the fly. After that, `say()` starts printing the new message
|
||||
@@ -41,14 +41,14 @@ without restarting the JVM.
|
||||
|
||||
### 1. Build (optional)
|
||||
|
||||
`playload.jar` and `target.jar` are already included by default.
|
||||
If you modified `playload/`, `target/` or `new_target/`, run:
|
||||
`payload.jar` and `target.jar` are already included by default.
|
||||
If you modified `payload/`, `target/` or `new_target/`, run:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
|
||||
to regenerate `payload.jar`, `target.jar` and `new_target.class`.
|
||||
|
||||
### 2. Run the target JVM
|
||||
|
||||
@@ -77,8 +77,8 @@ Input PID: 6644
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
and the output of `say()` changes from `Hello!` to:
|
||||
@@ -92,8 +92,8 @@ Retransformed!
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `playload`) |
|
||||
| `JarPath` | JAR path to inject (default: `./payload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `payload`) |
|
||||
| `EntryMethod` | Entry method, must be `public static void entry()` |
|
||||
|
||||
## Troubleshooting
|
||||
@@ -102,8 +102,8 @@ Retransformed!
|
||||
Install a JDK and add its `bin` directory to `PATH`.
|
||||
- `injector.exe` reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No `Playload loaded!` output appears:
|
||||
- No `Payload loaded!` output appears:
|
||||
Check `libagent.log` and `libloader.log` in this directory for the cause.
|
||||
- `say()` output does not change:
|
||||
Make sure `build.bat` was run after editing `new_target/`, and that
|
||||
`new_target.class` inside `playload.jar` is up to date.
|
||||
`new_target.class` inside `payload.jar` is up to date.
|
||||
@@ -9,10 +9,10 @@ Directory Files:
|
||||
config.toml - injection config
|
||||
build.bat - build script
|
||||
run.bat - run target JVM
|
||||
playload.jar - JAR to inject (built by build.bat)
|
||||
payload.jar - JAR to inject (built by build.bat)
|
||||
target.jar - target JVM program (built by build.bat)
|
||||
new_target.class - retransformed bytecode (built by build.bat)
|
||||
playload/ - payload source
|
||||
payload/ - payload source
|
||||
target/ - target source
|
||||
new_target/ - modified copy of target source
|
||||
|
||||
@@ -26,7 +26,7 @@ The target class "target" has a method say() that prints:
|
||||
new_target/target.java is a modified copy that also prints:
|
||||
Retransformed!
|
||||
|
||||
This example injects playload.jar into a running JVM. The payload reads
|
||||
This example injects payload.jar into a running JVM. The payload reads
|
||||
new_target.class from its own JAR and calls
|
||||
JuiceAgent.retransformClassByName("target", ...) to swap the already-loaded
|
||||
"target" class on the fly. After that, say() starts printing the new message
|
||||
@@ -37,10 +37,10 @@ without restarting the JVM.
|
||||
============================================
|
||||
|
||||
1. Build (optional)
|
||||
playload.jar and target.jar are already included by default.
|
||||
If you modified playload/, target/ or new_target/, run:
|
||||
payload.jar and target.jar are already included by default.
|
||||
If you modified payload/, target/ or new_target/, run:
|
||||
build.bat
|
||||
to regenerate playload.jar, target.jar and new_target.class.
|
||||
to regenerate payload.jar, target.jar and new_target.class.
|
||||
|
||||
2. Run the target JVM
|
||||
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||
@@ -57,8 +57,8 @@ without restarting the JVM.
|
||||
|
||||
4. Verify
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
and the output of say() changes from "Hello!" to:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -67,8 +67,8 @@ without restarting the JVM.
|
||||
Config / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - JAR path to inject (default: ./playload.jar)
|
||||
EntryClass - Entry class (default: playload)
|
||||
JarPath - JAR path to inject (default: ./payload.jar)
|
||||
EntryClass - Entry class (default: payload)
|
||||
EntryMethod - Entry method, must be public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -79,8 +79,8 @@ without restarting the JVM.
|
||||
Install a JDK and add its bin directory to PATH.
|
||||
- injector.exe reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No "Playload loaded!" output appears:
|
||||
- No "Payload loaded!" output appears:
|
||||
Check libagent.log and libloader.log in this directory for the cause.
|
||||
- say() output does not change:
|
||||
Make sure build.bat was run after editing new_target/, and that
|
||||
new_target.class inside playload.jar is up to date.
|
||||
new_target.class inside payload.jar is up to date.
|
||||
@@ -1,13 +1,13 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "API_JAR=playload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=playload.jar"
|
||||
set "API_JAR=payload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=payload.jar"
|
||||
set "TARGET_JAR=target.jar"
|
||||
|
||||
set "OUT=out"
|
||||
set "OUT_NT=%OUT%\new_target"
|
||||
set "OUT_PL=%OUT%\playload"
|
||||
set "OUT_PL=%OUT%\payload"
|
||||
set "OUT_TG=%OUT%\target"
|
||||
|
||||
set "NEW_TARGET_CLASS=new_target.class"
|
||||
@@ -29,8 +29,8 @@ if errorlevel 1 goto :error
|
||||
copy /y "%OUT_NT%\new_target.class" "%NEW_TARGET_CLASS%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling playload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" playload\playload.java
|
||||
echo === Compiling payload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" payload\payload.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling target ===
|
||||
@@ -38,7 +38,7 @@ javac -encoding UTF-8 --release 8 -d "%OUT_TG%" target\target.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging payload jar ===
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" playload.class
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" payload.class
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging target jar ===
|
||||
|
||||
@@ -14,6 +14,6 @@ Mode = "BuiltIn"
|
||||
|
||||
# InjectionDir only works when Mode is BuiltIn
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./playload.jar"
|
||||
EntryClass = "playload"
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "payload"
|
||||
EntryMethod = "entry"
|
||||
Binary file not shown.
File renamed without changes.
+3
-3
@@ -1,8 +1,8 @@
|
||||
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
|
||||
|
||||
public class playload {
|
||||
public class payload {
|
||||
public static void entry() throws java.io.IOException {
|
||||
System.out.println("Playload loaded!");
|
||||
System.out.println("Payload loaded!");
|
||||
|
||||
java.io.InputStream in = new java.io.FileInputStream("new_target.class");
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
@@ -20,6 +20,6 @@ public class playload {
|
||||
bytes.length
|
||||
);
|
||||
|
||||
System.out.println("Playload executed!");
|
||||
System.out.println("Payload executed!");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | 注入配置 |
|
||||
| `build.bat` | 构建脚本 |
|
||||
| `run.bat` | 运行目标 JVM |
|
||||
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `payload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
|
||||
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
|
||||
| `playload/` | payload 源码 |
|
||||
| `payload/` | payload 源码 |
|
||||
| `target/` | 目标类源码 |
|
||||
| `new_target/` | target 的修改版源码 |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 `payload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
|
||||
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -39,14 +39,14 @@ Retransformed!
|
||||
|
||||
### 1. 构建(可选)
|
||||
|
||||
`playload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
|
||||
`payload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `payload/`、`target/` 或 `new_target/`,运行:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
|
||||
重新生成 `payload.jar`、`target.jar` 和 `new_target.class`。
|
||||
|
||||
### 2. 运行目标 JVM
|
||||
|
||||
@@ -72,8 +72,8 @@ Input PID: 6644
|
||||
回到目标窗口,注入成功应看到:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
并且 `say()` 的输出从 `Hello!` 变为:
|
||||
@@ -87,8 +87,8 @@ Retransformed!
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `playload`) |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./payload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `payload`) |
|
||||
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
|
||||
|
||||
## 常见问题
|
||||
@@ -97,8 +97,8 @@ Retransformed!
|
||||
安装 JDK 并将 `bin` 目录加入 `PATH`。
|
||||
- `injector.exe` 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 `Playload loaded!` 输出:
|
||||
- 没有出现 `Payload loaded!` 输出:
|
||||
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
|
||||
- `say()` 输出没有变化:
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `payload.jar` 内的
|
||||
`new_target.class` 是最新的。
|
||||
@@ -9,10 +9,10 @@
|
||||
config.toml - 注入配置
|
||||
build.bat - 构建脚本
|
||||
run.bat - 运行目标 JVM
|
||||
playload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
payload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
target.jar - 目标 JVM 程序 (由 build.bat 生成)
|
||||
new_target.class - 重变换后的字节码 (由 build.bat 生成)
|
||||
playload/ - payload 源码
|
||||
payload/ - payload 源码
|
||||
target/ - 目标类源码
|
||||
new_target/ - target 的修改版源码
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
new_target/target.java 是它的修改版, 额外打印:
|
||||
Retransformed!
|
||||
|
||||
本示例把 playload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 payload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
在运行时动态替换已加载的 "target" 类。之后 say() 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -35,10 +35,10 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
============================================
|
||||
|
||||
1. 构建 (可选)
|
||||
playload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 playload/、target/ 或 new_target/, 运行:
|
||||
payload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 payload/、target/ 或 new_target/, 运行:
|
||||
build.bat
|
||||
重新生成 playload.jar、target.jar 和 new_target.class。
|
||||
重新生成 payload.jar、target.jar 和 new_target.class。
|
||||
|
||||
2. 运行目标 JVM
|
||||
双击 run.bat (或执行: java -jar target.jar)。黑窗口出现并每秒打印:
|
||||
@@ -53,8 +53,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
|
||||
4. 验证
|
||||
回到目标窗口, 注入成功应看到:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
并且 say() 的输出从 "Hello!" 变为:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -63,8 +63,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
配置 / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - 注入的 JAR 路径 (默认: ./playload.jar)
|
||||
EntryClass - 入口类 (默认: playload)
|
||||
JarPath - 注入的 JAR 路径 (默认: ./payload.jar)
|
||||
EntryClass - 入口类 (默认: payload)
|
||||
EntryMethod - 入口方法, 必须为 public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -75,8 +75,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
安装 JDK 并将 bin 目录加入 PATH。
|
||||
- injector.exe 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 "Playload loaded!" 输出:
|
||||
- 没有出现 "Payload loaded!" 输出:
|
||||
查看本目录下的 libagent.log 和 libloader.log 定位原因。
|
||||
- say() 输出没有变化:
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 playload.jar 内的
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 payload.jar 内的
|
||||
new_target.class 是最新的。
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JAWT_MD_H_
|
||||
#define _JAVASOFT_JAWT_MD_H_
|
||||
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include "jawt.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* X11-specific declarations for AWT native interface.
|
||||
* See notes in jawt.h for an example of use.
|
||||
*/
|
||||
typedef struct jawt_X11DrawingSurfaceInfo {
|
||||
Drawable drawable;
|
||||
Display* display;
|
||||
VisualID visualID;
|
||||
Colormap colormapID;
|
||||
int depth;
|
||||
/*
|
||||
* Since 1.4
|
||||
* Returns a pixel value from a set of RGB values.
|
||||
* This is useful for paletted color (256 color) modes.
|
||||
*/
|
||||
int (JNICALL *GetAWTColor)(JAWT_DrawingSurface* ds,
|
||||
int r, int g, int b);
|
||||
} JAWT_X11DrawingSurfaceInfo;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !_JAVASOFT_JAWT_MD_H_ */
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JNI_MD_H_
|
||||
#define _JAVASOFT_JNI_MD_H_
|
||||
|
||||
#ifndef __has_attribute
|
||||
#define __has_attribute(x) 0
|
||||
#endif
|
||||
|
||||
#ifndef JNIEXPORT
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIEXPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIEXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIEXPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIIMPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIIMPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIIMPORT
|
||||
#endif
|
||||
|
||||
#define JNICALL
|
||||
|
||||
typedef int jint;
|
||||
#ifdef _LP64
|
||||
typedef long jlong;
|
||||
#else
|
||||
typedef long long jlong;
|
||||
#endif
|
||||
|
||||
typedef signed char jbyte;
|
||||
|
||||
#endif /* !_JAVASOFT_JNI_MD_H_ */
|
||||
Submodule
+1
Submodule ptrace-inject-cpp added at 9d419c7a85.
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Linux counterpart of script/package.bat.
|
||||
#
|
||||
# Packs the Linux build in build/bin into
|
||||
# dist/JuiceAgent_v<major>.<minor>.<patch>_x64_linux.tar.gz
|
||||
#
|
||||
# Usage: ./script/package.sh
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
|
||||
|
||||
VERSION_FILE="${PROJECT_DIR}/Version.txt"
|
||||
BIN_DIR="${PROJECT_DIR}/build/bin"
|
||||
OUTPUT_DIR="${PROJECT_DIR}/dist"
|
||||
|
||||
# Read one "Key = value" entry from Version.txt.
|
||||
read_version_key() {
|
||||
local key="$1"
|
||||
sed -n -E "s/^[[:space:]]*${key}[[:space:]]*=[[:space:]]*([0-9]+)[[:space:]]*$/\1/p" \
|
||||
"${VERSION_FILE}" | head -n 1
|
||||
}
|
||||
|
||||
if [[ ! -f "${VERSION_FILE}" ]]; then
|
||||
echo "[ERROR] Version.txt not found: ${VERSION_FILE}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION_MAJOR="$(read_version_key Major)"
|
||||
VERSION_MINOR="$(read_version_key Minor)"
|
||||
VERSION_PATCH="$(read_version_key Patch)"
|
||||
|
||||
if [[ -z "${VERSION_MAJOR}" || -z "${VERSION_MINOR}" || -z "${VERSION_PATCH}" ]]; then
|
||||
echo "[ERROR] Invalid Version.txt: Major, Minor and Patch are required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Linux build artifacts (there is no libinject on this platform).
|
||||
PACKAGE_FILES=(
|
||||
injector
|
||||
libloader.so
|
||||
libagent.so
|
||||
)
|
||||
|
||||
for file_name in "${PACKAGE_FILES[@]}"; do
|
||||
if [[ ! -f "${BIN_DIR}/${file_name}" ]]; then
|
||||
echo "[ERROR] Required file not found: ${BIN_DIR}/${file_name}" >&2
|
||||
echo " Build first: cmake --preset release && cmake --build build" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
mkdir -p "${OUTPUT_DIR}"
|
||||
|
||||
OUTPUT_FILE="${OUTPUT_DIR}/JuiceAgent_v${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}_x64_linux.tar.gz"
|
||||
|
||||
rm -f "${OUTPUT_FILE}"
|
||||
|
||||
tar -czf "${OUTPUT_FILE}" -C "${BIN_DIR}" "${PACKAGE_FILES[@]}"
|
||||
|
||||
echo "[SUCCESS] Package created: ${OUTPUT_FILE}"
|
||||
@@ -1,2 +1,7 @@
|
||||
# injector
|
||||
add_executable(injector injector.c)
|
||||
if(WIN32)
|
||||
add_executable(injector injector.c)
|
||||
else()
|
||||
add_executable(injector injector_linux.cpp)
|
||||
target_link_libraries(injector PRIVATE ptrace_inject::ptrace_inject)
|
||||
endif()
|
||||
@@ -0,0 +1,115 @@
|
||||
#include <limits.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "ptrace_inject.h"
|
||||
|
||||
static void print_log(int level, const char* message, void* /*user_data*/) {
|
||||
const char* prefix = "[*]";
|
||||
switch (level) {
|
||||
case PTRACE_INJECT_LOG_DEBUG:
|
||||
prefix = "[debug]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_INFO:
|
||||
prefix = "[*]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_WARN:
|
||||
prefix = "[!]";
|
||||
break;
|
||||
case PTRACE_INJECT_LOG_ERROR:
|
||||
prefix = "[error]";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
std::fprintf(stderr, "%s %s\n", prefix, message);
|
||||
}
|
||||
|
||||
static void usage(const char* program) {
|
||||
std::fprintf(stderr,
|
||||
"Usage: %s (-p PID | -n NAME) <library.so>\n"
|
||||
"\n"
|
||||
"Inject a shared library into a running x86-64 Linux process.\n"
|
||||
"\n"
|
||||
" -p PID attach to this PID\n"
|
||||
" -n NAME attach to the first process whose executable name\n"
|
||||
" or path matches NAME\n"
|
||||
" -h show this help\n"
|
||||
"\n"
|
||||
"Requires the same uid and CAP_SYS_PTRACE, or a suitable\n"
|
||||
"kernel.yama.ptrace_scope setting.\n"
|
||||
"\n"
|
||||
"Example: %s -p 123456 ./libloader.so\n"
|
||||
"\n"
|
||||
"Default runtime directory: ${HOME}/.juiceagent/ \n"
|
||||
"See README for more information.\n",
|
||||
program, program);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
pid_t pid = -1;
|
||||
std::string name;
|
||||
|
||||
int option;
|
||||
while ((option = getopt(argc, argv, "p:n:h")) != -1) {
|
||||
switch (option) {
|
||||
case 'p': {
|
||||
try {
|
||||
const long value = std::stol(optarg);
|
||||
if (value <= 0 || value > INT_MAX) {
|
||||
throw std::out_of_range("pid");
|
||||
}
|
||||
pid = static_cast<pid_t>(value);
|
||||
} catch (const std::exception&) {
|
||||
std::fprintf(stderr, "error: invalid pid '%s'\n", optarg);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'n':
|
||||
name = optarg;
|
||||
break;
|
||||
case 'h':
|
||||
usage(argv[0]);
|
||||
return 0;
|
||||
default:
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (optind + 1 != argc) {
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
const char* library = argv[optind];
|
||||
|
||||
if ((pid == -1) == name.empty()) {
|
||||
std::fprintf(stderr, "error: specify exactly one of -p PID or -n NAME\n");
|
||||
usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
ptrace_inject_options options{};
|
||||
options.log_fn = print_log;
|
||||
|
||||
char error[512] = {};
|
||||
int result;
|
||||
if (!name.empty()) {
|
||||
result = ptrace_inject_by_name(name.c_str(), library, &options, nullptr,
|
||||
error, sizeof(error));
|
||||
} else {
|
||||
result = ptrace_inject_by_pid(pid, library, &options, error, sizeof(error));
|
||||
}
|
||||
|
||||
if (result != PTRACE_INJECT_OK) {
|
||||
std::fprintf(stderr, "error: %s\n", error);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -10,11 +10,17 @@ add_library(agent SHARED ${agent_sources})
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/includes
|
||||
)
|
||||
|
||||
target_link_libraries(agent PRIVATE
|
||||
ReflectiveDLLInjection
|
||||
jvm
|
||||
)
|
||||
if(WIN32)
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
target_link_libraries(agent PRIVATE jvm)
|
||||
else()
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/linux
|
||||
)
|
||||
endif()
|
||||
@@ -12,6 +12,15 @@ if (WIN32)
|
||||
)
|
||||
|
||||
list(APPEND loader_sources ${windows_sources})
|
||||
else()
|
||||
message(STATUS "Detected System: Linux or Other")
|
||||
|
||||
file(GLOB_RECURSE linux_sources CONFIGURE_DEPENDS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.c
|
||||
)
|
||||
|
||||
list(APPEND loader_sources ${linux_sources})
|
||||
endif()
|
||||
|
||||
add_library(loader SHARED ${loader_sources})
|
||||
@@ -27,11 +36,17 @@ endif()
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/includes
|
||||
)
|
||||
|
||||
target_link_libraries(loader PRIVATE
|
||||
jvm
|
||||
ReflectiveDLLInjection
|
||||
)
|
||||
if(WIN32)
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
target_link_libraries(loader PRIVATE jvm ReflectiveDLLInjection)
|
||||
else()
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/linux
|
||||
)
|
||||
endif()
|
||||
@@ -92,7 +92,14 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
|
||||
|
||||
JuiceAgent::Utils::Serializer ser;
|
||||
ser.add_kv("Version", cfg.get<int>("JuiceAgent.Version", -1));
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", (cfg.getRuntimeDir()/"libagent.dll").string()));
|
||||
|
||||
#ifdef _WIN32
|
||||
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.dll").string();
|
||||
#else
|
||||
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.so").string();
|
||||
#endif
|
||||
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", default_libagent_path));
|
||||
ser.add_kv("RuntimeDir", cfg.getRuntimeDir().string());
|
||||
|
||||
std::string args = ser.serialize();
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#include "JuiceAgent/Logger.hpp"
|
||||
#include "Loader.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static void run_loader() {
|
||||
const char* env = std::getenv("JuiceAgent_ConfigPath");
|
||||
std::string current_path;
|
||||
|
||||
if (env != nullptr && env[0] != '\0') {
|
||||
// Use the environment variable if it exists and is not empty.
|
||||
current_path = env;
|
||||
} else {
|
||||
spdlog::trace("[libloader] JuiceAgent_ConfigPath is not set");
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home == nullptr || home[0] == '\0') {
|
||||
spdlog::error("[libloader] HOME environment variable is not set");
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to $HOME/.juiceagent.
|
||||
fs::path config_dir = fs::path(home) / ".juiceagent";
|
||||
|
||||
std::error_code ec;
|
||||
fs::create_directories(config_dir, ec);
|
||||
|
||||
if (ec) {
|
||||
spdlog::error(
|
||||
"[libloader] Failed to create config directory: {}",
|
||||
ec.message()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
current_path = config_dir.string();
|
||||
}
|
||||
|
||||
spdlog::info("[libloader] current path: {}", current_path);
|
||||
|
||||
JuiceAgent::Loader::entrypoint(current_path.c_str());
|
||||
}
|
||||
|
||||
__attribute__((constructor))
|
||||
static void entry() {
|
||||
Logger::init();
|
||||
|
||||
spdlog::info("[libloader] loaded!");
|
||||
|
||||
std::thread([] {
|
||||
run_loader();
|
||||
}).detach();
|
||||
}
|
||||
Reference in new issue
Block a user