Compare commits

...
38 Commits
Author SHA1 Message Date
moloch-- 6a7bd0803a Update --save help 2026-01-28 17:21:35 -08:00
moloch-- 6c70c1c1e6 Add signature validation logic 2026-01-28 17:20:24 -08:00
moloch-- ddc222b8a2 Improvements to update 2026-01-28 17:07:47 -08:00
moloch-- 5506a582ac Add SliverPublicKey 2026-01-28 16:45:32 -08:00
Joe 63d872c98b Merge pull request #2142 from BishopFox/fix/sgn
Fix/sgn
2026-01-28 17:31:46 -07:00
moloch-- ef9f5dde0d Fix unit tests 2026-01-28 07:21:38 -08:00
moloch-- e35b7fdb97 Update sgn to v0.0.5 2026-01-27 21:28:21 -08:00
moloch-- efbbf382eb Merge branch 'master' into fix/sgn 2026-01-27 21:26:42 -08:00
moloch-- 0b8d00900d v1.6.7 2026-01-27 21:06:39 -08:00
moloch-- 9077596f25 Damn it Claude 2026-01-27 21:04:30 -08:00
moloch-- 0a8104a32e Damn it Claude 2026-01-27 21:03:25 -08:00
moloch-- 15a0ba4c1e Damn it Claude 2026-01-27 21:01:55 -08:00
moloch-- d452c8a676 Write .bin even if sgn fails 2026-01-27 20:49:28 -08:00
Joe fb74b491fa Merge pull request #2141 from BishopFox/fix/console-inputs
Update readline/console deps
2026-01-27 21:38:20 -07:00
moloch-- 2af6e11adc Update readline/console deps 2026-01-27 19:55:18 -08:00
Joe a3a98858fd Merge pull request #2135 from BishopFox/fix/sqlite
Add sqlite pragmas to db config
2026-01-21 22:28:56 -07:00
moloch-- d0652f2fd3 Add sqlite pragmas to db config 2026-01-21 16:08:07 -08:00
Joe 936f067363 Merge pull request #2130 from BishopFox/feature/website-info
Feature/website info
2026-01-21 10:25:56 -07:00
moloch-- 041c3c7048 Improve tab completer for websites cmd 2026-01-20 21:29:39 -08:00
moloch-- b48f74af58 Add original file name and sha256 to websites cmd 2026-01-20 19:13:42 -08:00
moloch-- 6ec8849b20 v1.6.6 2026-01-16 09:18:39 -08:00
Joe db7cf1ed62 Merge pull request #2125 from BishopFox/fix/winlsdir
Improved `err` and `nil` checks in `dirListHandler`
2026-01-16 10:17:01 -07:00
moloch-- 16e1e77068 Implement better err and nil checks in dirListHandler issue #2122 2026-01-16 07:06:43 -08:00
moloch-- 1cfa694aa2 Merge branch 'update/deps' into tui/adv-forms 2026-01-16 06:57:06 -08:00
moloch-- 5898877136 Fix --rc scripts 2026-01-16 06:56:41 -08:00
moloch-- a7d8cac565 Update generate form 2026-01-16 06:41:58 -08:00
moloch-- 0e73afca47 Update deps 2026-01-16 06:07:10 -08:00
moloch-- 432941d694 Tab complete parent commands from submenu 2026-01-16 05:58:35 -08:00
moloch-- ac521bf53c v1.6.4 2026-01-15 16:10:06 -08:00
Joe 9720c9f14f Merge pull request #2121 from BishopFox/feature/flag-completers
Improved flag completers
2026-01-15 17:09:30 -07:00
moloch-- 4a224fdb9c Improve completers for --interact flags 2026-01-15 15:14:20 -08:00
moloch-- 671eb4d777 Add tab completer to 'use' cmd 2026-01-15 15:03:21 -08:00
moloch-- 16cf816610 Implement os and arch completers 2026-01-15 13:54:21 -08:00
moloch-- 879f576c6e Add MCP to docs 2026-01-15 08:05:02 -08:00
moloch-- 2df78cdbf5 Update readme 2026-01-15 07:45:49 -08:00
moloch-- a05ffc0ae1 Fix footer/card z-index issue in docs site 2026-01-15 07:44:30 -08:00
moloch-- 6b4b218f09 Tweak docs 2026-01-15 07:33:40 -08:00
Joe 4d0d46afd6 Merge pull request #2118 from BishopFox/exec/env
Updates to `execute`
2026-01-13 22:45:02 -07:00
107 changed files with 3315 additions and 1573 deletions

