mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-07 17:08:13 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c8edb7294 | ||
|
|
2e2206e0ae | ||
|
|
a43648a24a | ||
|
|
f65f98bf65 | ||
|
|
26d14e15ad | ||
|
|
cee2cc76c4 | ||
|
|
daa33b6301 | ||
|
|
ef52973536 | ||
|
|
6a7bd0803a | ||
|
|
6c70c1c1e6 | ||
|
|
ddc222b8a2 | ||
|
|
5506a582ac | ||
|
|
63d872c98b | ||
|
|
ef9f5dde0d | ||
|
|
e35b7fdb97 | ||
|
|
efbbf382eb | ||
|
|
0b8d00900d | ||
|
|
9077596f25 | ||
|
|
0a8104a32e | ||
|
|
15a0ba4c1e | ||
|
|
d452c8a676 | ||
|
|
fb74b491fa | ||
|
|
2af6e11adc | ||
|
|
a3a98858fd | ||
|
|
d0652f2fd3 | ||
|
|
936f067363 | ||
|
|
041c3c7048 | ||
|
|
b48f74af58 | ||
|
|
6ec8849b20 | ||
|
|
db7cf1ed62 | ||
|
|
16e1e77068 | ||
|
|
1cfa694aa2 | ||
|
|
5898877136 | ||
|
|
a7d8cac565 | ||
|
|
0e73afca47 | ||
|
|
432941d694 | ||
|
|
ac521bf53c | ||
|
|
9720c9f14f | ||
|
|
4a224fdb9c | ||
|
|
671eb4d777 | ||
|
|
16cf816610 | ||
|
|
879f576c6e | ||
|
|
2df78cdbf5 | ||
|
|
a05ffc0ae1 | ||
|
|
6b4b218f09 | ||
|
|
4d0d46afd6 |
No files matched your search
@@ -29,11 +29,14 @@ MIN_SUPPORTED_GO_MAJOR_VERSION = 1
|
||||
MIN_SUPPORTED_GO_MINOR_VERSION = 24
|
||||
GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least $(MIN_SUPPORTED_GO_MAJOR_VERSION).$(MIN_SUPPORTED_GO_MINOR_VERSION)
|
||||
|
||||
SLIVER_PUBLIC_KEY ?= RWTZPg959v3b7tLG7VzKHRB1/QT+d3c71Uzetfa44qAoX5rH7mGoQTTR
|
||||
ARMORY_PUBLIC_KEY ?= RWSBpxpRWDrD7Fe+VvRE3c2VEDC2NK80rlNCj+BX0gz44Xw07r6KQD9L
|
||||
ARMORY_REPO_URL ?= https://api.github.com/repos/sliverarmory/armory/releases
|
||||
CLIENT_ASSETS_PKG = github.com/bishopfox/sliver/client/assets
|
||||
SLIVER_UPDATE_PKG = github.com/bishopfox/sliver/client/command/update
|
||||
|
||||
LDFLAGS = -ldflags "-s -w \
|
||||
-X $(SLIVER_UPDATE_PKG).SliverPublicKey=$(SLIVER_PUBLIC_KEY) \
|
||||
-X $(CLIENT_ASSETS_PKG).DefaultArmoryPublicKey=$(ARMORY_PUBLIC_KEY) \
|
||||
-X $(CLIENT_ASSETS_PKG).DefaultArmoryRepoURL=$(ARMORY_REPO_URL)"
|
||||
|
||||
|
||||
@@ -39,10 +39,6 @@ Please checkout the [wiki](https://sliver.sh/), or start a [GitHub discussion](h
|
||||
|
||||
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).
|
||||
|
||||
### License - GPLv3
|
||||
|
||||
Sliver is licensed under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html), some sub-components may have separate licenses. See their respective subdirectories in this project for details.
|
||||
+10
-5
@@ -34,12 +34,19 @@ const (
|
||||
SliverClientDirName = ".sliver-client"
|
||||
|
||||
versionFileName = "version"
|
||||
envVarName = "SLIVER_CLIENT_ROOT_DIR"
|
||||
)
|
||||
|
||||
// GetRootAppDir - Get the Sliver app dir ~/.sliver-client/
|
||||
func GetRootAppDir() string {
|
||||
user, _ := user.Current()
|
||||
dir := filepath.Join(user.HomeDir, SliverClientDirName)
|
||||
value := os.Getenv(envVarName)
|
||||
var dir string
|
||||
if len(value) == 0 {
|
||||
user, _ := user.Current()
|
||||
dir = filepath.Join(user.HomeDir, SliverClientDirName)
|
||||
} else {
|
||||
dir = value
|
||||
}
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
err = os.MkdirAll(dir, 0700)
|
||||
if err != nil {
|
||||
@@ -116,7 +123,5 @@ under certain conditions; type 'licenses' for details.`)
|
||||
}
|
||||
saveAssetVersion(appDir)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(appDir, settingsFileName)); os.IsNotExist(err) {
|
||||
SaveSettings(nil)
|
||||
}
|
||||
_, _ = LoadSettings()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func legacyBackupPath(legacyPath string) string {
|
||||
dir := filepath.Dir(legacyPath)
|
||||
base := filepath.Base(legacyPath)
|
||||
name := strings.TrimSuffix(base, filepath.Ext(base))
|
||||
return filepath.Join(dir, "."+name+".json-old")
|
||||
}
|
||||
|
||||
func renameLegacyConfig(legacyPath string) error {
|
||||
if _, err := os.Stat(legacyPath); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
backupPath := legacyBackupPath(legacyPath)
|
||||
if _, err := os.Stat(backupPath); err == nil {
|
||||
if err := os.Remove(backupPath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.Rename(legacyPath, backupPath)
|
||||
}
|
||||
+39
-16
@@ -22,35 +22,58 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
settingsFileName = "tui-settings.json"
|
||||
settingsFileName = "tui-settings.yaml"
|
||||
settingsLegacyFileName = "tui-settings.json"
|
||||
)
|
||||
|
||||
// ClientSettings - Client JSON config
|
||||
type ClientSettings struct {
|
||||
TableStyle string `json:"tables"`
|
||||
AutoAdult bool `json:"autoadult"`
|
||||
BeaconAutoResults bool `json:"beacon_autoresults"`
|
||||
SmallTermWidth int `json:"small_term_width"`
|
||||
AlwaysOverflow bool `json:"always_overflow"`
|
||||
VimMode bool `json:"vim_mode"`
|
||||
UserConnect bool `json:"user_connect"`
|
||||
ConsoleLogs bool `json:"console_logs"`
|
||||
TableStyle string `json:"tables" yaml:"tables"`
|
||||
AutoAdult bool `json:"autoadult" yaml:"autoadult"`
|
||||
BeaconAutoResults bool `json:"beacon_autoresults" yaml:"beacon_autoresults"`
|
||||
SmallTermWidth int `json:"small_term_width" yaml:"small_term_width"`
|
||||
AlwaysOverflow bool `json:"always_overflow" yaml:"always_overflow"`
|
||||
VimMode bool `json:"vim_mode" yaml:"vim_mode"`
|
||||
UserConnect bool `json:"user_connect" yaml:"user_connect"`
|
||||
ConsoleLogs bool `json:"console_logs" yaml:"console_logs"`
|
||||
}
|
||||
|
||||
// LoadSettings - Load the client settings from disk
|
||||
func LoadSettings() (*ClientSettings, error) {
|
||||
rootDir, _ := filepath.Abs(GetRootAppDir())
|
||||
data, err := os.ReadFile(filepath.Join(rootDir, settingsFileName))
|
||||
if err != nil {
|
||||
settingsPath := filepath.Join(rootDir, settingsFileName)
|
||||
legacyPath := filepath.Join(rootDir, settingsLegacyFileName)
|
||||
settings := defaultSettings()
|
||||
migratedLegacy := false
|
||||
|
||||
data, err := os.ReadFile(settingsPath)
|
||||
if err == nil {
|
||||
if err = yaml.Unmarshal(data, settings); err != nil {
|
||||
return defaultSettings(), err
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return defaultSettings(), err
|
||||
} else if data, err = os.ReadFile(legacyPath); err == nil {
|
||||
if err = json.Unmarshal(data, settings); err != nil {
|
||||
return defaultSettings(), err
|
||||
}
|
||||
migratedLegacy = true
|
||||
} else if !os.IsNotExist(err) {
|
||||
return defaultSettings(), err
|
||||
}
|
||||
settings := defaultSettings()
|
||||
err = json.Unmarshal(data, settings)
|
||||
if err != nil {
|
||||
return defaultSettings(), err
|
||||
|
||||
if err := SaveSettings(settings); err != nil {
|
||||
return settings, err
|
||||
}
|
||||
if migratedLegacy {
|
||||
if err := renameLegacyConfig(legacyPath); err != nil {
|
||||
return settings, err
|
||||
}
|
||||
}
|
||||
return settings, nil
|
||||
}
|
||||
@@ -73,7 +96,7 @@ func SaveSettings(settings *ClientSettings) error {
|
||||
if settings == nil {
|
||||
settings = defaultSettings()
|
||||
}
|
||||
data, err := json.MarshalIndent(settings, "", " ")
|
||||
data, err := yaml.Marshal(settings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadSettingsParsesYAML(t *testing.T) {
|
||||
t.Setenv(envVarName, t.TempDir())
|
||||
|
||||
rootDir, _ := filepath.Abs(GetRootAppDir())
|
||||
settingsPath := filepath.Join(rootDir, settingsFileName)
|
||||
|
||||
data := []byte(`tables: "Compact"
|
||||
autoadult: true
|
||||
beacon_autoresults: false
|
||||
small_term_width: 120
|
||||
always_overflow: true
|
||||
vim_mode: true
|
||||
user_connect: true
|
||||
console_logs: false
|
||||
`)
|
||||
if err := os.WriteFile(settingsPath, data, 0o600); err != nil {
|
||||
t.Fatalf("failed to write yaml settings: %v", err)
|
||||
}
|
||||
|
||||
settings, err := LoadSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if settings.TableStyle != "Compact" {
|
||||
t.Fatalf("expected TableStyle %q, got %q", "Compact", settings.TableStyle)
|
||||
}
|
||||
if !settings.AutoAdult {
|
||||
t.Fatalf("expected AutoAdult true")
|
||||
}
|
||||
if settings.BeaconAutoResults {
|
||||
t.Fatalf("expected BeaconAutoResults false")
|
||||
}
|
||||
if settings.SmallTermWidth != 120 {
|
||||
t.Fatalf("expected SmallTermWidth %d, got %d", 120, settings.SmallTermWidth)
|
||||
}
|
||||
if !settings.AlwaysOverflow {
|
||||
t.Fatalf("expected AlwaysOverflow true")
|
||||
}
|
||||
if !settings.VimMode {
|
||||
t.Fatalf("expected VimMode true")
|
||||
}
|
||||
if !settings.UserConnect {
|
||||
t.Fatalf("expected UserConnect true")
|
||||
}
|
||||
if settings.ConsoleLogs {
|
||||
t.Fatalf("expected ConsoleLogs false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSettingsMigratesLegacyJSON(t *testing.T) {
|
||||
t.Setenv(envVarName, t.TempDir())
|
||||
|
||||
rootDir, _ := filepath.Abs(GetRootAppDir())
|
||||
legacyPath := filepath.Join(rootDir, settingsLegacyFileName)
|
||||
|
||||
legacy := &ClientSettings{
|
||||
TableStyle: "Legacy",
|
||||
AutoAdult: true,
|
||||
BeaconAutoResults: false,
|
||||
SmallTermWidth: 200,
|
||||
AlwaysOverflow: true,
|
||||
VimMode: true,
|
||||
UserConnect: true,
|
||||
ConsoleLogs: false,
|
||||
}
|
||||
data, err := json.MarshalIndent(legacy, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal legacy settings: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(legacyPath, data, 0o600); err != nil {
|
||||
t.Fatalf("failed to write legacy settings: %v", err)
|
||||
}
|
||||
|
||||
settings, err := LoadSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if settings.TableStyle != "Legacy" {
|
||||
t.Fatalf("expected TableStyle %q, got %q", "Legacy", settings.TableStyle)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(rootDir, settingsFileName)); err != nil {
|
||||
t.Fatalf("expected yaml settings to exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected legacy settings to be renamed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyBackupPath(legacyPath)); err != nil {
|
||||
t.Fatalf("expected legacy backup to exist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSettingsWritesDefault(t *testing.T) {
|
||||
t.Setenv(envVarName, t.TempDir())
|
||||
|
||||
settings, err := LoadSettings()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if settings.TableStyle != "SliverDefault" {
|
||||
t.Fatalf("expected default TableStyle %q, got %q", "SliverDefault", settings.TableStyle)
|
||||
}
|
||||
rootDir, _ := filepath.Abs(GetRootAppDir())
|
||||
if _, err := os.Stat(filepath.Join(rootDir, settingsFileName)); err != nil {
|
||||
t.Fatalf("expected default settings to be written: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ import (
|
||||
func BeaconsCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
killFlag, _ := cmd.Flags().GetString("kill")
|
||||
killAll, _ := cmd.Flags().GetBool("kill-all")
|
||||
interact, _ := cmd.Flags().GetString("interact")
|
||||
|
||||
// Handle kill
|
||||
if killFlag != "" {
|
||||
@@ -72,6 +73,18 @@ func BeaconsCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
con.PrintInfof("Killed %s (%s)\n", beacon.Name, beacon.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if interact != "" {
|
||||
beacon, err := GetBeacon(con, interact)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
con.ActiveTarget.Set(nil, beacon)
|
||||
con.PrintInfof("Active beacon %s (%s)\n", beacon.Name, strings.Split(beacon.ID, "-")[0])
|
||||
return
|
||||
}
|
||||
|
||||
filter, _ := cmd.Flags().GetString("filter")
|
||||
var filterRegex *regexp.Regexp
|
||||
if filterRe, _ := cmd.Flags().GetString("filter-re"); filterRe != "" {
|
||||
|
||||
@@ -33,6 +33,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
flags.Bind("beacons", false, beaconsCmd, func(f *pflag.FlagSet) {
|
||||
f.StringP("kill", "k", "", "kill the designated beacon")
|
||||
f.BoolP("kill-all", "K", false, "kill all beacons")
|
||||
f.StringP("interact", "i", "", "interact with a beacon")
|
||||
f.BoolP("force", "F", false, "force killing the beacon")
|
||||
|
||||
f.StringP("filter", "f", "", "filter beacons by substring")
|
||||
@@ -40,7 +41,9 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
})
|
||||
flags.BindFlagCompletions(beaconsCmd, func(comp *carapace.ActionMap) {
|
||||
(*comp)["kill"] = BeaconIDCompleter(con)
|
||||
(*comp)["interact"] = BeaconIDCompleter(con)
|
||||
})
|
||||
registerBeaconIDFlagCompletion(beaconsCmd, "interact", con)
|
||||
beaconsRmCmd := &cobra.Command{
|
||||
Use: consts.RmStr,
|
||||
Short: "Remove a beacon",
|
||||
@@ -81,22 +84,74 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
// BeaconIDCompleter completes beacon IDs
|
||||
func BeaconIDCompleter(con *console.SliverClient) carapace.Action {
|
||||
callback := func(_ carapace.Context) carapace.Action {
|
||||
results := make([]string, 0)
|
||||
|
||||
beacons, err := con.Rpc.GetBeacons(context.Background(), &commonpb.Empty{})
|
||||
if err == nil {
|
||||
for _, b := range beacons.Beacons {
|
||||
link := fmt.Sprintf("[%s <- %s]", b.ActiveC2, b.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", b.Name, b.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", b.Username, b.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, b.ID[:8])
|
||||
results = append(results, desc)
|
||||
}
|
||||
}
|
||||
return carapace.ActionValuesDescribed(results...).Tag("beacons")
|
||||
return carapace.ActionValuesDescribed(beaconCompletionPairs(con)...).Tag("beacons")
|
||||
}
|
||||
|
||||
return carapace.ActionCallback(callback)
|
||||
}
|
||||
|
||||
func registerBeaconIDFlagCompletion(cmd *cobra.Command, name string, con *console.SliverClient) {
|
||||
if cmd == nil {
|
||||
return
|
||||
}
|
||||
if _, ok := cmd.GetFlagCompletionFunc(name); ok {
|
||||
return
|
||||
}
|
||||
if cmd.Flags().Lookup(name) == nil && cmd.PersistentFlags().Lookup(name) == nil {
|
||||
return
|
||||
}
|
||||
_ = cmd.RegisterFlagCompletionFunc(name, func(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
values := describedValuesToTabs(beaconCompletionPairs(con))
|
||||
return filterCompletionValues(values, toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
})
|
||||
}
|
||||
|
||||
func beaconCompletionPairs(con *console.SliverClient) []string {
|
||||
results := make([]string, 0)
|
||||
if con == nil || con.Rpc == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
beacons, err := con.Rpc.GetBeacons(context.Background(), &commonpb.Empty{})
|
||||
if err != nil {
|
||||
return results
|
||||
}
|
||||
|
||||
for _, b := range beacons.Beacons {
|
||||
link := fmt.Sprintf("[%s <- %s]", b.ActiveC2, b.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", b.Name, b.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", b.Username, b.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, b.ID[:8], desc)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func describedValuesToTabs(values []string) []string {
|
||||
tabbed := make([]string, 0, len(values)/2)
|
||||
for i := 0; i+1 < len(values); i += 2 {
|
||||
tabbed = append(tabbed, fmt.Sprintf("%s\t%s", values[i], values[i+1]))
|
||||
}
|
||||
return tabbed
|
||||
}
|
||||
|
||||
func filterCompletionValues(values []string, prefix string) []string {
|
||||
if prefix == "" {
|
||||
return values
|
||||
}
|
||||
|
||||
filtered := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
candidate := value
|
||||
if tab := strings.IndexByte(value, '\t'); tab >= 0 {
|
||||
candidate = value[:tab]
|
||||
}
|
||||
if strings.HasPrefix(candidate, prefix) {
|
||||
filtered = append(filtered, value)
|
||||
}
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func PrintCanaries(con *console.SliverClient, canaries []*clientpb.DNSCanary, bu
|
||||
tw := table.NewWriter()
|
||||
tw.SetStyle(settings.GetTableStyle(con))
|
||||
tw.AppendHeader(table.Row{
|
||||
"Sliver Name",
|
||||
"Implant Name",
|
||||
"Domain",
|
||||
"Triggered",
|
||||
"First Trigger",
|
||||
|
||||
@@ -357,6 +357,7 @@ func coreImplantFlagCompletions(cmd *cobra.Command, con *console.SliverClient) {
|
||||
(*comp)["traffic-encoders"] = TrafficEncodersCompleter(con).UniqueList(",")
|
||||
(*comp)["c2profile"] = HTTPC2Completer(con)
|
||||
})
|
||||
registerImplantTargetFlagCompletions(cmd, con)
|
||||
}
|
||||
|
||||
// coreBeaconFlags binds all flags specific to beacon implants (profiles or compiled).
|
||||
|
||||
@@ -22,7 +22,8 @@ var (
|
||||
// GenerateBeaconCmd - The main command used to generate implant binaries
|
||||
func GenerateBeaconCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
if shouldRunGenerateBeaconForm(cmd, con, args) {
|
||||
result, err := forms.GenerateBeaconForm()
|
||||
compiler, _ := compilerTargets(con)
|
||||
result, err := forms.GenerateBeaconForm(compiler)
|
||||
if err != nil {
|
||||
if errors.Is(err, forms.ErrUserAborted) {
|
||||
return
|
||||
|
||||
@@ -91,7 +91,8 @@ var (
|
||||
// GenerateCmd - The main command used to generate implant binaries
|
||||
func GenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
if shouldRunGenerateForm(cmd, con, args) {
|
||||
result, err := forms.GenerateForm()
|
||||
compiler, _ := compilerTargets(con)
|
||||
result, err := forms.GenerateForm(compiler)
|
||||
if err != nil {
|
||||
if errors.Is(err, forms.ErrUserAborted) {
|
||||
return
|
||||
@@ -118,14 +119,15 @@ func GenerateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
} else {
|
||||
_, err := externalBuild(name, config, save, con)
|
||||
if err != nil {
|
||||
if err == ErrNoExternalBuilder {
|
||||
switch err {
|
||||
case ErrNoExternalBuilder:
|
||||
con.PrintErrorf("There are no external builders currently connected to the server\n")
|
||||
con.PrintErrorf("See 'builders' command for more information\n")
|
||||
} else if err == ErrNoValidBuilders {
|
||||
case ErrNoValidBuilders:
|
||||
con.PrintErrorf("There are external builders connected to the server, but none can build the target you specified\n")
|
||||
con.PrintErrorf("Invalid target %s\n", fmt.Sprintf("%s:%s/%s", config.Format, config.GOOS, config.GOARCH))
|
||||
con.PrintErrorf("See 'builders' command for more information\n")
|
||||
} else {
|
||||
default:
|
||||
con.PrintErrorf("%s\n", err)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -3,11 +3,13 @@ package generate
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/rsteube/carapace"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// GetSliverBinary - Get the binary of an implant based on it's profile.
|
||||
@@ -51,71 +53,112 @@ func GetSliverBinary(profile *clientpb.ImplantProfile, con *console.SliverClient
|
||||
return data, err
|
||||
}
|
||||
|
||||
func compilerTargets(con *console.SliverClient) (*clientpb.Compiler, error) {
|
||||
if con == nil || con.Rpc == nil {
|
||||
return nil, fmt.Errorf("no compiler info")
|
||||
}
|
||||
return con.Rpc.GetCompiler(context.Background(), &commonpb.Empty{})
|
||||
}
|
||||
|
||||
func appendUnique(values []string, value string) []string {
|
||||
for _, existing := range values {
|
||||
if existing == value {
|
||||
return values
|
||||
}
|
||||
}
|
||||
return append(values, value)
|
||||
}
|
||||
|
||||
func compilerArchValues(compiler *clientpb.Compiler) []string {
|
||||
results := []string{}
|
||||
|
||||
for _, target := range compiler.Targets {
|
||||
results = appendUnique(results, target.GOARCH)
|
||||
}
|
||||
|
||||
for _, target := range compiler.UnsupportedTargets {
|
||||
results = appendUnique(results, target.GOARCH)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func compilerOSValues(compiler *clientpb.Compiler) []string {
|
||||
results := []string{}
|
||||
|
||||
for _, target := range compiler.Targets {
|
||||
results = appendUnique(results, target.GOOS)
|
||||
}
|
||||
|
||||
for _, target := range compiler.UnsupportedTargets {
|
||||
results = appendUnique(results, target.GOOS)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func filterByPrefix(values []string, prefix string) []string {
|
||||
if prefix == "" {
|
||||
return values
|
||||
}
|
||||
|
||||
filtered := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if strings.HasPrefix(value, prefix) {
|
||||
filtered = append(filtered, value)
|
||||
}
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
|
||||
func registerTargetFlagCompletion(cmd *cobra.Command, name string, valuesFn func(*clientpb.Compiler) []string, con *console.SliverClient) {
|
||||
if cmd == nil {
|
||||
return
|
||||
}
|
||||
if _, ok := cmd.GetFlagCompletionFunc(name); ok {
|
||||
return
|
||||
}
|
||||
if cmd.Flags().Lookup(name) == nil && cmd.PersistentFlags().Lookup(name) == nil {
|
||||
return
|
||||
}
|
||||
_ = cmd.RegisterFlagCompletionFunc(name, func(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
compiler, err := compilerTargets(con)
|
||||
if err != nil {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
||||
values := valuesFn(compiler)
|
||||
return filterByPrefix(values, toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
})
|
||||
}
|
||||
|
||||
func registerImplantTargetFlagCompletions(cmd *cobra.Command, con *console.SliverClient) {
|
||||
registerTargetFlagCompletion(cmd, "os", compilerOSValues, con)
|
||||
registerTargetFlagCompletion(cmd, "arch", compilerArchValues, con)
|
||||
}
|
||||
|
||||
// FormatCompleter completes builds' architectures.
|
||||
func ArchCompleter(con *console.SliverClient) carapace.Action {
|
||||
return carapace.ActionCallback(func(_ carapace.Context) carapace.Action {
|
||||
compiler, err := con.Rpc.GetCompiler(context.Background(), &commonpb.Empty{})
|
||||
compiler, err := compilerTargets(con)
|
||||
if err != nil {
|
||||
return carapace.ActionMessage("No compiler info: %s", err.Error())
|
||||
}
|
||||
|
||||
var results []string
|
||||
|
||||
nextTarget:
|
||||
for _, target := range compiler.Targets {
|
||||
for _, res := range results {
|
||||
if res == target.GOARCH {
|
||||
continue nextTarget
|
||||
}
|
||||
}
|
||||
results = append(results, target.GOARCH)
|
||||
}
|
||||
|
||||
nextUnsupported:
|
||||
for _, target := range compiler.UnsupportedTargets {
|
||||
for _, res := range results {
|
||||
if res == target.GOARCH {
|
||||
continue nextUnsupported
|
||||
}
|
||||
}
|
||||
results = append(results, target.GOARCH)
|
||||
}
|
||||
|
||||
return carapace.ActionValues(results...).Tag("architectures")
|
||||
return carapace.ActionValues(compilerArchValues(compiler)...).Tag("architectures")
|
||||
})
|
||||
}
|
||||
|
||||
// FormatCompleter completes build operating systems.
|
||||
func OSCompleter(con *console.SliverClient) carapace.Action {
|
||||
return carapace.ActionCallback(func(_ carapace.Context) carapace.Action {
|
||||
compiler, err := con.Rpc.GetCompiler(context.Background(), &commonpb.Empty{})
|
||||
compiler, err := compilerTargets(con)
|
||||
if err != nil {
|
||||
return carapace.ActionMessage("No compiler info: %s", err.Error())
|
||||
}
|
||||
|
||||
var results []string
|
||||
|
||||
nextTarget:
|
||||
for _, target := range compiler.Targets {
|
||||
for _, res := range results {
|
||||
if res == target.GOOS {
|
||||
continue nextTarget
|
||||
}
|
||||
}
|
||||
results = append(results, target.GOOS)
|
||||
}
|
||||
|
||||
nextUnsupported:
|
||||
for _, target := range compiler.UnsupportedTargets {
|
||||
for _, res := range results {
|
||||
if res == target.GOOS {
|
||||
continue nextUnsupported
|
||||
}
|
||||
}
|
||||
results = append(results, target.GOOS)
|
||||
}
|
||||
|
||||
return carapace.ActionValues(results...).Tag("operating systems")
|
||||
return carapace.ActionValues(compilerOSValues(compiler)...).Tag("operating systems")
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ func PrintImplantBuilds(builds *clientpb.ImplantBuilds, filters ImplantBuildFilt
|
||||
config.Format,
|
||||
strings.Join(c2URLs, "\n"),
|
||||
fmt.Sprintf("%v", config.Debug),
|
||||
fmt.Sprintf(config.HTTPC2ConfigName),
|
||||
fmt.Sprintf("%s", config.HTTPC2ConfigName),
|
||||
fmt.Sprintf("%v", builds.ResourceIDs[sliverName].Value),
|
||||
fmt.Sprintf("%v", builds.Staged[sliverName]),
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"github.com/bishopfox/sliver/client/command/settings"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
slivermcp "github.com/bishopfox/sliver/client/mcp"
|
||||
"github.com/spf13/cobra"
|
||||
@@ -26,6 +27,12 @@ func McpStartCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
ServerVersion: version,
|
||||
}.WithDefaults()
|
||||
|
||||
msg := `Do you know what prompt injection is and are you an adult?`
|
||||
if !settings.IsUserAnAdultWithPrompt(con, msg) {
|
||||
con.PrintErrorf("Failed to start MCP server, the user is not qualified to use feature\n")
|
||||
return
|
||||
}
|
||||
|
||||
if err := slivermcp.Start(cfg, con.Rpc); err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
|
||||
@@ -43,6 +43,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
(*comp)["interact"] = SessionIDCompleter(con)
|
||||
(*comp)["kill"] = SessionIDCompleter(con)
|
||||
})
|
||||
registerSessionIDFlagCompletion(sessionsCmd, "interact", con)
|
||||
|
||||
sessionsPruneCmd := &cobra.Command{
|
||||
Use: consts.PruneStr,
|
||||
@@ -63,26 +64,78 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
// SessionIDCompleter completes session IDs.
|
||||
func SessionIDCompleter(con *console.SliverClient) carapace.Action {
|
||||
callback := func(_ carapace.Context) carapace.Action {
|
||||
results := make([]string, 0)
|
||||
|
||||
sessions, err := con.Rpc.GetSessions(context.Background(), &commonpb.Empty{})
|
||||
if err == nil {
|
||||
for _, s := range sessions.Sessions {
|
||||
link := fmt.Sprintf("[%s <- %s]", s.ActiveC2, s.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", s.Name, s.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", s.Username, s.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, s.ID[:8])
|
||||
results = append(results, desc)
|
||||
}
|
||||
}
|
||||
return carapace.ActionValuesDescribed(results...).Tag("sessions")
|
||||
return carapace.ActionValuesDescribed(sessionCompletionPairs(con)...).Tag("sessions")
|
||||
}
|
||||
|
||||
return carapace.ActionCallback(callback)
|
||||
}
|
||||
|
||||
func registerSessionIDFlagCompletion(cmd *cobra.Command, name string, con *console.SliverClient) {
|
||||
if cmd == nil {
|
||||
return
|
||||
}
|
||||
if _, ok := cmd.GetFlagCompletionFunc(name); ok {
|
||||
return
|
||||
}
|
||||
if cmd.Flags().Lookup(name) == nil && cmd.PersistentFlags().Lookup(name) == nil {
|
||||
return
|
||||
}
|
||||
_ = cmd.RegisterFlagCompletionFunc(name, func(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
values := describedValuesToTabs(sessionCompletionPairs(con))
|
||||
return filterCompletionValues(values, toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
})
|
||||
}
|
||||
|
||||
func sessionCompletionPairs(con *console.SliverClient) []string {
|
||||
results := make([]string, 0)
|
||||
if con == nil || con.Rpc == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
sessions, err := con.Rpc.GetSessions(context.Background(), &commonpb.Empty{})
|
||||
if err != nil {
|
||||
return results
|
||||
}
|
||||
|
||||
for _, s := range sessions.Sessions {
|
||||
link := fmt.Sprintf("[%s <- %s]", s.ActiveC2, s.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", s.Name, s.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", s.Username, s.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, s.ID[:8], desc)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func describedValuesToTabs(values []string) []string {
|
||||
tabbed := make([]string, 0, len(values)/2)
|
||||
for i := 0; i+1 < len(values); i += 2 {
|
||||
tabbed = append(tabbed, fmt.Sprintf("%s\t%s", values[i], values[i+1]))
|
||||
}
|
||||
return tabbed
|
||||
}
|
||||
|
||||
func filterCompletionValues(values []string, prefix string) []string {
|
||||
if prefix == "" {
|
||||
return values
|
||||
}
|
||||
|
||||
filtered := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
candidate := value
|
||||
if tab := strings.IndexByte(value, '\t'); tab >= 0 {
|
||||
candidate = value[:tab]
|
||||
}
|
||||
if strings.HasPrefix(candidate, prefix) {
|
||||
filtered = append(filtered, value)
|
||||
}
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
|
||||
// SliverCommands returns all session control commands for the active target.
|
||||
func SliverCommands(con *console.SliverClient) []*cobra.Command {
|
||||
backgroundCmd := &cobra.Command{
|
||||
|
||||
@@ -41,11 +41,16 @@ func SettingsAutoAdultCmd(cmd *cobra.Command, con *console.SliverClient, args []
|
||||
|
||||
// IsUserAnAdult - This should be called for any dangerous (OPSEC-wise) functions.
|
||||
func IsUserAnAdult(con *console.SliverClient) bool {
|
||||
return IsUserAnAdultWithPrompt(con, "This action is bad OPSEC, are you an adult?")
|
||||
}
|
||||
|
||||
// IsUserAnAdultWithPrompt prompts with a custom message before continuing.
|
||||
func IsUserAnAdultWithPrompt(con *console.SliverClient, prompt string) bool {
|
||||
if GetAutoAdult(con) {
|
||||
return true
|
||||
}
|
||||
confirm := false
|
||||
_ = forms.Confirm("This action is bad OPSEC, are you an adult?", &confirm)
|
||||
_ = forms.Confirm(prompt, &confirm)
|
||||
return confirm
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,9 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
flags.Bind("update", false, updateCmd, func(f *pflag.FlagSet) {
|
||||
f.BoolP("prereleases", "P", false, "include pre-released (unstable) versions")
|
||||
f.StringP("proxy", "p", "", "specify a proxy url (e.g. http://localhost:8080)")
|
||||
f.StringP("save", "s", "", "save downloaded files to specific directory (default user home dir)")
|
||||
f.StringP("save", "s", "", "save downloaded files to specific directory (default downloads dir)")
|
||||
f.BoolP("insecure", "I", false, "skip tls certificate validation")
|
||||
f.Bool("force", false, "skip version comparison and download the latest release")
|
||||
f.IntP("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
|
||||
})
|
||||
flags.BindFlagCompletions(updateCmd, func(comp *carapace.ActionMap) {
|
||||
|
||||
+408
-36
@@ -21,6 +21,7 @@ package update
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
@@ -40,8 +41,19 @@ import (
|
||||
"github.com/bishopfox/sliver/client/version"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/util"
|
||||
"github.com/bishopfox/sliver/util/minisign"
|
||||
"github.com/cheggaaa/pb/v3"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var (
|
||||
SliverPublicKey string
|
||||
)
|
||||
|
||||
const (
|
||||
downloadAttempts = 3
|
||||
downloadBackoff = 750 * time.Millisecond
|
||||
)
|
||||
|
||||
// UpdateCmd - Check for updates.
|
||||
@@ -94,7 +106,13 @@ func UpdateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
|
||||
con.Printf("\nChecking for updates ... ")
|
||||
prereleases, _ := cmd.Flags().GetBool("prereleases")
|
||||
release, err := version.CheckForUpdates(client, prereleases)
|
||||
force, _ := cmd.Flags().GetBool("force")
|
||||
var release *version.Release
|
||||
if force {
|
||||
release, err = version.LatestRelease(client, prereleases)
|
||||
} else {
|
||||
release, err = version.CheckForUpdates(client, prereleases)
|
||||
}
|
||||
con.Printf("done!\n\n")
|
||||
if err != nil {
|
||||
con.PrintErrorf("Update check failed %s\n", err)
|
||||
@@ -107,9 +125,13 @@ func UpdateCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
updateAvailable(con, client, release, saveTo)
|
||||
updateAvailable(con, client, release, saveTo, force)
|
||||
} else {
|
||||
con.PrintInfof("No new releases.\n")
|
||||
if force {
|
||||
con.PrintInfof("No releases found.\n")
|
||||
} else {
|
||||
con.PrintInfof("No new releases.\n")
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
lastCheck := fmt.Appendf(nil, "%d", now.Unix())
|
||||
@@ -191,84 +213,434 @@ func findAssetFor(prefix string, suffixes []string, assets []version.Asset) *ver
|
||||
}
|
||||
|
||||
func serverAssetForGOOS(assets []version.Asset) *version.Asset {
|
||||
suffixes := []string{fmt.Sprintf("_%s.zip", runtime.GOOS), runtime.GOOS}
|
||||
if runtime.GOOS == "darwin" {
|
||||
suffixes = []string{"_macos.zip", "_macos"}
|
||||
if runtime.GOARCH == "arm64" {
|
||||
suffixes = []string{"_macos-arm64.zip", "_macos-arm64"}
|
||||
}
|
||||
}
|
||||
suffixes := assetSuffixes(runtime.GOOS, runtime.GOARCH)
|
||||
prefix := "sliver-server"
|
||||
return findAssetFor(prefix, suffixes, assets)
|
||||
}
|
||||
|
||||
func clientAssetForGOOS(assets []version.Asset) *version.Asset {
|
||||
suffixes := []string{fmt.Sprintf("_%s.zip", runtime.GOOS), runtime.GOOS}
|
||||
if runtime.GOOS == "darwin" {
|
||||
suffixes = []string{"_macos.zip", "_macos"}
|
||||
if runtime.GOARCH == "arm64" {
|
||||
suffixes = []string{"_macos-arm64.zip", "_macos-arm64"}
|
||||
}
|
||||
}
|
||||
suffixes := assetSuffixes(runtime.GOOS, runtime.GOARCH)
|
||||
prefix := "sliver-client"
|
||||
return findAssetFor(prefix, suffixes, assets)
|
||||
}
|
||||
|
||||
func updateAvailable(con *console.SliverClient, client *http.Client, release *version.Release, saveTo string) {
|
||||
func assetSuffixes(goos, goarch string) []string {
|
||||
suffixes := make([]string, 0, 8)
|
||||
seen := make(map[string]struct{}, 8)
|
||||
add := func(suffix string) {
|
||||
if suffix == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := seen[suffix]; ok {
|
||||
return
|
||||
}
|
||||
seen[suffix] = struct{}{}
|
||||
suffixes = append(suffixes, suffix)
|
||||
}
|
||||
|
||||
add(fmt.Sprintf("_%s-%s.zip", goos, goarch))
|
||||
add(fmt.Sprintf("_%s-%s", goos, goarch))
|
||||
add(fmt.Sprintf("_%s.zip", goos))
|
||||
add(fmt.Sprintf("_%s", goos))
|
||||
|
||||
if goos == "darwin" {
|
||||
add(fmt.Sprintf("_macos-%s.zip", goarch))
|
||||
add(fmt.Sprintf("_macos-%s", goarch))
|
||||
add("_macos.zip")
|
||||
add("_macos")
|
||||
}
|
||||
|
||||
return suffixes
|
||||
}
|
||||
|
||||
func updateAvailable(con *console.SliverClient, client *http.Client, release *version.Release, saveTo string, force bool) {
|
||||
serverAsset := serverAssetForGOOS(release.Assets)
|
||||
clientAsset := clientAssetForGOOS(release.Assets)
|
||||
|
||||
con.Printf("New version available %s\n", release.TagName)
|
||||
msg := "New version available"
|
||||
if force {
|
||||
msg = "Latest release available"
|
||||
}
|
||||
con.Printf("%s %s\n", msg, release.TagName)
|
||||
if serverAsset != nil {
|
||||
con.Printf(" - Server: %s\n", util.ByteCountBinary(int64(serverAsset.Size)))
|
||||
}
|
||||
if clientAsset != nil {
|
||||
con.Printf(" - Client: %s\n", util.ByteCountBinary(int64(clientAsset.Size)))
|
||||
}
|
||||
if serverAsset == nil {
|
||||
con.PrintWarnf("No server asset available for %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
if clientAsset == nil {
|
||||
con.PrintWarnf("No client asset available for %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
con.Println()
|
||||
|
||||
confirm := false
|
||||
forms.Confirm("Download update?", &confirm)
|
||||
if confirm {
|
||||
con.Printf("Please wait ...")
|
||||
err := downloadAsset(client, serverAsset, saveTo)
|
||||
if serverAsset == nil && clientAsset == nil {
|
||||
con.PrintWarnf("No matching assets found for %s/%s\n", runtime.GOOS, runtime.GOARCH)
|
||||
return
|
||||
}
|
||||
publicKey, err := loadSliverPublicKey()
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
err = downloadAsset(client, clientAsset, saveTo)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
downloads := []struct {
|
||||
label string
|
||||
asset *version.Asset
|
||||
}{
|
||||
{label: "server", asset: serverAsset},
|
||||
{label: "client", asset: clientAsset},
|
||||
}
|
||||
for _, item := range downloads {
|
||||
if item.asset == nil {
|
||||
continue
|
||||
}
|
||||
con.Printf("Downloading %s update from %s ...\n", item.label, item.asset.BrowserDownloadURL)
|
||||
if err := downloadAssetWithSignature(con, client, item.asset, release.Assets, saveTo, publicKey); err != nil {
|
||||
con.PrintErrorf("Failed to download %s update: %s\n", item.label, err)
|
||||
return
|
||||
}
|
||||
con.Println(console.Clearln)
|
||||
}
|
||||
con.Println(console.Clearln)
|
||||
con.PrintInfof("Saved updates to: %s\n", saveTo)
|
||||
}
|
||||
}
|
||||
|
||||
func downloadAsset(client *http.Client, asset *version.Asset, saveTo string) error {
|
||||
func downloadAssetWithSignature(con *console.SliverClient, client *http.Client, asset *version.Asset, assets []version.Asset, saveTo string, publicKey minisign.PublicKey) error {
|
||||
if asset == nil {
|
||||
return errors.New("no asset available for this platform")
|
||||
}
|
||||
downloadURL, err := url.Parse(asset.BrowserDownloadURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
assetFileName := filepath.Base(downloadURL.Path)
|
||||
finalPath := filepath.Join(saveTo, assetFileName)
|
||||
|
||||
limit := int64(asset.Size)
|
||||
writer, err := os.Create(filepath.Join(saveTo, assetFileName))
|
||||
sigURL := asset.BrowserDownloadURL + ".minisig"
|
||||
var sigLimit int64
|
||||
if sigAsset := signatureAssetFor(assetFileName, assets); sigAsset != nil && sigAsset.BrowserDownloadURL != "" {
|
||||
sigURL = sigAsset.BrowserDownloadURL
|
||||
sigLimit = int64(sigAsset.Size)
|
||||
}
|
||||
|
||||
assetTempPath, err := downloadWithRetries(client, asset.BrowserDownloadURL, saveTo, int64(asset.Size), "asset")
|
||||
if err != nil {
|
||||
return fmt.Errorf("download asset: %w", err)
|
||||
}
|
||||
|
||||
sigData, err := downloadBytesWithRetries(client, sigURL, sigLimit, "signature")
|
||||
if err != nil {
|
||||
cleanupAssetFiles(assetTempPath, finalPath)
|
||||
return fmt.Errorf("download signature: %w", err)
|
||||
}
|
||||
|
||||
if err := verifyMinisignSignature(assetTempPath, sigData, assetFileName, publicKey); err != nil {
|
||||
cleanupAssetFiles(assetTempPath, finalPath)
|
||||
return err
|
||||
}
|
||||
defer writer.Close()
|
||||
con.PrintSuccessf("Signature verified for %s\n", finalPath)
|
||||
|
||||
resp, err := client.Get(asset.BrowserDownloadURL)
|
||||
if err != nil {
|
||||
if err := replaceFile(assetTempPath, finalPath); err != nil {
|
||||
os.Remove(assetTempPath)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func signatureAssetFor(assetFileName string, assets []version.Asset) *version.Asset {
|
||||
want := assetFileName + ".minisig"
|
||||
for _, asset := range assets {
|
||||
if asset.Name == want {
|
||||
return &asset
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadSliverPublicKey() (minisign.PublicKey, error) {
|
||||
if strings.TrimSpace(SliverPublicKey) == "" {
|
||||
return minisign.PublicKey{}, errors.New("minisign public key not set at build time")
|
||||
}
|
||||
var publicKey minisign.PublicKey
|
||||
if err := publicKey.UnmarshalText([]byte(SliverPublicKey)); err != nil {
|
||||
return minisign.PublicKey{}, fmt.Errorf("invalid minisign public key: %w", err)
|
||||
}
|
||||
return publicKey, nil
|
||||
}
|
||||
|
||||
type httpStatusError struct {
|
||||
url string
|
||||
status int
|
||||
}
|
||||
|
||||
func (e httpStatusError) Error() string {
|
||||
return fmt.Sprintf("unexpected HTTP status %d for %s", e.status, e.url)
|
||||
}
|
||||
|
||||
func downloadWithRetries(client *http.Client, downloadURL, saveTo string, limit int64, label string) (string, error) {
|
||||
var lastErr error
|
||||
backoff := downloadBackoff
|
||||
for attempt := 1; attempt <= downloadAttempts; attempt++ {
|
||||
path, err := downloadOnce(client, downloadURL, saveTo, limit, label)
|
||||
if err == nil {
|
||||
return path, nil
|
||||
}
|
||||
lastErr = err
|
||||
if !isRetryableDownloadError(err) || attempt == downloadAttempts {
|
||||
break
|
||||
}
|
||||
time.Sleep(backoff)
|
||||
backoff *= 2
|
||||
}
|
||||
return "", lastErr
|
||||
}
|
||||
|
||||
func downloadBytesWithRetries(client *http.Client, downloadURL string, limit int64, label string) ([]byte, error) {
|
||||
var lastErr error
|
||||
backoff := downloadBackoff
|
||||
for attempt := 1; attempt <= downloadAttempts; attempt++ {
|
||||
data, err := downloadBytesOnce(client, downloadURL, limit, label)
|
||||
if err == nil {
|
||||
return data, nil
|
||||
}
|
||||
lastErr = err
|
||||
if !isRetryableDownloadError(err) || attempt == downloadAttempts {
|
||||
break
|
||||
}
|
||||
time.Sleep(backoff)
|
||||
backoff *= 2
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func downloadOnce(client *http.Client, downloadURL, saveTo string, limit int64, label string) (string, error) {
|
||||
parsedURL, err := url.Parse(downloadURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
baseName := filepath.Base(parsedURL.Path)
|
||||
tmpFile, err := os.CreateTemp(saveTo, baseName+".tmp-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
success := false
|
||||
defer func() {
|
||||
if !success {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpFile.Name())
|
||||
}
|
||||
}()
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, downloadURL, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
bar := pb.Full.Start64(limit)
|
||||
barReader := bar.NewProxyReader(resp.Body)
|
||||
io.Copy(writer, barReader)
|
||||
bar.Finish()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", httpStatusError{url: downloadURL, status: resp.StatusCode}
|
||||
}
|
||||
|
||||
if limit <= 0 && resp.ContentLength > 0 {
|
||||
limit = resp.ContentLength
|
||||
}
|
||||
|
||||
var reader io.Reader = resp.Body
|
||||
var bar *pb.ProgressBar
|
||||
if limit > 0 {
|
||||
bar = pb.Full.Start64(limit)
|
||||
bar.Set("prefix", fmt.Sprintf("%s: ", label))
|
||||
bar.Set(pb.Bytes, true)
|
||||
bar.Set(pb.CleanOnFinish, true)
|
||||
bar.Set(pb.ReturnSymbol, "\r")
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
bar.Set(pb.Terminal, true)
|
||||
}
|
||||
reader = bar.NewProxyReader(reader)
|
||||
}
|
||||
|
||||
n, copyErr := io.Copy(tmpFile, reader)
|
||||
if bar != nil {
|
||||
bar.Finish()
|
||||
}
|
||||
if copyErr != nil {
|
||||
return "", copyErr
|
||||
}
|
||||
|
||||
if limit > 0 && n != limit {
|
||||
return "", fmt.Errorf("downloaded %d bytes, expected %d", n, limit)
|
||||
}
|
||||
|
||||
if err := tmpFile.Sync(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
success = true
|
||||
return tmpFile.Name(), nil
|
||||
}
|
||||
|
||||
func downloadBytesOnce(client *http.Client, downloadURL string, limit int64, label string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, downloadURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, httpStatusError{url: downloadURL, status: resp.StatusCode}
|
||||
}
|
||||
|
||||
if limit <= 0 && resp.ContentLength > 0 {
|
||||
limit = resp.ContentLength
|
||||
}
|
||||
|
||||
var reader io.Reader = resp.Body
|
||||
var bar *pb.ProgressBar
|
||||
if limit > 0 {
|
||||
bar = pb.Full.Start64(limit)
|
||||
bar.Set("prefix", fmt.Sprintf("%s: ", label))
|
||||
bar.Set(pb.Bytes, true)
|
||||
bar.Set(pb.CleanOnFinish, true)
|
||||
bar.Set(pb.ReturnSymbol, "\r")
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
bar.Set(pb.Terminal, true)
|
||||
}
|
||||
reader = bar.NewProxyReader(reader)
|
||||
}
|
||||
|
||||
data, readErr := readAllWithLimit(reader, limit)
|
||||
if bar != nil {
|
||||
bar.Finish()
|
||||
}
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func isRetryableDownloadError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return true
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return netErr.Timeout() || netErr.Temporary()
|
||||
}
|
||||
var statusErr httpStatusError
|
||||
if errors.As(err, &statusErr) {
|
||||
switch statusErr.status {
|
||||
case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func verifyMinisignSignature(artifactPath string, sigData []byte, expectedFile string, publicKey minisign.PublicKey) error {
|
||||
artifact, err := os.Open(artifactPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open artifact: %w", err)
|
||||
}
|
||||
defer artifact.Close()
|
||||
|
||||
reader := minisign.NewReader(artifact)
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return fmt.Errorf("stream artifact: %w", err)
|
||||
}
|
||||
|
||||
if !reader.Verify(publicKey, sigData) {
|
||||
return errors.New("signature verification failed")
|
||||
}
|
||||
|
||||
if err := verifyTrustedComment(sigData, expectedFile); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readAllWithLimit(reader io.Reader, limit int64) ([]byte, error) {
|
||||
if limit <= 0 {
|
||||
return io.ReadAll(reader)
|
||||
}
|
||||
|
||||
lr := &io.LimitedReader{R: reader, N: limit + 1}
|
||||
data, err := io.ReadAll(lr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("downloaded %d bytes, expected %d", len(data), limit)
|
||||
}
|
||||
if int64(len(data)) != limit {
|
||||
return nil, fmt.Errorf("downloaded %d bytes, expected %d", len(data), limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func verifyTrustedComment(signature []byte, expectedFile string) error {
|
||||
var sig minisign.Signature
|
||||
if err := sig.UnmarshalText(signature); err != nil {
|
||||
return fmt.Errorf("parse signature: %w", err)
|
||||
}
|
||||
|
||||
fileField := trustedCommentFile(sig.TrustedComment)
|
||||
if fileField == "" {
|
||||
return fmt.Errorf("trusted comment missing file field: %q", sig.TrustedComment)
|
||||
}
|
||||
if fileField != expectedFile {
|
||||
return fmt.Errorf("trusted comment file mismatch: expected %q, got %q", expectedFile, fileField)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func trustedCommentFile(trustedComment string) string {
|
||||
for _, field := range strings.Fields(trustedComment) {
|
||||
if after, ok := strings.CutPrefix(field, "file:"); ok {
|
||||
return after
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func replaceFile(src, dst string) error {
|
||||
if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return os.Rename(src, dst)
|
||||
}
|
||||
|
||||
func cleanupAssetFiles(tempPath, finalPath string) {
|
||||
if tempPath != "" {
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
if finalPath != "" {
|
||||
_ = os.Remove(finalPath)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
f.Int64P("timeout", "t", flags.DefaultTimeout, "grpc timeout in seconds")
|
||||
})
|
||||
carapace.Gen(useCmd).PositionalCompletion(BeaconAndSessionIDCompleter(con))
|
||||
registerUseIDCompletion(useCmd, con, true, true)
|
||||
|
||||
useSessionCmd := &cobra.Command{
|
||||
Use: consts.SessionsStr,
|
||||
@@ -37,6 +38,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
},
|
||||
}
|
||||
carapace.Gen(useSessionCmd).PositionalCompletion(SessionIDCompleter(con))
|
||||
registerUseIDCompletion(useSessionCmd, con, true, false)
|
||||
useCmd.AddCommand(useSessionCmd)
|
||||
|
||||
useBeaconCmd := &cobra.Command{
|
||||
@@ -48,6 +50,7 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
},
|
||||
}
|
||||
carapace.Gen(useBeaconCmd).PositionalCompletion(beacons.BeaconIDCompleter(con))
|
||||
registerUseIDCompletion(useBeaconCmd, con, false, true)
|
||||
useCmd.AddCommand(useBeaconCmd)
|
||||
|
||||
return []*cobra.Command{useCmd}
|
||||
|
||||
@@ -39,6 +39,77 @@ import (
|
||||
|
||||
var ErrNoSelection = errors.New("no selection")
|
||||
|
||||
func registerUseIDCompletion(cmd *cobra.Command, con *console.SliverClient, includeSessions, includeBeacons bool) {
|
||||
if cmd == nil || cmd.ValidArgsFunction != nil {
|
||||
return
|
||||
}
|
||||
|
||||
cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) > 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
|
||||
values := useCompletionValues(con, includeSessions, includeBeacons)
|
||||
return filterCompletionValues(values, toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
}
|
||||
|
||||
func useCompletionValues(con *console.SliverClient, includeSessions, includeBeacons bool) []string {
|
||||
results := []string{}
|
||||
if con == nil || con.Rpc == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
if includeSessions {
|
||||
sessions, err := con.Rpc.GetSessions(context.Background(), &commonpb.Empty{})
|
||||
if err == nil {
|
||||
for _, session := range sessions.Sessions {
|
||||
link := fmt.Sprintf("[%s <- %s]", session.ActiveC2, session.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", session.Name, session.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", session.Username, session.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, fmt.Sprintf("%s\t%s", session.ID[:8], desc))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if includeBeacons {
|
||||
beacons, err := con.Rpc.GetBeacons(context.Background(), &commonpb.Empty{})
|
||||
if err == nil {
|
||||
for _, beacon := range beacons.Beacons {
|
||||
link := fmt.Sprintf("[%s <- %s]", beacon.ActiveC2, beacon.RemoteAddress)
|
||||
id := fmt.Sprintf("%s (%d)", beacon.Name, beacon.PID)
|
||||
userHost := fmt.Sprintf("%s@%s", beacon.Username, beacon.Hostname)
|
||||
desc := strings.Join([]string{id, userHost, link}, " ")
|
||||
|
||||
results = append(results, fmt.Sprintf("%s\t%s", beacon.ID[:8], desc))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func filterCompletionValues(values []string, prefix string) []string {
|
||||
if prefix == "" {
|
||||
return values
|
||||
}
|
||||
|
||||
filtered := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
candidate := value
|
||||
if tab := strings.IndexByte(value, '\t'); tab >= 0 {
|
||||
candidate = value[:tab]
|
||||
}
|
||||
if strings.HasPrefix(candidate, prefix) {
|
||||
filtered = append(filtered, value)
|
||||
}
|
||||
}
|
||||
|
||||
return filtered
|
||||
}
|
||||
|
||||
// UseCmd - Change the active session
|
||||
func UseCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
|
||||
var session *clientpb.Session
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package websites
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/command/flags"
|
||||
"github.com/bishopfox/sliver/client/command/help"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/rsteube/carapace"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
@@ -26,6 +30,41 @@ func Commands(con *console.SliverClient) []*cobra.Command {
|
||||
})
|
||||
carapace.Gen(websitesCmd).PositionalCompletion(WebsiteNameCompleter(con))
|
||||
|
||||
websitesListCmd := &cobra.Command{
|
||||
Use: consts.ListStr,
|
||||
Short: "List configured websites",
|
||||
Long: help.GetHelpFor([]string{consts.WebsitesStr, consts.ListStr}),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
ListWebsites(cmd, con, args)
|
||||
},
|
||||
}
|
||||
websitesCmd.AddCommand(websitesListCmd)
|
||||
|
||||
websitesShowCmd := &cobra.Command{
|
||||
Use: "show [name]",
|
||||
Short: "Show contents of a website",
|
||||
Long: help.GetHelpFor([]string{consts.WebsitesStr}),
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
ListWebsiteContent(args[0], con)
|
||||
},
|
||||
}
|
||||
carapace.Gen(websitesShowCmd).PositionalCompletion(WebsiteNameCompleter(con))
|
||||
websitesShowCmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
ws, err := con.Rpc.Websites(context.Background(), &commonpb.Empty{})
|
||||
if err != nil {
|
||||
return nil, cobra.ShellCompDirectiveError
|
||||
}
|
||||
out := []string{}
|
||||
for _, w := range ws.Websites {
|
||||
if strings.HasPrefix(w.Name, toComplete) {
|
||||
out = append(out, w.Name)
|
||||
}
|
||||
}
|
||||
return out, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
websitesCmd.AddCommand(websitesShowCmd)
|
||||
|
||||
websitesRmCmd := &cobra.Command{
|
||||
Use: consts.RmStr,
|
||||
Short: "Remove an entire website and all of its contents",
|
||||
|
||||
@@ -22,10 +22,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/client/forms"
|
||||
@@ -117,13 +119,14 @@ func webAddFile(web *clientpb.WebsiteAddContent, webpath string, contentType str
|
||||
}
|
||||
|
||||
if contentType == "" {
|
||||
contentType = sniffContentType(file)
|
||||
contentType = sniffContentType(file, contentPath)
|
||||
}
|
||||
|
||||
web.Contents[webpath] = &clientpb.WebContent{
|
||||
Path: webpath,
|
||||
ContentType: contentType,
|
||||
Content: data,
|
||||
Path: webpath,
|
||||
ContentType: contentType,
|
||||
OriginalFile: filepath.Base(contentPath),
|
||||
Content: data,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -134,13 +137,19 @@ func confirmAddDirectory() bool {
|
||||
return confirm
|
||||
}
|
||||
|
||||
func sniffContentType(out *os.File) string {
|
||||
func sniffContentType(out *os.File, contentPath string) string {
|
||||
ext := strings.ToLower(filepath.Ext(contentPath))
|
||||
if ext != "" {
|
||||
contentType := mime.TypeByExtension(ext)
|
||||
if contentType != "" {
|
||||
return contentType
|
||||
}
|
||||
}
|
||||
out.Seek(0, io.SeekStart)
|
||||
buffer := make([]byte, fileSampleSize)
|
||||
_, err := out.Read(buffer)
|
||||
if err != nil {
|
||||
return defaultMimeType
|
||||
}
|
||||
contentType := http.DetectContentType(buffer)
|
||||
return contentType
|
||||
return http.DetectContentType(buffer)
|
||||
}
|
||||
@@ -21,7 +21,6 @@ package websites
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/command/settings"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
@@ -58,11 +57,14 @@ func ListWebsites(cmd *cobra.Command, con *console.SliverClient, args []string)
|
||||
con.PrintInfof("No websites\n")
|
||||
return
|
||||
}
|
||||
con.Println("Websites")
|
||||
con.Println(strings.Repeat("=", len("Websites")))
|
||||
tw := table.NewWriter()
|
||||
tw.SetStyle(settings.GetTableStyle(con))
|
||||
tw.AppendHeader(table.Row{"Name", "Objects"})
|
||||
for _, site := range websites.Websites {
|
||||
con.Printf("%s%s%s - %d page(s)\n", console.Bold, site.Name, console.Normal, len(site.Contents))
|
||||
tw.AppendRow(table.Row{site.Name, len(site.Contents)})
|
||||
}
|
||||
|
||||
con.Println(tw.Render())
|
||||
}
|
||||
|
||||
// ListWebsiteContent - List the static contents of a website.
|
||||
@@ -91,6 +93,8 @@ func PrintWebsite(web *clientpb.Website, con *console.SliverClient) {
|
||||
"Path",
|
||||
"Content-type",
|
||||
"Size",
|
||||
"Original File",
|
||||
"SHA256",
|
||||
})
|
||||
sortedContents := []*clientpb.WebContent{}
|
||||
for _, content := range web.Contents {
|
||||
@@ -104,6 +108,8 @@ func PrintWebsite(web *clientpb.Website, con *console.SliverClient) {
|
||||
content.Path,
|
||||
content.ContentType,
|
||||
content.Size,
|
||||
content.OriginalFile,
|
||||
content.Sha256,
|
||||
})
|
||||
}
|
||||
con.Println(tw.Render())
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
"github.com/reeflective/console"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func (con *SliverClient) allowServerRootCommands(args []string) ([]string, error) {
|
||||
con.applyCommandFallback(args)
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func (con *SliverClient) prepareCompletion(line []rune, cursor int) {
|
||||
if con == nil || con.App == nil {
|
||||
return
|
||||
}
|
||||
|
||||
menu := con.App.ActiveMenu()
|
||||
if menu == nil {
|
||||
return
|
||||
}
|
||||
|
||||
con.setMenuCommandForCompletion(menu, line, cursor)
|
||||
}
|
||||
|
||||
func (con *SliverClient) applyCommandFallback(args []string) {
|
||||
if con == nil || con.App == nil {
|
||||
return
|
||||
}
|
||||
|
||||
con.setMenuCommand(con.App.ActiveMenu(), args)
|
||||
}
|
||||
|
||||
func (con *SliverClient) setMenuCommand(menu *console.Menu, args []string) {
|
||||
if menu == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if menu.Name() != consts.ImplantMenu {
|
||||
if menu.Command == nil && con.serverCmds != nil {
|
||||
menu.Command = con.serverCmds()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if menu.Command == nil {
|
||||
if con.sliverCmds == nil {
|
||||
return
|
||||
}
|
||||
menu.Command = con.sliverCmds()
|
||||
}
|
||||
|
||||
if con.serverCmds == nil {
|
||||
return
|
||||
}
|
||||
|
||||
name := firstNonFlagArg(args)
|
||||
if name == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if rootHasCommand(menu.Command, name) {
|
||||
return
|
||||
}
|
||||
|
||||
serverRoot := con.serverCmds()
|
||||
if serverRoot == nil || !rootHasCommand(serverRoot, name) {
|
||||
return
|
||||
}
|
||||
|
||||
menu.Command = serverRoot
|
||||
}
|
||||
|
||||
func (con *SliverClient) setMenuCommandForCompletion(menu *console.Menu, line []rune, cursor int) {
|
||||
if menu == nil || menu.Name() != consts.ImplantMenu {
|
||||
return
|
||||
}
|
||||
|
||||
if menu.Command == nil {
|
||||
if con.sliverCmds == nil {
|
||||
return
|
||||
}
|
||||
menu.Command = con.sliverCmds()
|
||||
}
|
||||
|
||||
if con.serverCmds == nil {
|
||||
return
|
||||
}
|
||||
|
||||
token := firstTokenFromLine(line, cursor)
|
||||
if token == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if rootHasCommandPrefix(menu.Command, token) {
|
||||
return
|
||||
}
|
||||
|
||||
serverRoot := con.serverCmds()
|
||||
if serverRoot == nil || !rootHasCommandPrefix(serverRoot, token) {
|
||||
return
|
||||
}
|
||||
|
||||
menu.Command = serverRoot
|
||||
hideFilteredCommands(menu, menu.Command)
|
||||
}
|
||||
|
||||
func firstNonFlagArg(args []string) string {
|
||||
for i := 0; i < len(args); i++ {
|
||||
arg := args[i]
|
||||
if arg == "--" {
|
||||
if i+1 < len(args) {
|
||||
return args[i+1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(arg, "-") {
|
||||
continue
|
||||
}
|
||||
return arg
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func firstTokenFromLine(line []rune, cursor int) string {
|
||||
if cursor > len(line) {
|
||||
cursor = len(line)
|
||||
}
|
||||
if cursor < 0 {
|
||||
cursor = 0
|
||||
}
|
||||
|
||||
pos := 0
|
||||
for pos < cursor && isSpace(line[pos]) {
|
||||
pos++
|
||||
}
|
||||
start := pos
|
||||
for pos < cursor && !isSpace(line[pos]) {
|
||||
pos++
|
||||
}
|
||||
if start == pos {
|
||||
return ""
|
||||
}
|
||||
return string(line[start:pos])
|
||||
}
|
||||
|
||||
func isSpace(r rune) bool {
|
||||
return r == ' ' || r == '\t' || r == '\n' || r == '\r'
|
||||
}
|
||||
|
||||
func rootHasCommand(root *cobra.Command, name string) bool {
|
||||
if root == nil || name == "" {
|
||||
return false
|
||||
}
|
||||
for _, cmd := range root.Commands() {
|
||||
if cmd.Name() == name || cmd.HasAlias(name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func rootHasCommandPrefix(root *cobra.Command, prefix string) bool {
|
||||
if root == nil || prefix == "" {
|
||||
return false
|
||||
}
|
||||
for _, cmd := range root.Commands() {
|
||||
if strings.HasPrefix(cmd.Name(), prefix) {
|
||||
return true
|
||||
}
|
||||
for _, alias := range cmd.Aliases {
|
||||
if strings.HasPrefix(alias, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hideFilteredCommands(menu *console.Menu, root *cobra.Command) {
|
||||
if menu == nil || root == nil {
|
||||
return
|
||||
}
|
||||
for _, cmd := range root.Commands() {
|
||||
if cmd.Hidden {
|
||||
continue
|
||||
}
|
||||
if filters := menu.ActiveFiltersFor(cmd); len(filters) > 0 {
|
||||
cmd.Hidden = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,8 @@ type SliverClient struct {
|
||||
Settings *assets.ClientSettings
|
||||
IsServer bool
|
||||
IsCLI bool
|
||||
serverCmds console.Commands
|
||||
sliverCmds console.Commands
|
||||
|
||||
jsonHandler slog.Handler
|
||||
printf func(format string, args ...any) (int, error)
|
||||
@@ -166,6 +168,8 @@ func NewConsole(isServer bool) *SliverClient {
|
||||
func StartClient(con *SliverClient, rpc rpcpb.SliverRPCClient, serverCmds, sliverCmds console.Commands, run bool, rcScript string) error {
|
||||
con.Rpc = rpc
|
||||
con.IsCLI = !run
|
||||
con.serverCmds = serverCmds
|
||||
con.sliverCmds = sliverCmds
|
||||
|
||||
// The console application needs to query the terminal for cursor positions
|
||||
// when asynchronously printing logs (that is, when no command is running).
|
||||
@@ -184,6 +188,15 @@ func StartClient(con *SliverClient, rpc rpcpb.SliverRPCClient, serverCmds, slive
|
||||
sliver := con.App.Menu(consts.ImplantMenu)
|
||||
sliver.SetCommands(sliverCmds)
|
||||
|
||||
con.App.PreCmdRunLineHooks = append(con.App.PreCmdRunLineHooks, con.allowServerRootCommands)
|
||||
if shell := con.App.Shell(); shell != nil && shell.Completer != nil {
|
||||
baseCompleter := shell.Completer
|
||||
shell.Completer = func(line []rune, cursor int) readline.Completions {
|
||||
con.prepareCompletion(line, cursor)
|
||||
return baseCompleter(line, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
// Events
|
||||
go con.startEventLoop()
|
||||
go core.TunnelLoop(rpc)
|
||||
@@ -250,6 +263,19 @@ func (con *SliverClient) runRCLine(serverCmds, sliverCmds console.Commands, line
|
||||
return fmt.Errorf("parse error: %w", err)
|
||||
}
|
||||
|
||||
if con.serverCmds == nil {
|
||||
con.serverCmds = serverCmds
|
||||
}
|
||||
if con.sliverCmds == nil {
|
||||
con.sliverCmds = sliverCmds
|
||||
}
|
||||
|
||||
menu := con.App.ActiveMenu()
|
||||
if menu != nil {
|
||||
// Reset per line to avoid stale roots when rc scripts switch menus.
|
||||
menu.Command = nil
|
||||
}
|
||||
|
||||
for _, hook := range con.App.PreCmdRunLineHooks {
|
||||
args, err = hook(args)
|
||||
if err != nil {
|
||||
@@ -261,11 +287,15 @@ func (con *SliverClient) runRCLine(serverCmds, sliverCmds console.Commands, line
|
||||
return nil
|
||||
}
|
||||
|
||||
menu := con.App.ActiveMenu()
|
||||
if menu.Name() == consts.ImplantMenu {
|
||||
menu.Command = sliverCmds()
|
||||
} else {
|
||||
menu.Command = serverCmds()
|
||||
menu = con.App.ActiveMenu()
|
||||
if menu == nil {
|
||||
return fmt.Errorf("no active menu")
|
||||
}
|
||||
if menu.Command == nil {
|
||||
con.setMenuCommand(menu, args)
|
||||
}
|
||||
if menu.Command == nil {
|
||||
return fmt.Errorf("no commands available")
|
||||
}
|
||||
|
||||
target, _, _ := menu.Command.Find(args)
|
||||
|
||||
@@ -227,6 +227,15 @@ func (con *SliverClient) PrintSuccessf(format string, args ...any) {
|
||||
con.printf(Clearln+Success+format, args...)
|
||||
}
|
||||
|
||||
// PrintSuccess prints a success message with a default or provided message.
|
||||
func (con *SliverClient) PrintSuccess(args ...any) {
|
||||
if len(args) == 0 {
|
||||
con.PrintSuccessf("Success")
|
||||
return
|
||||
}
|
||||
con.PrintSuccessf("%s", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// PrintWarnf a warning message immediately below the last line of output.
|
||||
func (con *SliverClient) PrintWarnf(format string, args ...any) {
|
||||
logger := slog.New(con.jsonHandler)
|
||||
|
||||
+30
-34
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/util"
|
||||
"github.com/charmbracelet/huh"
|
||||
)
|
||||
@@ -23,62 +24,57 @@ type GenerateFormResult struct {
|
||||
}
|
||||
|
||||
// GenerateForm prompts for core generate flags and returns the collected values.
|
||||
func GenerateForm() (*GenerateFormResult, error) {
|
||||
func GenerateForm(compiler *clientpb.Compiler) (*GenerateFormResult, error) {
|
||||
result := &GenerateFormResult{
|
||||
OS: "windows",
|
||||
Arch: "amd64",
|
||||
Format: "exe",
|
||||
C2Type: "mtls",
|
||||
}
|
||||
commonPlatformsOnly := true
|
||||
lastCommonPlatformsOnly := commonPlatformsOnly
|
||||
compilerTargets := compilerTargetList(compiler)
|
||||
targetBindings := &targetOptionBindings{
|
||||
Common: &commonPlatformsOnly,
|
||||
OS: &result.OS,
|
||||
Arch: &result.Arch,
|
||||
}
|
||||
|
||||
form := huh.NewForm(
|
||||
huh.NewGroup(
|
||||
huh.NewConfirm().
|
||||
Title("Common Platforms Only").
|
||||
Value(&commonPlatformsOnly),
|
||||
huh.NewSelect[string]().
|
||||
Title("Target operating system").
|
||||
Options(
|
||||
huh.NewOption("Windows", "windows"),
|
||||
huh.NewOption("Linux", "linux"),
|
||||
huh.NewOption("macOS", "darwin"),
|
||||
).
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonOSOptions()
|
||||
}
|
||||
return osOptionsFromTargets(compilerTargets)
|
||||
}, targetBindings).
|
||||
Value(&result.OS),
|
||||
huh.NewSelect[string]().
|
||||
Title("CPU architecture").
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
switch result.OS {
|
||||
case "darwin":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
}
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonArchOptions(result.OS)
|
||||
}
|
||||
}, &result.OS).
|
||||
return archOptionsFromTargets(compilerTargets, result.OS)
|
||||
}, targetBindings).
|
||||
Height(3).
|
||||
Value(&result.Arch),
|
||||
huh.NewSelect[string]().
|
||||
Title("Output format").
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
options := []huh.Option[string]{
|
||||
huh.NewOption("Executable", "exe"),
|
||||
huh.NewOption("Shared library", "shared"),
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonFormatOptions(result.OS)
|
||||
}
|
||||
if result.OS == "windows" {
|
||||
options = append(options,
|
||||
huh.NewOption("Service", "service"),
|
||||
huh.NewOption("Shellcode", "shellcode"),
|
||||
)
|
||||
}
|
||||
return options
|
||||
}, &result.OS).
|
||||
return formatOptionsFromTargets(compilerTargets, result.OS, result.Arch)
|
||||
}, targetBindings).
|
||||
Height(3).
|
||||
Value(&result.Format),
|
||||
),
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/util"
|
||||
"github.com/charmbracelet/huh"
|
||||
)
|
||||
@@ -26,62 +27,57 @@ type GenerateBeaconFormResult struct {
|
||||
}
|
||||
|
||||
// GenerateBeaconForm prompts for generate beacon flags and returns the collected values.
|
||||
func GenerateBeaconForm() (*GenerateBeaconFormResult, error) {
|
||||
func GenerateBeaconForm(compiler *clientpb.Compiler) (*GenerateBeaconFormResult, error) {
|
||||
result := &GenerateBeaconFormResult{
|
||||
OS: "windows",
|
||||
Arch: "amd64",
|
||||
Format: "exe",
|
||||
C2Type: "mtls",
|
||||
}
|
||||
commonPlatformsOnly := true
|
||||
lastCommonPlatformsOnly := commonPlatformsOnly
|
||||
compilerTargets := compilerTargetList(compiler)
|
||||
targetBindings := &targetOptionBindings{
|
||||
Common: &commonPlatformsOnly,
|
||||
OS: &result.OS,
|
||||
Arch: &result.Arch,
|
||||
}
|
||||
|
||||
form := huh.NewForm(
|
||||
huh.NewGroup(
|
||||
huh.NewConfirm().
|
||||
Title("Common Platforms Only").
|
||||
Value(&commonPlatformsOnly),
|
||||
huh.NewSelect[string]().
|
||||
Title("Target operating system").
|
||||
Options(
|
||||
huh.NewOption("Windows", "windows"),
|
||||
huh.NewOption("Linux", "linux"),
|
||||
huh.NewOption("macOS", "darwin"),
|
||||
).
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonOSOptions()
|
||||
}
|
||||
return osOptionsFromTargets(compilerTargets)
|
||||
}, targetBindings).
|
||||
Value(&result.OS),
|
||||
huh.NewSelect[string]().
|
||||
Title("CPU architecture").
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
switch result.OS {
|
||||
case "darwin":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
}
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonArchOptions(result.OS)
|
||||
}
|
||||
}, &result.OS).
|
||||
return archOptionsFromTargets(compilerTargets, result.OS)
|
||||
}, targetBindings).
|
||||
Height(3).
|
||||
Value(&result.Arch),
|
||||
huh.NewSelect[string]().
|
||||
Title("Output format").
|
||||
OptionsFunc(func() []huh.Option[string] {
|
||||
options := []huh.Option[string]{
|
||||
huh.NewOption("Executable", "exe"),
|
||||
huh.NewOption("Shared library", "shared"),
|
||||
maybeResetTargets(commonPlatformsOnly, &lastCommonPlatformsOnly, compilerTargets, &result.OS, &result.Arch, &result.Format)
|
||||
if commonPlatformsOnly || len(compilerTargets) == 0 {
|
||||
return commonFormatOptions(result.OS)
|
||||
}
|
||||
if result.OS == "windows" {
|
||||
options = append(options,
|
||||
huh.NewOption("Service", "service"),
|
||||
huh.NewOption("Shellcode", "shellcode"),
|
||||
)
|
||||
}
|
||||
return options
|
||||
}, &result.OS).
|
||||
return formatOptionsFromTargets(compilerTargets, result.OS, result.Arch)
|
||||
}, targetBindings).
|
||||
Height(3).
|
||||
Value(&result.Format),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package forms
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/charmbracelet/huh"
|
||||
)
|
||||
|
||||
type formatOption struct {
|
||||
format clientpb.OutputFormat
|
||||
label string
|
||||
value string
|
||||
}
|
||||
|
||||
type targetOptionBindings struct {
|
||||
Common *bool
|
||||
OS *string
|
||||
Arch *string
|
||||
}
|
||||
|
||||
var formatOptionOrder = []formatOption{
|
||||
{format: clientpb.OutputFormat_EXECUTABLE, label: "Executable", value: "exe"},
|
||||
{format: clientpb.OutputFormat_SHARED_LIB, label: "Shared library", value: "shared"},
|
||||
{format: clientpb.OutputFormat_SERVICE, label: "Service", value: "service"},
|
||||
{format: clientpb.OutputFormat_SHELLCODE, label: "Shellcode", value: "shellcode"},
|
||||
}
|
||||
|
||||
func commonOSOptions() []huh.Option[string] {
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("Windows", "windows"),
|
||||
huh.NewOption("Linux", "linux"),
|
||||
huh.NewOption("macOS", "darwin"),
|
||||
}
|
||||
}
|
||||
|
||||
func commonArchOptions(goos string) []huh.Option[string] {
|
||||
switch goos {
|
||||
case "darwin":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("arm64", "arm64"),
|
||||
}
|
||||
case "linux":
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
default:
|
||||
return []huh.Option[string]{
|
||||
huh.NewOption("amd64", "amd64"),
|
||||
huh.NewOption("386", "386"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func commonFormatOptions(goos string) []huh.Option[string] {
|
||||
options := []huh.Option[string]{
|
||||
huh.NewOption("Executable", "exe"),
|
||||
huh.NewOption("Shared library", "shared"),
|
||||
}
|
||||
if goos == "windows" {
|
||||
options = append(options,
|
||||
huh.NewOption("Service", "service"),
|
||||
huh.NewOption("Shellcode", "shellcode"),
|
||||
)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func firstOptionValue(options []huh.Option[string]) (string, bool) {
|
||||
if len(options) == 0 {
|
||||
return "", false
|
||||
}
|
||||
return options[0].Value, true
|
||||
}
|
||||
|
||||
func maybeResetTargets(commonPlatformsOnly bool, lastCommonPlatformsOnly *bool, compilerTargets []*clientpb.CompilerTarget, goos, goarch, format *string) {
|
||||
if lastCommonPlatformsOnly == nil || goos == nil || goarch == nil || format == nil {
|
||||
return
|
||||
}
|
||||
if commonPlatformsOnly == *lastCommonPlatformsOnly {
|
||||
return
|
||||
}
|
||||
*lastCommonPlatformsOnly = commonPlatformsOnly
|
||||
if commonPlatformsOnly {
|
||||
return
|
||||
}
|
||||
|
||||
osOptions := commonOSOptions()
|
||||
if len(compilerTargets) > 0 {
|
||||
osOptions = osOptionsFromTargets(compilerTargets)
|
||||
if len(osOptions) == 0 {
|
||||
osOptions = commonOSOptions()
|
||||
}
|
||||
}
|
||||
if value, ok := firstOptionValue(osOptions); ok {
|
||||
*goos = value
|
||||
}
|
||||
|
||||
archOptions := commonArchOptions(*goos)
|
||||
if len(compilerTargets) > 0 {
|
||||
archOptions = archOptionsFromTargets(compilerTargets, *goos)
|
||||
if len(archOptions) == 0 {
|
||||
archOptions = commonArchOptions(*goos)
|
||||
}
|
||||
}
|
||||
if value, ok := firstOptionValue(archOptions); ok {
|
||||
*goarch = value
|
||||
}
|
||||
|
||||
formatOptions := commonFormatOptions(*goos)
|
||||
if len(compilerTargets) > 0 {
|
||||
formatOptions = formatOptionsFromTargets(compilerTargets, *goos, *goarch)
|
||||
if len(formatOptions) == 0 {
|
||||
formatOptions = commonFormatOptions(*goos)
|
||||
}
|
||||
}
|
||||
if value, ok := firstOptionValue(formatOptions); ok {
|
||||
*format = value
|
||||
}
|
||||
}
|
||||
|
||||
func compilerTargetList(compiler *clientpb.Compiler) []*clientpb.CompilerTarget {
|
||||
if compiler == nil {
|
||||
return nil
|
||||
}
|
||||
targets := make([]*clientpb.CompilerTarget, 0, len(compiler.Targets)+len(compiler.UnsupportedTargets))
|
||||
targets = append(targets, compiler.Targets...)
|
||||
targets = append(targets, compiler.UnsupportedTargets...)
|
||||
return targets
|
||||
}
|
||||
|
||||
func osOptionsFromTargets(targets []*clientpb.CompilerTarget) []huh.Option[string] {
|
||||
if len(targets) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for _, target := range targets {
|
||||
if target.GOOS == "" {
|
||||
continue
|
||||
}
|
||||
seen[target.GOOS] = struct{}{}
|
||||
}
|
||||
values := make([]string, 0, len(seen))
|
||||
for value := range seen {
|
||||
values = append(values, value)
|
||||
}
|
||||
sort.Strings(values)
|
||||
|
||||
options := make([]huh.Option[string], 0, len(values))
|
||||
for _, value := range values {
|
||||
options = append(options, huh.NewOption(osLabel(value), value))
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func archOptionsFromTargets(targets []*clientpb.CompilerTarget, goos string) []huh.Option[string] {
|
||||
if len(targets) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
for _, target := range targets {
|
||||
if goos != "" && target.GOOS != goos {
|
||||
continue
|
||||
}
|
||||
if target.GOARCH == "" {
|
||||
continue
|
||||
}
|
||||
seen[target.GOARCH] = struct{}{}
|
||||
}
|
||||
values := make([]string, 0, len(seen))
|
||||
for value := range seen {
|
||||
values = append(values, value)
|
||||
}
|
||||
sort.Strings(values)
|
||||
|
||||
options := make([]huh.Option[string], 0, len(values))
|
||||
for _, value := range values {
|
||||
options = append(options, huh.NewOption(value, value))
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func formatOptionsFromTargets(targets []*clientpb.CompilerTarget, goos, goarch string) []huh.Option[string] {
|
||||
if len(targets) == 0 {
|
||||
return nil
|
||||
}
|
||||
available := map[clientpb.OutputFormat]struct{}{}
|
||||
for _, target := range targets {
|
||||
if goos != "" && target.GOOS != goos {
|
||||
continue
|
||||
}
|
||||
if goarch != "" && target.GOARCH != goarch {
|
||||
continue
|
||||
}
|
||||
available[target.Format] = struct{}{}
|
||||
}
|
||||
|
||||
options := make([]huh.Option[string], 0, len(available))
|
||||
for _, option := range formatOptionOrder {
|
||||
if _, ok := available[option.format]; ok {
|
||||
options = append(options, huh.NewOption(option.label, option.value))
|
||||
}
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
func osLabel(value string) string {
|
||||
switch value {
|
||||
case "windows":
|
||||
return "Windows"
|
||||
case "linux":
|
||||
return "Linux"
|
||||
case "darwin":
|
||||
return "macOS"
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
+65
-20
@@ -63,6 +63,68 @@ func (r *Release) Published() (time.Time, error) {
|
||||
// occurs we don't really try to recover. If client is nil we just use the Go
|
||||
// default client with default settings.
|
||||
func CheckForUpdates(client *http.Client, prereleases bool) (*Release, error) {
|
||||
releases, err := fetchReleases(client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(releases) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
current := canonicalSemver(Version)
|
||||
if current == "" {
|
||||
current = "v0.0.0"
|
||||
}
|
||||
for _, release := range releases {
|
||||
if release == nil {
|
||||
continue
|
||||
}
|
||||
if release.Prerelease && !prereleases {
|
||||
continue
|
||||
}
|
||||
releaseVersion := canonicalSemver(release.TagName)
|
||||
if releaseVersion == "" {
|
||||
continue
|
||||
}
|
||||
if semver.Compare(releaseVersion, current) > 0 {
|
||||
return release, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// LatestRelease - Returns the latest release without comparing to the current version.
|
||||
func LatestRelease(client *http.Client, prereleases bool) (*Release, error) {
|
||||
releases, err := fetchReleases(client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(releases) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var latest *Release
|
||||
var latestVersion string
|
||||
for _, release := range releases {
|
||||
if release == nil {
|
||||
continue
|
||||
}
|
||||
if release.Prerelease && !prereleases {
|
||||
continue
|
||||
}
|
||||
releaseVersion := canonicalSemver(release.TagName)
|
||||
if releaseVersion == "" {
|
||||
continue
|
||||
}
|
||||
if latest == nil || semver.Compare(releaseVersion, latestVersion) > 0 {
|
||||
latest = release
|
||||
latestVersion = releaseVersion
|
||||
}
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
func fetchReleases(client *http.Client) ([]*Release, error) {
|
||||
skip := os.Getenv(skipCheckEnv)
|
||||
if skip != "" || GithubReleasesURL == "" {
|
||||
return nil, nil
|
||||
@@ -84,27 +146,10 @@ func CheckForUpdates(client *http.Client, prereleases bool) (*Release, error) {
|
||||
if resp.StatusCode != 200 {
|
||||
return nil, errors.New("API returned non-200 status code")
|
||||
}
|
||||
releases := &[]*Release{}
|
||||
err = json.Unmarshal(body, releases)
|
||||
if err != nil {
|
||||
releases := []*Release{}
|
||||
if err := json.Unmarshal(body, &releases); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
current := canonicalSemver(Version)
|
||||
if current == "" {
|
||||
current = "v0.0.0"
|
||||
}
|
||||
for _, release := range *releases {
|
||||
if release.Prerelease && !prereleases {
|
||||
continue
|
||||
}
|
||||
releaseVersion := canonicalSemver(release.TagName)
|
||||
if releaseVersion == "" {
|
||||
continue
|
||||
}
|
||||
if semver.Compare(releaseVersion, current) > 0 {
|
||||
return release, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
return releases, nil
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export type TutorialCardCardProps = {
|
||||
|
||||
export default function TutorialCard(props: TutorialCardCardProps) {
|
||||
return (
|
||||
<Card isFooterBlurred>
|
||||
<Card isFooterBlurred className="relative z-0">
|
||||
<CardHeader className="absolute z-10 top-1 flex-col items-end">
|
||||
<p className="text-md text-white/70 uppercase font-bold">
|
||||
{props.name}
|
||||
@@ -41,7 +41,7 @@ export default function TutorialCard(props: TutorialCardCardProps) {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CardFooter className="absolute bg-black/40 bottom-0 z-100 border-t-1 border-default-600 dark:border-default-100">
|
||||
<CardFooter className="absolute bottom-0 z-10 bg-black/40 border-t-1 border-default-600 dark:border-default-100">
|
||||
<div className="flex flex-row w-full items-center">
|
||||
<p
|
||||
className={
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
__IMPORTANT:__ MCP (Model Context Protocol) support is _experimental_ and NOT ALL FUNCTIONALITY IS SUPPORTED YET. Pull requests and testing feedback are welcome!
|
||||
|
||||
There are two main ways to connect an AI model to sliver using MCP: locally over stdio, or over a network using HTTP/SSE transports. The `sliver-client` supports both stdio and http/sse, but the `sliver-server` binary only supports HTTP/SSE. We recommend using the `sliver-client` and [Multiplayer Mode](/docs?name=Multi-player+Mode) to connect to a remote server with the stdio transport.
|
||||
|
||||
|
||||
## MCP Over STDIO
|
||||
|
||||
Example configurations for various AIs, you'll need to configure [Multiplayer Mode](/docs?name=Multi-player+Mode) first:
|
||||
|
||||
### OpenAI Codex
|
||||
|
||||
```
|
||||
[mcp_servers.sliver]
|
||||
args = ["mcp", "--config", "/path/to/multiplayer.cfg"]
|
||||
command = "/path/to/sliver-client"
|
||||
```
|
||||
|
||||
### Anthropic Claude Code
|
||||
|
||||
```
|
||||
claude mcp add sliver -- /path/to/sliver-client mcp --config /path/to/multiplayer.cfg
|
||||
```
|
||||
|
||||
## MCP Over HTTP/SSE
|
||||
|
||||
The MCP HTTP/SSE server can be started from either the `sliver-client` or `sliver-server`, however _where you run the command is where the server will start_ i.e., starting the HTTP/SSE MCP using `sliver-client` will turn that `sliver-client` binary into the MCP server (connected to whatever Sliver server you're currently connected to). Running the command from the `sliver-server` console will start a HTTP/SSE MCP server locally bound on the server.
|
||||
|
||||
```
|
||||
.------..------..------..------..------..------.
|
||||
|S.--. ||L.--. ||I.--. ||V.--. ||E.--. ||R.--. |
|
||||
| :/\: || :/\: || (\/) || :(): || (\/) || :(): |
|
||||
| :\/: || (__) || :\/: || ()() || :\/: || ()() |
|
||||
| '--'S|| '--'L|| '--'I|| '--'V|| '--'E|| '--'R|
|
||||
`------'`------'`------'`------'`------'`------'
|
||||
|
||||
All hackers gain skulk
|
||||
[*] Server v1.6.4 - 4d0d46afd6e1cbcaafde92687144cb28694a68ce
|
||||
[*] Welcome to the sliver shell, please type 'help' for options
|
||||
sliver > mcp
|
||||
|
||||
Status: stopped
|
||||
Transport: sse
|
||||
Listen: 127.0.0.1:8080
|
||||
Endpoint: http://127.0.0.1:8080/sse
|
||||
|
||||
sliver > mcp start --transport http
|
||||
|
||||
[*] Starting MCP server (http) on 127.0.0.1:8080
|
||||
[*] Endpoint: http://127.0.0.1:8080/mcp
|
||||
```
|
||||
|
||||
You can use `mcp stop` to stop the server, see `mcp start --help` for additional options when starting the MCP server. Authentication is not yet supported for MCP over HTTP/SSE.
|
||||
@@ -1,5 +1,3 @@
|
||||
# This course is intended for the 1.6 version of Sliver, which is not yet published
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# This course is intended for the 1.6 version of Sliver, which is not yet published
|
||||
|
||||
When using Sliver during a live engagement, you’re going to need to use custom stagers, which are essentially a first binary or commandline that will retrieve and/or load Sliver into memory on your target system. Sliver can generate shellcode for your stager to execute by using the `profiles` command.
|
||||
|
||||
For this exercise, we will create a new beacon profile and prepare to stage it.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# This course is intended for the 1.6 version of Sliver, which is not yet published
|
||||
|
||||
Pivots allow routing implant traffic through other implants. This can be useful in environments that don’t have any outbound access, but are reachable from other parts of the network that you have access to.
|
||||
|
||||
Sliver supports two types of pivots: TCP, which can be used on all operating systems, and named pipes, which are Windows-only.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# This course is intended for the 1.6 version of Sliver, which is not yet published
|
||||
|
||||
Reactions are a basic way to automate tasks in the sliver console, they allow you to specify sliver commands to run on a list of events.
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# This course is intended for the 1.6 version of Sliver, which is not yet published
|
||||
|
||||
The Sliver armory is used to install and maintain third party extensions and aliases within sliver. The full list of available extensions can be found at https://github.com/sliverarmory/armory, keep in mind this is community maintained so not all modules are necessarily up to date.
|
||||
|
||||
You can download all configured extensions/aliases using the armory command.
|
||||
|
||||
@@ -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\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 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\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":"Sliver 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 ID Name Transport Username Operating System Last Check-Line truncated
|
||||
@@ -4,7 +4,9 @@ go 1.25.5
|
||||
|
||||
replace github.com/rsteube/carapace v0.36.3 => github.com/reeflective/carapace v0.46.3-0.20231214181515-27e49f3c3b69
|
||||
|
||||
replace github.com/reeflective/readline => github.com/moloch--/readline v0.0.0-20260104185423-d3ac1d6c561d
|
||||
replace github.com/reeflective/readline => github.com/moloch--/readline v0.0.0-20260129035512-cb5b3e87d51a
|
||||
|
||||
replace github.com/reeflective/console => github.com/moloch--/console v0.0.0-20260129035459-883dcb25c701
|
||||
|
||||
require (
|
||||
filippo.io/age v1.3.1
|
||||
@@ -36,10 +38,10 @@ require (
|
||||
github.com/miekg/dns v1.1.70
|
||||
github.com/moloch--/asciicast v0.1.1
|
||||
github.com/moloch--/memmod v0.0.0-20230225130813-fd77d905589e
|
||||
github.com/moloch--/sgn v0.0.4
|
||||
github.com/moloch--/sgn v0.0.5
|
||||
github.com/ncruces/go-sqlite3 v0.30.4
|
||||
github.com/reeflective/console v0.1.25
|
||||
github.com/reeflective/readline v1.1.3
|
||||
github.com/reeflective/readline v1.1.4
|
||||
github.com/rsteube/carapace v0.50.2
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.10.2
|
||||
@@ -99,8 +101,8 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/config v1.31.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssm v1.65.1 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/carapace-sh/carapace v1.9.0 // indirect
|
||||
github.com/carapace-sh/carapace-shlex v1.1.0 // indirect
|
||||
github.com/carapace-sh/carapace v1.11.0
|
||||
github.com/carapace-sh/carapace-shlex v1.1.1 // indirect
|
||||
github.com/catppuccin/go v0.3.0 // indirect
|
||||
github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect
|
||||
github.com/charmbracelet/bubbletea v1.3.10 // indirect
|
||||
@@ -194,7 +196,7 @@ require (
|
||||
gopkg.in/jcmturner/goidentity.v3 v3.0.0 // indirect
|
||||
gopkg.in/jcmturner/gokrb5.v7 v7.5.0 // indirect
|
||||
gopkg.in/jcmturner/rpc.v1 v1.1.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
|
||||
@@ -91,10 +91,10 @@ github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xW
|
||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/carapace-sh/carapace v1.9.0 h1:IuEP6YeeK4fhrH7MoOyL0I3GMhvROerkw6YGxkx8Fbw=
|
||||
github.com/carapace-sh/carapace v1.9.0/go.mod h1:Zs3DpsawpFm+8fEfRVYE9EzMBYH8u7S3Aw9yAAKX0JM=
|
||||
github.com/carapace-sh/carapace-shlex v1.1.0 h1:58QSJTUxghpa/rEn6+Z9UM/Hy0ipVHDUn9S1mp4i+ZE=
|
||||
github.com/carapace-sh/carapace-shlex v1.1.0/go.mod h1:lJ4ZsdxytE0wHJ8Ta9S7Qq0XpjgjU0mdfCqiI2FHx7M=
|
||||
github.com/carapace-sh/carapace v1.11.0 h1:dTUFXvIrUTLd9BGLsfDt4wCgEyPl8bJeZOFDmN7fIfo=
|
||||
github.com/carapace-sh/carapace v1.11.0/go.mod h1:NVkuv1s8wyFvu7d98rdgYwqGKMB6GO1MEUZp5RcWri8=
|
||||
github.com/carapace-sh/carapace-shlex v1.1.1 h1:ccmNeetAYZOk4IcV36youFDsXusT9uCNW2Njkw+QS+Q=
|
||||
github.com/carapace-sh/carapace-shlex v1.1.1/go.mod h1:lJ4ZsdxytE0wHJ8Ta9S7Qq0XpjgjU0mdfCqiI2FHx7M=
|
||||
github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
|
||||
github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
@@ -350,14 +350,16 @@ github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
|
||||
github.com/moloch--/asciicast v0.1.1 h1:btwwniCK9br3ys33XZ71IG/M3ZujSSCcBzsH/sieiXg=
|
||||
github.com/moloch--/asciicast v0.1.1/go.mod h1:OckO16UDLgxVLclrCnbocL1ix15Br/8Xv/caBoYq98o=
|
||||
github.com/moloch--/console v0.0.0-20260129035459-883dcb25c701 h1:6caCgDZpovjvv+eclRytFDf0GpVEnjDmoJRHpfkb42E=
|
||||
github.com/moloch--/console v0.0.0-20260129035459-883dcb25c701/go.mod h1:UdqyqqCSnPu3Zc8Q3kpDszrq1hcyBHsG17hlWlRJmWI=
|
||||
github.com/moloch--/go-keystone v0.0.2 h1:xThbYs45CSzoDUz5kBZxAyTPIpK3t5M7NB1x+NTTRL8=
|
||||
github.com/moloch--/go-keystone v0.0.2/go.mod h1:kpGRJpw9b7Eq3MluHrba+GPKZhSyDrvhLULSwH5nGGM=
|
||||
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/moloch--/readline v0.0.0-20260104185423-d3ac1d6c561d h1:9RbKockJl6ZdgoEh2QqU3An6Ij/NWZtRWS3J6yG0+qo=
|
||||
github.com/moloch--/readline v0.0.0-20260104185423-d3ac1d6c561d/go.mod h1:CwNkh9BmFBBCSO6mdDaNWb34rOqQsI9eYbxyqvOEazY=
|
||||
github.com/moloch--/sgn v0.0.4 h1:90IC5rx3TmPEfrqPnENB0yyiqcbcNk9LqezXx7uruF0=
|
||||
github.com/moloch--/sgn v0.0.4/go.mod h1:FyWfCtdynywgLmVR71vTJztZ3WkGSkR91Y4EOijUutE=
|
||||
github.com/moloch--/readline v0.0.0-20260129035512-cb5b3e87d51a h1:Q69DxLWF+Z8oIjuNbeKC6Xygk8Z4heWzzO79Io1cEYA=
|
||||
github.com/moloch--/readline v0.0.0-20260129035512-cb5b3e87d51a/go.mod h1:CwNkh9BmFBBCSO6mdDaNWb34rOqQsI9eYbxyqvOEazY=
|
||||
github.com/moloch--/sgn v0.0.5 h1:92GFaRpe+353uhqzFiNKXKgmTiD4dBxnvb8gd4MaV/g=
|
||||
github.com/moloch--/sgn v0.0.5/go.mod h1:FyWfCtdynywgLmVR71vTJztZ3WkGSkR91Y4EOijUutE=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
@@ -397,8 +399,6 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
|
||||
github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
|
||||
github.com/reeflective/console v0.1.25 h1:do/r6rcKH6pCQDEzh5PhoVFcqHkqcjd0N6tNjpmYWWQ=
|
||||
github.com/reeflective/console v0.1.25/go.mod h1:It/IqEjo0PowaBuxBS9pEi5EYUgmtvQd0ytMtlS77kk=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
@@ -419,11 +419,9 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs
|
||||
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
|
||||
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
|
||||
@@ -166,10 +166,14 @@ func dirListHandler(data []byte, resp RPCResponse) {
|
||||
dirList.Exists = true
|
||||
} else {
|
||||
dirList.Exists = false
|
||||
dirList.Response = &commonpb.Response{Err: err.Error()}
|
||||
}
|
||||
dirList.Files = []*sliverpb.FileInfo{}
|
||||
rootDirInfo, err := rootDirEntry.Info()
|
||||
if err == nil && filter == "" {
|
||||
var rootDirInfo fs.FileInfo
|
||||
if rootDirEntry != nil {
|
||||
rootDirInfo, err = rootDirEntry.Info()
|
||||
}
|
||||
if err == nil && rootDirInfo != nil && filter == "" {
|
||||
// We should not get an error because we created the DirEntry object from the FileInfo object
|
||||
dirList.Files = append(dirList.Files, &sliverpb.FileInfo{
|
||||
Name: ".", // Cannot use the name from the FileInfo / DirEntry because that is the name of the directory
|
||||
@@ -193,6 +197,7 @@ func dirListHandler(data []byte, resp RPCResponse) {
|
||||
if err != nil {
|
||||
// Then this is a bad filter, and it will be a bad filter
|
||||
// on every iteration of the loop, so we might as well break now
|
||||
dirList.Response = &commonpb.Response{Err: err.Error()}
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -249,22 +254,26 @@ func getDirList(target string) (string, fs.DirEntry, []fs.DirEntry, error) {
|
||||
// {{end}}
|
||||
return "", nil, nil, err
|
||||
}
|
||||
if rootInfo, err := os.Stat(dir); !os.IsNotExist(err) {
|
||||
/*
|
||||
We could place the entry for the directory itself
|
||||
at the beginning of the returned slice of DirEntry
|
||||
objects, but then it is not clear if that is the
|
||||
root directory or a directory / file in the root
|
||||
directory with the same name as the root directory.
|
||||
|
||||
Using WalkDir is not great here because you cannot
|
||||
tell it to not be recursive, so we will be wasting
|
||||
cycles telling it to skip directories and files
|
||||
*/
|
||||
files, err := os.ReadDir(dir)
|
||||
return dir, fs.FileInfoToDirEntry(rootInfo), files, err
|
||||
rootInfo, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return dir, nil, []fs.DirEntry{}, errors.New("directory does not exist")
|
||||
}
|
||||
return dir, nil, []fs.DirEntry{}, err
|
||||
}
|
||||
return dir, nil, []fs.DirEntry{}, errors.New("directory does not exist")
|
||||
/*
|
||||
We could place the entry for the directory itself
|
||||
at the beginning of the returned slice of DirEntry
|
||||
objects, but then it is not clear if that is the
|
||||
root directory or a directory / file in the root
|
||||
directory with the same name as the root directory.
|
||||
|
||||
Using WalkDir is not great here because you cannot
|
||||
tell it to not be recursive, so we will be wasting
|
||||
cycles telling it to skip directories and files
|
||||
*/
|
||||
files, err := os.ReadDir(dir)
|
||||
return dir, fs.FileInfoToDirEntry(rootInfo), files, err
|
||||
}
|
||||
|
||||
func rmHandler(data []byte, resp RPCResponse) {
|
||||
|
||||
+1027
-1007
File diff suppressed because it is too large.
Load diff
@@ -586,6 +586,9 @@ message WebContent {
|
||||
string ContentType = 4;
|
||||
uint64 Size = 5 [ jstype = JS_STRING ];
|
||||
|
||||
string OriginalFile = 6;
|
||||
string Sha256 = 7;
|
||||
|
||||
bytes Content = 9;
|
||||
}
|
||||
|
||||
@@ -1316,4 +1319,4 @@ message CertificateData {
|
||||
|
||||
message CertificateInfo {
|
||||
repeated CertificateData info = 1;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.26.0
|
||||
// protoc v6.33.2
|
||||
// protoc v3.15.8
|
||||
// source: commonpb/common.proto
|
||||
|
||||
package commonpb
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.26.0
|
||||
// protoc v6.33.2
|
||||
// protoc v3.15.8
|
||||
// source: dnspb/dns.proto
|
||||
|
||||
package dnspb
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.26.0
|
||||
// protoc v6.33.2
|
||||
// protoc v3.15.8
|
||||
// source: rpcpb/services.proto
|
||||
|
||||
package rpcpb
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.26.0
|
||||
// protoc v6.33.2
|
||||
// protoc v3.15.8
|
||||
// source: sliverpb/sliver.proto
|
||||
|
||||
package sliverpb
|
||||
|
||||
@@ -136,6 +136,7 @@ var rootCmd = &cobra.Command{
|
||||
cryptography.AgeServerKeyPair()
|
||||
cryptography.MinisignServerPrivateKey()
|
||||
c2.SetupDefaultC2Profiles()
|
||||
_, _ = configs.LoadCrackConfig()
|
||||
|
||||
serverConfig := configs.GetServerConfig()
|
||||
listenerJobs, err := db.ListenerJobs()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/bishopfox/sliver/server/assets"
|
||||
"github.com/bishopfox/sliver/server/c2"
|
||||
"github.com/bishopfox/sliver/server/certs"
|
||||
"github.com/bishopfox/sliver/server/configs"
|
||||
"github.com/bishopfox/sliver/server/console"
|
||||
"github.com/bishopfox/sliver/server/cryptography"
|
||||
"github.com/bishopfox/sliver/server/daemon"
|
||||
@@ -63,6 +64,7 @@ var daemonCmd = &cobra.Command{
|
||||
certs.SetupWGKeys()
|
||||
cryptography.AgeServerKeyPair()
|
||||
cryptography.MinisignServerPrivateKey()
|
||||
_, _ = configs.LoadCrackConfig()
|
||||
|
||||
listenerJobs, err := db.ListenerJobs()
|
||||
if err != nil {
|
||||
|
||||
+83
-25
@@ -26,17 +26,19 @@ import (
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/server/assets"
|
||||
"github.com/bishopfox/sliver/server/log"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
crackConfigFileName = "crack.json"
|
||||
crackConfigFileName = "crack.yaml"
|
||||
crackLegacyConfigFileName = "crack.json"
|
||||
)
|
||||
|
||||
var (
|
||||
crackConfigLog = log.NamedLogger("config", "crack")
|
||||
)
|
||||
|
||||
// getCrackConfigPath - File path to config.json
|
||||
// getCrackConfigPath - File path to config.yaml
|
||||
func getCrackConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
confPath := filepath.Join(appDir, "configs", crackConfigFileName)
|
||||
@@ -44,6 +46,41 @@ func getCrackConfigPath() string {
|
||||
return confPath
|
||||
}
|
||||
|
||||
func getCrackLegacyConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
return filepath.Join(appDir, "configs", crackLegacyConfigFileName)
|
||||
}
|
||||
|
||||
type crackConfigYAML struct {
|
||||
AutoFire bool `yaml:"AutoFire"`
|
||||
MaxFileSize int64 `yaml:"MaxFileSize"`
|
||||
ChunkSize int64 `yaml:"ChunkSize"`
|
||||
MaxDiskUsage int64 `yaml:"MaxDiskUsage"`
|
||||
}
|
||||
|
||||
func crackConfigFromYAML(data []byte) (*clientpb.CrackConfig, error) {
|
||||
var raw crackConfigYAML
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &clientpb.CrackConfig{
|
||||
AutoFire: raw.AutoFire,
|
||||
MaxFileSize: raw.MaxFileSize,
|
||||
ChunkSize: raw.ChunkSize,
|
||||
MaxDiskUsage: raw.MaxDiskUsage,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func crackConfigToYAML(config *clientpb.CrackConfig) ([]byte, error) {
|
||||
raw := crackConfigYAML{
|
||||
AutoFire: config.AutoFire,
|
||||
MaxFileSize: config.MaxFileSize,
|
||||
ChunkSize: config.ChunkSize,
|
||||
MaxDiskUsage: config.MaxDiskUsage,
|
||||
}
|
||||
return yaml.Marshal(raw)
|
||||
}
|
||||
|
||||
// Save - Save config file to disk
|
||||
func SaveCrackConfig(config *clientpb.CrackConfig) error {
|
||||
configPath := getCrackConfigPath()
|
||||
@@ -55,7 +92,7 @@ func SaveCrackConfig(config *clientpb.CrackConfig) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
data, err := json.MarshalIndent(config, "", " ")
|
||||
data, err := crackConfigToYAML(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -70,6 +107,7 @@ func SaveCrackConfig(config *clientpb.CrackConfig) error {
|
||||
// LoadCrackConfig - Get config value
|
||||
func LoadCrackConfig() (*clientpb.CrackConfig, error) {
|
||||
configPath := getCrackConfigPath()
|
||||
legacyPath := getCrackLegacyConfigPath()
|
||||
const defaultMaxFileSize = 10 * 1024 * 1024 * 1024 // 10GB - max size of any one file
|
||||
const defaultMaxDiskUsage = 5 * defaultMaxFileSize // 50GB - total disk usage for all files
|
||||
const maxChunkSize = 1024 * 1024 * 1024 // 1GB - max size of any one chunk
|
||||
@@ -80,15 +118,28 @@ func LoadCrackConfig() (*clientpb.CrackConfig, error) {
|
||||
ChunkSize: defaultChunkSize,
|
||||
MaxDiskUsage: defaultMaxDiskUsage,
|
||||
}
|
||||
migratedLegacy := false
|
||||
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
crackConfigLog.Errorf("Failed to read crack config file %s", err)
|
||||
return config, err
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
parsed, err := crackConfigFromYAML(data)
|
||||
if err != nil {
|
||||
crackConfigLog.Errorf("Failed to parse crack config file %s", err)
|
||||
return config, err
|
||||
}
|
||||
config = parsed
|
||||
} else if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(legacyPath)
|
||||
if err != nil {
|
||||
crackConfigLog.Errorf("Failed to read legacy crack config file %s", err)
|
||||
return config, err
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
if err != nil {
|
||||
crackConfigLog.Errorf("Failed to parse legacy crack config file %s", err)
|
||||
return &clientpb.CrackConfig{
|
||||
AutoFire: true,
|
||||
MaxFileSize: defaultMaxFileSize,
|
||||
@@ -96,33 +147,40 @@ func LoadCrackConfig() (*clientpb.CrackConfig, error) {
|
||||
MaxDiskUsage: defaultMaxDiskUsage,
|
||||
}, err
|
||||
}
|
||||
if config.ChunkSize < 1024 {
|
||||
crackConfigLog.Warnf("Invalid chunk size %d, using default %d", config.ChunkSize, defaultChunkSize)
|
||||
config.ChunkSize = defaultChunkSize
|
||||
}
|
||||
if config.MaxFileSize < 1024 {
|
||||
crackConfigLog.Warnf("Invalid max file size %d, using default %d", config.MaxFileSize, defaultMaxFileSize)
|
||||
config.MaxFileSize = defaultMaxFileSize
|
||||
}
|
||||
if maxChunkSize < config.ChunkSize {
|
||||
crackConfigLog.Warnf("Chunk size is too large, setting to %d", maxChunkSize)
|
||||
config.ChunkSize = maxChunkSize
|
||||
}
|
||||
if config.MaxFileSize < config.ChunkSize {
|
||||
crackConfigLog.Warnf("Chunk size is larger than max file size, setting to %d", config.MaxFileSize)
|
||||
config.ChunkSize = config.MaxFileSize
|
||||
}
|
||||
if config.MaxDiskUsage < config.MaxFileSize {
|
||||
crackConfigLog.Warnf("Max disk usage is smaller than max file size, setting to %d", config.MaxFileSize)
|
||||
config.MaxDiskUsage = config.MaxFileSize
|
||||
}
|
||||
return config, nil
|
||||
migratedLegacy = true
|
||||
crackConfigLog.Infof("Migrating legacy config %s to %s", legacyPath, configPath)
|
||||
} else {
|
||||
crackConfigLog.Debugf("Crack config file does not exist, using defaults")
|
||||
}
|
||||
if config.ChunkSize < 1024 {
|
||||
crackConfigLog.Warnf("Invalid chunk size %d, using default %d", config.ChunkSize, defaultChunkSize)
|
||||
config.ChunkSize = defaultChunkSize
|
||||
}
|
||||
if config.MaxFileSize < 1024 {
|
||||
crackConfigLog.Warnf("Invalid max file size %d, using default %d", config.MaxFileSize, defaultMaxFileSize)
|
||||
config.MaxFileSize = defaultMaxFileSize
|
||||
}
|
||||
if maxChunkSize < config.ChunkSize {
|
||||
crackConfigLog.Warnf("Chunk size is too large, setting to %d", maxChunkSize)
|
||||
config.ChunkSize = maxChunkSize
|
||||
}
|
||||
if config.MaxFileSize < config.ChunkSize {
|
||||
crackConfigLog.Warnf("Chunk size is larger than max file size, setting to %d", config.MaxFileSize)
|
||||
config.ChunkSize = config.MaxFileSize
|
||||
}
|
||||
if config.MaxDiskUsage < config.MaxFileSize {
|
||||
crackConfigLog.Warnf("Max disk usage is smaller than max file size, setting to %d", config.MaxFileSize)
|
||||
config.MaxDiskUsage = config.MaxFileSize
|
||||
}
|
||||
err := SaveCrackConfig(config) // This updates the config with any missing fields
|
||||
if err != nil {
|
||||
crackConfigLog.Errorf("Failed to save default config %s", err)
|
||||
return config, err
|
||||
}
|
||||
if migratedLegacy {
|
||||
if err := renameLegacyConfig(legacyPath); err != nil {
|
||||
crackConfigLog.Errorf("Failed to rename legacy config %s", err)
|
||||
}
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
)
|
||||
|
||||
func TestCrackConfigParsesYAML(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configPath := getCrackConfigPath()
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
|
||||
data := []byte(`AutoFire: false
|
||||
MaxFileSize: 2048
|
||||
ChunkSize: 1024
|
||||
MaxDiskUsage: 4096
|
||||
`)
|
||||
if err := os.WriteFile(configPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write yaml config: %v", err)
|
||||
}
|
||||
|
||||
config, err := LoadCrackConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if config.AutoFire {
|
||||
t.Fatalf("expected AutoFire false")
|
||||
}
|
||||
if config.MaxFileSize != 2048 {
|
||||
t.Fatalf("expected MaxFileSize %d, got %d", 2048, config.MaxFileSize)
|
||||
}
|
||||
if config.ChunkSize != 1024 {
|
||||
t.Fatalf("expected ChunkSize %d, got %d", 1024, config.ChunkSize)
|
||||
}
|
||||
if config.MaxDiskUsage != 4096 {
|
||||
t.Fatalf("expected MaxDiskUsage %d, got %d", 4096, config.MaxDiskUsage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrackConfigWritesDefault(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
config, err := LoadCrackConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if config == nil {
|
||||
t.Fatalf("expected default crack config")
|
||||
}
|
||||
if _, err := os.Stat(getCrackConfigPath()); err != nil {
|
||||
t.Fatalf("expected default config file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrackConfigMigratesLegacyJSON(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configDir := filepath.Dir(getCrackConfigPath())
|
||||
if err := os.MkdirAll(configDir, 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
legacyPath := filepath.Join(configDir, crackLegacyConfigFileName)
|
||||
|
||||
legacy := &clientpb.CrackConfig{
|
||||
AutoFire: false,
|
||||
MaxFileSize: 4096,
|
||||
ChunkSize: 2048,
|
||||
MaxDiskUsage: 8192,
|
||||
}
|
||||
data, err := json.MarshalIndent(legacy, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal legacy config: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write legacy config: %v", err)
|
||||
}
|
||||
|
||||
config, err := LoadCrackConfig()
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got %v", err)
|
||||
}
|
||||
if config.MaxFileSize != 4096 {
|
||||
t.Fatalf("expected MaxFileSize %d, got %d", 4096, config.MaxFileSize)
|
||||
}
|
||||
if _, err := os.Stat(getCrackConfigPath()); err != nil {
|
||||
t.Fatalf("expected migrated yaml config file to exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected legacy config to be renamed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyBackupPath(legacyPath)); err != nil {
|
||||
t.Fatalf("expected legacy backup file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
+112
-15
@@ -26,9 +26,11 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
|
||||
"github.com/bishopfox/sliver/server/assets"
|
||||
"github.com/bishopfox/sliver/server/log"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -39,7 +41,8 @@ const (
|
||||
// MySQL - MySQL protocol
|
||||
MySQL = "mysql"
|
||||
|
||||
databaseConfigFileName = "database.json"
|
||||
databaseConfigFileName = "database.yaml"
|
||||
databaseLegacyConfigFileName = "database.json"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -47,9 +50,16 @@ var (
|
||||
ErrInvalidDialect = errors.New("invalid SQL Dialect")
|
||||
|
||||
databaseConfigLog = log.NamedLogger("config", "database")
|
||||
|
||||
defaultSQLitePragmas = map[string]string{
|
||||
"journal_mode": "WAL", // reduce writer blocking, better concurrency
|
||||
"busy_timeout": "5000", // wait for locks instead of failing fast (ms)
|
||||
"synchronous": "NORMAL", // faster WAL syncs while retaining durability
|
||||
"temp_store": "MEMORY", // keep temp structures off disk for quicker startup
|
||||
}
|
||||
)
|
||||
|
||||
// GetDatabaseConfigPath - File path to config.json
|
||||
// GetDatabaseConfigPath - File path to config.yaml
|
||||
func GetDatabaseConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
databaseConfigPath := filepath.Join(appDir, "configs", databaseConfigFileName)
|
||||
@@ -57,21 +67,27 @@ func GetDatabaseConfigPath() string {
|
||||
return databaseConfigPath
|
||||
}
|
||||
|
||||
func getDatabaseLegacyConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
return filepath.Join(appDir, "configs", databaseLegacyConfigFileName)
|
||||
}
|
||||
|
||||
// DatabaseConfig - Server config
|
||||
type DatabaseConfig struct {
|
||||
Dialect string `json:"dialect"`
|
||||
Database string `json:"database"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
Dialect string `json:"dialect" yaml:"dialect"`
|
||||
Database string `json:"database" yaml:"database"`
|
||||
Username string `json:"username" yaml:"username"`
|
||||
Password string `json:"password" yaml:"password"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
|
||||
Params map[string]string `json:"params"`
|
||||
Params map[string]string `json:"params" yaml:"params"`
|
||||
Pragmas map[string]string `json:"pragmas" yaml:"pragmas"`
|
||||
|
||||
MaxIdleConns int `json:"max_idle_conns"`
|
||||
MaxOpenConns int `json:"max_open_conns"`
|
||||
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
|
||||
MaxOpenConns int `json:"max_open_conns" yaml:"max_open_conns"`
|
||||
|
||||
LogLevel string `json:"log_level"`
|
||||
LogLevel string `json:"log_level" yaml:"log_level"`
|
||||
}
|
||||
|
||||
// DSN - Get the db connections string
|
||||
@@ -80,7 +96,7 @@ func (c *DatabaseConfig) DSN() (string, error) {
|
||||
switch c.Dialect {
|
||||
case Sqlite:
|
||||
filePath := filepath.Join(assets.GetRootAppDir(), "sliver.db")
|
||||
params := encodeParams(c.Params)
|
||||
params := encodeSQLiteParams(c.Params, c.Pragmas)
|
||||
return fmt.Sprintf("file:%s?%s", filePath, params), nil
|
||||
case MySQL:
|
||||
user := url.QueryEscape(c.Username)
|
||||
@@ -112,6 +128,44 @@ func encodeParams(rawParams map[string]string) string {
|
||||
return params.Encode()
|
||||
}
|
||||
|
||||
func encodeSQLiteParams(rawParams map[string]string, pragmas map[string]string) string {
|
||||
if rawParams == nil {
|
||||
rawParams = map[string]string{}
|
||||
}
|
||||
params := url.Values{}
|
||||
|
||||
// Preserve any user-provided parameters first.
|
||||
for key, value := range rawParams {
|
||||
params.Add(key, value)
|
||||
}
|
||||
|
||||
// Apply safer defaults only when the user has not set any custom pragma.
|
||||
if _, ok := rawParams["_pragma"]; !ok {
|
||||
selectedPragmas := pragmas
|
||||
if len(selectedPragmas) == 0 {
|
||||
selectedPragmas = defaultSQLitePragmas
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(selectedPragmas))
|
||||
for key := range selectedPragmas {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
for _, key := range keys {
|
||||
value := selectedPragmas[key]
|
||||
params.Add("_pragma", fmt.Sprintf("%s(%s)", key, value))
|
||||
}
|
||||
}
|
||||
|
||||
// Encourage shared cache to play nicer with WAL and multiple connections.
|
||||
if _, ok := rawParams["cache"]; !ok {
|
||||
params.Add("cache", "shared")
|
||||
}
|
||||
|
||||
return params.Encode()
|
||||
}
|
||||
|
||||
// Save - Save config file to disk
|
||||
func (c *DatabaseConfig) Save() error {
|
||||
configPath := GetDatabaseConfigPath()
|
||||
@@ -123,7 +177,7 @@ func (c *DatabaseConfig) Save() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
data, err := json.MarshalIndent(c, "", " ")
|
||||
data, err := yaml.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -138,18 +192,33 @@ func (c *DatabaseConfig) Save() error {
|
||||
// GetDatabaseConfig - Get config value
|
||||
func GetDatabaseConfig() *DatabaseConfig {
|
||||
configPath := GetDatabaseConfigPath()
|
||||
legacyPath := getDatabaseLegacyConfigPath()
|
||||
config := getDefaultDatabaseConfig()
|
||||
migratedLegacy := false
|
||||
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
databaseConfigLog.Errorf("Failed to read config file %s", err)
|
||||
return config
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
err = yaml.Unmarshal(data, config)
|
||||
if err != nil {
|
||||
databaseConfigLog.Errorf("Failed to parse config file %s", err)
|
||||
return config
|
||||
}
|
||||
} else if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(legacyPath)
|
||||
if err != nil {
|
||||
databaseConfigLog.Errorf("Failed to read legacy config file %s", err)
|
||||
return config
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
if err != nil {
|
||||
databaseConfigLog.Errorf("Failed to parse legacy config file %s", err)
|
||||
return config
|
||||
}
|
||||
migratedLegacy = true
|
||||
databaseConfigLog.Infof("Migrating legacy config %s to %s", legacyPath, configPath)
|
||||
} else {
|
||||
databaseConfigLog.Warnf("Config file does not exist, using defaults")
|
||||
}
|
||||
@@ -161,9 +230,17 @@ func GetDatabaseConfig() *DatabaseConfig {
|
||||
config.MaxOpenConns = 1
|
||||
}
|
||||
|
||||
ensureSQLiteDefaults(config)
|
||||
|
||||
err := config.Save() // This updates the config with any missing fields
|
||||
if err != nil {
|
||||
databaseConfigLog.Errorf("Failed to save default config %s", err)
|
||||
return config
|
||||
}
|
||||
if migratedLegacy {
|
||||
if err := renameLegacyConfig(legacyPath); err != nil {
|
||||
databaseConfigLog.Errorf("Failed to rename legacy config %s", err)
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
@@ -171,9 +248,29 @@ func GetDatabaseConfig() *DatabaseConfig {
|
||||
func getDefaultDatabaseConfig() *DatabaseConfig {
|
||||
return &DatabaseConfig{
|
||||
Dialect: Sqlite,
|
||||
Pragmas: defaultSQLitePragmas,
|
||||
MaxIdleConns: 10,
|
||||
MaxOpenConns: 100,
|
||||
|
||||
LogLevel: "warn",
|
||||
}
|
||||
}
|
||||
|
||||
func ensureSQLiteDefaults(c *DatabaseConfig) {
|
||||
if c.Dialect != Sqlite {
|
||||
return
|
||||
}
|
||||
if c.Params == nil {
|
||||
c.Params = map[string]string{}
|
||||
}
|
||||
if _, ok := c.Params["_pragma"]; ok {
|
||||
// User provided explicit pragmas; leave Pragmas untouched to avoid confusion.
|
||||
return
|
||||
}
|
||||
if len(c.Pragmas) == 0 {
|
||||
c.Pragmas = defaultSQLitePragmas
|
||||
}
|
||||
if _, ok := c.Params["cache"]; !ok {
|
||||
c.Params["cache"] = "shared"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDatabaseConfigParsesYAML(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configPath := GetDatabaseConfigPath()
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
|
||||
data := []byte(`dialect: mysql
|
||||
database: "sliver"
|
||||
username: "tester"
|
||||
password: "secret"
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
params:
|
||||
charset: "utf8mb4"
|
||||
pragmas: {}
|
||||
max_idle_conns: 7
|
||||
max_open_conns: 15
|
||||
log_level: "info"
|
||||
`)
|
||||
if err := os.WriteFile(configPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write yaml config: %v", err)
|
||||
}
|
||||
|
||||
config := GetDatabaseConfig()
|
||||
if config.Dialect != MySQL {
|
||||
t.Fatalf("expected dialect %q, got %q", MySQL, config.Dialect)
|
||||
}
|
||||
if config.Database != "sliver" {
|
||||
t.Fatalf("expected database %q, got %q", "sliver", config.Database)
|
||||
}
|
||||
if config.Username != "tester" {
|
||||
t.Fatalf("expected username %q, got %q", "tester", config.Username)
|
||||
}
|
||||
if config.Password != "secret" {
|
||||
t.Fatalf("expected password %q, got %q", "secret", config.Password)
|
||||
}
|
||||
if config.Host != "127.0.0.1" {
|
||||
t.Fatalf("expected host %q, got %q", "127.0.0.1", config.Host)
|
||||
}
|
||||
if config.Port != 3306 {
|
||||
t.Fatalf("expected port %d, got %d", 3306, config.Port)
|
||||
}
|
||||
if config.Params["charset"] != "utf8mb4" {
|
||||
t.Fatalf("expected charset param %q, got %q", "utf8mb4", config.Params["charset"])
|
||||
}
|
||||
if config.MaxIdleConns != 7 {
|
||||
t.Fatalf("expected max_idle_conns %d, got %d", 7, config.MaxIdleConns)
|
||||
}
|
||||
if config.MaxOpenConns != 15 {
|
||||
t.Fatalf("expected max_open_conns %d, got %d", 15, config.MaxOpenConns)
|
||||
}
|
||||
if config.LogLevel != "info" {
|
||||
t.Fatalf("expected log_level %q, got %q", "info", config.LogLevel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseConfigWritesDefault(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
config := GetDatabaseConfig()
|
||||
if config.Dialect != Sqlite {
|
||||
t.Fatalf("expected default dialect %q, got %q", Sqlite, config.Dialect)
|
||||
}
|
||||
if _, err := os.Stat(GetDatabaseConfigPath()); err != nil {
|
||||
t.Fatalf("expected default config file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseConfigMigratesLegacyJSON(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configDir := filepath.Dir(GetDatabaseConfigPath())
|
||||
if err := os.MkdirAll(configDir, 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
legacyPath := filepath.Join(configDir, databaseLegacyConfigFileName)
|
||||
|
||||
legacy := &DatabaseConfig{
|
||||
Dialect: Postgres,
|
||||
Database: "sliver",
|
||||
Username: "legacy",
|
||||
Password: "pass",
|
||||
Host: "db.internal",
|
||||
Port: 5432,
|
||||
Params: map[string]string{"sslmode": "disable"},
|
||||
Pragmas: map[string]string{},
|
||||
MaxIdleConns: 4,
|
||||
MaxOpenConns: 9,
|
||||
LogLevel: "debug",
|
||||
}
|
||||
data, err := json.MarshalIndent(legacy, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal legacy config: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write legacy config: %v", err)
|
||||
}
|
||||
|
||||
config := GetDatabaseConfig()
|
||||
if config.Dialect != Postgres {
|
||||
t.Fatalf("expected dialect %q, got %q", Postgres, config.Dialect)
|
||||
}
|
||||
if config.Database != "sliver" {
|
||||
t.Fatalf("expected database %q, got %q", "sliver", config.Database)
|
||||
}
|
||||
if config.Params["sslmode"] != "disable" {
|
||||
t.Fatalf("expected sslmode param %q, got %q", "disable", config.Params["sslmode"])
|
||||
}
|
||||
if _, err := os.Stat(GetDatabaseConfigPath()); err != nil {
|
||||
t.Fatalf("expected migrated yaml config file to exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected legacy config to be renamed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyBackupPath(legacyPath)); err != nil {
|
||||
t.Fatalf("expected legacy backup file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func legacyBackupPath(legacyPath string) string {
|
||||
dir := filepath.Dir(legacyPath)
|
||||
base := filepath.Base(legacyPath)
|
||||
name := strings.TrimSuffix(base, filepath.Ext(base))
|
||||
return filepath.Join(dir, "."+name+".json-old")
|
||||
}
|
||||
|
||||
func renameLegacyConfig(legacyPath string) error {
|
||||
if _, err := os.Stat(legacyPath); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
backupPath := legacyBackupPath(legacyPath)
|
||||
if _, err := os.Stat(backupPath); err == nil {
|
||||
if err := os.Remove(backupPath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.Rename(legacyPath, backupPath)
|
||||
}
|
||||
+130
-62
@@ -24,20 +24,21 @@ 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"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
serverConfigFileName = "server.json"
|
||||
serverConfigFileName = "server.yaml"
|
||||
serverLegacyConfigFileName = "server.json"
|
||||
)
|
||||
|
||||
var (
|
||||
serverConfigLog = log.NamedLogger("config", "server")
|
||||
)
|
||||
|
||||
// GetServerConfigPath - File path to config.json
|
||||
// GetServerConfigPath - File path to config.yaml
|
||||
func GetServerConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
serverConfigPath := filepath.Join(appDir, "configs", serverConfigFileName)
|
||||
@@ -45,104 +46,150 @@ func GetServerConfigPath() string {
|
||||
return serverConfigPath
|
||||
}
|
||||
|
||||
func getServerLegacyConfigPath() string {
|
||||
appDir := assets.GetRootAppDir()
|
||||
return filepath.Join(appDir, "configs", serverLegacyConfigFileName)
|
||||
}
|
||||
|
||||
// LogConfig - Server logging config
|
||||
type LogConfig struct {
|
||||
Level int `json:"level"`
|
||||
GRPCUnaryPayloads bool `json:"grpc_unary_payloads"`
|
||||
GRPCStreamPayloads bool `json:"grpc_stream_payloads"`
|
||||
TLSKeyLogger bool `json:"tls_key_logger"`
|
||||
Level int `json:"level" yaml:"level"`
|
||||
GRPCUnaryPayloads bool `json:"grpc_unary_payloads" yaml:"grpc_unary_payloads"`
|
||||
GRPCStreamPayloads bool `json:"grpc_stream_payloads" yaml:"grpc_stream_payloads"`
|
||||
TLSKeyLogger bool `json:"tls_key_logger" yaml:"tls_key_logger"`
|
||||
}
|
||||
|
||||
// DaemonConfig - Configure daemon mode
|
||||
type DaemonConfig struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Tailscale bool `json:"tailscale"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port int `json:"port" yaml:"port"`
|
||||
Tailscale bool `json:"tailscale" yaml:"tailscale"`
|
||||
}
|
||||
|
||||
// JobConfig - Restart Jobs on Load
|
||||
type JobConfig struct {
|
||||
Multiplayer []*MultiplayerJobConfig `json:"multiplayer"`
|
||||
MTLS []*MTLSJobConfig `json:"mtls,omitempty"`
|
||||
WG []*WGJobConfig `json:"wg,omitempty"`
|
||||
DNS []*DNSJobConfig `json:"dns,omitempty"`
|
||||
HTTP []*HTTPJobConfig `json:"http,omitempty"`
|
||||
Multiplayer []*MultiplayerJobConfig `json:"multiplayer" yaml:"multiplayer"`
|
||||
MTLS []*MTLSJobConfig `json:"mtls,omitempty" yaml:"mtls,omitempty"`
|
||||
WG []*WGJobConfig `json:"wg,omitempty" yaml:"wg,omitempty"`
|
||||
DNS []*DNSJobConfig `json:"dns,omitempty" yaml:"dns,omitempty"`
|
||||
HTTP []*HTTPJobConfig `json:"http,omitempty" yaml:"http,omitempty"`
|
||||
}
|
||||
|
||||
type MultiplayerJobConfig struct {
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
JobID string `json:"job_id"`
|
||||
Tailscale bool `json:"tailscale"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
JobID string `json:"job_id" yaml:"job_id"`
|
||||
Tailscale bool `json:"tailscale" yaml:"tailscale"`
|
||||
}
|
||||
|
||||
// MTLSJobConfig - Per-type job configs
|
||||
type MTLSJobConfig struct {
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
JobID string `json:"job_id"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
JobID string `json:"job_id" yaml:"job_id"`
|
||||
}
|
||||
|
||||
// WGJobConfig - Per-type job configs
|
||||
type WGJobConfig struct {
|
||||
Port uint16 `json:"port"`
|
||||
NPort uint16 `json:"nport"`
|
||||
KeyPort uint16 `json:"key_port"`
|
||||
JobID string `json:"job_id"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
NPort uint16 `json:"nport" yaml:"nport"`
|
||||
KeyPort uint16 `json:"key_port" yaml:"key_port"`
|
||||
JobID string `json:"job_id" yaml:"job_id"`
|
||||
}
|
||||
|
||||
// DNSJobConfig - Persistent DNS job config
|
||||
type DNSJobConfig struct {
|
||||
Domains []string `json:"domains"`
|
||||
Canaries bool `json:"canaries"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
JobID string `json:"job_id"`
|
||||
EnforceOTP bool `json:"enforce_otp"`
|
||||
Domains []string `json:"domains" yaml:"domains"`
|
||||
Canaries bool `json:"canaries" yaml:"canaries"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
JobID string `json:"job_id" yaml:"job_id"`
|
||||
EnforceOTP bool `json:"enforce_otp" yaml:"enforce_otp"`
|
||||
}
|
||||
|
||||
// HTTPJobConfig - Persistent HTTP job config
|
||||
type HTTPJobConfig struct {
|
||||
Domain string `json:"domain"`
|
||||
Host string `json:"host"`
|
||||
Port uint16 `json:"port"`
|
||||
Secure bool `json:"secure"`
|
||||
Website string `json:"website"`
|
||||
Cert []byte `json:"cert"`
|
||||
Key []byte `json:"key"`
|
||||
ACME bool `json:"acme"`
|
||||
JobID string `json:"job_id"`
|
||||
EnforceOTP bool `json:"enforce_otp"`
|
||||
LongPollTimeout int64 `json:"long_poll_timeout"`
|
||||
LongPollJitter int64 `json:"long_poll_jitter"`
|
||||
RandomizeJARM bool `json:"randomize_jarm"`
|
||||
Domain string `json:"domain" yaml:"domain"`
|
||||
Host string `json:"host" yaml:"host"`
|
||||
Port uint16 `json:"port" yaml:"port"`
|
||||
Secure bool `json:"secure" yaml:"secure"`
|
||||
Website string `json:"website" yaml:"website"`
|
||||
Cert []byte `json:"cert" yaml:"cert"`
|
||||
Key []byte `json:"key" yaml:"key"`
|
||||
ACME bool `json:"acme" yaml:"acme"`
|
||||
JobID string `json:"job_id" yaml:"job_id"`
|
||||
EnforceOTP bool `json:"enforce_otp" yaml:"enforce_otp"`
|
||||
LongPollTimeout int64 `json:"long_poll_timeout" yaml:"long_poll_timeout"`
|
||||
LongPollJitter int64 `json:"long_poll_jitter" yaml:"long_poll_jitter"`
|
||||
RandomizeJARM bool `json:"randomize_jarm" yaml:"randomize_jarm"`
|
||||
}
|
||||
|
||||
// WatchTowerConfig - Watch Tower job config
|
||||
type WatchTowerConfig struct {
|
||||
VTApiKey string `json:"vt_api_key"`
|
||||
XForceApiKey string `json:"xforce_api_key"`
|
||||
XForceApiPassword string `json:"xforce_api_password"`
|
||||
VTApiKey string `json:"vt_api_key" yaml:"vt_api_key"`
|
||||
XForceApiKey string `json:"xforce_api_key" yaml:"xforce_api_key"`
|
||||
XForceApiPassword string `json:"xforce_api_password" yaml:"xforce_api_password"`
|
||||
}
|
||||
|
||||
// http server defaults for anonymous requests
|
||||
type HttpDefaultHeader struct {
|
||||
Method string `json:"method" yaml:"method"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Value string `json:"value" yaml:"value"`
|
||||
Probability int32 `json:"probability" yaml:"probability"`
|
||||
}
|
||||
|
||||
type httpDefaultHeaderLegacy struct {
|
||||
Method string `json:"method" yaml:"method"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Value string `json:"value" yaml:"value"`
|
||||
Probability int32 `json:"probability" yaml:"probability"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
HttpC2ServerConfigID *string `json:"httpc2serverconfigid" yaml:"httpc2serverconfigid"`
|
||||
HttpC2ImplantConfigID *string `json:"httpc2implantconfigid" yaml:"httpc2implantconfigid"`
|
||||
}
|
||||
|
||||
func (h *HttpDefaultHeader) UnmarshalJSON(data []byte) error {
|
||||
var raw httpDefaultHeaderLegacy
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
h.Method = raw.Method
|
||||
h.Name = raw.Name
|
||||
h.Value = raw.Value
|
||||
h.Probability = raw.Probability
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *HttpDefaultHeader) UnmarshalYAML(node *yaml.Node) error {
|
||||
var raw httpDefaultHeaderLegacy
|
||||
if err := node.Decode(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
h.Method = raw.Method
|
||||
h.Name = raw.Name
|
||||
h.Value = raw.Value
|
||||
h.Probability = raw.Probability
|
||||
return nil
|
||||
}
|
||||
|
||||
type HttpDefaultConfig struct {
|
||||
Headers []models.HttpC2Header `json:"headers"`
|
||||
Headers []HttpDefaultHeader `json:"headers" yaml:"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" yaml:"daemon_mode"`
|
||||
DaemonConfig *DaemonConfig `json:"daemon" yaml:"daemon"`
|
||||
Logs *LogConfig `json:"logs" yaml:"logs"`
|
||||
Watchtower *WatchTowerConfig `json:"watch_tower" yaml:"watch_tower"`
|
||||
GoProxy string `json:"go_proxy" yaml:"go_proxy"`
|
||||
HTTPDefaults *HttpDefaultConfig `json:"http_default" yaml:"http_default"`
|
||||
DonutBypass int `json:"donut_bypass" yaml:"donut_bypass"` // 1=skip, 2=abort on fail, 3=continue on fail.
|
||||
|
||||
// 'GOOS/GOARCH' -> CC path
|
||||
CC map[string]string `json:"cc"`
|
||||
CXX map[string]string `json:"cxx"`
|
||||
CC map[string]string `json:"cc" yaml:"cc"`
|
||||
CXX map[string]string `json:"cxx" yaml:"cxx"`
|
||||
}
|
||||
|
||||
// Save - Save config file to disk
|
||||
@@ -156,7 +203,7 @@ func (c *ServerConfig) Save() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
data, err := json.MarshalIndent(c, "", " ")
|
||||
data, err := yaml.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -171,18 +218,33 @@ func (c *ServerConfig) Save() error {
|
||||
// GetServerConfig - Get config value
|
||||
func GetServerConfig() *ServerConfig {
|
||||
configPath := GetServerConfigPath()
|
||||
legacyPath := getServerLegacyConfigPath()
|
||||
config := getDefaultServerConfig()
|
||||
migratedLegacy := false
|
||||
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
serverConfigLog.Errorf("Failed to read config file %s", err)
|
||||
return config
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
err = yaml.Unmarshal(data, config)
|
||||
if err != nil {
|
||||
serverConfigLog.Errorf("Failed to parse config file %s", err)
|
||||
return config
|
||||
}
|
||||
} else if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
data, err := os.ReadFile(legacyPath)
|
||||
if err != nil {
|
||||
serverConfigLog.Errorf("Failed to read legacy config file %s", err)
|
||||
return config
|
||||
}
|
||||
err = json.Unmarshal(data, config)
|
||||
if err != nil {
|
||||
serverConfigLog.Errorf("Failed to parse legacy config file %s", err)
|
||||
return config
|
||||
}
|
||||
migratedLegacy = true
|
||||
serverConfigLog.Infof("Migrating legacy config %s to %s", legacyPath, configPath)
|
||||
} else {
|
||||
serverConfigLog.Warnf("Config file does not exist, using defaults")
|
||||
}
|
||||
@@ -202,6 +264,12 @@ func GetServerConfig() *ServerConfig {
|
||||
err := config.Save() // This updates the config with any missing fields
|
||||
if err != nil {
|
||||
serverConfigLog.Errorf("Failed to save default config %s", err)
|
||||
return config
|
||||
}
|
||||
if migratedLegacy {
|
||||
if err := renameLegacyConfig(legacyPath); err != nil {
|
||||
serverConfigLog.Errorf("Failed to rename legacy config %s", err)
|
||||
}
|
||||
}
|
||||
return config
|
||||
}
|
||||
@@ -219,8 +287,8 @@ func getDefaultServerConfig() *ServerConfig {
|
||||
GRPCStreamPayloads: false,
|
||||
},
|
||||
HTTPDefaults: &HttpDefaultConfig{
|
||||
Headers: []models.HttpC2Header{
|
||||
models.HttpC2Header{
|
||||
Headers: []HttpDefaultHeader{
|
||||
{
|
||||
Method: "GET",
|
||||
Name: "Cache-Control",
|
||||
Value: "no-store, no-cache, must-revalidate",
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package configs
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestServerConfigParsesYAML(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configPath := GetServerConfigPath()
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
|
||||
data := []byte(`daemon_mode: true
|
||||
daemon:
|
||||
host: "127.0.0.1"
|
||||
port: 4444
|
||||
tailscale: true
|
||||
logs:
|
||||
level: 5
|
||||
grpc_unary_payloads: true
|
||||
grpc_stream_payloads: true
|
||||
tls_key_logger: true
|
||||
watch_tower:
|
||||
vt_api_key: "vt"
|
||||
xforce_api_key: "xforce"
|
||||
xforce_api_password: "secret"
|
||||
go_proxy: "https://proxy.example"
|
||||
http_default:
|
||||
headers:
|
||||
- method: "POST"
|
||||
name: "X-Test"
|
||||
value: "abc"
|
||||
probability: 50
|
||||
donut_bypass: 2
|
||||
cc:
|
||||
linux/amd64: "/usr/bin/cc"
|
||||
cxx:
|
||||
linux/amd64: "/usr/bin/c++"
|
||||
`)
|
||||
if err := os.WriteFile(configPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write yaml config: %v", err)
|
||||
}
|
||||
|
||||
config := GetServerConfig()
|
||||
if !config.DaemonMode {
|
||||
t.Fatalf("expected daemon_mode true")
|
||||
}
|
||||
if config.DaemonConfig == nil || config.DaemonConfig.Port != 4444 {
|
||||
t.Fatalf("expected daemon port %d, got %v", 4444, config.DaemonConfig)
|
||||
}
|
||||
if config.Logs == nil || config.Logs.Level != 5 {
|
||||
t.Fatalf("expected logs level %d, got %v", 5, config.Logs)
|
||||
}
|
||||
if config.Logs == nil || !config.Logs.TLSKeyLogger {
|
||||
t.Fatalf("expected tls_key_logger true")
|
||||
}
|
||||
if config.Watchtower == nil || config.Watchtower.VTApiKey != "vt" {
|
||||
t.Fatalf("expected watch_tower vt_api_key %q, got %v", "vt", config.Watchtower)
|
||||
}
|
||||
if config.GoProxy != "https://proxy.example" {
|
||||
t.Fatalf("expected go_proxy %q, got %q", "https://proxy.example", config.GoProxy)
|
||||
}
|
||||
if config.HTTPDefaults == nil || len(config.HTTPDefaults.Headers) != 1 {
|
||||
t.Fatalf("expected 1 http default header, got %v", config.HTTPDefaults)
|
||||
}
|
||||
header := config.HTTPDefaults.Headers[0]
|
||||
if header.Method != "POST" || header.Name != "X-Test" || header.Value != "abc" || header.Probability != 50 {
|
||||
t.Fatalf("unexpected header values: %#v", header)
|
||||
}
|
||||
if config.DonutBypass != 2 {
|
||||
t.Fatalf("expected donut_bypass %d, got %d", 2, config.DonutBypass)
|
||||
}
|
||||
if config.CC["linux/amd64"] != "/usr/bin/cc" {
|
||||
t.Fatalf("expected cc override %q, got %q", "/usr/bin/cc", config.CC["linux/amd64"])
|
||||
}
|
||||
if config.CXX["linux/amd64"] != "/usr/bin/c++" {
|
||||
t.Fatalf("expected cxx override %q, got %q", "/usr/bin/c++", config.CXX["linux/amd64"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerConfigWritesDefault(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
config := GetServerConfig()
|
||||
if config.DaemonConfig == nil {
|
||||
t.Fatalf("expected default daemon config")
|
||||
}
|
||||
if _, err := os.Stat(GetServerConfigPath()); err != nil {
|
||||
t.Fatalf("expected default config file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerConfigMigratesLegacyJSON(t *testing.T) {
|
||||
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
|
||||
|
||||
configDir := filepath.Dir(GetServerConfigPath())
|
||||
if err := os.MkdirAll(configDir, 0700); err != nil {
|
||||
t.Fatalf("failed to create config dir: %v", err)
|
||||
}
|
||||
legacyPath := filepath.Join(configDir, serverLegacyConfigFileName)
|
||||
|
||||
type legacyHeader struct {
|
||||
ID string `json:"id"`
|
||||
HttpC2ServerConfigID *string `json:"httpc2serverconfigid"`
|
||||
HttpC2ImplantConfigID *string `json:"httpc2implantconfigid"`
|
||||
Method string `json:"method"`
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Probability int32 `json:"probability"`
|
||||
}
|
||||
type legacyHTTPDefaults struct {
|
||||
Headers []legacyHeader `json:"headers"`
|
||||
}
|
||||
type legacyServerConfig 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 *legacyHTTPDefaults `json:"http_default"`
|
||||
DonutBypass int `json:"donut_bypass"`
|
||||
CC map[string]string `json:"cc"`
|
||||
CXX map[string]string `json:"cxx"`
|
||||
}
|
||||
legacy := &legacyServerConfig{
|
||||
DaemonMode: true,
|
||||
DaemonConfig: &DaemonConfig{
|
||||
Host: "127.0.0.1",
|
||||
Port: 31338,
|
||||
Tailscale: false,
|
||||
},
|
||||
Logs: &LogConfig{
|
||||
Level: 4,
|
||||
GRPCUnaryPayloads: true,
|
||||
GRPCStreamPayloads: true,
|
||||
TLSKeyLogger: true,
|
||||
},
|
||||
Watchtower: &WatchTowerConfig{
|
||||
VTApiKey: "vt-legacy",
|
||||
XForceApiKey: "xforce-legacy",
|
||||
XForceApiPassword: "secret",
|
||||
},
|
||||
GoProxy: "https://proxy.legacy",
|
||||
HTTPDefaults: &legacyHTTPDefaults{
|
||||
Headers: []legacyHeader{
|
||||
{
|
||||
ID: "00000000-0000-0000-0000-000000000000",
|
||||
Method: "GET",
|
||||
Name: "Cache-Control",
|
||||
Value: "no-cache",
|
||||
Probability: 42,
|
||||
},
|
||||
},
|
||||
},
|
||||
DonutBypass: 2,
|
||||
CC: map[string]string{"linux/amd64": "/usr/bin/cc"},
|
||||
CXX: map[string]string{"linux/amd64": "/usr/bin/c++"},
|
||||
}
|
||||
data, err := json.MarshalIndent(legacy, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal legacy config: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(legacyPath, data, 0600); err != nil {
|
||||
t.Fatalf("failed to write legacy config: %v", err)
|
||||
}
|
||||
|
||||
config := GetServerConfig()
|
||||
if !config.DaemonMode || config.DaemonConfig == nil || config.DaemonConfig.Port != 31338 {
|
||||
t.Fatalf("expected legacy daemon config to load")
|
||||
}
|
||||
if config.Watchtower == nil || config.Watchtower.VTApiKey != "vt-legacy" {
|
||||
t.Fatalf("expected legacy watch_tower to load")
|
||||
}
|
||||
if config.GoProxy != "https://proxy.legacy" {
|
||||
t.Fatalf("expected legacy go_proxy %q, got %q", "https://proxy.legacy", config.GoProxy)
|
||||
}
|
||||
if config.HTTPDefaults == nil || len(config.HTTPDefaults.Headers) != 1 {
|
||||
t.Fatalf("expected legacy http defaults to load")
|
||||
}
|
||||
if _, err := os.Stat(GetServerConfigPath()); err != nil {
|
||||
t.Fatalf("expected migrated yaml config file to exist: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected legacy config to be renamed: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(legacyBackupPath(legacyPath)); err != nil {
|
||||
t.Fatalf("expected legacy backup file to exist: %v", err)
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -789,8 +789,18 @@ func AddContent(pbWebContent *clientpb.WebContent, webContentDir string) (*clien
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
dbWebContent.ContentType = pbWebContent.ContentType
|
||||
dbWebContent.Size = pbWebContent.Size
|
||||
if pbWebContent.ContentType != "" {
|
||||
dbWebContent.ContentType = pbWebContent.ContentType
|
||||
}
|
||||
if pbWebContent.Size != 0 {
|
||||
dbWebContent.Size = pbWebContent.Size
|
||||
}
|
||||
if pbWebContent.OriginalFile != "" {
|
||||
dbWebContent.OriginalFile = pbWebContent.OriginalFile
|
||||
}
|
||||
if pbWebContent.Sha256 != "" {
|
||||
dbWebContent.Sha256 = pbWebContent.Sha256
|
||||
}
|
||||
|
||||
dbModelWebContent := models.WebContentFromProtobuf(dbWebContent)
|
||||
err = Session().Save(&dbModelWebContent).Error
|
||||
|
||||
+20
-14
@@ -67,9 +67,11 @@ type WebContent struct {
|
||||
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
|
||||
WebsiteID uuid.UUID `gorm:"type:uuid;"`
|
||||
|
||||
Path string `gorm:"primaryKey"`
|
||||
Size uint64
|
||||
ContentType string
|
||||
Path string `gorm:"primaryKey"`
|
||||
Size uint64
|
||||
ContentType string
|
||||
OriginalFile string
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
// BeforeCreate - GORM hook to automatically set values
|
||||
@@ -81,12 +83,14 @@ func (wc *WebContent) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
// ToProtobuf - Converts to protobuf object
|
||||
func (wc *WebContent) ToProtobuf(content *[]byte) *clientpb.WebContent {
|
||||
return &clientpb.WebContent{
|
||||
ID: wc.ID.String(),
|
||||
WebsiteID: wc.WebsiteID.String(),
|
||||
Path: wc.Path,
|
||||
Size: uint64(wc.Size),
|
||||
ContentType: wc.ContentType,
|
||||
Content: *content,
|
||||
ID: wc.ID.String(),
|
||||
WebsiteID: wc.WebsiteID.String(),
|
||||
Path: wc.Path,
|
||||
Size: uint64(wc.Size),
|
||||
ContentType: wc.ContentType,
|
||||
OriginalFile: wc.OriginalFile,
|
||||
Sha256: wc.Sha256,
|
||||
Content: *content,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,10 +99,12 @@ func WebContentFromProtobuf(pbWebContent *clientpb.WebContent) WebContent {
|
||||
websiteUUID, _ := uuid.FromString(pbWebContent.WebsiteID)
|
||||
|
||||
return WebContent{
|
||||
ID: siteUUID,
|
||||
WebsiteID: websiteUUID,
|
||||
Path: pbWebContent.Path,
|
||||
Size: pbWebContent.Size,
|
||||
ContentType: pbWebContent.ContentType,
|
||||
ID: siteUUID,
|
||||
WebsiteID: websiteUUID,
|
||||
Path: pbWebContent.Path,
|
||||
Size: pbWebContent.Size,
|
||||
ContentType: pbWebContent.ContentType,
|
||||
OriginalFile: pbWebContent.OriginalFile,
|
||||
Sha256: pbWebContent.Sha256,
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,10 @@ func TestSliverSharedLibWindows(t *testing.T) {
|
||||
// 386
|
||||
multiLibrary(t, "windows", "386", true)
|
||||
multiLibrary(t, "windows", "386", false)
|
||||
|
||||
// Shared Library Shellcode
|
||||
multiWindowsLibraryShellcode(t, true)
|
||||
multiWindowsLibraryShellcode(t, false)
|
||||
}
|
||||
|
||||
func TestSliverExecutableLinux(t *testing.T) {
|
||||
@@ -554,7 +558,8 @@ func multiWindowsLibraryShellcode(t *testing.T, debug bool) {
|
||||
Debug: debug,
|
||||
ObfuscateSymbols: true,
|
||||
Format: clientpb.OutputFormat_SHELLCODE,
|
||||
IsSharedLib: true,
|
||||
IsShellcode: true,
|
||||
IsSharedLib: false,
|
||||
Exports: []string{"FoobarW"},
|
||||
IncludeMTLS: true,
|
||||
IncludeHTTP: true,
|
||||
|
||||
@@ -20,10 +20,13 @@ package rpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/server/sgn"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// ShellcodeEncode - Encode a piece shellcode
|
||||
@@ -35,9 +38,11 @@ func (rpc *Server) ShellcodeEncoder(ctx context.Context, req *clientpb.Shellcode
|
||||
switch req.Encoder {
|
||||
case clientpb.ShellcodeEncoder_SHIKATA_GA_NAI:
|
||||
rpcLog.Infof("[rpc] Shellcode encoder request for: SHIKATA_GA_NAI")
|
||||
rpcLog.Infof("[rpc] Encoding shellcode (%d bytes) for architecture %s with %d iterations and badchars: %v", len(req.Data), req.Architecture, req.Iterations, req.BadChars)
|
||||
resp.Data, err = sgn.EncodeShellcode(req.Data, req.Architecture, int(req.Iterations), req.BadChars)
|
||||
if err != nil {
|
||||
resp.Response.Err = err.Error()
|
||||
rpcLog.Errorf("[rpc] Failed to encode shellcode: %v", err)
|
||||
return nil, status.Error(codes.Internal, fmt.Sprintf("Failed to encode shellcode (%s)", err))
|
||||
}
|
||||
default:
|
||||
resp.Response.Err = "Unknown encoder"
|
||||
|
||||
+8
-5
@@ -56,9 +56,12 @@ type SGNConfig struct {
|
||||
// EncodeShellcode - Encode a shellcode
|
||||
func EncodeShellcode(shellcode []byte, arch string, iterations int, badChars []byte) ([]byte, error) {
|
||||
cfg := SGNConfig{
|
||||
Architecture: arch,
|
||||
Iterations: iterations,
|
||||
BadChars: badChars,
|
||||
Architecture: arch,
|
||||
Iterations: iterations,
|
||||
BadChars: badChars,
|
||||
PlainDecoder: false,
|
||||
Safe: true,
|
||||
MaxObfuscation: 100,
|
||||
}
|
||||
return EncodeShellcodeWithConfig(shellcode, cfg)
|
||||
}
|
||||
@@ -83,10 +86,10 @@ func EncodeShellcodeWithConfig(shellcode []byte, cfg SGNConfig) ([]byte, error)
|
||||
|
||||
needsConstraints := cfg.Asci || len(cfg.BadChars) > 0
|
||||
seed := sgnpkg.GetRandomByte()
|
||||
const maxAttempts = 512
|
||||
const maxAttempts = 64
|
||||
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < maxAttempts; attempt++ {
|
||||
for attempt := range maxAttempts {
|
||||
encoder, err := newEncoderWithConfig(arch, cfg)
|
||||
if err != nil {
|
||||
sgnLog.Errorf("[sgn] EncodeShellcode setup failed: %s", err)
|
||||
|
||||
@@ -19,6 +19,8 @@ package website
|
||||
*/
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -87,14 +89,30 @@ func AddContent(name string, pbWebContent *clientpb.WebContent) error {
|
||||
pbWebContent.WebsiteID = website.ID
|
||||
}
|
||||
|
||||
if pbWebContent.Size == 0 && len(pbWebContent.Content) > 0 {
|
||||
pbWebContent.Size = uint64(len(pbWebContent.Content))
|
||||
}
|
||||
if pbWebContent.OriginalFile == "" {
|
||||
pbWebContent.OriginalFile = filepath.Base(pbWebContent.Path)
|
||||
}
|
||||
|
||||
if len(pbWebContent.Content) > 0 {
|
||||
sha := sha256.Sum256(pbWebContent.Content)
|
||||
pbWebContent.Sha256 = hex.EncodeToString(sha[:])
|
||||
}
|
||||
|
||||
webContent, err := db.AddContent(pbWebContent, webContentDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Write content to disk
|
||||
webContentPath := filepath.Join(webContentDir, webContent.ID)
|
||||
return os.WriteFile(webContentPath, pbWebContent.Content, 0600)
|
||||
// Write content to disk when provided (metadata-only updates skip disk writes)
|
||||
if len(pbWebContent.Content) > 0 {
|
||||
webContentPath := filepath.Join(webContentDir, webContent.ID)
|
||||
return os.WriteFile(webContentPath, pbWebContent.Content, 0600)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveContent - Remove website content for a path
|
||||
|
||||
+5
-1
@@ -111,8 +111,12 @@ func (t TokenSlice) WordbreakPrefix() string {
|
||||
break
|
||||
}
|
||||
|
||||
if token.Type == WORDBREAK_TOKEN {
|
||||
if !found && token.Type == WORDBREAK_TOKEN {
|
||||
found = true
|
||||
if token.Value == "@" {
|
||||
// Seems although `@` is a wordbreak, it weirdly is not part of the prefix.
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ package shlex
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
const BASH_WORDBREAKS = " \t\r\n" + `"'><=;|&(:`
|
||||
const BASH_WORDBREAKS = " \t\r\n" + `"'@><=;|&(:`
|
||||
|
||||
type WordbreakType int
|
||||
|
||||
|
||||
+27
-3
@@ -437,6 +437,15 @@ func (a Action) Timeout(d time.Duration, alternative Action) Action {
|
||||
})
|
||||
}
|
||||
|
||||
// Unique ensures the Action only contains unique values.
|
||||
func (a Action) Unique() Action {
|
||||
return ActionCallback(func(c Context) Action {
|
||||
invoked := a.Invoke(c)
|
||||
invoked.action.rawValues = invoked.action.rawValues.Unique()
|
||||
return invoked.ToA()
|
||||
})
|
||||
}
|
||||
|
||||
// UniqueList wraps the Action in an ActionMultiParts with given divider.
|
||||
func (a Action) UniqueList(divider string) Action {
|
||||
return ActionMultiParts(divider, func(c Context) Action {
|
||||
@@ -513,9 +522,14 @@ func (a Action) UidF(f func(s string, uc uid.Context) (*url.URL, error)) Action
|
||||
}
|
||||
|
||||
// Usage sets the usage.
|
||||
func (a Action) Usage(usage string, args ...interface{}) Action {
|
||||
func (a Action) Usage(usage string, args ...any) Action {
|
||||
return a.UsageF(func() string {
|
||||
return fmt.Sprintf(usage, args...)
|
||||
if len(args) == 0 {
|
||||
return usage
|
||||
}
|
||||
return func(u string, a ...any) string { // avoids failed inferred printf check: non-constant format string
|
||||
return fmt.Sprintf(u, a...)
|
||||
}(usage, args...)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -548,6 +562,9 @@ func (a Action) Query(scheme, host, path string, opts ...string) Action {
|
||||
values.Set(opts[i], opts[i+1])
|
||||
}
|
||||
}
|
||||
if c.Value != "" {
|
||||
values.Set("C_VALUE", c.Value)
|
||||
}
|
||||
query.RawQuery = values.Encode()
|
||||
}
|
||||
a.meta.Queries.Add(query.String())
|
||||
@@ -558,10 +575,17 @@ func (a Action) Query(scheme, host, path string, opts ...string) Action {
|
||||
// QueryF TODO experimental
|
||||
func (a Action) QueryF(f func(s string, uc uid.Context) (*url.URL, error)) Action { // TODO remove the string
|
||||
return ActionCallback(func(c Context) Action {
|
||||
query, err := f(c.Value, c)
|
||||
query, err := f("", c) // TODO string parameter from uid isn't really needed here
|
||||
if err != nil {
|
||||
return ActionMessage(err.Error())
|
||||
}
|
||||
|
||||
if c.Value != "" {
|
||||
values := query.Query()
|
||||
values.Set("C_VALUE", c.Value)
|
||||
query.RawQuery = values.Encode()
|
||||
}
|
||||
|
||||
a.meta.Queries.Add(query.String())
|
||||
return a
|
||||
})
|
||||
|
||||
+3
-4
@@ -2,6 +2,7 @@
|
||||
package carapace
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"os"
|
||||
|
||||
"github.com/carapace-sh/carapace/internal/shell"
|
||||
@@ -79,9 +80,7 @@ func (c Carapace) FlagCompletion(actions ActionMap) {
|
||||
if e.flag == nil {
|
||||
e.flag = actions
|
||||
} else {
|
||||
for name, action := range actions {
|
||||
e.flag[name] = action
|
||||
}
|
||||
maps.Copy(e.flag, actions)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,7 +125,7 @@ func IsCallback() bool {
|
||||
// func TestCarapace(t *testing.T) {
|
||||
// carapace.Test(t)
|
||||
// }
|
||||
func Test(t interface{ Error(args ...interface{}) }) {
|
||||
func Test(t interface{ Error(args ...any) }) {
|
||||
for _, e := range storage.check() {
|
||||
t.Error(e)
|
||||
}
|
||||
|
||||
+20
-32
@@ -8,6 +8,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/carapace-sh/carapace/internal/common"
|
||||
@@ -135,6 +136,10 @@ func ActionExecute(cmd *cobra.Command) Action {
|
||||
// ActionDirectories completes directories.
|
||||
func ActionDirectories() Action {
|
||||
return ActionCallback(func(c Context) Action {
|
||||
cDir, err := c.Abs(c.Dir)
|
||||
if err != nil {
|
||||
return ActionMessage(err.Error())
|
||||
}
|
||||
return actionPath([]string{""}, true).
|
||||
MultiParts("/").
|
||||
StyleF(style.ForPath).
|
||||
@@ -145,19 +150,17 @@ func ActionDirectories() Action {
|
||||
}
|
||||
return url.Parse("file://" + uid.PathEscape(abs))
|
||||
}).
|
||||
QueryF(func(s string, uc uid.Context) (*url.URL, error) {
|
||||
abs, err := c.Abs(c.Dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return url.Parse(fmt.Sprintf("file://%v?directories=true", uid.PathEscape(abs)))
|
||||
})
|
||||
Query("file", "directories", "", "C_DIR", cDir)
|
||||
}).Tag("directories")
|
||||
}
|
||||
|
||||
// ActionFiles completes files with optional suffix filtering.
|
||||
func ActionFiles(suffix ...string) Action {
|
||||
return ActionCallback(func(c Context) Action {
|
||||
cDir, err := c.Abs(c.Dir)
|
||||
if err != nil {
|
||||
return ActionMessage(err.Error())
|
||||
}
|
||||
return actionPath(suffix, false).
|
||||
MultiParts("/").
|
||||
StyleF(style.ForPath).
|
||||
@@ -168,23 +171,9 @@ func ActionFiles(suffix ...string) Action {
|
||||
}
|
||||
return url.Parse("file://" + uid.PathEscape(abs))
|
||||
}).
|
||||
QueryF(func(s string, uc uid.Context) (*url.URL, error) {
|
||||
abs, err := c.Abs(c.Dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := &url.URL{
|
||||
Scheme: "file",
|
||||
Path: abs,
|
||||
}
|
||||
if len(suffix) > 0 {
|
||||
values := query.Query()
|
||||
values.Set("suffix", strings.Join(suffix, ","))
|
||||
query.RawQuery = values.Encode()
|
||||
}
|
||||
return query, nil
|
||||
})
|
||||
// Query("file", "", c.Dir, "suffix", strings.Join(suffix, ","))
|
||||
Query("file", "files", "",
|
||||
"C_DIR", cDir,
|
||||
"suffix", strings.Join(suffix, ","))
|
||||
}).Tag("files")
|
||||
}
|
||||
|
||||
@@ -247,7 +236,7 @@ func ActionStyledValuesDescribed(values ...string) Action {
|
||||
}
|
||||
|
||||
// ActionMessage displays a help messages in places where no completions can be generated.
|
||||
func ActionMessage(msg string, args ...interface{}) Action {
|
||||
func ActionMessage(msg string, args ...any) Action {
|
||||
return ActionCallback(func(c Context) Action {
|
||||
if len(args) > 0 {
|
||||
msg = fmt.Sprintf(msg, args...)
|
||||
@@ -477,14 +466,15 @@ func ActionExecutables(dirs ...string) Action {
|
||||
}
|
||||
manDescriptions := man.Descriptions(c.Value) // TODO allow additional descriptions to be registered somewhere for carapace-bin (key, value,...)
|
||||
batch := Batch()
|
||||
for i := len(dirs) - 1; i >= 0; i-- {
|
||||
batch = append(batch, actionDirectoryExecutables(dirs[i], c.Value, manDescriptions))
|
||||
for _, dir := range dirs {
|
||||
batch = append(batch, actionDirectoryExecutables(dir, c.Value, manDescriptions))
|
||||
}
|
||||
return batch.ToA().
|
||||
UidF(func(s string, uc uid.Context) (*url.URL, error) {
|
||||
return &url.URL{Scheme: "cmd", Host: uid.PathEscape(s)}, nil
|
||||
}).
|
||||
Query("cmd", "", "", "directories", strings.Join(dirs, ", "))
|
||||
Query("cmd", "", "", "directories", strings.Join(dirs, ", ")).
|
||||
Unique()
|
||||
}).Tag("executables")
|
||||
}
|
||||
|
||||
@@ -553,10 +543,8 @@ func ActionCommands(cmd *cobra.Command) Action {
|
||||
return ActionCallback(func(c Context) Action {
|
||||
if len(c.Args) > 0 {
|
||||
for _, subCommand := range cmd.Commands() {
|
||||
for _, name := range append(subCommand.Aliases, subCommand.Name()) {
|
||||
if name == c.Args[0] { // cmd.Find is too lenient
|
||||
return ActionCommands(subCommand).Shift(1)
|
||||
}
|
||||
if slices.Contains(append(subCommand.Aliases, subCommand.Name()), c.Args[0]) { // cmd.Find is too lenient
|
||||
return ActionCommands(subCommand).Shift(1)
|
||||
}
|
||||
}
|
||||
return ActionMessage("unknown subcommand %#v for %#v", c.Args[0], cmd.Name())
|
||||
|
||||
+26
@@ -1,6 +1,8 @@
|
||||
package carapace
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/carapace-sh/carapace/internal/common"
|
||||
"github.com/carapace-sh/carapace/pkg/style"
|
||||
)
|
||||
@@ -42,3 +44,27 @@ func Diff(original, new Action) Action {
|
||||
return mergedBatch.ToA()
|
||||
})
|
||||
}
|
||||
|
||||
// TODO experimental - needs different signature
|
||||
// TODO return patch format
|
||||
func DiffPatch(original, new Action, c Context) []string {
|
||||
diff := Diff(original, new).Invoke(c)
|
||||
patch := make([]string, 0)
|
||||
for _, v := range diff.action.rawValues {
|
||||
s := v.Value
|
||||
if v.Description != "" {
|
||||
s += fmt.Sprintf(" (%v)", v.Description)
|
||||
}
|
||||
|
||||
switch v.Style {
|
||||
case style.Red:
|
||||
s = "- " + s
|
||||
case style.Green:
|
||||
s = "+ " + s
|
||||
default:
|
||||
s = " " + s
|
||||
}
|
||||
patch = append(patch, s)
|
||||
}
|
||||
return patch
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
go 1.19
|
||||
go 1.24
|
||||
|
||||
use (
|
||||
.
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
github.com/carapace-sh/carapace-shlex v1.0.0/go.mod h1:lJ4ZsdxytE0wHJ8Ta9S7Qq0XpjgjU0mdfCqiI2FHx7M=
|
||||
github.com/carapace-sh/carapace-pflag v1.1.0 h1:uB33wch8ADjP878NadQnbZ5vyROcj/Ac+wUQKMcIrQM=
|
||||
github.com/carapace-sh/carapace-pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
+1
-1
@@ -20,7 +20,7 @@ func (m Mock) WorkDir() string {
|
||||
|
||||
type t interface {
|
||||
Name() string
|
||||
Fatal(...interface{})
|
||||
Fatal(...any)
|
||||
}
|
||||
|
||||
func NewMock(t t) *Mock {
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
// FromInvokedAction provides access to RawValues within an InvokedAction.
|
||||
// It is intended for testing purposes in Sandbox (circumventing dependency issues).
|
||||
var FromInvokedAction func(action interface{}) (Meta, RawValues)
|
||||
var FromInvokedAction func(action any) (Meta, RawValues)
|
||||
|
||||
// RawValue represents a completion candidate.
|
||||
type RawValue struct {
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/carapace-sh/carapace/pkg/xdg"
|
||||
)
|
||||
|
||||
type configMap map[string]interface{}
|
||||
type configMap map[string]any
|
||||
|
||||
func (c configMap) Keys() []string {
|
||||
keys := make([]string, 0)
|
||||
@@ -52,7 +52,7 @@ var config = struct {
|
||||
Styles: make(configMap),
|
||||
}
|
||||
|
||||
func RegisterStyle(name string, i interface{}) {
|
||||
func RegisterStyle(name string, i any) {
|
||||
config.Styles[name] = i
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -81,7 +81,11 @@ func CoverDir() string {
|
||||
return os.Getenv(CARAPACE_COVERDIR) // custom env for GOCOVERDIR so that it works together with `-coverprofile`
|
||||
}
|
||||
|
||||
func isGoRun() bool { return strings.HasPrefix(os.Args[0], os.TempDir()+"/go-build") }
|
||||
func isGoRun() bool {
|
||||
// go 1.24+: /home/rsteube/.cache/go-build/a7/a7883331b606dc3250005f1abdf4d17dea05c9eccf4ece0df5518311a118d211-d/example
|
||||
// go 1.23-: /tmp/go-build1035720725/b001/exe/example
|
||||
return strings.Contains(os.Args[0], "/go-build")
|
||||
}
|
||||
|
||||
func Match() string { // see match.Match
|
||||
return os.Getenv(CARAPACE_MATCH)
|
||||
|
||||
+2
-2
@@ -20,8 +20,8 @@ func Descriptions(s string) (descriptions map[string]string) {
|
||||
}
|
||||
|
||||
r := regexp.MustCompile(`^(?P<name>[^ ]+) [^-]+- (?P<description>.*)$`)
|
||||
lines := strings.Split(string(output), "\n")
|
||||
for _, line := range lines {
|
||||
lines := strings.SplitSeq(string(output), "\n")
|
||||
for line := range lines {
|
||||
if matches := r.FindStringSubmatch(line); len(matches) > 2 {
|
||||
descriptions[matches[1]] = matches[2]
|
||||
}
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ func (f FlagSet) IsShorthandSeries(arg string) bool {
|
||||
func (f FlagSet) IsMutuallyExclusive(flag *pflag.Flag) bool {
|
||||
if groups, ok := flag.Annotations["cobra_annotation_mutually_exclusive"]; ok {
|
||||
for _, group := range groups {
|
||||
for _, name := range strings.Split(group, " ") {
|
||||
for name := range strings.SplitSeq(group, " ") {
|
||||
if other := f.Lookup(name); other != nil && other.Changed && other != flag {
|
||||
return true
|
||||
}
|
||||
|
||||
+9
-9
@@ -11,7 +11,7 @@ import (
|
||||
// Snippet creates the bash completion script.
|
||||
func Snippet(cmd *cobra.Command) string {
|
||||
result := fmt.Sprintf(`#!/bin/bash
|
||||
_%v_completion() {
|
||||
_%[1]v_completion() {
|
||||
export COMP_LINE
|
||||
export COMP_POINT
|
||||
export COMP_TYPE
|
||||
@@ -19,12 +19,12 @@ _%v_completion() {
|
||||
|
||||
local nospace data compline="${COMP_LINE:0:${COMP_POINT}}"
|
||||
|
||||
if echo ${compline}"''" | xargs echo 2>/dev/null > /dev/null; then
|
||||
data=$(echo ${compline}"''" | xargs %v _carapace bash)
|
||||
elif echo ${compline} | sed "s/\$/'/" | xargs echo 2>/dev/null > /dev/null; then
|
||||
data=$(echo ${compline} | sed "s/\$/'/" | xargs %v _carapace bash)
|
||||
else
|
||||
data=$(echo ${compline} | sed 's/$/"/' | xargs %v _carapace bash)
|
||||
data=$(echo "${compline}''" | xargs %[2]v _carapace bash 2>/dev/null)
|
||||
if [ $? -eq 1 ]; then
|
||||
data=$(echo "${compline}'" | xargs %[2]v _carapace bash 2>/dev/null)
|
||||
if [ $? -eq 1 ]; then
|
||||
data=$(echo "${compline}\"" | xargs %[2]v _carapace bash 2>/dev/null)
|
||||
fi
|
||||
fi
|
||||
|
||||
IFS=$'\001' read -r -d '' nospace data <<<"${data}"
|
||||
@@ -36,8 +36,8 @@ _%v_completion() {
|
||||
[[ "${COMPREPLY[*]}" == "" ]] && COMPREPLY=() # fix for mapfile creating a non-empty array from empty command output
|
||||
}
|
||||
|
||||
complete -o noquote -F _%v_completion %v
|
||||
`, cmd.Name(), uid.Executable(), uid.Executable(), uid.Executable(), cmd.Name(), cmd.Name())
|
||||
complete -o noquote -F _%[1]v_completion %[1]v
|
||||
`, cmd.Name(), uid.Executable())
|
||||
|
||||
return result
|
||||
}
|
||||
+32
-19
@@ -8,28 +8,41 @@ import (
|
||||
)
|
||||
|
||||
func Snippet(cmd *cobra.Command) string {
|
||||
result := fmt.Sprintf(`local function %v_completion(word, word_index, line_state, match_builder)
|
||||
local compline = string.sub(line_state:getline(), 1, line_state:getcursor())
|
||||
result := fmt.Sprintf(`local function %[1]s_completion(word, word_index, line_state, match_builder)
|
||||
match_builder:setnosort()
|
||||
match_builder:setvolatile()
|
||||
os.setenv('CARAPACE_COMPLINE', line_state:getline():sub(1, line_state:getcursor()))
|
||||
|
||||
local output = io.popen("env CARAPACE_COMPLINE=" .. string.format("%%q", compline) .. " %v _carapace cmd-clink \"\""):read("*a")
|
||||
for line in string.gmatch(output, '[^\r\n]+') do
|
||||
local matches = {}
|
||||
for m in string.gmatch(line, '[^\t]+') do
|
||||
table.insert(matches, m)
|
||||
local file, pclose = io.popenyield('%[2]s _carapace cmd-clink %[1]s')
|
||||
|
||||
if not file then
|
||||
return false
|
||||
end
|
||||
match_builder:addmatch({
|
||||
match = matches[1],
|
||||
display = matches[2],
|
||||
description = matches[3],
|
||||
type = "word",
|
||||
appendchar = matches[4],
|
||||
suppressappend = false
|
||||
})
|
||||
end
|
||||
return true
|
||||
|
||||
for line in file:lines() do
|
||||
local matches = string.explode(line, '\t')
|
||||
|
||||
if matches[1] then
|
||||
match_builder:addmatch({
|
||||
match = matches[1],
|
||||
display = matches[2],
|
||||
description = matches[3],
|
||||
type = 'word',
|
||||
appendchar = matches[4] or ''
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
if pclose then
|
||||
pclose()
|
||||
else
|
||||
file:close()
|
||||
end
|
||||
|
||||
return not match_builder:isempty()
|
||||
end
|
||||
|
||||
clink.argmatcher("%v"):addarg({nowordbreakchars="'‵+;,", %v_completion}):loop(1)
|
||||
`, cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name())
|
||||
clink.argmatcher(50, '%[1]s', '%[1]s.exe'):addarg({nowordbreakchars="'`+"`"+`=+;,", %[1]s_completion}):loop(1)
|
||||
`, cmd.Name(), uid.Executable())
|
||||
return result
|
||||
}
|
||||
+11
-15
@@ -10,23 +10,19 @@ import (
|
||||
|
||||
// Snippet creates the fish completion script.
|
||||
func Snippet(cmd *cobra.Command) string {
|
||||
return fmt.Sprintf(`function _%v_quote_suffix
|
||||
if not commandline -cp | xargs echo 2>/dev/null >/dev/null
|
||||
if commandline -cp | sed 's/$/"/'| xargs echo 2>/dev/null >/dev/null
|
||||
echo '"'
|
||||
else if commandline -cp | sed "s/\$/'/"| xargs echo 2>/dev/null >/dev/null
|
||||
echo "'"
|
||||
return fmt.Sprintf(`function _%[1]v_completion
|
||||
set --local data
|
||||
IFS='' set data (echo (commandline -cp)'' | sed "s/ \$/ ''/" | xargs %[2]v _carapace fish 2>/dev/null)
|
||||
if [ $status -eq 1 ]
|
||||
IFS='' set data (echo (commandline -cp)"'" | sed "s/ \$/ ''/" | xargs %[2]v _carapace fish 2>/dev/null)
|
||||
if [ $status -eq 1 ]
|
||||
IFS='' set data (echo (commandline -cp)'"' | sed "s/ \$/ ''/" | xargs %[2]v _carapace fish 2>/dev/null)
|
||||
end
|
||||
else
|
||||
echo ""
|
||||
end
|
||||
echo $data
|
||||
end
|
||||
|
||||
function _%v_callback
|
||||
commandline -cp | sed "s/\$/"(_%v_quote_suffix)"/" | sed "s/ \$/ ''/" | xargs %v _carapace fish
|
||||
end
|
||||
|
||||
complete -e '%v'
|
||||
complete -c '%v' -f -a '(_%v_callback)' -r
|
||||
`, cmd.Name(), cmd.Name(), cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name(), cmd.Name())
|
||||
complete -e '%[1]v'
|
||||
complete -c '%[1]v' -f -a '(_%[1]v_completion)' -r
|
||||
`, cmd.Name(), uid.Executable())
|
||||
}
|
||||
+1
-1
@@ -36,7 +36,7 @@ func (nd *namedDirectories) Replace(s string) string {
|
||||
|
||||
func init() {
|
||||
if hashDirs := env.Hashdirs(); hashDirs != "" {
|
||||
for _, line := range strings.Split(hashDirs, "\n") {
|
||||
for line := range strings.SplitSeq(hashDirs, "\n") {
|
||||
if splitted := strings.SplitN(line, "=", 2); len(splitted) == 2 {
|
||||
NamedDirectories[splitted[0]] = splitted[1]
|
||||
}
|
||||
|
||||
+12
-11
@@ -11,17 +11,18 @@ import (
|
||||
// Snippet creates the zsh completion script
|
||||
func Snippet(cmd *cobra.Command) string {
|
||||
return fmt.Sprintf(`#compdef %v
|
||||
function _%v_completion {
|
||||
local words=${words[@]:0:$CURRENT}
|
||||
function _%[1]v_completion {
|
||||
local compline=${words[@]:0:$CURRENT}
|
||||
local IFS=$'\n'
|
||||
local lines
|
||||
|
||||
# shellcheck disable=SC2086,SC2154,SC2155
|
||||
if echo ${words}"''" | xargs echo 2>/dev/null > /dev/null; then
|
||||
local lines="$(echo ${words}"''" | CARAPACE_COMPLINE="${words}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh )"
|
||||
elif echo ${words} | sed "s/\$/'/" | xargs echo 2>/dev/null > /dev/null; then
|
||||
local lines="$(echo ${words} | sed "s/\$/'/" | CARAPACE_COMPLINE="${words}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh)"
|
||||
else
|
||||
local lines="$(echo ${words} | sed 's/$/"/' | CARAPACE_COMPLINE="${words}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh)"
|
||||
lines="$(echo "${compline}''" | CARAPACE_COMPLINE="${compline}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %[2]v _carapace zsh 2>/dev/null)"
|
||||
if [ $? -eq 1 ]; then
|
||||
lines="$(echo "${compline}'" | CARAPACE_COMPLINE="${compline}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %[2]v _carapace zsh 2>/dev/null)"
|
||||
if [ $? -eq 1 ]; then
|
||||
lines="$(echo "${compline}\"" | CARAPACE_COMPLINE="${compline}" CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %[2]v _carapace zsh 2>/dev/null)"
|
||||
fi
|
||||
fi
|
||||
|
||||
local zstyle message data
|
||||
@@ -41,7 +42,7 @@ function _%v_completion {
|
||||
[[ ${#valuesArr[@]} -gt 1 ]] && _describe -t "${tag}" "${tag}" displaysArr valuesArr -Q -S ''
|
||||
done <<<"${data}"
|
||||
}
|
||||
compquote '' 2>/dev/null && _%v_completion
|
||||
compdef _%v_completion %v
|
||||
`, cmd.Name(), cmd.Name(), uid.Executable(), uid.Executable(), uid.Executable(), cmd.Name(), cmd.Name(), cmd.Name())
|
||||
compquote '' 2>/dev/null && _%[1]v_completion
|
||||
compdef _%[1]v_completion %[1]v
|
||||
`, cmd.Name(), uid.Executable())
|
||||
}
|
||||
+2
-2
@@ -172,7 +172,7 @@ func (ia InvokedAction) ToMultiPartsA(dividers ...string) Action {
|
||||
})
|
||||
}
|
||||
|
||||
func (ia InvokedAction) Query(q string) InvokedAction {
|
||||
func (ia InvokedAction) QueryS(q string) InvokedAction {
|
||||
ia.action.meta.Queries.Add(q)
|
||||
return ia
|
||||
}
|
||||
@@ -182,7 +182,7 @@ func (ia InvokedAction) value(shell string, value string) string {
|
||||
}
|
||||
|
||||
func init() {
|
||||
common.FromInvokedAction = func(i interface{}) (common.Meta, common.RawValues) {
|
||||
common.FromInvokedAction = func(i any) (common.Meta, common.RawValues) {
|
||||
if invoked, ok := i.(InvokedAction); ok {
|
||||
return invoked.action.meta, invoked.action.rawValues
|
||||
}
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ import (
|
||||
// func init() {
|
||||
// Register("carapace", &Carapace)
|
||||
// }
|
||||
func Register(name string, i interface{}) { config.RegisterStyle(name, i) }
|
||||
func Register(name string, i any) { config.RegisterStyle(name, i) }
|
||||
|
||||
// Set a style
|
||||
//
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ func SGR(s string) string { return Parse(s).SGR() }
|
||||
|
||||
func Parse(s string) ui.Style {
|
||||
stylings := make([]ui.Styling, 0)
|
||||
for _, word := range strings.Split(s, " ") {
|
||||
for word := range strings.SplitSeq(s, " ") {
|
||||
if styling := ui.ParseStyling(word); styling != nil {
|
||||
stylings = append(stylings, styling)
|
||||
}
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ func ConfigDirs() (dirs []string, err error) {
|
||||
|
||||
if v, ok := os.LookupEnv("XDG_CONFIG_DIRS"); ok {
|
||||
xdgDirs := make([]string, 0)
|
||||
for _, dir := range strings.Split(v, string(os.PathSeparator)) {
|
||||
for dir := range strings.SplitSeq(v, string(os.PathSeparator)) {
|
||||
if filepath.IsAbs(dir) {
|
||||
xdgDirs = append(xdgDirs, dir)
|
||||
}
|
||||
|
||||
Generated
Vendored
+8
-11
@@ -76,13 +76,10 @@ func toSubstr(s string, args ...string) string {
|
||||
if pos < 0 {
|
||||
// if pos is negative (counts from the end) add it
|
||||
// to length to get first character offset
|
||||
pos = len(s) + pos
|
||||
|
||||
// if negative offset exceeds the length of the string
|
||||
// start from 0
|
||||
if pos < 0 {
|
||||
pos = 0
|
||||
}
|
||||
pos = max(
|
||||
// if negative offset exceeds the length of the string
|
||||
// start from 0
|
||||
len(s)+pos, 0)
|
||||
}
|
||||
|
||||
if len(args) == 1 {
|
||||
@@ -122,9 +119,9 @@ func replaceAll(s string, args ...string) string {
|
||||
case 0:
|
||||
return s
|
||||
case 1:
|
||||
return strings.Replace(s, args[0], "", -1)
|
||||
return strings.ReplaceAll(s, args[0], "")
|
||||
default:
|
||||
return strings.Replace(s, args[0], args[1], -1)
|
||||
return strings.ReplaceAll(s, args[0], args[1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +156,8 @@ func replaceSuffix(s string, args ...string) string {
|
||||
if len(args) != 2 {
|
||||
return s
|
||||
}
|
||||
if strings.HasSuffix(s, args[0]) {
|
||||
s = strings.TrimSuffix(s, args[0])
|
||||
if before, ok := strings.CutSuffix(s, args[0]); ok {
|
||||
s = before
|
||||
s = s + args[1]
|
||||
}
|
||||
return s
|
||||
|
||||
Generated
Vendored
-4
@@ -235,10 +235,6 @@ func acceptOneHash(r rune, i int) bool {
|
||||
return r == '#' && i == 1
|
||||
}
|
||||
|
||||
func acceptNone(r rune, i int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func acceptNotClosing(r rune, i int) bool {
|
||||
return r != '}'
|
||||
}
|
||||
|
||||
Generated
Vendored
+2
-2
@@ -3,7 +3,7 @@ package envsubst
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/carapace-sh/carapace/third_party/github.com/drone/envsubst/parse"
|
||||
)
|
||||
@@ -38,7 +38,7 @@ func Parse(s string) (t *Template, err error) {
|
||||
// ParseFile creates a new shell format template and parses the template
|
||||
// definition from the named file.
|
||||
func ParseFile(path string) (*Template, error) {
|
||||
b, err := ioutil.ReadFile(path)
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Generated
Vendored
+2
-2
@@ -79,14 +79,14 @@ var featureForName = map[string]feature{
|
||||
// fields are silently ignored.
|
||||
func parseLsColor(s string) *colorist {
|
||||
lc := &colorist{make(map[feature]string), make(map[string]string)}
|
||||
for _, spec := range strings.Split(s, ":") {
|
||||
for spec := range strings.SplitSeq(s, ":") {
|
||||
words := strings.Split(spec, "=")
|
||||
if len(words) != 2 {
|
||||
continue
|
||||
}
|
||||
key, value := words[0], words[1]
|
||||
filterValues := []string{}
|
||||
for _, splitValue := range strings.Split(value, ";") {
|
||||
for splitValue := range strings.SplitSeq(value, ";") {
|
||||
if strings.Count(splitValue, "0") == len(splitValue) {
|
||||
continue
|
||||
}
|
||||
|
||||
Generated
Vendored
+1
-2
@@ -1,11 +1,10 @@
|
||||
//go:build !solaris
|
||||
// +build !solaris
|
||||
|
||||
package lscolors
|
||||
|
||||
import "os"
|
||||
|
||||
func isDoor(info os.FileInfo) bool {
|
||||
func isDoor(_ os.FileInfo) bool {
|
||||
// Doors are only supported on Solaris.
|
||||
return false
|
||||
}
|
||||
Generated
Vendored
-1
@@ -1,5 +1,4 @@
|
||||
//go:build !windows && !plan9
|
||||
// +build !windows,!plan9
|
||||
|
||||
package lscolors
|
||||
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -2,7 +2,7 @@ package lscolors
|
||||
|
||||
import "os"
|
||||
|
||||
func isMultiHardlink(info os.FileInfo) bool {
|
||||
func isMultiHardlink(_ os.FileInfo) bool {
|
||||
// Windows supports hardlinks, but it is not exposed directly. We omit the
|
||||
// implementation for now.
|
||||
// TODO: Maybe implement it?
|
||||
|
||||
Generated
Vendored
+1
-3
@@ -5,8 +5,6 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sgrPrefix = "\033["
|
||||
|
||||
var sgrStyling = map[int]Styling{
|
||||
0: Reset,
|
||||
1: Bold,
|
||||
@@ -73,7 +71,7 @@ func StylingFromSGR(s string) Styling {
|
||||
|
||||
func getSGRCodes(s string) []int {
|
||||
var codes []int
|
||||
for _, part := range strings.Split(s, ";") {
|
||||
for part := range strings.SplitSeq(s, ";") {
|
||||
if part == "" {
|
||||
codes = append(codes, 0)
|
||||
} else {
|
||||
|
||||
Generated
Vendored
+3
-3
@@ -44,8 +44,8 @@ func (s Style) SGR() string {
|
||||
|
||||
// MergeFromOptions merges all recognized values from a map to the current
|
||||
// Style.
|
||||
func (s *Style) MergeFromOptions(options map[string]interface{}) error {
|
||||
assignColor := func(val interface{}, colorField *Color) string {
|
||||
func (s *Style) MergeFromOptions(options map[string]any) error {
|
||||
assignColor := func(val any, colorField *Color) string {
|
||||
if val == "default" {
|
||||
*colorField = nil
|
||||
return ""
|
||||
@@ -58,7 +58,7 @@ func (s *Style) MergeFromOptions(options map[string]interface{}) error {
|
||||
}
|
||||
return "valid color string"
|
||||
}
|
||||
assignBool := func(val interface{}, attrField *bool) string {
|
||||
assignBool := func(val any, attrField *bool) string {
|
||||
if b, ok := val.(bool); ok {
|
||||
*attrField = b
|
||||
} else {
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -144,7 +144,7 @@ func ParseStyling(s string) Styling {
|
||||
return parseOneStyling(s)
|
||||
}
|
||||
var joint jointStyling
|
||||
for _, subs := range strings.Split(s, " ") {
|
||||
for subs := range strings.SplitSeq(s, " ") {
|
||||
parsed := parseOneStyling(subs)
|
||||
if parsed == nil {
|
||||
return nil
|
||||
|
||||
Generated
Vendored
-1
@@ -1,5 +1,4 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package ps
|
||||
|
||||
|
||||
Generated
Vendored
+1
-2
@@ -1,5 +1,4 @@
|
||||
//go:build freebsd
|
||||
// +build freebsd
|
||||
|
||||
package ps
|
||||
|
||||
@@ -188,7 +187,7 @@ func processes() ([]Process, error) {
|
||||
count := int(length / uint64(procinfo_len))
|
||||
|
||||
// parse buf to procs
|
||||
for i := 0; i < count; i++ {
|
||||
for i := range count {
|
||||
b := buf[i*procinfo_len : i*procinfo_len+procinfo_len]
|
||||
k, err := parse_kinfo_proc(b)
|
||||
if err != nil {
|
||||
|
||||
Generated
Vendored
-1
@@ -1,5 +1,4 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package ps
|
||||
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user