No files matched your search

+3
View File
@@ -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)"
+2 -4
View File
@@ -39,10 +39,8 @@ 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.
+13
View File
@@ -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 != "" {
+70 -15
View File
@@ -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
}
+1 -1
View File
@@ -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",
+1
View File
@@ -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).
+2 -1
View File
@@ -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
+6 -4
View File
@@ -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
+91 -48
View File
@@ -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")
})
}
+1 -1
View File
@@ -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]),
})
+7
View File
@@ -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
+68 -15
View File
@@ -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{
+6 -1
View File
@@ -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
}
+2 -1
View File
@@ -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
View File
@@ -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)
}
}
+3
View File
@@ -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}
+71
View File
@@ -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
+39
View File
@@ -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",
@@ -121,9 +121,10 @@ func webAddFile(web *clientpb.WebsiteAddContent, webpath string, contentType str
}
web.Contents[webpath] = &clientpb.WebContent{
Path: webpath,
ContentType: contentType,
Content: data,
Path: webpath,
ContentType: contentType,
OriginalFile: filepath.Base(contentPath),
Content: data,
}
return nil
}
+10 -4
View File
@@ -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())
+195
View File
@@ -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
}
}
}
+35 -5
View File
@@ -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)
+9
View File
@@ -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
View File
@@ -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),
),
+30 -34
View File
@@ -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),
),
+220
View File
@@ -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
View File
@@ -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={
+52
View File
@@ -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
View File
@@ -1 +1 @@
{"tutorials":[{"name":"1 - Getting Started","content":"# This course is intended for the 1.6 version of Sliver, which is not yet published\n\n`sliver-server` is the binary you want to use to run the Sliver C2 server, `sliver-client` is solely a client to connect to a Sliver C2 server. Sliver server also acts as a client on its own, so you don’t necessarily run sliver server and client separately.\n\nFirst time running Sliver will take a couple seconds as it's retrieving its dependencies. Consecutive executions will be much faster. Go ahead and launch the `sliver-server`.\n\n```asciinema\n{\"src\": \"/asciinema/startup.cast\", \"cols\": \"132\", \"rows\": \"28\", \"idleTimeLimit\": 8}\n```\n\nLet's take a couple minutes to discuss what Sliver actually is and how it's set up.\n\n![Alt text](/images/Architecture.png)\n\nNow that Sliver is running, lets generate and execute your first implant to try out some of the basic features of Sliver, for now we’re going to run everything on the local host.\n\nHere's what we're going to do: \n* Generate your implant using the `generate` command as shown below.\n* Start HTTP listener on port 80\n* Execute implant in a separate terminal\n\n```asciinema\n{\"src\": \"/asciinema/first-implant.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNow let’s select our implant and run our first command using the `use` command.\n\n```bash\n[server] sliver > use\n? Select a session or beacon: \nSESSION 1884a365 RELATED_EARDRUM [::1]:49153 test.local tester darwin/amd64\n[*] Active session RELATED_EARDRUM (1884a365-085f-4506-b28e-80c481730fd0)\n\n[server] sliver (RELATED_EARDRUM) > pwd\n\n[*] /Users/tester/tools\n```\n\nOnce you have reached this point, go ahead and explore some of the commands listed below. In each case, first check out the command's help using the **`-h`** flag then try it out!\n\n```bash\nExploring and interacting with the filesystem\n\nFilesystem\n cat Dump file to stdout\n cd Change directory\n cp Copy a file\n download Download a file\n grep Search for strings that match a regex within a file or directory\n head Grab the first number of bytes or lines from a file\n ls List current directory\n mkdir Make a directory\n mv Move or rename a file\n pwd Print working directory\n rm Remove a file or directory\n tail Grab the last number of bytes or lines from a file\n upload Upload a file\n```\n\n```asciinema\n{\"src\": \"/asciinema/filesystem.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nGetting some environmental information\n```bash\nInfo\n env List environment variables\n getgid Get session process GID\n getpid Get session pid\n getuid Get session process UID\n info Get session info\n ping Send round trip message to implant (does not use ICMP)\n whoami Get session user execution context\n```\nExecute a binary\n\n```asciinema\n{\"src\": \"/asciinema/execute.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nRunning an interactive shell\n\n```asciinema\n{\"src\": \"/asciinema/shell.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNot all commands are supported for all operating systems or meant to be used on all operating systems, here are a few examples:\n\n```\nmount Get information on mounted filesystems (only for Windows and Linux)\nscreenshot Take a screenshot (only for Windows and Linux)\nmemfiles List current memfiles (Linux only)\n```\n\nThis is an open-source project if you see a bug please file an issue! Pull requests are always welcome."},{"name":"2 - Beacons vs Sessions","content":"# This course is intended for the 1.6 version of Sliver, which is not yet published\n\nSliver implants support two types of connections, sessions and beacons.\n\nSessions use long-polling connections, which means they constantly maintain a single TCP connection open while communicating with the server. Beacons on the other hand call back periodically and will sleep when not active which can help keep their presence hidden. You could limit callbacks to once every 6 hours for example and only 'activate' the beacon when needed by switching its sleeping time to a shorter duration.\n\nTypically during an engagement you will want to deploy a beacon on the target system and switch to a session while doing more active enumeration.\n\nLet’s start with generating and deploying a beacon using `http`.\n\n```asciinema\n{\"src\": \"/asciinema/beacon_generation.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nYou can see the beacon callback times either in the `info` command or using `beacons watch`.\n\n```bash\n[server] sliver > beacons watch\n\n Line truncated
{"tutorials":[{"name":"1 - Getting Started","content":"# This course is intended for the 1.6 version of Sliver, which is not yet published\n\n`sliver-server` is the binary you want to use to run the Sliver C2 server, `sliver-client` is solely a client to connect to a Sliver C2 server. Sliver server also acts as a client on its own, so you don’t necessarily run sliver server and client separately.\n\nFirst time running Sliver will take a couple seconds as it's retrieving its dependencies. Consecutive executions will be much faster. Go ahead and launch the `sliver-server`.\n\n```asciinema\n{\"src\": \"/asciinema/startup.cast\", \"cols\": \"132\", \"rows\": \"28\", \"idleTimeLimit\": 8}\n```\n\nLet's take a couple minutes to discuss what Sliver actually is and how it's set up.\n\n![Alt text](/images/Architecture.png)\n\nNow that Sliver is running, lets generate and execute your first implant to try out some of the basic features of Sliver, for now we’re going to run everything on the local host.\n\nHere's what we're going to do: \n* Generate your implant using the `generate` command as shown below.\n* Start HTTP listener on port 80\n* Execute implant in a separate terminal\n\n```asciinema\n{\"src\": \"/asciinema/first-implant.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNow let’s select our implant and run our first command using the `use` command.\n\n```bash\n[server] sliver > use\n? Select a session or beacon: \nSESSION 1884a365 RELATED_EARDRUM [::1]:49153 test.local tester darwin/amd64\n[*] Active session RELATED_EARDRUM (1884a365-085f-4506-b28e-80c481730fd0)\n\n[server] sliver (RELATED_EARDRUM) > pwd\n\n[*] /Users/tester/tools\n```\n\nOnce you have reached this point, go ahead and explore some of the commands listed below. In each case, first check out the command's help using the **`-h`** flag then try it out!\n\n```bash\nExploring and interacting with the filesystem\n\nFilesystem\n cat Dump file to stdout\n cd Change directory\n cp Copy a file\n download Download a file\n grep Search for strings that match a regex within a file or directory\n head Grab the first number of bytes or lines from a file\n ls List current directory\n mkdir Make a directory\n mv Move or rename a file\n pwd Print working directory\n rm Remove a file or directory\n tail Grab the last number of bytes or lines from a file\n upload Upload a file\n```\n\n```asciinema\n{\"src\": \"/asciinema/filesystem.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nGetting some environmental information\n```bash\nInfo\n env List environment variables\n getgid Get session process GID\n getpid Get session pid\n getuid Get session process UID\n info Get session info\n ping Send round trip message to implant (does not use ICMP)\n whoami Get session user execution context\n```\nExecute a binary\n\n```asciinema\n{\"src\": \"/asciinema/execute.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nRunning an interactive shell\n\n```asciinema\n{\"src\": \"/asciinema/shell.cast\", \"cols\": \"132\", \"rows\": \"14\", \"idleTimeLimit\": 8}\n```\n\nNot all commands are supported for all operating systems or meant to be used on all operating systems, here are a few examples:\n\n```\nmount Get information on mounted filesystems (only for Windows and Linux)\nscreenshot Take a screenshot (only for Windows and Linux)\nmemfiles List current memfiles (Linux only)\n```\n\nThis is an open-source project if you see a bug please file an issue! Pull requests are always welcome."},{"name":"2 - Beacons vs Sessions","content":"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
+7 -5
View File
@@ -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-20260128035102-9f373ad18989
replace github.com/reeflective/console => github.com/moloch--/console v0.0.0-20260128035037-680800942770
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
+10 -12
View File
@@ -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-20260128035037-680800942770 h1:JtfE7Od0O5ISD4b9r9AX7FTlAf8sT6O4qr5HV6Ey5U0=
github.com/moloch--/console v0.0.0-20260128035037-680800942770/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-20260128035102-9f373ad18989 h1:g0EfxAWzDGYarN0RAPibsjz2M/f0pAqYNiEpCPWRDok=
github.com/moloch--/readline v0.0.0-20260128035102-9f373ad18989/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=
+26 -17
View File
@@ -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) {
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -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 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.2
// protoc v3.15.8
// source: commonpb/common.proto
package commonpb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.2
// protoc v3.15.8
// source: dnspb/dns.proto
package dnspb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.2
// protoc v3.15.8
// source: rpcpb/services.proto
package rpcpb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.2
// protoc v3.15.8
// source: sliverpb/sliver.proto
package sliverpb
+71 -2
View File
@@ -26,6 +26,7 @@ import (
"os"
"path"
"path/filepath"
"sort"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/log"
@@ -47,6 +48,13 @@ 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
@@ -66,7 +74,8 @@ type DatabaseConfig struct {
Host string `json:"host"`
Port uint16 `json:"port"`
Params map[string]string `json:"params"`
Params map[string]string `json:"params"`
Pragmas map[string]string `json:"pragmas"`
MaxIdleConns int `json:"max_idle_conns"`
MaxOpenConns int `json:"max_open_conns"`
@@ -80,7 +89,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 +121,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()
@@ -161,6 +208,8 @@ 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)
@@ -171,9 +220,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"
}
}
+12 -2
View File
@@ -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
View File
@@ -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,
}
}
+6 -1
View File
@@ -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,
+6 -1
View File
@@ -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
View File
@@ -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)
+21 -3
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -1,4 +1,4 @@
go 1.19
go 1.24
use (
.
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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="'&backprime;+;,", %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
View File
@@ -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())
}
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
@@ -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
@@ -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 != '}'
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -1,5 +1,4 @@
//go:build !windows && !plan9
// +build !windows,!plan9
package lscolors
@@ -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?
@@ -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 {
@@ -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 {
@@ -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
@@ -1,5 +1,4 @@
//go:build darwin
// +build darwin
package ps
@@ -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 {
@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package ps
@@ -1,5 +1,4 @@
//go:build solaris
// +build solaris
package ps
@@ -88,7 +87,7 @@ func (p *UnixProcess) Refresh() error {
}
func toString(array []byte, len int) string {
for i := 0; i < len; i++ {
for i := range len {
if array[i] == 0 {
return string(array[:i])
}
@@ -1,5 +1,4 @@
//go:build linux || solaris
// +build linux solaris
package ps
@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package ps
+56
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"math/rand"
"strings"
keystone "github.com/moloch--/go-keystone"
)
@@ -197,6 +198,12 @@ func (encoder Encoder) Assemble(asm string) ([]byte, bool) {
return nil, false
}
asm = normalizeAssembly(asm)
if asm == "" {
return []byte{}, true
}
asm = addCodeDirective(asm, encoder.architecture)
ks, err := keystone.NewEngine(keystone.ARCH_X86, mode)
if err != nil {
return nil, false
@@ -227,6 +234,12 @@ func (encoder Encoder) GetAssemblySize(asm string) int {
return -1
}
asm = normalizeAssembly(asm)
if asm == "" {
return 0
}
asm = addCodeDirective(asm, encoder.architecture)
ks, err := keystone.NewEngine(keystone.ARCH_X86, mode)
if err != nil {
return -1
@@ -247,6 +260,49 @@ func (encoder Encoder) GetAssemblySize(asm string) int {
return len(bin)
}
func normalizeAssembly(asm string) string {
if asm == "" {
return ""
}
cleaned := strings.ReplaceAll(asm, ";", "\n")
lines := strings.Split(cleaned, "\n")
out := make([]string, 0, len(lines))
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
out = append(out, line)
}
return strings.Join(out, "\n")
}
func addCodeDirective(asm string, arch int) string {
if asm == "" || hasCodeDirective(asm) {
return asm
}
switch arch {
case 32:
return ".code32\n" + asm
case 64:
return ".code64\n" + asm
default:
return asm
}
}
func hasCodeDirective(asm string) bool {
for _, line := range strings.Split(asm, "\n") {
trimmed := strings.ToLower(strings.TrimSpace(line))
if strings.HasPrefix(trimmed, ".code") {
return true
}
}
return false
}
// GenerateIPToStack function generates instructions series that pushes the instruction pointer to stack
func (encoder Encoder) GenerateIPToStack() []byte {
-3
View File
@@ -60,9 +60,6 @@ func (c *Console) complete(input []rune, pos int) readline.Completions {
comps = comps.Usage("%s", completions.Usage)
comps = c.justifyCommandComps(comps)
// Display extension and alias arguments as a list (one per line)
comps = comps.DisplayList("extension arguments", "alias arguments")
// If any errors arose from the completion call itself.
if err != nil {
comps = readline.CompleteMessage("failed to load config: " + err.Error())
+78 -2
View File
@@ -1,11 +1,13 @@
package readline
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/rivo/uniseg"
@@ -448,8 +450,82 @@ func (rl *Shell) selfInsert() {
}
func (rl *Shell) bracketedPasteBegin() {
// keys, _ := rl.Keys.PeekAllBytes()
// fmt.Println(string(keys))
rl.History.SkipSave()
rl.completer.TrimSuffix()
const endSeq = "\x1b[201~"
data := rl.Keys.DrainBuffer()
for {
if idx := bytes.Index(data, []byte(endSeq)); idx >= 0 {
payload := data[:idx]
rest := data[idx+len(endSeq):]
if len(rest) > 0 {
rl.Keys.PrependBuffer(rest)
}
rl.insertPastedBytes(payload)
return
}
more, err := rl.Keys.ReadInput()
if err != nil {
rl.insertPastedBytes(data)
return
}
if len(more) == 0 {
continue
}
data = append(data, more...)
}
}
func (rl *Shell) insertPastedBytes(data []byte) {
if len(data) == 0 {
return
}
runes := normalizePasteBytes(data)
if len(runes) == 0 {
return
}
rl.cursor.InsertAt(runes...)
rl.Keys.SetMatched(runes...)
}
func normalizePasteBytes(data []byte) []rune {
if len(data) == 0 {
return nil
}
out := make([]rune, 0, len(data))
for len(data) > 0 {
if data[0] == '\r' {
if len(data) > 1 && data[1] == '\n' {
data = data[1:]
}
out = append(out, '\n')
data = data[1:]
continue
}
r, size := utf8.DecodeRune(data)
if r == utf8.RuneError && size == 1 {
out = append(out, rune(data[0]))
data = data[1:]
continue
}
out = append(out, r)
data = data[size:]
}
return out
}
// Drag the character before point forward over the character
+2 -2
View File
@@ -21,7 +21,7 @@ func Display(eng *Engine, maxRows int) {
// little more time. The engine itself is responsible for
// deleting those lists when it deems them useless.
if eng.Matches() == 0 || eng.skipDisplay {
fmt.Print(term.ClearLineAfter)
term.WriteString(term.ClearLineAfter)
return
}
@@ -36,7 +36,7 @@ func Display(eng *Engine, maxRows int) {
completions, eng.usedY = eng.cropCompletions(completions, maxRows)
if completions != "" {
fmt.Print(completions)
term.WriteString(completions)
}
}
+84 -1
View File
@@ -13,7 +13,7 @@ import (
)
const (
keyScanBufSize = 1024
keyScanBufSize = 8192
)
// Stdin is used by the Keys struct to read and write keys.
@@ -238,6 +238,89 @@ func FlushUsed(keys *Keys) {
defer keys.mutex.Unlock()
}
// Pending returns the number of buffered keys waiting to be processed.
func (k *Keys) Pending() int {
k.mutex.RLock()
defer k.mutex.RUnlock()
return len(k.buf) + len(k.macroKeys)
}
// BufferSize returns the number of raw input bytes buffered.
func (k *Keys) BufferSize() int {
k.mutex.RLock()
defer k.mutex.RUnlock()
return len(k.buf)
}
// PeekBuffer returns up to max bytes from the raw input buffer.
func (k *Keys) PeekBuffer(max int) []byte {
k.mutex.RLock()
defer k.mutex.RUnlock()
if max <= 0 || len(k.buf) <= max {
return append([]byte(nil), k.buf...)
}
return append([]byte(nil), k.buf[:max]...)
}
// DrainBuffer returns all buffered raw input bytes and clears the buffer.
func (k *Keys) DrainBuffer() []byte {
k.mutex.Lock()
defer k.mutex.Unlock()
if len(k.buf) == 0 {
return nil
}
buf := append([]byte(nil), k.buf...)
k.buf = nil
return buf
}
// PrependBuffer pushes raw input bytes back to the front of the buffer.
func (k *Keys) PrependBuffer(keys []byte) {
if len(keys) == 0 {
return
}
k.mutex.Lock()
k.buf = append(keys, k.buf...)
k.mutex.Unlock()
}
// AppendMatched appends keys to the matched buffer, so they can be recorded by macros.
func (k *Keys) AppendMatched(keys ...rune) {
if len(keys) == 0 {
return
}
k.mutex.Lock()
k.matched = append(k.matched, keys...)
k.mutex.Unlock()
}
// SetMatched replaces the matched buffer with the provided keys.
func (k *Keys) SetMatched(keys ...rune) {
k.mutex.Lock()
if len(keys) == 0 {
k.matched = nil
k.mutex.Unlock()
return
}
k.matched = append(k.matched[:0], keys...)
k.mutex.Unlock()
}
// ReadInput reads raw input bytes from stdin, passing through the input filter.
func (k *Keys) ReadInput() ([]byte, error) {
return k.readInputFiltered()
}
// ReadKey reads keys from stdin like Read(), but immediately
// returns them instead of storing them in the stack, along with
// an indication on whether this key is an escape/abort one.
+1 -2
View File
@@ -1,7 +1,6 @@
package core
import (
"fmt"
"regexp"
"strings"
"unicode"
@@ -344,7 +343,7 @@ func DisplayLine(l *Line, indent int) {
line += term.NewlineReturn
}
fmt.Print(line)
term.WriteString(line)
}
}
+56 -21
View File
@@ -1,7 +1,7 @@
package display
import (
"fmt"
"regexp"
"github.com/reeflective/readline/inputrc"
"github.com/reeflective/readline/internal/color"
@@ -32,6 +32,10 @@ type Engine struct {
hintRows int
compRows int
primaryPrinted bool
cursorKnown bool
cursorDirty bool
commentBegin string
commentRegexp *regexp.Regexp
// UI components
keys *core.Keys
@@ -69,7 +73,10 @@ func Init(e *Engine, highlighter func([]rune) string) {
// Refresh recomputes and redisplays the entire readline interface, except
// the first lines of the primary prompt when the latter is a multiline one.
func (e *Engine) Refresh() {
fmt.Print(term.HideCursor)
term.BeginBuffer()
defer term.EndBuffer()
term.WriteString(term.HideCursor)
// Go back to the first column, and if the primary prompt
// was not printed yet, back up to the line's beginning row.
@@ -82,6 +89,12 @@ func (e *Engine) Refresh() {
// Print either all or the last line of the prompt.
e.prompt.LastPrint()
// Flush prompt output before querying the cursor position.
if term.ShouldQueryCursorPos() {
term.EndBuffer()
term.BeginBuffer()
}
// Get all positions required for the redisplay to come:
// prompt end (thus indentation), cursor positions, etc.
e.computeCoordinates(true)
@@ -99,7 +112,7 @@ func (e *Engine) Refresh() {
} else {
e.lineEndToCursorPos()
}
fmt.Print(term.ShowCursor)
term.WriteString(term.ShowCursor)
}
// PrintPrimaryPrompt redraws the primary prompt.
@@ -108,12 +121,13 @@ func (e *Engine) Refresh() {
func (e *Engine) PrintPrimaryPrompt() {
e.prompt.PrimaryPrint()
e.primaryPrinted = true
e.MarkCursorDirty()
}
// ClearHelpers clears the hint and completion sections below the line.
func (e *Engine) ClearHelpers() {
e.CursorBelowLine()
fmt.Print(term.ClearScreenBelow)
term.WriteString(term.ClearScreenBelow)
term.MoveCursorUp(1)
term.MoveCursorUp(e.lineRows)
@@ -140,14 +154,15 @@ func (e *Engine) AcceptLine() {
term.MoveCursorBackwards(term.GetWidth())
term.MoveCursorDown(e.lineRows)
term.MoveCursorForwards(e.lineCol)
fmt.Print(term.ClearScreenBelow)
term.WriteString(term.ClearScreenBelow)
// Reprint the right-side prompt if it's not a tooltip one.
e.prompt.RightPrint(e.lineCol, false)
// Go below this non-suggested line and clear everything.
term.MoveCursorBackwards(term.GetWidth())
fmt.Print(term.NewlineReturn)
term.WriteString(term.NewlineReturn)
e.MarkCursorDirty()
}
// RefreshTransient goes back to the first line of the input buffer
@@ -164,7 +179,8 @@ func (e *Engine) RefreshTransient() {
// And redisplay the transient/primary/line.
e.prompt.TransientPrint()
e.displayLine()
fmt.Print(term.NewlineReturn)
term.WriteString(term.NewlineReturn)
e.MarkCursorDirty()
}
// CursorToLineStart moves the cursor just after the primary prompt.
@@ -183,7 +199,7 @@ func (e *Engine) CursorToLineStart() {
func (e *Engine) CursorBelowLine() {
term.MoveCursorUp(e.cursorRow)
term.MoveCursorDown(e.lineRows)
fmt.Print(term.NewlineReturn)
term.WriteString(term.NewlineReturn)
}
// lineStartToCursorPos can be used if the cursor is currently
@@ -202,6 +218,11 @@ func (e *Engine) cursorHintToLineStart() {
e.CursorToLineStart()
}
// MarkCursorDirty forces the next refresh to query the cursor position.
func (e *Engine) MarkCursorDirty() {
e.cursorDirty = true
}
func (e *Engine) computeCoordinates(suggested bool) {
// Get the new input line and auto-suggested one.
e.line, e.cursor = e.completer.Line()
@@ -211,17 +232,31 @@ func (e *Engine) computeCoordinates(suggested bool) {
e.suggested = e.histories.Suggest(e.line)
}
// Get the position of the line's beginning by querying
// the terminal for the cursor position.
e.startCols, e.startRows = e.keys.GetCursorPos()
// Get the position of the line's beginning. When possible, reuse the
// cached cursor row to avoid the expensive terminal query.
if term.ShouldQueryCursorPos() && (!e.cursorKnown || e.cursorDirty) {
e.startCols, e.startRows = e.keys.GetCursorPos()
if e.startCols > 0 {
e.startCols--
}
if e.startCols > 0 {
e.startCols--
}
// Cursor position might be misleading if invalid (negative).
if e.startCols == -1 {
e.startCols = e.prompt.LastUsed()
// Cursor position might be misleading if invalid (negative).
if e.startCols == -1 {
e.startCols = e.prompt.LastUsed()
}
e.cursorKnown = true
e.cursorDirty = false
} else {
e.startCols = e.prompt.LastCols()
if e.startCols == 0 {
e.startCols = e.prompt.LastUsed()
}
if !e.cursorKnown {
e.startRows = 0
e.cursorKnown = true
}
}
e.cursorCol, e.cursorRow = core.CoordinatesCursor(e.cursor, e.startCols)
@@ -269,8 +304,8 @@ func (e *Engine) displayLine() {
// Adjust the cursor if the line fits exactly in the terminal width.
if e.lineCol == 0 {
fmt.Print(term.NewlineReturn)
fmt.Print(term.ClearLineAfter)
term.WriteString(term.NewlineReturn)
term.WriteString(term.ClearLineAfter)
}
}
@@ -310,7 +345,7 @@ func (e *Engine) displayHelpers() bool {
return false
}
fmt.Print(term.NewlineReturn)
term.WriteString(term.NewlineReturn)
prevHintRows := e.hintRows
prevCompRows := e.compRows
@@ -327,7 +362,7 @@ func (e *Engine) displayHelpers() bool {
}
if e.hintRows+e.compRows < prevHintRows+prevCompRows {
fmt.Print(term.ClearScreenBelow)
term.WriteString(term.ClearScreenBelow)
}
// Go back to the first line below the input line.
+28 -15
View File
@@ -19,29 +19,41 @@ func (e *Engine) highlightLine(line []rune, selection core.Selection) string {
sorted := sortHighlights(selection)
colors := e.getHighlights(line, sorted)
var highlighted string
var highlighted strings.Builder
// And apply highlighting before each rune.
for i, r := range line {
if highlight, found := colors[i]; found {
highlighted += string(highlight)
highlighted.WriteString(highlight)
}
highlighted += string(r)
highlighted.WriteRune(r)
}
// Finally, highlight comments using a regex.
result := highlighted.String()
// Finally, highlight comments using a cached regex.
comment := strings.Trim(e.opts.GetString("comment-begin"), "\"")
commentPattern := fmt.Sprintf(`(^|\s)%s.*`, comment)
if comment != e.commentBegin {
e.commentBegin = comment
e.commentRegexp = nil
if commentsMatch, err := regexp.Compile(commentPattern); err == nil {
commentColor := color.SGRStart + color.Fg + "244" + color.SGREnd
highlighted = commentsMatch.ReplaceAllString(highlighted, fmt.Sprintf("%s${0}%s", commentColor, color.Reset))
if comment != "" {
commentPattern := fmt.Sprintf(`(^|\s)%s.*`, comment)
if commentsMatch, err := regexp.Compile(commentPattern); err == nil {
e.commentRegexp = commentsMatch
}
}
}
highlighted += color.Reset
if e.commentRegexp != nil {
commentColor := color.SGRStart + color.Fg + "244" + color.SGREnd
result = e.commentRegexp.ReplaceAllString(result, fmt.Sprintf("%s${0}%s", commentColor, color.Reset))
}
return highlighted
result += color.Reset
return result
}
func sortHighlights(vhl core.Selection) []core.Selection {
@@ -95,15 +107,16 @@ func sortHighlights(vhl core.Selection) []core.Selection {
return sorted
}
func (e *Engine) getHighlights(line []rune, sorted []core.Selection) map[int][]rune {
highlights := make(map[int][]rune)
var colorSeqRegexp = regexp.MustCompile(`\x1b\[[0-9;]+m`)
func (e *Engine) getHighlights(line []rune, sorted []core.Selection) map[int]string {
highlights := make(map[int]string)
// Find any highlighting already applied on the line,
// and keep the indexes so that we can skip those.
var colors [][]int
colorMatch := regexp.MustCompile(`\x1b\[[0-9;]+m`)
colors = colorMatch.FindAllStringIndex(string(line), -1)
colors = colorSeqRegexp.FindAllStringIndex(string(line), -1)
// marks that started highlighting, but not done yet.
regions := make([]core.Selection, 0)
@@ -149,7 +162,7 @@ func (e *Engine) getHighlights(line []rune, sorted []core.Selection) map[int][]r
// Add to the line, with the raw index since
// we must take into account embedded colors.
if len(posHl) > 0 {
highlights[rawIndex] = posHl
highlights[rawIndex] = string(posHl)
}
}
+7 -21
View File
@@ -1,7 +1,6 @@
package keymap
import (
"sort"
"strings"
"github.com/reeflective/readline/inputrc"
@@ -180,32 +179,19 @@ func (m *Engine) matchBind(keys []byte, binds map[string]inputrc.Bind) (inputrc.
var match inputrc.Bind
var prefixed []inputrc.Bind
// Make a sorted list with all keys in the binds map.
var sequences []string
for sequence := range binds {
sequences = append(sequences, sequence)
}
keysStr := string(keys)
// Sort the list of sequences by alphabetical order and length.
sort.Slice(sequences, func(i, j int) bool {
if len(sequences[i]) == len(sequences[j]) {
return sequences[i] < sequences[j]
}
return len(sequences[i]) < len(sequences[j])
})
// Iterate over the sorted list of sequences and find all binds
// Iterate over the list of sequences and find all binds
// that match the sequence either by prefix or exactly.
for _, sequence := range sequences {
for sequence, bind := range binds {
seq := strutil.ConvertMeta([]rune(sequence))
if len(string(keys)) < len(seq) && strings.HasPrefix(seq, string(keys)) {
prefixed = append(prefixed, binds[sequence])
if len(keysStr) < len(seq) && strings.HasPrefix(seq, keysStr) {
prefixed = append(prefixed, bind)
}
if string(keys) == seq {
match = binds[sequence]
if keysStr == seq {
match = bind
}
}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more