Compare commits

...
Author SHA1 Message Date
moloch-- 92d85cb8ff Tweak styling 2026-05-01 07:17:02 -07:00
moloch-- f5e831844a Fix various docs ui quirks in hero v3 2026-04-30 18:21:06 -07:00
moloch-- ab2fc7dc4a Initial update to heroui v3 2026-04-30 17:59:11 -07:00
Joe 5e377019e4 Merge pull request #2254 from smeukinou/fix-sliverpy
fix: safely close event broker subscription channels
2026-04-30 11:37:01 -07:00
smeukinou 88a4bebca0 fix: safely close event broker subscription channels
Moves the responsibility of closing the event subscription channel to the broker.Start() goroutine when processing an unsubscribe request. This prevents potential data races and panics caused by closing a channel concurrently while the broker might still be attempting to publish events to it.
2026-04-29 23:07:40 +02:00
Joe 2daccb5bd3 Merge pull request #2250 from BishopFox/wg/opt-in
Disable wg wrapper on multiplayer by default
2026-04-21 21:24:17 -07:00
Joe e2a009d4ac Merge pull request #2249 from Moriz82/fix/services-windows-nil-deref
fix(implant): services list panics on nil error on Windows (#1989)
2026-04-21 21:03:40 -07:00
moloch-- eda51f826a Disable wg wrapper on multiplayer by default 2026-04-21 20:51:06 -07:00
Will DeDominico f83dc42a64 fix(implant): services list panics on nil error (#1989)
servicesListHandler called err.Error() unconditionally after
service.ListServices(). On a healthy Windows host ListServices returns
nil error, causing a nil pointer dereference that crashed the implant.

serviceDetailHandler in the same file already guards correctly with
if err != nil. Apply the same pattern to servicesListHandler by
extracting response construction into a buildServicesResp helper with
a proper nil check.

Verified on Windows 11 VM: unfixed helper panics with "runtime error:
invalid memory address or nil pointer dereference" on the nil-error
path; fixed helper passes.

Fixes #1989
2026-04-20 20:13:46 -05:00
Joe 17e8c996a6 Merge pull request #2244 from Moriz82/fix/localtask-process-isolation
fix(implant): run LocalTask shellcode in forked child (#2237)
2026-04-19 08:44:56 -07:00
Will DeDominico 2b667f0e7e fix(implant): run LocalTask shellcode in forked child (#2237)
The previous implementation ran shellcode in a goroutine inside the
beacon; payloads that terminate via exit/execve killed the whole
beacon. Fork a child instead and let the parent wait for it.

Linux uses SYS_CLONE(SIGCHLD) since linux/arm64 has no SYS_FORK.
Darwin uses SYS_FORK, with the isChild check routed through the r1==1
convention that libSystem's fork() wrapper normally hides.

Post-fork the child runs only raw syscalls: runtime_BeforeFork poisons
stackguard0 and AfterForkInChild clears inherited signal handlers.
Mprotect happens in the child so the parent's page table stays
writable, inherited FDs are closed to avoid leaking C2 sockets into
exec'd payloads, and the child exits via SYS_EXIT_GROUP (Linux) or
SYS_EXIT (Darwin).

Tests under implant/sliver/taskrunner/ cover parent survival and
non-zero-exit error reporting on both Linux and Darwin.
2026-04-16 20:52:38 -05:00
Ronan Kervella 73bcf40bfd Merge pull request #2240 from BishopFox/CLD-10806/update-codeowners-replace-red-team
chore(doc): replace red-team with bf-red-team in CODEOWNERS (CLD-10806)
2026-04-10 09:02:55 -07:00
George Robbins b635adcb3c chore(doc): replace red-team with bf-red-team in CODEOWNERS (CLD-10806) 2026-04-10 10:56:01 -05:00
Joe 2b92397e07 Merge pull request #2236 from BishopFox/codex/pr2234-wg-ci
Fix WG client Windows CI regressions
2026-04-09 10:11:57 -07:00
moloch-- c23067a0e0 Wait for AI RPC event streams to subscribe 2026-04-02 09:17:33 -07:00
moloch-- 3aefc39c08 Stabilize AI RPC event stream tests 2026-04-02 08:50:19 -07:00
moloch-- abd8c83df8 Stabilize Windows WireGuard reconnects 2026-04-02 08:22:51 -07:00
Joe 6cce9426f2 Merge pull request #2235 from skoveit/fix/pkg-cache-delete-wrong-argument
fix: pkgCache.Delete(value) should be pkgCache.Delete(key)
2026-04-01 17:30:20 -07:00
skove 2e742863a1 fix: pass key instead of value to pkgcache.delete() 2026-04-01 14:47:39 +02:00
moloch-- dc13a5bb93 Add connecting animation 2026-03-31 13:33:19 -07:00
moloch-- 1f2946eb87 Revert changes to netstack 2026-03-31 09:45:40 -07:00
moloch-- 5eeda4c02b console now keeps the long-lived background WG streams on one connection 2026-03-31 09:36:05 -07:00
moloch-- 55a3386313 Improve reliabilty of multiplayer/wg setup 2026-03-30 20:02:55 -07:00
moloch-- b34589a002 Merge branch 'master' of github.com:BishopFox/sliver 2026-03-30 15:56:54 -07:00
moloch-- 4486b17b49 Tweak release trigger 2026-03-30 15:56:45 -07:00
Joe 377ee5ca7c Merge pull request #2229 from BishopFox/docs/multiplayer-wg
Update docs for wg+grpc/mtls multiplayer
2026-03-30 12:13:43 -07:00
moloch-- 4765f40854 v1.7.4 2026-03-30 11:51:15 -07:00
moloch-- e239d85821 v1.7.4 2026-03-30 11:48:34 -07:00
Joe dec419b284 Merge pull request #2232 from BishopFox/fix/linux-ver
Implement Detailed Linux Version Info
2026-03-30 09:52:39 -07:00
moloch-- 6d51a23cc9 Implement linux detailed version info 2026-03-29 19:11:48 -07:00
moloch-- 3d6eec47be Implement linux detailed version info 2026-03-29 19:11:40 -07:00
moloch-- 464fb7008c Tweak ai.yaml config schema 2026-03-29 18:41:06 -07:00
moloch-- ffa5f89f5f Tweak styling of system prompt 2026-03-29 09:00:15 -07:00
moloch-- f19cbdc957 Give agent encoder/decoder tools 2026-03-29 08:43:14 -07:00
moloch-- 83bfc8d8e6 Add default prompt to ai.yaml config 2026-03-27 21:36:58 -07:00
moloch-- 365bb3596e Add aliases and extensions to agent tools 2026-03-27 20:22:15 -07:00
moloch-- 9ee96c2ce6 Add ctx window usage to tui 2026-03-27 19:43:42 -07:00
moloch-- e776e266d0 Stack toast 2026-03-27 18:46:08 -07:00
moloch-- d080c8a646 Implement more tools for the ai to use 2026-03-27 18:15:46 -07:00
moloch-- cb6402245e Implement more tools for the ai to use 2026-03-27 18:15:37 -07:00
moloch-- e4357277ec Add web search to oai models 2026-03-27 17:33:15 -07:00
moloch-- 5dc2ab1490 Render reasoning text as md 2026-03-27 17:13:39 -07:00
moloch-- 9f034a9956 Implement better reasoning ui 2026-03-27 17:10:24 -07:00
moloch-- f700535997 Implement selectable text 2026-03-27 16:59:08 -07:00
moloch-- 31bca034d8 Remove layout text 2026-03-27 16:48:08 -07:00
moloch-- fac4ad5fb7 Add mouse support to ai tui 2026-03-27 16:40:33 -07:00
moloch-- c128d33514 Add toast notifications to tui 2026-03-27 13:01:34 -07:00
moloch-- 4a37262bcf Implement scroll wheel support for conversation pane 2026-03-27 11:56:58 -07:00
moloch-- a2295112bd Clean up various styling in ai tui 2026-03-27 11:47:39 -07:00
moloch-- 834dff0f6e Add lic header 2026-03-27 08:38:41 -07:00
Joe f4a0431fdd Merge pull request #2231 from BishopFox/fix/pivots-dos
Fix/pivots dos
2026-03-26 21:40:23 -07:00
moloch-- d072b328c0 Fix pivot handler test helper collision 2026-03-26 19:44:18 -07:00
moloch-- 435bbcbd7e Merge master 2026-03-26 18:51:05 -07:00
moloch-- 84dc28e584 Fix nil deref in pivots 2026-03-26 18:50:13 -07:00
Joe 639592cb02 Merge pull request #2230 from BishopFox/fix/tunnel-dos
Fix/tunnel dos
2026-03-26 18:03:16 -07:00
moloch-- 8c7a1a6b40 Fix dos/panic in tunnel closed 2026-03-26 17:40:57 -07:00
moloch-- 06274c4061 Fix dos/panic in tunnel closed 2026-03-26 17:40:46 -07:00
119 changed files with 15858 additions and 5322 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
* @BishopFox/red-team
* @BishopFox/bf-red-team
+16 -5
View File
@@ -2,8 +2,8 @@ name: Release
on:
push:
branches:
- master
tags:
- "v*.*.*"
permissions:
contents: write
@@ -21,11 +21,22 @@ jobs:
with:
fetch-depth: 0
- name: Find Semver Tag
- name: Validate Release Tag
id: tag
run: |
git fetch --prune --tags -f
tag=$(git tag --points-at "$GITHUB_SHA" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n 1)
git fetch --prune --tags -f origin
tag="${GITHUB_REF_NAME}"
if ! printf '%s\n' "$tag" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Tag $tag is not a release semver tag."
exit 0
fi
if ! git merge-base --is-ancestor "$GITHUB_SHA" "origin/master"; then
echo "Tag $tag does not point to a commit on origin/master."
exit 0
fi
echo "tag=$tag" >> "$GITHUB_OUTPUT"
release:
+1 -2
View File
@@ -52,8 +52,7 @@ func init() {
rootCmd.TraverseChildren = true
rootCmd.Flags().String(RCFlagName, "", "path to rc script file")
rootCmd.PersistentFlags().Bool(disableWGFlag, false, "connect to multiplayer directly even if the operator config includes a WireGuard wrapper")
rootCmd.PersistentFlags().Bool(requireWGFlag, false, "require the operator config's WireGuard wrapper for multiplayer connections")
rootCmd.PersistentFlags().Bool(enableWGFlag, false, "connect to multiplayer through the operator config's WireGuard wrapper")
// Create the console client, without any RPC or commands bound to it yet.
// This created before anything so that multiple commands can make use of
+177
View File
@@ -0,0 +1,177 @@
package cli
import (
"fmt"
"io"
"strings"
"time"
"unicode/utf8"
bspinner "charm.land/bubbles/v2/spinner"
"github.com/bishopfox/sliver/client/transport"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"google.golang.org/grpc"
)
const (
minConnectSpinnerDuration = 900 * time.Millisecond
minConnectStatusDuration = 350 * time.Millisecond
)
type connectResult struct {
rpc rpcpb.SliverRPCClient
conn *grpc.ClientConn
err error
}
func connectWithSpinner(out io.Writer, target string, connect func(transport.ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error)) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
statusCh := make(chan string, 8)
resultCh := make(chan connectResult, 1)
go func() {
rpc, conn, err := connect(func(status string) {
sendStatus(statusCh, status)
})
resultCh <- connectResult{rpc: rpc, conn: conn, err: err}
}()
currentStatus := ""
currentStatusSince := time.Time{}
queuedStatus := ""
lastWidth := 0
spinner := bspinner.New(bspinner.WithSpinner(bspinner.Line))
ticker := time.NewTicker(spinner.Spinner.FPS)
defer ticker.Stop()
startedAt := time.Now()
var pendingResult *connectResult
setStatus := func(status string) {
status = strings.TrimSpace(status)
if status == "" || status == currentStatus {
return
}
currentStatus = status
currentStatusSince = time.Now()
}
stageStatus := func(status string) {
status = strings.TrimSpace(status)
if status == "" {
return
}
if currentStatus == "" || time.Since(currentStatusSince) >= minConnectStatusDuration {
queuedStatus = ""
setStatus(status)
return
}
queuedStatus = status
}
flushQueuedStatus := func() {
if queuedStatus == "" || time.Since(currentStatusSince) < minConnectStatusDuration {
return
}
nextStatus := queuedStatus
queuedStatus = ""
setStatus(nextStatus)
}
canReturnPendingResult := func() bool {
if pendingResult == nil {
return false
}
if pendingResult.err != nil {
return true
}
if time.Since(startedAt) < minConnectSpinnerDuration {
return false
}
if queuedStatus != "" {
return false
}
if !currentStatusSince.IsZero() && time.Since(currentStatusSince) < minConnectStatusDuration {
return false
}
return true
}
render := func() {
line := fmt.Sprintf("%s %s", spinner.View(), formatConnectSpinnerMessage(target, currentStatus))
lastWidth = writeSpinnerLine(out, line, lastWidth)
}
render()
for {
select {
case status := <-statusCh:
stageStatus(status)
spinner, _ = spinner.Update(spinner.Tick())
render()
case result := <-resultCh:
pendingResult = &result
case <-ticker.C:
spinner, _ = spinner.Update(spinner.Tick())
flushQueuedStatus()
render()
if canReturnPendingResult() {
result := *pendingResult
pendingResult = nil
clearSpinnerLine(out, lastWidth)
return result.rpc, result.conn, result.err
}
}
if pendingResult != nil && pendingResult.err != nil {
result := *pendingResult
pendingResult = nil
clearSpinnerLine(out, lastWidth)
return result.rpc, result.conn, result.err
}
}
}
func sendStatus(statusCh chan string, status string) {
status = strings.TrimSpace(status)
if status == "" {
return
}
statusCh <- status
}
func formatConnectSpinnerMessage(target string, status string) string {
target = strings.TrimSpace(target)
status = strings.TrimSpace(status)
if target == "" {
if status == "" {
return "Connecting ..."
}
return fmt.Sprintf("Connecting (%s) ...", status)
}
if status == "" {
return fmt.Sprintf("Connecting to %s ...", target)
}
return fmt.Sprintf("Connecting to %s (%s) ...", target, status)
}
func writeSpinnerLine(out io.Writer, line string, lastWidth int) int {
width := utf8.RuneCountInString(line)
padding := ""
if lastWidth > width {
padding = strings.Repeat(" ", lastWidth-width)
}
fmt.Fprintf(out, "\r%s%s", line, padding)
if width > lastWidth {
return width
}
return lastWidth
}
func clearSpinnerLine(out io.Writer, lastWidth int) {
if lastWidth <= 0 {
return
}
fmt.Fprintf(out, "\r%s\r", strings.Repeat(" ", lastWidth))
}
+132
View File
@@ -0,0 +1,132 @@
package cli
import (
"bytes"
"strings"
"testing"
"time"
"github.com/bishopfox/sliver/client/transport"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"google.golang.org/grpc"
)
func TestFormatConnectSpinnerMessage(t *testing.T) {
tests := []struct {
name string
target string
status string
want string
}{
{
name: "target only",
target: "127.0.0.1:31337",
want: "Connecting to 127.0.0.1:31337 ...",
},
{
name: "target with status",
target: "127.0.0.1:31337",
status: "wireguard",
want: "Connecting to 127.0.0.1:31337 (wireguard) ...",
},
{
name: "status without target",
status: "grpc/mtls",
want: "Connecting (grpc/mtls) ...",
},
{
name: "trim whitespace",
target: " 127.0.0.1:31337 ",
status: " grpc/mtls over wireguard ",
want: "Connecting to 127.0.0.1:31337 (grpc/mtls over wireguard) ...",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := formatConnectSpinnerMessage(test.target, test.status); got != test.want {
t.Fatalf("expected %q, got %q", test.want, got)
}
})
}
}
func TestConnectWithSpinnerOutput(t *testing.T) {
var out bytes.Buffer
spinnerDelay := 2 * (100 * time.Millisecond)
_, _, err := connectWithSpinner(&out, "127.0.0.1:31337", func(statusFn transport.ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
statusFn("wireguard")
time.Sleep(spinnerDelay)
statusFn("grpc/mtls over wireguard")
time.Sleep(spinnerDelay)
return nil, nil, nil
})
if err != nil {
t.Fatalf("connectWithSpinner returned error: %v", err)
}
got := out.String()
if !strings.Contains(got, "Connecting to 127.0.0.1:31337 (wireguard) ...") {
t.Fatalf("expected wireguard status in output, got %q", got)
}
if !strings.Contains(got, "Connecting to 127.0.0.1:31337 (grpc/mtls over wireguard) ...") {
t.Fatalf("expected grpc over wireguard status in output, got %q", got)
}
frameCount := 0
for _, frame := range []string{"|", "/", "-", "\\"} {
if strings.Contains(got, frame+" Connecting to 127.0.0.1:31337") {
frameCount++
}
}
if frameCount < 2 {
t.Fatalf("expected multiple spinner frames in output, got %q", got)
}
}
func TestConnectWithSpinnerFastSuccessStillShowsMultipleFrames(t *testing.T) {
var out bytes.Buffer
_, _, err := connectWithSpinner(&out, "127.0.0.1:31337", func(statusFn transport.ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
statusFn("grpc/mtls")
return nil, nil, nil
})
if err != nil {
t.Fatalf("connectWithSpinner returned error: %v", err)
}
got := out.String()
frameCount := 0
for _, frame := range []string{"|", "/", "-", "\\"} {
if strings.Contains(got, frame+" Connecting to 127.0.0.1:31337 (grpc/mtls) ...") {
frameCount++
}
}
if frameCount < 2 {
t.Fatalf("expected multiple spinner frames for fast success, got %q", got)
}
}
func TestConnectWithSpinnerFastSuccessShowsEachStatus(t *testing.T) {
var out bytes.Buffer
_, _, err := connectWithSpinner(&out, "127.0.0.1:31337", func(statusFn transport.ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
statusFn("wireguard")
statusFn("grpc/mtls over wireguard")
return nil, nil, nil
})
if err != nil {
t.Fatalf("connectWithSpinner returned error: %v", err)
}
got := out.String()
if !strings.Contains(got, "Connecting to 127.0.0.1:31337 (wireguard) ...") {
t.Fatalf("expected fast success output to include wireguard status, got %q", got)
}
if !strings.Contains(got, "Connecting to 127.0.0.1:31337 (grpc/mtls over wireguard) ...") {
t.Fatalf("expected fast success output to include grpc over wireguard status, got %q", got)
}
if strings.Contains(got, "Connected to 127.0.0.1:31337") {
t.Fatalf("did not expect past-tense success output, got %q", got)
}
}
+11 -7
View File
@@ -20,6 +20,7 @@ package cli
import (
"fmt"
"os"
"github.com/bishopfox/sliver/client/assets"
"github.com/bishopfox/sliver/client/command"
@@ -64,17 +65,20 @@ func consoleRunnerCmd(con *console.SliverClient, run bool) (pre, post func(cmd *
return nil
}
// Don't clobber output when simply running an implant command from system shell.
if run {
fmt.Printf("Connecting to %s:%d ...\n", config.LHost, config.LPort)
}
target := fmt.Sprintf("%s:%d", config.LHost, config.LPort)
var rpc rpcpb.SliverRPCClient
var ln *grpc.ClientConn
rpc, ln, err = transport.MTLSConnect(config)
// Don't clobber output when simply running an implant command from system shell.
if run {
rpc, ln, err = connectWithSpinner(os.Stdout, target, func(statusFn transport.ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
return transport.MTLSConnectWithStatus(config, statusFn)
})
} else {
rpc, ln, err = transport.MTLSConnect(config)
}
if err != nil {
fmt.Printf("Connection to server failed %s", err)
fmt.Printf("Connection to server failed %s\n", err)
return nil
}
return console.StartClient(con, rpc, ln, &console.ConnectionDetails{ConfigKey: configKey, Config: config}, command.ServerCommands(con, nil), command.SliverCommands(con), run, rcScript)
+6 -19
View File
@@ -1,41 +1,28 @@
package cli
import (
"fmt"
"github.com/bishopfox/sliver/client/transport"
"github.com/spf13/cobra"
)
const (
requireWGFlag = "require-wg"
disableWGFlag = "disable-wg"
enableWGFlag = "enable-wg"
)
func applyMultiplayerConnectMode(cmd *cobra.Command) error {
if cmd == nil {
transport.SetMultiplayerConnectMode(transport.MultiplayerConnectAuto)
transport.SetMultiplayerConnectMode(transport.MultiplayerConnectDirect)
return nil
}
requireWG, err := cmd.Flags().GetBool(requireWGFlag)
enableWG, err := cmd.Flags().GetBool(enableWGFlag)
if err != nil {
return err
}
disableWG, err := cmd.Flags().GetBool(disableWGFlag)
if err != nil {
return err
}
if requireWG && disableWG {
return fmt.Errorf("--%s and --%s cannot be used together", requireWGFlag, disableWGFlag)
}
mode := transport.MultiplayerConnectAuto
switch {
case requireWG:
mode = transport.MultiplayerConnectRequireWG
case disableWG:
mode = transport.MultiplayerConnectDisableWG
mode := transport.MultiplayerConnectDirect
if enableWG {
mode = transport.MultiplayerConnectEnableWG
}
transport.SetMultiplayerConnectMode(mode)
return nil
+131 -39
View File
@@ -1,17 +1,40 @@
package ai
/*
Sliver Implant Framework
Copyright (C) 2026 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"fmt"
"os"
"strings"
"time"
tea "charm.land/bubbletea/v2"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/client/termio"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/charmbracelet/colorprofile"
"github.com/spf13/cobra"
"golang.org/x/term"
)
var openAIProgramTTY = tea.OpenTTY
// AICmd launches the AI conversation TUI.
func AICmd(_ *cobra.Command, con *console.SliverClient, _ []string) {
if con == nil || con.Rpc == nil {
@@ -23,6 +46,8 @@ func AICmd(_ *cobra.Command, con *console.SliverClient, _ []string) {
listenerID, listener := con.CreateEventListener()
defer con.RemoveEventListener(listenerID)
restoreEventNotifications := con.SuppressEventNotifications()
defer restoreEventNotifications()
model := newAIModel(con, buildAIContext(con), listener)
model.showExperimentalWarningModal()
@@ -32,16 +57,61 @@ func AICmd(_ *cobra.Command, con *console.SliverClient, _ []string) {
width, height = w, h
}
program := tea.NewProgram(
model,
opts := []tea.ProgramOption{
tea.WithWindowSize(width, height),
tea.WithColorProfile(colorprofile.TrueColor),
)
}
ttyOpts, cleanup := configureAIProgramTTY()
if cleanup != nil {
defer cleanup()
}
opts = append(opts, ttyOpts...)
program := tea.NewProgram(model, opts...)
if _, err := program.Run(); err != nil {
con.PrintErrorf("AI TUI error: %s\n", err)
}
}
// Console logging can swap stdout/stderr to pipes so session output can be tee'd
// to disk. Bubble Tea needs a real TTY output to enable terminal features like
// mouse reporting, so bind the AI TUI back to the interactive terminal when
// stdout is no longer the controlling TTY.
func configureAIProgramTTY() ([]tea.ProgramOption, func()) {
stdinTTY := isAITTY(os.Stdin)
stdoutTTY := isAITTY(os.Stdout)
switch {
case !stdinTTY || stdoutTTY:
return nil, nil
case isAITTY(termio.InteractiveInput()) && isAITTY(termio.InteractiveOutput()):
return []tea.ProgramOption{
tea.WithInput(termio.InteractiveInput()),
tea.WithOutput(termio.InteractiveOutput()),
}, nil
default:
inTTY, outTTY, err := openAIProgramTTY()
if err != nil {
return nil, nil
}
return []tea.ProgramOption{
tea.WithInput(inTTY),
tea.WithOutput(outTTY),
}, func() {
_ = inTTY.Close()
if outTTY != inTTY {
_ = outTTY.Close()
}
}
}
}
func isAITTY(file *os.File) bool {
return file != nil && term.IsTerminal(int(file.Fd()))
}
type aiContext struct {
target aiTargetSummary
connection aiConnectionSummary
@@ -67,16 +137,64 @@ type aiConnectionSummary struct {
State string
}
func defaultAITargetSummary() aiTargetSummary {
return aiTargetSummary{
Label: "No active target",
Host: "Select a session or beacon with `use` or ctrl+s",
Mode: "offline preview",
C2: "n/a",
OS: "unknown",
Arch: "unknown",
}
}
func aiSessionTargetSummary(session *clientpb.Session) aiTargetSummary {
if session == nil {
return defaultAITargetSummary()
}
return aiTargetSummary{
SessionID: session.ID,
Label: fmt.Sprintf("Session %s", fallback(session.Name, session.ID)),
Host: fallback(session.Hostname, "<unknown host>"),
OS: fallback(session.OS, "unknown"),
Arch: fallback(session.Arch, "unknown"),
C2: fallback(session.ActiveC2, "unknown"),
Mode: "interactive session",
Details: []string{
fmt.Sprintf("User: %s", fallback(session.Username, "<unknown>")),
fmt.Sprintf("PID: %d", session.PID),
fmt.Sprintf("Remote: %s", fallback(session.RemoteAddress, "<unknown>")),
},
}
}
func aiBeaconTargetSummary(beacon *clientpb.Beacon) aiTargetSummary {
if beacon == nil {
return defaultAITargetSummary()
}
return aiTargetSummary{
BeaconID: beacon.ID,
Label: fmt.Sprintf("Beacon %s", fallback(beacon.Name, beacon.ID)),
Host: fallback(beacon.Hostname, "<unknown host>"),
OS: fallback(beacon.OS, "unknown"),
Arch: fallback(beacon.Arch, "unknown"),
C2: fallback(beacon.ActiveC2, "unknown"),
Mode: "asynchronous beacon",
Details: []string{
fmt.Sprintf("User: %s", fallback(beacon.Username, "<unknown>")),
fmt.Sprintf("PID: %d", beacon.PID),
fmt.Sprintf("Remote: %s", fallback(beacon.RemoteAddress, "<unknown>")),
fmt.Sprintf("Interval: %s", time.Duration(beacon.Interval).String()),
fmt.Sprintf("Next checkin: %s", formatUnix(beacon.NextCheckin)),
},
}
}
func buildAIContext(con *console.SliverClient) aiContext {
ctx := aiContext{
target: aiTargetSummary{
Label: "No active target",
Host: "Select a session or beacon with `use`",
Mode: "offline preview",
C2: "n/a",
OS: "unknown",
Arch: "unknown",
},
target: defaultAITargetSummary(),
connection: aiConnectionSummary{
Profile: "<disconnected>",
Server: "<unknown>",
@@ -99,35 +217,9 @@ func buildAIContext(con *console.SliverClient) aiContext {
session, beacon := con.ActiveTarget.Get()
switch {
case session != nil:
ctx.target = aiTargetSummary{
SessionID: session.ID,
Label: fmt.Sprintf("Session %s", fallback(session.Name, session.ID)),
Host: fallback(session.Hostname, "<unknown host>"),
OS: fallback(session.OS, "unknown"),
Arch: fallback(session.Arch, "unknown"),
C2: fallback(session.ActiveC2, "unknown"),
Mode: "interactive session",
Details: []string{
fmt.Sprintf("User: %s", fallback(session.Username, "<unknown>")),
fmt.Sprintf("PID: %d", session.PID),
fmt.Sprintf("Remote: %s", fallback(session.RemoteAddress, "<unknown>")),
},
}
ctx.target = aiSessionTargetSummary(session)
case beacon != nil:
ctx.target = aiTargetSummary{
BeaconID: beacon.ID,
Label: fmt.Sprintf("Beacon %s", fallback(beacon.Name, beacon.ID)),
Host: fallback(beacon.Hostname, "<unknown host>"),
OS: fallback(beacon.OS, "unknown"),
Arch: fallback(beacon.Arch, "unknown"),
C2: fallback(beacon.ActiveC2, "unknown"),
Mode: "asynchronous beacon",
Details: []string{
fmt.Sprintf("User: %s", fallback(beacon.Username, "<unknown>")),
fmt.Sprintf("Interval: %s", time.Duration(beacon.Interval).String()),
fmt.Sprintf("Next checkin: %s", formatUnix(beacon.NextCheckin)),
},
}
ctx.target = aiBeaconTargetSummary(beacon)
}
}
+18
View File
@@ -1,5 +1,23 @@
package ai
/*
Sliver Implant Framework
Copyright (C) 2026 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
+83 -11
View File
@@ -1,5 +1,23 @@
package ai
/*
Sliver Implant Framework
Copyright (C) 2026 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"context"
"net"
@@ -87,24 +105,27 @@ func TestLoadAIStateCmdCreatesConversationWhenNoneExist(t *testing.T) {
providersResp: &clientpb.AIProviderConfigs{
Providers: []*clientpb.AIProviderConfig{{Name: "openai", Configured: true}},
Config: &clientpb.AIConfigSummary{
Provider: "openai",
Model: "gpt-test",
Valid: true,
Provider: "openai",
Model: "gpt-test",
SystemPrompt: "Stay concise.",
Valid: true,
},
},
conversationsResp: &clientpb.AIConversations{},
saveConversationResp: &clientpb.AIConversation{
ID: "conv-created",
Provider: "openai",
Model: "gpt-test",
Title: "New conversation",
ID: "conv-created",
Provider: "openai",
Model: "gpt-test",
Title: "New conversation",
SystemPrompt: "Stay concise.",
},
conversationByID: map[string]*clientpb.AIConversation{
"conv-created": {
ID: "conv-created",
Provider: "openai",
Model: "gpt-test",
Title: "New conversation",
ID: "conv-created",
Provider: "openai",
Model: "gpt-test",
Title: "New conversation",
SystemPrompt: "Stay concise.",
},
},
}
@@ -134,6 +155,9 @@ func TestLoadAIStateCmdCreatesConversationWhenNoneExist(t *testing.T) {
if request.GetProvider() != "openai" || request.GetModel() != "gpt-test" || request.GetTitle() != "New conversation" {
t.Fatalf("unexpected SaveAIConversation request: %+v", request)
}
if request.GetSystemPrompt() != "Stay concise." {
t.Fatalf("unexpected SaveAIConversation system prompt: %q", request.GetSystemPrompt())
}
}
func TestSubmitPromptCmdCreatesConversationAndSavesUserMessage(t *testing.T) {
@@ -161,6 +185,7 @@ func TestSubmitPromptCmdCreatesConversationAndSavesUserMessage(t *testing.T) {
nil,
"openai",
"gpt-test",
"Stay concise.",
"Explain the workflow.\n\nWith details.",
)()
@@ -183,6 +208,9 @@ func TestSubmitPromptCmdCreatesConversationAndSavesUserMessage(t *testing.T) {
if server.saveConversationReqs[0].GetTargetSessionID() != "session-1" {
t.Fatalf("expected target session to be forwarded, got %+v", server.saveConversationReqs[0])
}
if server.saveConversationReqs[0].GetSystemPrompt() != "Stay concise." {
t.Fatalf("unexpected conversation system prompt: %q", server.saveConversationReqs[0].GetSystemPrompt())
}
if len(server.saveMessageReqs) != 1 {
t.Fatalf("expected SaveAIConversationMessage to be called once, got %d", len(server.saveMessageReqs))
}
@@ -214,6 +242,7 @@ func TestSubmitPromptCmdUsesExistingConversationSettings(t *testing.T) {
&clientpb.AIConversation{ID: "conv-1", Provider: "anthropic", Model: "claude-test", Title: "Thread"},
"openai",
"gpt-test",
"Stay concise.",
"hello",
)()
@@ -294,6 +323,25 @@ func TestWaitForAIConversationEventCmdFiltersForAIEvents(t *testing.T) {
}
}
func TestWaitForAIConversationEventCmdReturnsToastMessages(t *testing.T) {
listener := make(chan *clientpb.Event, 1)
listener <- &clientpb.Event{
EventType: consts.ClientToastEvent,
Data: []byte("Session alpha connected"),
Err: "info",
}
msg := waitForAIConversationEventCmd(listener)()
toast, ok := msg.(aiToastMsg)
if !ok {
t.Fatalf("expected aiToastMsg, got %T", msg)
}
if toast.level != "info" || toast.message != "Session alpha connected" {
t.Fatalf("unexpected toast payload: %+v", toast)
}
}
func TestWaitForAIConversationEventCmdReturnsClosedMessage(t *testing.T) {
listener := make(chan *clientpb.Event)
close(listener)
@@ -391,9 +439,13 @@ type aiRPCServer struct {
conversationByID map[string]*clientpb.AIConversation
saveConversationResp *clientpb.AIConversation
saveMessageResp *clientpb.AIConversationMessage
sessionsResp *clientpb.Sessions
beaconsResp *clientpb.Beacons
getProvidersCalls int
getConversationsCalls int
getSessionsCalls int
getBeaconsCalls int
getConversationReqs []*clientpb.AIConversationReq
deleteConversationReqs []*clientpb.AIConversationReq
saveConversationReqs []*clientpb.AIConversation
@@ -424,6 +476,26 @@ func (s *aiRPCServer) GetAIConversations(context.Context, *commonpb.Empty) (*cli
return proto.Clone(s.conversationsResp).(*clientpb.AIConversations), nil
}
func (s *aiRPCServer) GetSessions(context.Context, *commonpb.Empty) (*clientpb.Sessions, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.getSessionsCalls++
if s.sessionsResp == nil {
return &clientpb.Sessions{}, nil
}
return proto.Clone(s.sessionsResp).(*clientpb.Sessions), nil
}
func (s *aiRPCServer) GetBeacons(context.Context, *commonpb.Empty) (*clientpb.Beacons, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.getBeaconsCalls++
if s.beaconsResp == nil {
return &clientpb.Beacons{}, nil
}
return proto.Clone(s.beaconsResp).(*clientpb.Beacons), nil
}
func (s *aiRPCServer) GetAIConversation(_ context.Context, req *clientpb.AIConversationReq) (*clientpb.AIConversation, error) {
s.mu.Lock()
defer s.mu.Unlock()
+2006 -172
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -164,7 +164,7 @@ func ArmoryCmd(cmd *cobra.Command, con *console.SliverClient, args []string) {
cacheEntry, ok := value.(pkgCacheEntry)
if !ok {
// Something is wrong with this entry
pkgCache.Delete(value)
pkgCache.Delete(key)
return true
}
if cacheEntry.ArmoryConfig.PublicKey != index.ArmoryConfig.PublicKey {
+18
View File
@@ -1,5 +1,23 @@
package armory
/*
Sliver Implant Framework
Copyright (C) 2026 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
+18
View File
@@ -1,5 +1,23 @@
package armory
/*
Sliver Implant Framework
Copyright (C) 2026 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"fmt"
"os"
+84 -17
View File
@@ -46,6 +46,9 @@ func (con *SliverClient) SetConnection(rpc rpcpb.SliverRPCClient, grpcConn *grpc
con.Rpc = rpc
con.grpcConn = grpcConn
con.connDetails = details
con.backgroundRPC = nil
con.backgroundConn = nil
con.backgroundDedicated = false
if con.Rpc == nil || con.grpcConn == nil {
return nil
@@ -58,31 +61,49 @@ func (con *SliverClient) SetConnection(rpc rpcpb.SliverRPCClient, grpcConn *grpc
con.BeaconTaskCallbacksMutex.Unlock()
con.ActiveTarget.Set(nil, nil)
if details != nil && details.Config != nil && details.Config.WG != nil {
con.backgroundDedicated = true
commandRPC, commandConn, err := transport.MTLSConnect(details.Config)
if err != nil {
log.Printf("Dedicated command WireGuard connection unavailable, async console streams disabled to preserve command reliability: %v", err)
} else {
con.backgroundRPC = con.Rpc
con.backgroundConn = con.grpcConn
con.Rpc = commandRPC
con.grpcConn = commandConn
}
}
ctx, cancel := context.WithCancel(context.Background())
con.connCancel = cancel
wg := &sync.WaitGroup{}
con.connWg = wg
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
con.startEventLoop(ctx)
}(wg)
backgroundRPC := con.backgroundRPCClientLocked()
if backgroundRPC != nil {
wg.Add(1)
go func(wg *sync.WaitGroup, rpc rpcpb.SliverRPCClient) {
defer wg.Done()
con.startEventLoop(ctx, rpc)
}(wg, backgroundRPC)
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
if err := core.TunnelLoop(ctx, con.Rpc); err != nil && !errors.Is(err, context.Canceled) {
log.Printf("TunnelLoop error: %v", err)
}
}(wg)
wg.Add(1)
go func(wg *sync.WaitGroup, rpc rpcpb.SliverRPCClient) {
defer wg.Done()
if err := core.TunnelLoop(ctx, rpc); err != nil && !errors.Is(err, context.Canceled) {
log.Printf("TunnelLoop error: %v", err)
}
}(wg, backgroundRPC)
}
wg.Add(1)
go func(wg *sync.WaitGroup, conn *grpc.ClientConn) {
defer wg.Done()
con.monitorConnectionLost(ctx, conn)
}(wg, con.grpcConn)
if !con.backgroundDedicated || con.backgroundConn == nil {
wg.Add(1)
go func(wg *sync.WaitGroup, conn *grpc.ClientConn) {
defer wg.Done()
con.monitorConnectionLost(ctx, conn)
}(wg, con.grpcConn)
}
con.refreshRemoteLogStreamsLocked()
@@ -127,13 +148,59 @@ func (con *SliverClient) detachConnectionLocked() {
_ = transport.CloseGRPCConnection(con.grpcConn)
con.grpcConn = nil
}
if con.backgroundConn != nil {
_ = transport.CloseGRPCConnection(con.backgroundConn)
con.backgroundConn = nil
}
con.Rpc = nil
con.backgroundRPC = nil
con.backgroundDedicated = false
con.connDetails = nil
// Tear down any singleton network tooling that was tied to the previous server.
core.ResetClientState()
}
func (con *SliverClient) backgroundRPCClientLocked() rpcpb.SliverRPCClient {
if con.backgroundRPC != nil {
return con.backgroundRPC
}
if con.backgroundDedicated {
return nil
}
return con.Rpc
}
func (con *SliverClient) refreshDedicatedCommandConnectionHook(args []string) ([]string, error) {
if err := con.refreshDedicatedCommandConnection(); err != nil {
return args, err
}
return args, nil
}
func (con *SliverClient) refreshDedicatedCommandConnection() error {
con.connMu.Lock()
defer con.connMu.Unlock()
if !con.backgroundDedicated || con.backgroundConn == nil || con.connDetails == nil || con.connDetails.Config == nil {
return nil
}
rpc, conn, err := transport.MTLSConnect(con.connDetails.Config)
if err != nil {
return fmt.Errorf("refresh command connection: %w", err)
}
oldConn := con.grpcConn
con.Rpc = rpc
con.grpcConn = conn
if oldConn != nil {
_ = transport.CloseGRPCConnection(oldConn)
}
return nil
}
func (con *SliverClient) monitorConnectionLost(ctx context.Context, conn *grpc.ClientConn) {
if conn == nil {
return
+108 -14
View File
@@ -29,6 +29,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bishopfox/sliver/client/assets"
@@ -94,11 +95,15 @@ type SliverClient struct {
connMu sync.Mutex
grpcConn *grpc.ClientConn
backgroundRPC rpcpb.SliverRPCClient
backgroundConn *grpc.ClientConn
backgroundDedicated bool
connDetails *ConnectionDetails
connCancel context.CancelFunc
connWg *sync.WaitGroup
connectionHooksApplied bool
logCommandHookApplied bool
suppressedEventNotifs atomic.Int32
// These writers are always safe to use (never error); the underlying stream
// can be swapped on server switch to avoid breaking io.MultiWriter/io.Copy.
@@ -324,6 +329,7 @@ func (con *SliverClient) applyConnectionHooksOnce() {
con.App.PreReadlineHooks = append(con.App.PreReadlineHooks, con.syncOutputHook)
con.App.PostCmdRunHooks = append(con.App.PostCmdRunHooks, con.syncOutputHook)
con.App.PreCmdRunLineHooks = append(con.App.PreCmdRunLineHooks, con.refreshDedicatedCommandConnectionHook)
con.App.PreCmdRunLineHooks = append(con.App.PreCmdRunLineHooks, con.allowServerRootCommands)
if shell := con.App.Shell(); shell != nil && shell.Completer != nil {
baseCompleter := shell.Completer
@@ -334,8 +340,12 @@ func (con *SliverClient) applyConnectionHooksOnce() {
}
}
func (con *SliverClient) startEventLoop(ctx context.Context) {
eventStream, err := con.Rpc.Events(ctx, &commonpb.Empty{})
func (con *SliverClient) startEventLoop(ctx context.Context, rpc rpcpb.SliverRPCClient) {
if rpc == nil {
return
}
eventStream, err := rpc.Events(ctx, &commonpb.Empty{})
if err != nil {
fmt.Printf("%s%s\n", Warn, err)
return
@@ -352,8 +362,20 @@ func (con *SliverClient) startEventLoop(ctx context.Context) {
switch event.EventType {
case consts.CanaryEvent:
con.PrintEventErrorf("%s %s has been burned (DNS Canary)", StyleBold.Render("WARNING:"), event.Session.Name)
sessions := con.GetSessionsByName(event.Session.Name)
if con.eventNotificationsSuppressed() {
affected := make([]string, 0, len(sessions))
for _, session := range sessions {
affected = append(affected, strings.Split(session.ID, "-")[0])
}
message := fmt.Sprintf("%s %s has been burned (DNS Canary)", StyleBold.Render("WARNING:"), event.Session.Name)
if len(affected) > 0 {
message += " Affected sessions: " + strings.Join(affected, ", ")
}
con.emitToastEvent("error", message)
break
}
con.PrintEventErrorf("%s %s has been burned (DNS Canary)", StyleBold.Render("WARNING:"), event.Session.Name)
for _, session := range sessions {
shortID := strings.Split(session.ID, "-")[0]
con.PrintErrorf("\t🔥 Session %s is affected", shortID)
@@ -361,8 +383,20 @@ func (con *SliverClient) startEventLoop(ctx context.Context) {
case consts.WatchtowerEvent:
msg := string(event.Data)
con.PrintEventErrorf("%s %s has been burned (seen on %s)", StyleBold.Render("WARNING:"), event.Session.Name, msg)
sessions := con.GetSessionsByName(event.Session.Name)
if con.eventNotificationsSuppressed() {
affected := make([]string, 0, len(sessions))
for _, session := range sessions {
affected = append(affected, strings.Split(session.ID, "-")[0])
}
message := fmt.Sprintf("%s %s has been burned (seen on %s)", StyleBold.Render("WARNING:"), event.Session.Name, msg)
if len(affected) > 0 {
message += " Affected sessions: " + strings.Join(affected, ", ")
}
con.emitToastEvent("error", message)
break
}
con.PrintEventErrorf("%s %s has been burned (seen on %s)", StyleBold.Render("WARNING:"), event.Session.Name, msg)
for _, session := range sessions {
shortID := strings.Split(session.ID, "-")[0]
con.PrintErrorf("\t🔥 Session %s is affected", shortID)
@@ -370,42 +404,42 @@ func (con *SliverClient) startEventLoop(ctx context.Context) {
case consts.JoinedEvent:
if con.Settings.UserConnect {
con.PrintInfof("%s has joined the game", event.Client.Operator.Name)
con.emitConsoleNotification("info", false, "%s has joined the game", event.Client.Operator.Name)
}
case consts.LeftEvent:
if con.Settings.UserConnect {
con.PrintInfof("%s left the game", event.Client.Operator.Name)
con.emitConsoleNotification("info", false, "%s left the game", event.Client.Operator.Name)
}
case consts.JobStoppedEvent:
job := event.Job
con.PrintErrorf("Job #%d stopped (%s/%s)", job.ID, job.Protocol, job.Name)
con.emitConsoleNotification("error", false, "Job #%d stopped (%s/%s)", job.ID, job.Protocol, job.Name)
case consts.SessionOpenedEvent:
session := event.Session
currentTime := time.Now().Format(time.RFC1123)
shortID := strings.Split(session.ID, "-")[0]
con.PrintEventInfof("Session %s %s - %s (%s) - %s/%s - %v",
con.emitConsoleNotification("info", true, "Session %s %s - %s (%s) - %s/%s - %v",
shortID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch, currentTime)
case consts.SessionUpdateEvent:
session := event.Session
currentTime := time.Now().Format(time.RFC1123)
shortID := strings.Split(session.ID, "-")[0]
con.PrintInfof("Session %s has been updated - %v", shortID, currentTime)
con.emitConsoleNotification("info", false, "Session %s has been updated - %v", shortID, currentTime)
case consts.SessionClosedEvent:
session := event.Session
currentTime := time.Now().Format(time.RFC1123)
shortID := strings.Split(session.ID, "-")[0]
con.PrintEventErrorf("Lost session %s %s - %s (%s) - %s/%s - %v",
con.emitConsoleNotification("error", true, "Lost session %s %s - %s (%s) - %s/%s - %v",
shortID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch, currentTime)
activeSession := con.ActiveTarget.GetSession()
core.GetTunnels().CloseForSession(session.ID)
core.CloseCursedProcesses(session.ID)
if activeSession != nil && activeSession.ID == session.ID {
con.ActiveTarget.Set(nil, nil)
con.PrintErrorf("Active session disconnected")
con.emitConsoleNotification("error", false, "Active session disconnected")
}
case consts.BeaconRegisteredEvent:
@@ -413,7 +447,7 @@ func (con *SliverClient) startEventLoop(ctx context.Context) {
proto.Unmarshal(event.Data, beacon)
currentTime := time.Now().Format(time.RFC1123)
shortID := strings.Split(beacon.ID, "-")[0]
con.PrintEventInfof("Beacon %s %s - %s (%s) - %s/%s - %v",
con.emitConsoleNotification("info", true, "Beacon %s %s - %s (%s) - %s/%s - %v",
shortID, beacon.Name, beacon.RemoteAddress, beacon.Hostname, beacon.OS, beacon.Arch, currentTime)
case consts.BeaconTaskResultEvent:
@@ -433,6 +467,66 @@ func (con *SliverClient) CreateEventListener() (string, <-chan *clientpb.Event)
return listenerID.String(), listener
}
// SuppressEventNotifications redirects console event messages to local listeners instead of stdout.
func (con *SliverClient) SuppressEventNotifications() func() {
if con == nil {
return func() {}
}
con.suppressedEventNotifs.Add(1)
return func() {
if con == nil {
return
}
if con.suppressedEventNotifs.Add(-1) < 0 {
con.suppressedEventNotifs.Store(0)
}
}
}
func (con *SliverClient) eventNotificationsSuppressed() bool {
return con != nil && con.suppressedEventNotifs.Load() > 0
}
func (con *SliverClient) emitToastEvent(level string, message string) {
if con == nil || con.EventListeners == nil || strings.TrimSpace(message) == "" {
return
}
con.triggerEventListeners(&clientpb.Event{
EventType: consts.ClientToastEvent,
Data: []byte(message),
Err: strings.TrimSpace(level),
})
}
func (con *SliverClient) emitConsoleNotification(level string, emphasized bool, format string, args ...any) {
message := fmt.Sprintf(format, args...)
if con.eventNotificationsSuppressed() {
con.emitToastEvent(level, message)
return
}
switch strings.ToLower(strings.TrimSpace(level)) {
case "error", "warn", "warning":
if emphasized {
con.PrintEventErrorf("%s", message)
} else {
con.PrintErrorf("%s", message)
}
case "success":
if emphasized {
con.PrintEventSuccessf("%s", message)
} else {
con.PrintSuccessf("%s", message)
}
default:
if emphasized {
con.PrintEventInfof("%s", message)
} else {
con.PrintInfof("%s", message)
}
}
}
// RemoveEventListener - removes an event listener given its id.
func (con *SliverClient) RemoveEventListener(listenerID string) {
value, ok := con.EventListeners.LoadAndDelete(listenerID)
@@ -477,10 +571,10 @@ func (con *SliverClient) triggerReactions(event *clientpb.Event) {
for _, reaction := range reactions {
for _, line := range reaction.Commands {
con.PrintInfof("%s '%s'", StyleBold.Render("Execute reaction:"), line)
con.emitConsoleNotification("info", false, "%s '%s'", StyleBold.Render("Execute reaction:"), line)
err := con.App.ActiveMenu().RunCommandLine(context.Background(), line)
if err != nil {
con.PrintErrorf("Reaction command error: %s\n", err)
con.emitConsoleNotification("error", false, "Reaction command error: %s", err)
}
}
}
+15 -4
View File
@@ -107,7 +107,8 @@ func (con *SliverClient) refreshRemoteLogStreamsLocked() {
if con.jsonRemoteWriter == nil && con.asciicastRemoteWriter == nil {
return
}
if con.Rpc == nil {
rpc := con.backgroundRPCClientLocked()
if rpc == nil {
con.setRemoteLogStreamsLocked(nil, nil)
return
}
@@ -116,7 +117,7 @@ func (con *SliverClient) refreshRemoteLogStreamsLocked() {
var asciicastStream *ConsoleClientLogger
if con.jsonRemoteWriter != nil {
s, err := con.ClientLogStream("json")
s, err := con.clientLogStream(rpc, "json")
if err != nil {
log.Printf("Could not get client json log stream: %s", err)
} else {
@@ -124,7 +125,7 @@ func (con *SliverClient) refreshRemoteLogStreamsLocked() {
}
}
if con.asciicastRemoteWriter != nil {
s, err := con.ClientLogStream("asciicast")
s, err := con.clientLogStream(rpc, "asciicast")
if err != nil {
log.Printf("Could not get client asciicast log stream: %s", err)
} else {
@@ -166,7 +167,17 @@ func (con *SliverClient) setRemoteLogStreamsLocked(jsonStream, asciicastStream *
// ClientLogStream requires a log stream name, used to save the logs
// going through this stream in a specific log subdirectory/file.
func (con *SliverClient) ClientLogStream(name string) (*ConsoleClientLogger, error) {
stream, err := con.Rpc.ClientLog(context.Background())
con.connMu.Lock()
rpc := con.backgroundRPCClientLocked()
con.connMu.Unlock()
if rpc == nil {
return nil, fmt.Errorf("no RPC connection available for client log stream %q", name)
}
return con.clientLogStream(rpc, name)
}
func (con *SliverClient) clientLogStream(rpc rpcpb.SliverRPCClient, name string) (*ConsoleClientLogger, error) {
stream, err := rpc.ClientLog(context.Background())
if err != nil {
return nil, err
}
+33
View File
@@ -3,8 +3,11 @@ package console
import (
"bytes"
"os"
"sync"
"testing"
"time"
consts "github.com/bishopfox/sliver/client/constants"
)
func TestDrainStdoutPipeBufferStripsSyncFrames(t *testing.T) {
@@ -102,3 +105,33 @@ func TestSyncOutputWaitsForPipeDrain(t *testing.T) {
t.Fatalf("unexpected final output %q", got.String())
}
}
func TestSuppressEventNotificationsRedirectsMessagesToListeners(t *testing.T) {
con := &SliverClient{
EventListeners: &sync.Map{},
printf: func(string, ...any) (int, error) { return 0, nil },
}
listenerID, listener := con.CreateEventListener()
defer con.RemoveEventListener(listenerID)
restore := con.SuppressEventNotifications()
defer restore()
con.emitConsoleNotification("info", true, "Session %s connected", "alpha")
select {
case event := <-listener:
if event.GetEventType() != consts.ClientToastEvent {
t.Fatalf("expected toast event, got %q", event.GetEventType())
}
if got := string(event.GetData()); got != "Session alpha connected" {
t.Fatalf("unexpected toast payload %q", got)
}
if got := event.GetErr(); got != "info" {
t.Fatalf("unexpected toast level %q", got)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for redirected event notification")
}
}
+3
View File
@@ -119,6 +119,9 @@ const (
// AIConversationEvent - Fires whenever an AI conversation or message changes.
AIConversationEvent = "ai-conversation"
// ClientToastEvent - Local-only event used to surface console notifications inside TUIs.
ClientToastEvent = "client-toast"
)
// Commands.
+4 -5
View File
@@ -11,9 +11,8 @@ import (
type MultiplayerConnectMode int
const (
MultiplayerConnectAuto MultiplayerConnectMode = iota
MultiplayerConnectDisableWG
MultiplayerConnectRequireWG
MultiplayerConnectDirect MultiplayerConnectMode = iota
MultiplayerConnectEnableWG
)
type connectionCloser interface {
@@ -22,7 +21,7 @@ type connectionCloser interface {
var (
multiplayerConnectModeMu sync.RWMutex
multiplayerConnectMode = MultiplayerConnectAuto
multiplayerConnectMode = MultiplayerConnectDirect
connClosers sync.Map // *grpc.ClientConn -> connectionCloser
)
@@ -65,9 +64,9 @@ func CloseGRPCConnection(conn *grpc.ClientConn) error {
}
var errs []error
errs = append(errs, conn.Close())
if closer := unregisterConnCloser(conn); closer != nil {
errs = append(errs, closer.Close())
}
errs = append(errs, conn.Close())
return errors.Join(errs...)
}
+27 -13
View File
@@ -58,6 +58,15 @@ const (
multiplayerDialWireGuard
)
const (
connectStatusGRPCMTLS = "grpc/mtls"
connectStatusWireGuard = "wireguard"
connectStatusGRPCMTLSOverWireGuard = "grpc/mtls over wireguard"
)
// ConnectStatusFn receives human-readable connection phase updates.
type ConnectStatusFn func(string)
// Return value is mapped to request headers.
func (t TokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
return map[string]string{
@@ -71,6 +80,12 @@ func (TokenAuth) RequireTransportSecurity() bool {
// MTLSConnect - Connect to the sliver server
func MTLSConnect(config *assets.ClientConfig) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
return MTLSConnectWithStatus(config, nil)
}
// MTLSConnectWithStatus connects to the sliver server and optionally reports
// transport phase updates, such as WireGuard setup and gRPC dialing.
func MTLSConnectWithStatus(config *assets.ClientConfig, statusFn ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
strategy, err := selectMultiplayerDialStrategy(config)
if err != nil {
return nil, nil, err
@@ -78,9 +93,9 @@ func MTLSConnect(config *assets.ClientConfig) (rpcpb.SliverRPCClient, *grpc.Clie
switch strategy {
case multiplayerDialWireGuard:
return wireGuardMTLSConnect(config)
return wireGuardMTLSConnect(config, statusFn)
default:
return directMTLSConnect(config)
return directMTLSConnect(config, statusFn)
}
}
@@ -90,25 +105,18 @@ func selectMultiplayerDialStrategy(config *assets.ClientConfig) (multiplayerDial
}
switch getMultiplayerConnectMode() {
case MultiplayerConnectDisableWG:
return multiplayerDialDirect, nil
case MultiplayerConnectRequireWG:
case MultiplayerConnectEnableWG:
if err := validateWireGuardConfig(config); err != nil {
return multiplayerDialDirect, err
}
return multiplayerDialWireGuard, nil
default:
if config.WG == nil {
return multiplayerDialDirect, nil
}
if err := validateWireGuardConfig(config); err != nil {
return multiplayerDialDirect, err
}
return multiplayerDialWireGuard, nil
return multiplayerDialDirect, nil
}
}
func directMTLSConnect(config *assets.ClientConfig) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
func directMTLSConnect(config *assets.ClientConfig, statusFn ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
notifyConnectStatus(statusFn, connectStatusGRPCMTLS)
options, err := newMTLSDialOptions(config)
if err != nil {
return nil, nil, err
@@ -116,6 +124,12 @@ func directMTLSConnect(config *assets.ClientConfig) (rpcpb.SliverRPCClient, *grp
return dialRPCClient(fmt.Sprintf("%s:%d", config.LHost, config.LPort), options, nil)
}
func notifyConnectStatus(statusFn ConnectStatusFn, status string) {
if statusFn != nil {
statusFn(status)
}
}
func newMTLSDialOptions(config *assets.ClientConfig) ([]grpc.DialOption, error) {
tlsConfig, err := getTLSConfig(config.CACertificate, config.Certificate, config.PrivateKey)
if err != nil {
+56 -10
View File
@@ -5,10 +5,13 @@ import (
"testing"
"github.com/bishopfox/sliver/client/assets"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
)
func TestSelectMultiplayerDialStrategyLegacyConfigUsesDirectMTLS(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectAuto)
setTestMultiplayerConnectMode(t, MultiplayerConnectDirect)
strategy, err := selectMultiplayerDialStrategy(&assets.ClientConfig{})
if err != nil {
@@ -19,8 +22,25 @@ func TestSelectMultiplayerDialStrategyLegacyConfigUsesDirectMTLS(t *testing.T) {
}
}
func TestSelectMultiplayerDialStrategyRequireWGRejectsMissingWGConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectRequireWG)
func TestSelectMultiplayerDialStrategyDefaultIgnoresIncompleteWGConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectDirect)
strategy, err := selectMultiplayerDialStrategy(&assets.ClientConfig{
WG: &assets.ClientWGConfig{
ServerPubKey: "server-pub",
ClientIP: "100.64.0.2",
},
})
if err != nil {
t.Fatalf("select dial strategy: %v", err)
}
if strategy != multiplayerDialDirect {
t.Fatalf("expected direct mTLS strategy, got %v", strategy)
}
}
func TestSelectMultiplayerDialStrategyEnableWGRejectsMissingWGConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectEnableWG)
_, err := selectMultiplayerDialStrategy(&assets.ClientConfig{})
if !errors.Is(err, ErrMissingWireGuardConfig) {
@@ -28,8 +48,8 @@ func TestSelectMultiplayerDialStrategyRequireWGRejectsMissingWGConfig(t *testing
}
}
func TestSelectMultiplayerDialStrategyRejectsIncompleteWGConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectAuto)
func TestSelectMultiplayerDialStrategyEnableWGRejectsIncompleteWGConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectEnableWG)
_, err := selectMultiplayerDialStrategy(&assets.ClientConfig{
WG: &assets.ClientWGConfig{
@@ -42,8 +62,8 @@ func TestSelectMultiplayerDialStrategyRejectsIncompleteWGConfig(t *testing.T) {
}
}
func TestSelectMultiplayerDialStrategyUsesWireGuardWhenConfigComplete(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectAuto)
func TestSelectMultiplayerDialStrategyEnableWGUsesWireGuardWhenConfigComplete(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectEnableWG)
strategy, err := selectMultiplayerDialStrategy(&assets.ClientConfig{
WG: &assets.ClientWGConfig{
@@ -60,8 +80,8 @@ func TestSelectMultiplayerDialStrategyUsesWireGuardWhenConfigComplete(t *testing
}
}
func TestSelectMultiplayerDialStrategyDisableWGOverridesCompleteConfig(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectDisableWG)
func TestSelectMultiplayerDialStrategyDefaultUsesDirectMTLSEvenWhenWGConfigComplete(t *testing.T) {
setTestMultiplayerConnectMode(t, MultiplayerConnectDirect)
strategy, err := selectMultiplayerDialStrategy(&assets.ClientConfig{
WG: &assets.ClientWGConfig{
@@ -74,7 +94,7 @@ func TestSelectMultiplayerDialStrategyDisableWGOverridesCompleteConfig(t *testin
t.Fatalf("select dial strategy: %v", err)
}
if strategy != multiplayerDialDirect {
t.Fatalf("expected direct strategy when WG is disabled, got %v", strategy)
t.Fatalf("expected direct strategy when WG is not explicitly enabled, got %v", strategy)
}
}
@@ -87,3 +107,29 @@ func setTestMultiplayerConnectMode(t *testing.T, mode MultiplayerConnectMode) {
SetMultiplayerConnectMode(previous)
})
}
func TestCloseGRPCConnectionClosesConnBeforeTransportCloser(t *testing.T) {
conn, err := grpc.NewClient("passthrough:///sliver-test", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("create grpc client: %v", err)
}
var stateSeen connectivity.State
registerConnCloser(conn, testConnectionCloser(func() error {
stateSeen = conn.GetState()
return nil
}))
if err := CloseGRPCConnection(conn); err != nil {
t.Fatalf("close grpc connection: %v", err)
}
if stateSeen != connectivity.Shutdown {
t.Fatalf("expected transport closer to run after grpc shutdown, got state %v", stateSeen)
}
}
type testConnectionCloser func() error
func (fn testConnectionCloser) Close() error {
return fn()
}
+145 -10
View File
@@ -11,6 +11,7 @@ import (
"strconv"
"strings"
"sync"
"time"
"github.com/bishopfox/sliver/client/assets"
"github.com/bishopfox/sliver/protobuf/rpcpb"
@@ -23,11 +24,17 @@ const (
multiplayerWireGuardDefaultServerIP = "100.65.0.1"
multiplayerWireGuardMTU = 1420
multiplayerWireGuardKeepalive = 25
multiplayerWireGuardDialTimeout = 30 * time.Second
multiplayerWireGuardRetryDelay = 250 * time.Millisecond
)
var (
ErrMissingWireGuardConfig = errors.New("operator config has no wg block")
ErrIncompleteWireGuardConfig = errors.New("operator config has incomplete wg block")
multiplayerWireGuardIdleTimeout = 5 * time.Second
wireGuardTunnelCacheMu sync.Mutex
wireGuardTunnelCache = map[string]*cachedWireGuardTunnel{}
)
type wireGuardTunnel struct {
@@ -37,6 +44,19 @@ type wireGuardTunnel struct {
closeOnce sync.Once
}
type cachedWireGuardTunnel struct {
tunnel *wireGuardTunnel
target string
timer *time.Timer
}
type idleWireGuardTunnelCloser struct {
key string
tunnel *wireGuardTunnel
target string
}
func (t *wireGuardTunnel) Close() error {
if t == nil {
return nil
@@ -44,6 +64,7 @@ func (t *wireGuardTunnel) Close() error {
t.closeOnce.Do(func() {
if t.dev != nil {
t.dev.Close()
<-t.dev.Wait()
}
})
return nil
@@ -56,22 +77,136 @@ func (t *wireGuardTunnel) DialContext(ctx context.Context, address string) (net.
return t.net.DialContext(ctx, "tcp", address)
}
func wireGuardMTLSConnect(config *assets.ClientConfig) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
func (c *idleWireGuardTunnelCloser) Close() error {
if c == nil || c.key == "" || c.tunnel == nil {
return nil
}
cacheIdleWireGuardTunnel(c.key, c.tunnel, c.target)
return nil
}
func wireGuardMTLSConnect(config *assets.ClientConfig, statusFn ConnectStatusFn) (rpcpb.SliverRPCClient, *grpc.ClientConn, error) {
deadline := time.Now().Add(multiplayerWireGuardDialTimeout)
var lastErr error
attempts := 0
for {
attempts++
notifyConnectStatus(statusFn, connectStatusWireGuard)
cacheKey, tunnel, target, err := acquireWireGuardTunnel(config)
if err != nil {
return nil, nil, err
}
options, err := newMTLSDialOptions(config)
if err != nil {
_ = tunnel.Close()
return nil, nil, err
}
options = append(options, grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return tunnel.DialContext(ctx, addr)
}))
notifyConnectStatus(statusFn, connectStatusGRPCMTLSOverWireGuard)
rpcClient, conn, err := dialRPCClient(target, options, nil)
if err == nil {
registerConnCloser(conn, &idleWireGuardTunnelCloser{
key: cacheKey,
tunnel: tunnel,
target: target,
})
return rpcClient, conn, nil
}
_ = tunnel.Close()
lastErr = err
if !errors.Is(err, context.DeadlineExceeded) || !time.Now().Before(deadline) {
break
}
time.Sleep(multiplayerWireGuardRetryDelay)
}
if attempts > 1 {
return nil, nil, fmt.Errorf("wireguard multiplayer connect failed after %d attempts: %w", attempts, lastErr)
}
return nil, nil, lastErr
}
func acquireWireGuardTunnel(config *assets.ClientConfig) (string, *wireGuardTunnel, string, error) {
key, err := wireGuardTunnelCacheKey(config)
if err != nil {
return "", nil, "", err
}
wireGuardTunnelCacheMu.Lock()
if cached := wireGuardTunnelCache[key]; cached != nil && cached.tunnel != nil {
delete(wireGuardTunnelCache, key)
if cached.timer != nil {
cached.timer.Stop()
cached.timer = nil
}
tunnel := cached.tunnel
target := cached.target
wireGuardTunnelCacheMu.Unlock()
return key, tunnel, target, nil
}
wireGuardTunnelCacheMu.Unlock()
tunnel, target, err := newWireGuardTunnel(config)
if err != nil {
return nil, nil, err
return "", nil, "", err
}
return key, tunnel, target, nil
}
options, err := newMTLSDialOptions(config)
if err != nil {
_ = tunnel.Close()
return nil, nil, err
func cacheIdleWireGuardTunnel(key string, tunnel *wireGuardTunnel, target string) {
if key == "" || tunnel == nil {
return
}
options = append(options, grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return tunnel.DialContext(ctx, addr)
}))
wireGuardTunnelCacheMu.Lock()
previous := wireGuardTunnelCache[key]
cached := &cachedWireGuardTunnel{
tunnel: tunnel,
target: target,
}
wireGuardTunnelCache[key] = cached
if previous != nil && previous.timer != nil {
previous.timer.Stop()
}
cached.timer = time.AfterFunc(multiplayerWireGuardIdleTimeout, func() {
wireGuardTunnelCacheMu.Lock()
current := wireGuardTunnelCache[key]
if current != cached || current == nil {
wireGuardTunnelCacheMu.Unlock()
return
}
delete(wireGuardTunnelCache, key)
current.timer = nil
tunnel := current.tunnel
wireGuardTunnelCacheMu.Unlock()
if tunnel != nil {
_ = tunnel.Close()
}
})
wireGuardTunnelCacheMu.Unlock()
if previous != nil && previous.tunnel != nil {
_ = previous.tunnel.Close()
}
}
return dialRPCClient(target, options, tunnel)
func wireGuardTunnelCacheKey(config *assets.ClientConfig) (string, error) {
if err := validateWireGuardConfig(config); err != nil {
return "", err
}
return strings.Join([]string{
strings.TrimSpace(config.LHost),
strconv.Itoa(config.LPort),
strings.TrimSpace(config.WG.ServerPubKey),
strings.TrimSpace(config.WG.ClientPrivateKey),
strings.TrimSpace(config.WG.ClientIP),
strings.TrimSpace(config.WG.ServerIP),
}, "\x00"), nil
}
func newWireGuardTunnel(config *assets.ClientConfig) (*wireGuardTunnel, string, error) {
+44 -3
View File
@@ -38,6 +38,11 @@ type transportTun struct {
type transportNet transportTun
const (
transportTCPReceiveBufferMax = 8 << 20
transportTCPSendBufferMax = 6 << 20
)
func createTransportNetTUN(localAddresses []netip.Addr, mtu int) (tun.Device, *transportNet, error) {
n, err := rand.Int(rand.Reader, big.NewInt(0xFFFFFFFF))
if err != nil {
@@ -60,9 +65,8 @@ func createTransportNetTUN(localAddresses []netip.Addr, mtu int) (tun.Device, *t
mtu: mtu,
}
sackEnabledOpt := tcpip.TCPSACKEnabled(true)
if tcpipErr := dev.stack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt); tcpipErr != nil {
return nil, nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
if err := configureTransportTCPStack(dev.stack); err != nil {
return nil, nil, err
}
dev.notifyHandle = dev.ep.AddNotify(dev)
@@ -102,6 +106,43 @@ func createTransportNetTUN(localAddresses []netip.Addr, mtu int) (tun.Device, *t
return dev, (*transportNet)(dev), nil
}
func configureTransportTCPStack(ipstack *stack.Stack) error {
sackEnabledOpt := tcpip.TCPSACKEnabled(true)
if tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt); tcpipErr != nil {
return fmt.Errorf("could not enable TCP SACK: %v", tcpipErr)
}
tcpRecoveryOpt := tcpip.TCPRecovery(0)
if tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRecoveryOpt); tcpipErr != nil {
return fmt.Errorf("could not disable TCP RACK: %v", tcpipErr)
}
renoOpt := tcpip.CongestionControlOption("reno")
if tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &renoOpt); tcpipErr != nil {
return fmt.Errorf("could not set TCP congestion control to reno: %v", tcpipErr)
}
tcpRXBufOpt := tcpip.TCPReceiveBufferSizeRangeOption{
Min: tcp.MinBufferSize,
Default: tcp.DefaultSendBufferSize,
Max: transportTCPReceiveBufferMax,
}
if tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpRXBufOpt); tcpipErr != nil {
return fmt.Errorf("could not set TCP RX buffer size: %v", tcpipErr)
}
tcpTXBufOpt := tcpip.TCPSendBufferSizeRangeOption{
Min: tcp.MinBufferSize,
Default: tcp.DefaultReceiveBufferSize,
Max: transportTCPSendBufferMax,
}
if tcpipErr := ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &tcpTXBufOpt); tcpipErr != nil {
return fmt.Errorf("could not set TCP TX buffer size: %v", tcpipErr)
}
return nil
}
func (tun *transportTun) Name() (string, error) {
return "go", nil
}
+86
View File
@@ -0,0 +1,86 @@
package transport
import (
"testing"
"time"
"github.com/bishopfox/sliver/client/assets"
)
func TestWireGuardTunnelCacheKeyIncludesConfigMaterial(t *testing.T) {
config := &assets.ClientConfig{
LHost: "127.0.0.1",
LPort: 31337,
WG: &assets.ClientWGConfig{
ServerPubKey: "server-pub",
ClientPrivateKey: "client-priv",
ClientIP: "100.65.0.2",
ServerIP: "100.65.0.1",
},
}
key1, err := wireGuardTunnelCacheKey(config)
if err != nil {
t.Fatalf("cache key: %v", err)
}
config.WG.ClientPrivateKey = "other-client-priv"
key2, err := wireGuardTunnelCacheKey(config)
if err != nil {
t.Fatalf("cache key after config change: %v", err)
}
if key1 == key2 {
t.Fatal("expected cache key to change when wireguard config changes")
}
}
func TestCacheIdleWireGuardTunnelRemovesIdleTunnel(t *testing.T) {
resetWireGuardTunnelCacheForTest(t)
previousIdleTimeout := multiplayerWireGuardIdleTimeout
multiplayerWireGuardIdleTimeout = 10 * time.Millisecond
t.Cleanup(func() {
multiplayerWireGuardIdleTimeout = previousIdleTimeout
})
const cacheKey = "test-cache-key"
cacheIdleWireGuardTunnel(cacheKey, &wireGuardTunnel{}, "100.65.0.1:31337")
deadline := time.Now().Add(250 * time.Millisecond)
for time.Now().Before(deadline) {
wireGuardTunnelCacheMu.Lock()
_, exists := wireGuardTunnelCache[cacheKey]
wireGuardTunnelCacheMu.Unlock()
if !exists {
return
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("expected idle tunnel cache entry to be removed")
}
func resetWireGuardTunnelCacheForTest(t *testing.T) {
t.Helper()
wireGuardTunnelCacheMu.Lock()
for key, shared := range wireGuardTunnelCache {
if shared != nil && shared.timer != nil {
shared.timer.Stop()
}
delete(wireGuardTunnelCache, key)
}
wireGuardTunnelCacheMu.Unlock()
t.Cleanup(func() {
wireGuardTunnelCacheMu.Lock()
for key, shared := range wireGuardTunnelCache {
if shared != nil && shared.timer != nil {
shared.timer.Stop()
}
delete(wireGuardTunnelCache, key)
}
wireGuardTunnelCacheMu.Unlock()
})
}
+10 -7
View File
@@ -74,6 +74,7 @@ The target fields bind a conversation to the active session or beacon so server-
- `Kind`: chat, reasoning, or tool call
- `Visibility`: context or UI-only
- `IncludeInContext`: whether the block should be replayed into the provider context window
- `State`: in progress, completed, or failed
- `TurnID`
- `ItemID`
@@ -83,7 +84,7 @@ This keeps one ordered transcript table while still distinguishing chat context
### UI-Only Persistence
Reasoning and tool-call items are stored as normal conversation messages, but with `Visibility = UI_ONLY`.
Reasoning, tool-call, and intermediate assistant chat items can be stored as normal conversation messages with `Visibility = UI_ONLY`.
That gives Sliver:
@@ -91,7 +92,7 @@ That gives Sliver:
- transcript restoration after reconnect or TUI restart
- ordered replay of an entire turn, including intermediate items
At the same time, the model context builder filters out any non-context item, so the provider only receives actual user/assistant chat context.
At the same time, the model context builder keys off `IncludeInContext`, so UI visibility and provider visibility are now independent.
### Event Model
@@ -127,9 +128,10 @@ For each new user message:
4. If the runtime supports the Responses API loop, Sliver runs the agentic loop.
5. Reasoning items are persisted as completed UI-only reasoning blocks.
6. Tool calls are persisted as in-progress UI-only tool blocks, executed locally, then updated in place to completed or failed.
7. Tool outputs are fed back into the Responses API with `previous_response_id`.
8. When the model returns final assistant text, that assistant message is persisted as a normal context-visible chat item.
9. The conversation turn state is cleared with `TURN_COMPLETED`.
7. Intermediate assistant chat blocks on tool-use turns are persisted as UI-only chat items with `IncludeInContext = false`.
8. Tool outputs are fed back into the Responses API with `previous_response_id`.
9. When the model returns final assistant text, that assistant message is persisted as a normal context-visible chat item with `IncludeInContext = true`.
10. The conversation turn state is cleared with `TURN_COMPLETED`.
If anything fails:
@@ -157,10 +159,10 @@ Beacon-backed tools wait for task completion on the server before emitting the c
## Context Filtering
Only messages with:
Only chat messages with:
- `Kind = CHAT`
- `Visibility = CONTEXT`
- `IncludeInContext = true`
are included in future provider requests.
@@ -168,6 +170,7 @@ That means these items are excluded from the model context window:
- reasoning blocks
- tool call blocks
- UI-only intermediate assistant chat blocks
- failed system status blocks
This is the main rule that preserves transcript richness without degrading prompt quality.
@@ -3,8 +3,9 @@ import React from "react";
const LoadingState: React.FC = () => {
return (
<div className="flex min-h-screen w-full items-center justify-center">
<Spinner label="Loading ..." labelColor="foreground" />
<div className="flex min-h-screen w-full items-center justify-center gap-3 text-foreground">
<Spinner aria-label="Loading" />
<span>Loading...</span>
</div>
);
};
+209 -236
View File
@@ -1,7 +1,6 @@
"use client";
import { SliversIcon } from "@/components/icons/slivers";
import { useSearchContext } from "@/util/search-context";
import { Themes } from "@/util/themes";
import { faDiscord, faGithub } from "@fortawesome/free-brands-svg-icons";
import {
@@ -13,281 +12,255 @@ import {
faXmark,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Button,
Input,
Link,
Navbar,
NavbarBrand,
NavbarContent,
NavbarItem,
Tooltip,
} from "@heroui/react";
import { Button, SearchField, Tooltip } from "@heroui/react";
import { useTheme } from "next-themes";
import { useRouter } from "next/router";
import React from "react";
export type TopNavbarProps = {};
const routes = [
{ href: "/tutorials", label: "Tutorials" },
{ href: "/talks", label: "Talks" },
{ href: "/docs", label: "Docs" },
];
export default function TopNavbar(props: TopNavbarProps) {
export default function TopNavbar() {
const router = useRouter();
const search = useSearchContext();
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
const lightDarkModeIcon = React.useMemo(() => {
if (!mounted) {
return faMoon;
}
return theme === Themes.DARK ? faSun : faMoon;
}, [mounted, theme]);
const [query, setQuery] = React.useState("");
const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);
React.useEffect(() => {
setIsMobileMenuOpen(false);
}, [router.pathname]);
const activeTheme = theme || Themes.DARK;
const lightDarkModeIcon = React.useMemo(() => {
return activeTheme === Themes.DARK ? faSun : faMoon;
}, [activeTheme]);
const handleSearchSubmit = React.useCallback(() => {
if (query.trim().length === 0) {
return;
}
router.push({ pathname: "/search/", query: { search: query } });
setQuery("");
}, [query, router]);
const handleSearchSubmit = React.useCallback(
(value = query) => {
const searchQuery = value.trim();
if (searchQuery.length === 0) {
return;
}
router.push({ pathname: "/search/", query: { search: searchQuery } });
setQuery("");
setIsMobileMenuOpen(false);
},
[query, router],
);
const renderTooltip = React.useCallback(
(content: string, children: React.ReactNode) => (
<Tooltip delay={0}>
{children}
<Tooltip.Content>{content}</Tooltip.Content>
</Tooltip>
),
[],
);
const renderSearchInput = (wrapperClassName?: string) => (
<div className={wrapperClassName}>
<Tooltip content="Press enter to search" isOpen={query.length > 0}>
<Input
size="sm"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
onClear={() => setQuery("")}
startContent={<FontAwesomeIcon icon={faSearch} />}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSearchSubmit();
}
}}
/>
</Tooltip>
</div>
<SearchField
aria-label="Search documentation"
className={wrapperClassName}
fullWidth
value={query}
onChange={setQuery}
onSubmit={handleSearchSubmit}
>
<SearchField.Group>
<SearchField.SearchIcon>
<FontAwesomeIcon icon={faSearch} />
</SearchField.SearchIcon>
<SearchField.Input placeholder="Search..." />
{query.length > 0 ? <SearchField.ClearButton aria-label="Clear search" /> : null}
</SearchField.Group>
</SearchField>
);
const renderDesktopRoute = (href: string, label: string) => {
const isActive = router.pathname.startsWith(href);
return (
<li key={href}>
<Button
variant={isActive ? "secondary" : "ghost"}
onPress={() => router.push(href)}
>
{label}
</Button>
</li>
);
};
const renderMobileRoute = (href: string, label: string) => {
const isActive = href === "/" ? router.pathname === "/" : router.pathname.startsWith(href);
return (
<Button
key={href}
fullWidth
variant={isActive ? "primary" : "ghost"}
onPress={() => {
router.push(href);
setIsMobileMenuOpen(false);
}}
>
{href === "/" ? <FontAwesomeIcon fixedWidth icon={faHome} /> : null}
{label}
</Button>
);
};
return (
<>
<Navbar
isBordered
maxWidth="full"
classNames={{
item: [
"flex",
"relative",
"h-full",
"items-center",
"data-[active=true]:after:content-['']",
"data-[active=true]:after:absolute",
"data-[active=true]:after:bottom-0",
"data-[active=true]:after:left-0",
"data-[active=true]:after:right-0",
"data-[active=true]:after:h-[2px]",
"data-[active=true]:after:rounded-[2px]",
"data-[active=true]:after:bg-primary",
],
}}
>
<NavbarBrand>
<SliversIcon />
<span className="hidden sm:block font-bold text-inherit">
&nbsp; Sliver C2
</span>
</NavbarBrand>
<NavbarContent className="hidden md:flex">
<NavbarItem isActive={router.pathname === "/"}>
<Button
variant="light"
color={router.pathname === "/" ? "primary" : "default"}
as={Link}
onPress={() => router.push("/")}
>
<FontAwesomeIcon fixedWidth icon={faHome} />
</Button>
</NavbarItem>
<NavbarItem isActive={router.pathname.startsWith("/tutorials")}>
<Button
variant="light"
color={router.pathname === "/tutorials" ? "primary" : "default"}
as={Link}
onPress={() => router.push("/tutorials")}
>
Tutorials
</Button>
</NavbarItem>
<NavbarItem isActive={router.pathname.startsWith("/talks")}>
<Button
variant="light"
color={router.pathname === "/talks" ? "primary" : "default"}
as={Link}
onPress={() => router.push("/talks")}
>
Talks
</Button>
</NavbarItem>
<NavbarItem isActive={router.pathname.startsWith("/docs")}>
<Button
variant="light"
color={router.pathname === "/docs" ? "primary" : "default"}
as={Link}
onPress={() => router.push("/docs")}
>
Docs
</Button>
</NavbarItem>
</NavbarContent>
<NavbarContent as="div" justify="end" className="hidden md:flex">
{renderSearchInput("w-64")}
<Tooltip
content={theme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode"}
>
<Button
variant="ghost"
onPress={() => {
setTheme(theme === Themes.DARK ? Themes.LIGHT : Themes.DARK);
<nav className="sliver-navbar-glass sticky top-0 z-40 px-4 shadow-sm md:px-6">
<div className="flex h-16 items-center gap-4">
<button
type="button"
className="flex items-center gap-2 text-foreground"
onClick={() => {
router.push("/");
setIsMobileMenuOpen(false);
}}
isDisabled={!mounted}
aria-label="Sliver C2 home"
>
<FontAwesomeIcon icon={lightDarkModeIcon} />
</Button>
</Tooltip>
<SliversIcon />
<span className="hidden font-bold text-inherit sm:block">
Sliver C2
</span>
</button>
<Tooltip content="Join Discord">
<Button
variant="ghost"
onPress={() => {
window.open(
"https://discord.com/channels/791066041198968873/1339996286514106409",
"_blank",
);
}}
>
<FontAwesomeIcon icon={faDiscord} />
</Button>
</Tooltip>
<ul className="hidden items-center gap-2 md:flex">
<li>
{renderTooltip(
"Home",
<Button
isIconOnly
aria-label="Home"
variant={router.pathname === "/" ? "secondary" : "ghost"}
onPress={() => router.push("/")}
>
<FontAwesomeIcon fixedWidth icon={faHome} />
</Button>,
)}
</li>
{routes.map((route) => renderDesktopRoute(route.href, route.label))}
</ul>
<Tooltip content="View on GitHub">
<Button
variant="ghost"
onPress={() => {
window.open("https://github.com/BishopFox/sliver", "_blank");
}}
>
<FontAwesomeIcon icon={faGithub} />
</Button>
</Tooltip>
</NavbarContent>
<div className="ml-auto hidden items-center gap-2 md:flex">
{renderSearchInput("w-64")}
{renderTooltip(
activeTheme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode",
<Button
isIconOnly
aria-label={activeTheme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode"}
variant="ghost"
onPress={() => {
setTheme(activeTheme === Themes.DARK ? Themes.LIGHT : Themes.DARK);
}}
>
<FontAwesomeIcon icon={lightDarkModeIcon} />
</Button>,
)}
<div className="flex items-center gap-2 md:hidden">
<Tooltip
content={theme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode"}
>
<Button
variant="ghost"
onPress={() => {
setTheme(theme === Themes.DARK ? Themes.LIGHT : Themes.DARK);
}}
isDisabled={!mounted}
>
<FontAwesomeIcon icon={lightDarkModeIcon} />
</Button>
</Tooltip>
<Tooltip content={isMobileMenuOpen ? "Close menu" : "Open menu"}>
<Button
variant="ghost"
aria-label={isMobileMenuOpen ? "Close menu" : "Open menu"}
onPress={() => setIsMobileMenuOpen((current) => !current)}
>
<FontAwesomeIcon icon={isMobileMenuOpen ? faXmark : faBars} />
</Button>
</Tooltip>
</div>
</Navbar>
{renderTooltip(
"Join Discord",
<Button
isIconOnly
aria-label="Join Discord"
variant="ghost"
onPress={() => {
window.open(
"https://discord.com/channels/791066041198968873/1339996286514106409",
"_blank",
"noopener,noreferrer",
);
}}
>
<FontAwesomeIcon icon={faDiscord} />
</Button>,
)}
{renderTooltip(
"View on GitHub",
<Button
isIconOnly
aria-label="View on GitHub"
variant="ghost"
onPress={() => {
window.open(
"https://github.com/BishopFox/sliver",
"_blank",
"noopener,noreferrer",
);
}}
>
<FontAwesomeIcon icon={faGithub} />
</Button>,
)}
</div>
<div className="ml-auto flex items-center gap-2 md:hidden">
{renderTooltip(
activeTheme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode",
<Button
isIconOnly
aria-label={activeTheme === Themes.DARK ? "Switch to light mode" : "Switch to dark mode"}
variant="ghost"
onPress={() => {
setTheme(activeTheme === Themes.DARK ? Themes.LIGHT : Themes.DARK);
}}
>
<FontAwesomeIcon icon={lightDarkModeIcon} />
</Button>,
)}
{renderTooltip(
isMobileMenuOpen ? "Close menu" : "Open menu",
<Button
isIconOnly
variant="ghost"
aria-label={isMobileMenuOpen ? "Close menu" : "Open menu"}
onPress={() => setIsMobileMenuOpen((current) => !current)}
>
<FontAwesomeIcon icon={isMobileMenuOpen ? faXmark : faBars} />
</Button>,
)}
</div>
</div>
</nav>
{isMobileMenuOpen ? (
<div className="md:hidden border-b border-default-200 dark:border-default-100/40 bg-content1 px-4 pb-4 shadow-sm">
<div className="sliver-navbar-glass px-4 pb-4 shadow-sm md:hidden">
<div className="mt-3">{renderSearchInput("w-full")}</div>
<div className="mt-4 flex flex-col gap-2">
{renderMobileRoute("/", "Home")}
{routes.map((route) => renderMobileRoute(route.href, route.label))}
<Button
variant={router.pathname === "/" ? "solid" : "light"}
color={router.pathname === "/" ? "primary" : "default"}
onPress={() => {
router.push("/");
setIsMobileMenuOpen(false);
}}
startContent={<FontAwesomeIcon fixedWidth icon={faHome} />}
>
Home
</Button>
<Button
variant={router.pathname.startsWith("/tutorials") ? "solid" : "light"}
color={router.pathname.startsWith("/tutorials") ? "primary" : "default"}
onPress={() => {
router.push("/tutorials");
setIsMobileMenuOpen(false);
}}
>
Tutorials
</Button>
<Button
variant={router.pathname.startsWith("/talks") ? "solid" : "light"}
color={router.pathname.startsWith("/talks") ? "primary" : "default"}
onPress={() => {
router.push("/talks");
setIsMobileMenuOpen(false);
}}
>
Talks
</Button>
<Button
variant={router.pathname.startsWith("/docs") ? "solid" : "light"}
color={router.pathname.startsWith("/docs") ? "primary" : "default"}
onPress={() => {
router.push("/docs");
setIsMobileMenuOpen(false);
}}
>
Docs
</Button>
<Button
variant="light"
fullWidth
variant="ghost"
onPress={() => {
window.open(
"https://discord.com/channels/791066041198968873/1339996286514106409",
"_blank",
"noopener,noreferrer",
);
}}
startContent={<FontAwesomeIcon icon={faDiscord} />}
>
<FontAwesomeIcon icon={faDiscord} />
Discord
</Button>
<Button
variant="light"
fullWidth
variant="ghost"
onPress={() => {
window.open("https://github.com/BishopFox/sliver", "_blank");
window.open(
"https://github.com/BishopFox/sliver",
"_blank",
"noopener,noreferrer",
);
}}
startContent={<FontAwesomeIcon icon={faGithub} />}
>
<FontAwesomeIcon icon={faGithub} />
GitHub
</Button>
</div>
+16 -14
View File
@@ -1,4 +1,4 @@
import { Button, Card, CardFooter, CardHeader } from "@heroui/react";
import { Button, Card } from "@heroui/react";
import AsciinemaPlayer from "./asciinema";
import { faChevronRight } from "@fortawesome/free-solid-svg-icons";
@@ -21,15 +21,18 @@ export type TutorialCardCardProps = {
};
export default function TutorialCard(props: TutorialCardCardProps) {
const actionButtonClassName =
"ml-auto h-auto min-h-0 shrink-0 px-0 py-0 text-sm font-semibold [--button-bg-hover:transparent] [--button-bg-pressed:transparent] [--button-bg:transparent] [--button-fg:var(--warning)]";
return (
<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">
<Card className="relative z-0 gap-0 overflow-hidden p-0">
<Card.Header className="absolute left-3 right-3 top-3 z-10 flex-col items-end p-0 text-right">
<p className="text-sm font-bold uppercase leading-none text-white/70">
{props.name}
</p>
</CardHeader>
</Card.Header>
<div className={styles["hide-control-bar"]}>
<div className={`${styles["hide-control-bar"]} overflow-hidden`}>
<AsciinemaPlayer
src={props.asciiCast}
rows={props.rows ? props.rows : "18"}
@@ -41,13 +44,13 @@ export default function TutorialCard(props: TutorialCardCardProps) {
/>
</div>
<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">
<Card.Footer className="absolute bottom-0 left-0 right-0 z-10 border-t border-white/20 bg-black/40 p-3 backdrop-blur-md">
<div className="flex min-h-10 w-full flex-row items-center gap-4">
<p
className={
props.italicDescription
? "text-xs text-white/80 italic"
: "text-xs text-white/80"
? "min-w-0 flex-1 text-sm leading-snug text-white/80 italic"
: "min-w-0 flex-1 text-sm leading-snug text-white/80"
}
>
{props.description}
@@ -56,19 +59,18 @@ export default function TutorialCard(props: TutorialCardCardProps) {
{props.showButton ? (
<Button
variant="ghost"
color="warning"
size="sm"
onPress={props.onPress}
className="ml-auto"
className={actionButtonClassName}
>
{props.buttonText ? props.buttonText : "Read Tutorial"}{" "}
{props.buttonText ? props.buttonText : "Read Tutorial"}
<FontAwesomeIcon icon={faChevronRight} />
</Button>
) : (
<></>
)}
</div>
</CardFooter>
</Card.Footer>
</Card>
);
}
+1
View File
@@ -1,6 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true,
reactStrictMode: true,
images: {
unoptimized: true,
+1055 -3680
View File
File diff suppressed because it is too large. Load diff
+30 -25
View File
@@ -14,40 +14,45 @@
},
"dependencies": {
"@fontsource/fira-code": "^5.2.7",
"@fortawesome/fontawesome-svg-core": "^7.1.0",
"@fortawesome/free-brands-svg-icons": "^7.1.0",
"@fortawesome/free-solid-svg-icons": "^7.1.0",
"@fortawesome/react-fontawesome": "^3.1.0",
"@heroui/react": "^2.8.5",
"@fortawesome/fontawesome-svg-core": "^7.2.0",
"@fortawesome/free-brands-svg-icons": "^7.2.0",
"@fortawesome/free-solid-svg-icons": "^7.2.0",
"@fortawesome/react-fontawesome": "^3.3.1",
"@heroui/react": "^3.0.3",
"@heroui/styles": "^3.0.3",
"@monaco-editor/react": "^4.7.0",
"@tailwindcss/postcss": "^4.1.14",
"@tanstack/react-query": "^5.90.2",
"asciinema-player": "^3.11.0",
"framer-motion": "^12.23.22",
"fuse.js": "^7.1.0",
"@tailwindcss/postcss": "^4.2.4",
"@tanstack/react-query": "^5.100.6",
"asciinema-player": "^3.15.1",
"fuse.js": "^7.3.0",
"lunr": "^2.3.9",
"mermaid": "^11.12.2",
"next": "^16.1.6",
"mermaid": "^11.14.0",
"next": "^16.2.4",
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"react-markdown": "^10.1.0",
"react-syntax-highlighter": "^15.6.6",
"react-syntax-highlighter": "^16.1.1",
"remark-gfm": "^4.0.1"
},
"devDependencies": {
"@tailwindcss/typography": "^0.5.19",
"@types/lunr": "^2.3.7",
"@types/node": "^24.6.2",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@types/node": "^25.6.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/react-syntax-highlighter": "^15.5.13",
"autoprefixer": "^10.4.21",
"concurrently": "^9.1.0",
"eslint": "^9.37.0",
"eslint-config-next": "^16.1.6",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.14",
"typescript": "^5.9.3"
"autoprefixer": "^10.5.0",
"concurrently": "^9.2.1",
"eslint": "^9.39.4",
"eslint-config-next": "^16.2.4",
"postcss": "^8.5.13",
"tailwindcss": "^4.2.4",
"typescript": "^6.0.3"
},
"overrides": {
"dompurify": "^3.4.2",
"postcss": "^8.5.13",
"uuid": "^14.0.0"
}
}
+59 -62
View File
@@ -8,7 +8,6 @@ import { fetchDocs as fetchDocsContent, fetchTutorials as fetchTutorialsContent
import { Themes } from "@/util/themes";
import { faExternalLink } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { HeroUIProvider } from "@heroui/react";
import {
HydrationBoundary,
QueryClient,
@@ -94,66 +93,64 @@ export default function App({ Component, pageProps }: AppProps) {
});
return (
<HeroUIProvider>
<NextThemesProvider
attribute="class"
defaultTheme={Themes.DARK}
enableSystem={false}
storageKey="theme"
>
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={pageProps.dehydratedState}>
<SearchContext.Provider value={search}>
<Navbar />
<Component {...pageProps} />
<div className="mb-16 md:mb-20"></div>
<footer className="z-20 w-full border-t border-gray-200 bg-white px-3 py-4 text-center shadow dark:bg-black dark:border-gray-600 md:fixed md:bottom-0 md:left-0 md:flex md:items-center md:justify-between md:px-6 md:py-4">
<div className="flex flex-col items-center gap-2 text-xs leading-snug text-gray-500 sm:text-sm md:flex-row md:items-center md:gap-3 md:text-left dark:text-gray-400">
<span>
© {new Date().getFullYear()}&nbsp;
<a
href="https://bishopfox.com/"
className="hover:underline"
rel="noreferrer"
target="_blank"
>
Bishop Fox
</a>
</span>
<span className="hidden md:inline" aria-hidden="true">
·
</span>
<span className="max-w-xs md:max-w-none">
<a
href="https://github.com/BishopFox/sliver/pulls"
rel="noreferrer"
className="hover:underline"
target="_blank"
>
Help improve this documentation
<span className="ml-1 inline-block">
<FontAwesomeIcon icon={faExternalLink} />
</span>
</a>
</span>
</div>
<ul className="mt-3 flex flex-wrap items-center justify-center gap-3 text-xs font-medium text-gray-500 md:mt-0 md:gap-6 md:text-sm dark:text-gray-400">
<li>
<a
href="https://github.com/BishopFox/sliver/blob/master/LICENSE"
target="_blank"
rel="noreferrer"
className="hover:underline"
>
GPLv3 License
</a>
</li>
</ul>
</footer>
</SearchContext.Provider>
</HydrationBoundary>
</QueryClientProvider>
</NextThemesProvider>
</HeroUIProvider>
<NextThemesProvider
attribute="class"
defaultTheme={Themes.DARK}
enableSystem={false}
storageKey="theme"
>
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={pageProps.dehydratedState}>
<SearchContext.Provider value={search}>
<Navbar />
<Component {...pageProps} />
<div className="mb-16 md:mb-20"></div>
<footer className="z-20 w-full border-t border-separator bg-surface/80 px-3 py-4 text-center shadow backdrop-blur-md dark:bg-black/75 md:fixed md:bottom-0 md:left-0 md:right-0 md:flex md:items-center md:justify-between md:px-6 md:py-4">
<div className="flex flex-col items-center gap-2 text-xs leading-snug text-muted sm:text-sm md:flex-row md:items-center md:gap-3 md:text-left">
<span>
© {new Date().getFullYear()}&nbsp;
<a
href="https://bishopfox.com/"
className="hover:underline"
rel="noreferrer"
target="_blank"
>
Bishop Fox
</a>
</span>
<span className="hidden md:inline" aria-hidden="true">
·
</span>
<span className="max-w-xs md:max-w-none">
<a
href="https://github.com/BishopFox/sliver/pulls"
rel="noreferrer"
className="hover:underline"
target="_blank"
>
Help improve this documentation
<span className="ml-1 inline-block">
<FontAwesomeIcon icon={faExternalLink} />
</span>
</a>
</span>
</div>
<ul className="mt-3 flex flex-wrap items-center justify-center gap-3 text-xs font-medium text-muted md:mt-0 md:gap-6 md:text-sm">
<li>
<a
href="https://github.com/BishopFox/sliver/blob/master/LICENSE"
target="_blank"
rel="noreferrer"
className="hover:underline"
>
GPLv3 License
</a>
</li>
</ul>
</footer>
</SearchContext.Provider>
</HydrationBoundary>
</QueryClientProvider>
</NextThemesProvider>
);
}
+47 -55
View File
@@ -3,30 +3,24 @@ import LoadingState from "@/components/loading-state";
import { Docs } from "@/util/docs";
import { PREBUILD_VERSION } from "@/util/__generated__/prebuild-version";
import { fetchDocs as fetchDocsContent } from "@/util/content-fetchers";
import { Themes } from "@/util/themes";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Card,
CardBody,
CardHeader,
Divider,
Input,
Listbox,
ListboxItem,
ListBox,
ScrollShadow,
SearchField,
Separator,
} from "@heroui/react";
import { useQuery } from "@tanstack/react-query";
import Fuse from "fuse.js";
import { NextPage } from "next";
import { useTheme } from "next-themes";
import Head from "next/head";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
import React from "react";
const DocsIndexPage: NextPage = () => {
const { theme } = useTheme();
const router = useRouter();
const { data: docs, isLoading } = useQuery({
@@ -75,13 +69,28 @@ const DocsIndexPage: NextPage = () => {
return selectedDoc ? [selectedDoc, ...visibleDocs] : visibleDocs;
}, [docs, name, visibleDocs]);
const listboxClasses = React.useMemo(() => {
if (theme === Themes.DARK) {
return "p-0 gap-0 divide-y divide-default-300/50 dark:divide-default-100/80 bg-content1 overflow-visible shadow-small rounded-large";
} else {
return "p-0 gap-0 divide-y divide-default-300/50 dark:divide-default-100/80 bg-content1 overflow-visible rounded-large";
}
}, [theme]);
const listboxClasses =
"p-0 gap-0 divide-y divide-separator bg-surface overflow-visible rounded-lg shadow-sm";
const renderFilterInput = (className?: string) => (
<SearchField
aria-label="Filter documents"
className={className}
fullWidth
value={filterValue}
onChange={setFilterValue}
>
<SearchField.Group>
<SearchField.SearchIcon>
<FontAwesomeIcon icon={faSearch} />
</SearchField.SearchIcon>
<SearchField.Input placeholder="Filter..." />
{filterValue.length > 0 ? (
<SearchField.ClearButton aria-label="Clear document filter" />
) : null}
</SearchField.Group>
</SearchField>
);
if (isLoading || !docs || (hasNameQueryInPath && !name)) {
return <LoadingState />;
@@ -99,19 +108,10 @@ const DocsIndexPage: NextPage = () => {
>
Select a document
</label>
<div className="mt-2">
<Input
placeholder="Filter..."
startContent={<FontAwesomeIcon icon={faSearch} />}
value={filterValue}
onChange={(e) => setFilterValue(e.target.value)}
isClearable={true}
onClear={() => setFilterValue("")}
/>
</div>
<div className="mt-2">{renderFilterInput()}</div>
<select
id="docs-mobile-selector"
className="mt-3 w-full rounded-lg border border-default-200 bg-content1 p-2 text-sm dark:border-default-100/60"
className="mt-3 w-full rounded-lg border border-separator bg-surface p-2 text-sm"
value={name}
onChange={(event) => {
const selectedName = event.target.value;
@@ -132,58 +132,50 @@ const DocsIndexPage: NextPage = () => {
<div className="grid grid-cols-1 gap-6 lg:grid-cols-12 lg:gap-8">
<aside className="hidden lg:block lg:col-span-3">
<div className="sticky top-16 ml-4 flex flex-col gap-3">
<Input
className="mt-2"
placeholder="Filter..."
startContent={<FontAwesomeIcon icon={faSearch} />}
value={filterValue}
onChange={(e) => setFilterValue(e.target.value)}
isClearable={true}
onClear={() => setFilterValue("")}
/>
<ScrollShadow className="max-h-[calc(100vh-15rem)] sliver-scrollbar overflow-y-auto pr-1 rounded-large">
<Listbox
{renderFilterInput("mt-2")}
<ScrollShadow className="max-h-[calc(100vh-15rem)] sliver-scrollbar overflow-y-auto pr-1 rounded-lg">
<ListBox
aria-label="Toolbox Menu"
className={listboxClasses}
itemClasses={{
base: "px-3 first:rounded-t-large last:rounded-b-large rounded-none gap-3 h-12 data-[hover=true]:bg-default-100/80",
onAction={(key) => {
router.push({
pathname: "/docs",
query: { name: String(key) },
});
}}
>
{visibleDocs.map((doc) => (
<ListboxItem
<ListBox.Item
key={doc.name}
onClick={() => {
router.push({
pathname: "/docs",
query: { name: doc.name },
});
}}
id={doc.name}
textValue={doc.name}
className="h-12 rounded-none px-3 first:rounded-t-lg last:rounded-b-lg"
>
{doc.name}
</ListboxItem>
</ListBox.Item>
))}
</Listbox>
</ListBox>
</ScrollShadow>
</div>
</aside>
<div className="px-4 pb-8 lg:col-span-9 lg:px-8">
{name !== "" ? (
<Card className="mt-2">
<CardHeader>
<Card.Header>
<span className="text-3xl">{name}</span>
</CardHeader>
<Divider />
<CardBody>
</Card.Header>
<Separator />
<Card.Content>
<MarkdownViewer
key={name}
markdown={markdown || ""}
/>
</CardBody>
</Card.Content>
</Card>
) : (
<div className="mt-8 text-center text-2xl text-foreground/90">
Welcome to the Sliver Wiki!
<div className="mt-2 text-xl text-default-500">
<div className="mt-2 text-xl text-muted">
Please select a document
</div>
</div>
@@ -1,5 +1,18 @@
Sliver allows an operator to extend the local client console and its features by adding new commands based on third party tools. The easiest way to install an alias or extension is using the [armory](/docs?name=Armory).
## Server AI Access
Aliases and extensions used from the client console still live under `~/.sliver-client/aliases` and `~/.sliver-client/extensions`.
The server-side AI agent uses a separate store under `~/.sliver/ai/aliases` and `~/.sliver/ai/extensions`. To make a package available to the AI agent, copy the unpacked package directory into the matching server-side path so the manifest and payload artifacts are present together. For example:
- `~/.sliver/ai/aliases/Rubeus/alias.json`
- `~/.sliver/ai/aliases/Rubeus/Rubeus.exe`
- `~/.sliver/ai/extensions/nanodump/extension.json`
- `~/.sliver/ai/extensions/nanodump/nanodump.x64.o`
There is currently no dedicated UI for this workflow. The AI agent can search and execute only the packages that have been copied into these server-side directories.
#### Aliases Command Parsing
**⚠️ IMPORTANT:** It's important to understand that all alias commands have certain Sliver shell flags (those that appear in `--help`). Your Sliver shell commands are lexically parsed by the Sliver shell first, and only unnamed positional arguments are passed to the alias code. This means you may need to escape certain arguments in order for them to be correctly parsed.
+4
View File
@@ -4,6 +4,8 @@ The armory downloads packages from `github.com` and `api.github.com` so you'll n
Aliases and extensions are installed on the "sliver client"-side, and thus are not shared among operators in [multiplayer mode](/docs?name=Multi-player+Mode).
The server-side AI agent uses a separate store under `~/.sliver/ai/aliases` and `~/.sliver/ai/extensions`. If you want the AI agent to discover and execute an alias or extension, copy the unpacked package directory (the manifest plus its artifacts) into the matching server-side path. There is currently no dedicated UI or install command for the AI store.
You can also use `armory install all` to install _everything_ if you really want to.
## The Official Armory
@@ -44,6 +46,8 @@ You remove packages installed from the `armory` using the `aliases rm` and `exte
Installed alias and extension files are stored in `~/.sliver-client/` by default if you want to manually remove a package simply delete its corresponding directory and restart the client.
If you also copied a package into the server-side AI store, remove that copy separately from `~/.sliver/ai/aliases` or `~/.sliver/ai/extensions`.
## Private Armories
Sliver has experimental support for self-hosted private armories, but I have not gotten around to testing and writing the documentation for these, so you'll have to read through the source code to figure out how they work for now. I'll eventually update this documentation and release a reference implementation. If you do play around with this, just know the design is subject to change before becoming a real feature.
@@ -6,7 +6,7 @@ BOF support is provided via the [COFF Loader](https://github.com/sliverarmory/CO
The easiest way to install a BOF extension, for example [`nanodump`](https://github.com/sliverarmory/nanodump), is using the [armory](/docs?name=Armory) package manager:
**IMPORTANT:** BOF Extensions are installed per-sliver client, they are not stored on the server. Thus extensions are not shared across operators, each operator must install the extension to use it.
**IMPORTANT:** BOF extensions are still installed per-sliver client for normal operator use, so they are not shared across operators automatically. If you want the server-side AI agent to use a BOF, copy the unpacked BOF directory into `~/.sliver/ai/extensions` on the server as well, and copy any dependency such as `coff-loader` into that same server-side AI store.
```
sliver > armory install nanodump
@@ -114,6 +114,8 @@ Looking at the script we can see the BOF requires a single integer argument. The
Once the manifest is defined load it into your client using `extensions load`, locally loaded extensions do not need to be cryptographically signed. The paths in the manifest should be relative to the manifest file, parent directories are not allowed.
If you want the server-side AI agent to discover and run the same BOF, copy that unpacked directory into `~/.sliver/ai/extensions/<name>/` so the `extension.json` file and `.o` artifact are available on the server.
More details can be found on the [Aliases & Extensions](/docs?name=Aliases+and+Extensions) page.
**IMPORTANT:** For BOF extensions to be properly detected by the Sliver client, the `path` must use the `.o` file extension.
@@ -12,7 +12,7 @@ daemon:
host: ""
port: 31337
tailscale: false
disable_wg: false
enable_wg: false
logs:
level: 4
grpc_unary_payloads: false
@@ -54,7 +54,7 @@ cxx: {}
- `host` - Interface to bind the daemon listener to. Empty string means all interfaces.
- `port` - Listen port for the multiplayer listener.
- `tailscale` - Enable Tailscale for daemon listener setup. When enabled, Sliver does not wrap multiplayer in its own WireGuard layer.
- `disable_wg` - Expose multiplayer directly over mTLS instead of the default WireGuard-protected mode.
- `enable_wg` - Wrap multiplayer in WireGuard. If omitted or false, multiplayer is exposed directly over mTLS.
- `logs` - Server logging options.
- `level` - `logrus` level (`0`-`6`, clamped by Sliver). `4` is `INFO`, `5` is `DEBUG`, `6` is `TRACE`.
- `grpc_unary_payloads` - Log gRPC unary payloads.
@@ -159,4 +159,4 @@ The `wg` block is optional:
- When present, `sliver-client` automatically brings up the multiplayer WireGuard wrapper and then dials the in-tunnel gRPC/mTLS service.
- When absent, the client connects directly to the multiplayer mTLS listener.
- Generate a direct-only profile with `new-operator --disable-wg` or `sliver-server operator --disable-wg` when you need compatibility with external gRPC clients that do not implement the multiplayer WireGuard wrapper.
- Generate a WireGuard-enabled profile with `new-operator --enable-wg` or `sliver-server operator --enable-wg` when you want the multiplayer WireGuard wrapper.
@@ -7,7 +7,7 @@ Current Sliver releases generate multiplayer operator configs with a `wg` block
If you are writing a custom client in another language, you have two options:
- Implement the multiplayer WireGuard wrapper described in [multiplayer mode](/docs?name=Multi-player+Mode), then connect to the in-tunnel gRPC/mTLS service.
- Keep multiplayer in direct mode by starting the listener with `multiplayer --disable-wg` or `sliver-server daemon --disable-wg`, then generate operator profiles with `new-operator --disable-wg` or `sliver-server operator --disable-wg`.
- Keep multiplayer in direct mode by default, or explicitly opt into the wrapper with `multiplayer --enable-wg` or `sliver-server daemon --enable-wg`. Generate matching operator profiles with `new-operator --enable-wg` or `sliver-server operator --enable-wg` when you want the client-side WireGuard wrapper.
Once connected, the client/server API is still gRPC, so any language with gRPC support can in theory be used to create a custom client.
@@ -15,11 +15,11 @@ If `server.yaml` does not exist, Sliver generates it. If a legacy `server.json`
- `-l, --lhost` multiplayer listener host
- `-p, --lport` multiplayer listener port
- `-t, --tailscale` enable Tailscale listener
- `--disable-wg` expose multiplayer directly over mTLS instead of using the default WireGuard wrapper
- `--enable-wg` wrap multiplayer in WireGuard instead of exposing it directly over mTLS
- `-f, --force` force unpack static assets
- For `sliver-server daemon`, `--lhost` and `--lport` override config values. If omitted, Sliver uses `daemon.host` and `daemon.port` from `server.yaml`.
- For normal startup (`sliver-server`) with `daemon_mode: true`, Sliver uses `daemon.tailscale` and `daemon.disable_wg` from `server.yaml`.
- With `--disable-wg` or `daemon.disable_wg: true`, multiplayer falls back to direct TCP mTLS on the configured port.
- For normal startup (`sliver-server`) with `daemon_mode: true`, Sliver uses `daemon.tailscale` and `daemon.enable_wg` from `server.yaml`.
- With `--enable-wg` or `daemon.enable_wg: true`, multiplayer is wrapped in WireGuard. Otherwise it stays on direct TCP mTLS.
### Example Config
@@ -29,7 +29,7 @@ daemon:
host: ""
port: 31337
tailscale: false
disable_wg: false
enable_wg: false
logs:
level: 4
grpc_unary_payloads: false
@@ -49,7 +49,7 @@ Since daemon mode does not provide an interactive server console, generate opera
./sliver-server operator --name zer0cool --lhost 1.2.3.4 --permissions all --save zer0cool.cfg
```
The `operator` CLI matches the daemon's multiplayer exposure by default. If the daemon is running in direct mode or over Tailscale, the generated config omits the multiplayer `wg` block automatically. You can also force a direct-only profile with `--disable-wg`.
The `operator` CLI generates direct multiplayer profiles by default. Add `--enable-wg` when the daemon is running with the WireGuard wrapper.
### Shutdown Behavior
@@ -1,6 +1,6 @@
Multiplayer mode allows multiple operators to connect to the same Sliver server and collaborate on engagements. The easiest way to set up a server for multiplayer is to use the [Linux install script](/docs?name=Linux+Install+Script), which configures the server as a systemd service. However, any `sliver-server` binary supports multiplayer mode.
By default, Sliver now protects the operator-facing multiplayer listener with a dedicated WireGuard wrapper. The gRPC/mTLS authentication stack is still used inside the tunnel, but the server no longer exposes the multiplayer gRPC listener directly unless you explicitly opt out with `--disable-wg`.
Sliver exposes the operator-facing multiplayer listener directly over gRPC/mTLS by default. You can opt into a dedicated WireGuard wrapper with `--enable-wg`; the gRPC/mTLS authentication stack still runs inside that tunnel.
```
┌──────────────────┐ C2
@@ -53,7 +53,7 @@ From the server, start the multiplayer listener and generate an operator config
[*] Saved new client config to: /Users/moloch/Desktop/moloch_example.com.cfg
```
**IMPORTANT:** Before clients can connect to a server you must start a multiplayer listener with the `multiplayer` command. In the default WireGuard-protected mode the outer listener is UDP/31337. If you disable the wrapper, multiplayer is exposed directly on TCP/31337 instead.
**IMPORTANT:** Before clients can connect to a server you must start a multiplayer listener with the `multiplayer` command. By default multiplayer is exposed directly on TCP/31337. If you enable the wrapper, the outer listener becomes UDP/31337 and the gRPC/mTLS service stays inside the tunnel.
You can now give this configuration file `moloch_example.com.cfg` to the operator and they can connect to the server using the `sliver-client` binary. The Sliver client will look for configuration files in `~/.sliver-client/configs/` or you can import configs using the `import` CLI. The configs directory can contain multiple configs for different servers.
@@ -71,11 +71,11 @@ $ ./sliver-client
If you want the old behavior, or you need compatibility with third-party gRPC clients that do not implement the multiplayer WireGuard wrapper, disable it on both the listener and the generated operator profile:
```
[server] sliver > multiplayer --disable-wg
[server] sliver > multiplayer
[*] Multiplayer mode enabled!
[server] sliver > new-operator --name tester --lhost 1.2.3.4 --permissions all --disable-wg
[server] sliver > new-operator --name tester --lhost 1.2.3.4 --permissions all
[*] Generating new client certificate, please wait ...
[*] Saved new client config to: /Users/tester/Desktop/tester_example.com.cfg
@@ -85,14 +85,13 @@ In direct mode:
- Multiplayer is exposed directly over TCP on `--lport` (default `31337`).
- Generated operator configs omit the `wg` block.
- `sliver-client --disable-wg` forces a direct connection even if the config includes a `wg` block.
- `sliver-client --require-wg` fails fast if the config does not contain a valid `wg` block.
- `sliver-client --enable-wg` opts into the multiplayer WireGuard wrapper when the operator config includes a `wg` block.
The listener mode and the operator config need to match. A WireGuard-enabled config cannot talk to a direct listener, and a direct-only client cannot talk to the default WireGuard-wrapped listener.
The listener mode, operator config, and client flag need to match. A WireGuard-wrapped listener needs a `wg` block in the operator profile plus `sliver-client --enable-wg`. Direct multiplayer works without the `wg` block and without the flag.
### Server CLI / Daemon Mode Multiplayer
If the server is running in daemon mode, the multiplayer listener is started for you without an interactive console. By default the daemon uses the same WireGuard-protected multiplayer mode described above. You can switch the daemon back to direct exposure with `sliver-server daemon --disable-wg` or `daemon.disable_wg: true` in `server.yaml`.
If the server is running in daemon mode, the multiplayer listener is started for you without an interactive console. By default the daemon uses direct multiplayer mTLS. You can opt into the WireGuard wrapper with `sliver-server daemon --enable-wg` or `daemon.enable_wg: true` in `server.yaml`.
Use the server CLI to generate operator configuration files:
@@ -100,7 +99,7 @@ Use the server CLI to generate operator configuration files:
./sliver-server operator --name zer0cool --lhost 1.2.3.4 --permissions all --save zer0cool.cfg
```
When daemon mode is configured for direct multiplayer or Tailscale, the CLI automatically omits the `wg` block by default. You can also force a direct-only profile with `--disable-wg`.
Operator profiles omit the multiplayer `wg` block by default. Add `--enable-wg` when the listener is wrapped in WireGuard.
The installation script places the `sliver-server` binary in `/root` by default.
@@ -117,4 +116,4 @@ $ ./sliver-server
sliver > multiplayer -T
```
You should now see a new Tailscale host named `sliver-server-<machine>`. Use that hostname as `--lhost` when generating operator configs for other hosts on the same tailnet. If you generate the operator config before enabling Tailscale multiplayer, add `--disable-wg` explicitly so the profile does not include the multiplayer `wg` block.
You should now see a new Tailscale host named `sliver-server-<machine>`. Use that hostname as `--lhost` when generating operator configs for other hosts on the same tailnet. Tailscale multiplayer does not use the multiplayer WireGuard wrapper, so operator profiles should be generated without `--enable-wg`.
+27 -31
View File
@@ -4,7 +4,7 @@ import TutorialCard from "@/components/tutorial-card";
import { Themes } from "@/util/themes";
import { faDownload, faExternalLink } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Button, Card, CardBody, CardHeader, Divider, Link } from "@heroui/react";
import { Button, Card, Separator } from "@heroui/react";
import { useTheme } from "next-themes";
import { useRouter } from "next/router";
import React from "react";
@@ -12,23 +12,15 @@ import React from "react";
export default function Home() {
const router = useRouter();
const { resolvedTheme } = useTheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
const isDarkTheme = React.useMemo(() => {
if (!mounted) {
return true;
}
return (resolvedTheme || Themes.DARK) !== Themes.LIGHT;
}, [mounted, resolvedTheme]);
}, [resolvedTheme]);
return (
<div className="mt-6 flex flex-col gap-6 px-4 sm:px-6 lg:grid lg:grid-cols-12 lg:px-12">
<div className="lg:col-span-6">
<div className="w-full overflow-hidden rounded-xl border border-default-200 bg-content1 shadow-sm dark:border-default-100/60">
<div className="w-full overflow-hidden rounded-xl border border-separator bg-surface shadow-sm">
<div className="w-full overflow-x-auto lg:overflow-visible">
<AsciinemaPlayer
src="/asciinema/intro.cast"
@@ -44,14 +36,14 @@ export default function Home() {
</div>
<div className="lg:col-span-6 lg:ml-2">
<Card className="mx-auto max-w-3xl lg:mx-0">
<CardHeader>
<Card.Header>
<div className="flex items-center">
<SliversIcon className="mr-2" height={28} />
<span className="text-2xl">Sliver Command &amp; Control</span>
</div>
</CardHeader>
<Divider />
<CardBody>
</Card.Header>
<Separator />
<Card.Content>
<p className={isDarkTheme ? "prose dark:prose-invert" : "prose prose-slate"}>
Sliver is a powerful command and control (C2) framework designed
to provide advanced capabilities for covertly managing and
@@ -69,35 +61,39 @@ export default function Home() {
<div className="mt-4 flex w-full gap-3">
<Button
className="flex-1"
color="primary"
variant="shadow"
as={Link}
href="https://github.com/BishopFox/sliver/releases/latest"
target="_blank"
rel="noopener noreferrer"
startContent={<FontAwesomeIcon icon={faDownload} />}
variant="primary"
onPress={() => {
window.open(
"https://github.com/BishopFox/sliver/releases/latest",
"_blank",
"noopener,noreferrer",
);
}}
>
<FontAwesomeIcon icon={faDownload} />
Download Latest Release
</Button>
<Button
className="flex-1"
color="secondary"
className="sliver-armory-ghost flex-1"
variant="ghost"
as={Link}
href="https://github.com/sliverarmory"
target="_blank"
rel="noopener noreferrer"
endContent={<FontAwesomeIcon icon={faExternalLink} />}
onPress={() => {
window.open(
"https://github.com/sliverarmory",
"_blank",
"noopener,noreferrer",
);
}}
>
Visit the Armory
<FontAwesomeIcon icon={faExternalLink} />
</Button>
</div>
</CardBody>
</Card.Content>
</Card>
</div>
<div className="col-span-12 mt-8">
<Divider />
<Separator />
</div>
<div className="col-span-12 mt-8">
+5 -5
View File
@@ -2,7 +2,7 @@ import MarkdownViewer from "@/components/markdown";
import { useSearchContext } from "@/util/search-context";
import { faChevronCircleRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Button, Card, CardBody, Divider } from "@heroui/react";
import { Button, Card, Separator } from "@heroui/react";
import { NextPage } from "next";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
@@ -34,13 +34,13 @@ const SearchPage: NextPage = (props: SearchPageProps) => {
{searchResults.map((doc) => (
<Card key={doc.name}>
<CardBody className="flex flex-col gap-3">
<Card.Content className="flex flex-col gap-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<span className="text-xl">{doc.name}</span>
<div className="flex-1"></div>
<Button
size="sm"
color="secondary"
variant="secondary"
className="w-full sm:w-[150px]"
onPress={() => {
router.push(`/docs?name=${doc.name}`);
@@ -51,12 +51,12 @@ const SearchPage: NextPage = (props: SearchPageProps) => {
</Button>
</div>
<Divider />
<Separator />
<div className="max-h-[200px] overflow-hidden">
<MarkdownViewer markdown={doc.content} />
</div>
</CardBody>
</Card.Content>
</Card>
))}
</div>
+27 -15
View File
@@ -1,7 +1,7 @@
import Youtube from "@/components/youtube";
import { faChevronRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Accordion, AccordionItem, Button, Card, CardFooter } from "@heroui/react";
import { Accordion, Button, Card } from "@heroui/react";
import { NextPage } from "next";
import Head from "next/head";
import React from "react";
@@ -103,6 +103,8 @@ const TalksIndexPage: NextPage = () => {
const [footerHidden, setFooterHidden] = React.useState<Record<string, boolean>>(
{}
);
const actionButtonClassName =
"ml-auto h-auto min-h-0 shrink-0 px-0 py-0 text-sm font-semibold [--button-bg-hover:transparent] [--button-bg-pressed:transparent] [--button-bg:transparent] [--button-fg:var(--warning)]";
const hideFooterFor = React.useCallback((url: string) => {
setFooterHidden((prev) => (prev[url] ? prev : { ...prev, [url]: true }));
@@ -115,22 +117,31 @@ const TalksIndexPage: NextPage = () => {
</Head>
<div className="mt-6 px-4 pb-8 sm:px-6 lg:px-12">
<Accordion
selectionMode="multiple"
allowsMultipleExpanded
defaultExpandedKeys={["workshops", "general-tradecraft"]}
showDivider={false}
hideSeparator
className="px-0"
>
{talkSections.map((section) => (
<AccordionItem
<Accordion.Item
key={section.key}
aria-label={section.title}
title={section.title}
subtitle={section.description}
id={section.key}
>
<Accordion.Heading>
<Accordion.Trigger>
<span className="flex flex-col items-start text-left">
<span className="text-lg font-semibold">{section.title}</span>
<span className="text-sm text-muted">{section.description}</span>
</span>
<Accordion.Indicator className="ml-auto" />
</Accordion.Trigger>
</Accordion.Heading>
<Accordion.Panel>
<Accordion.Body>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-9">
{section.talks.map((talk) => (
<div key={talk.url} className="sm:col-span-1 lg:col-span-3">
<Card isFooterBlurred className="relative z-0 overflow-hidden">
<Card className="relative z-0 gap-0 overflow-hidden p-0">
<Youtube
className="w-full"
url={talk.url}
@@ -139,14 +150,13 @@ const TalksIndexPage: NextPage = () => {
/>
{footerHidden[talk.url] ? null : (
<CardFooter className="absolute bottom-0 z-10 bg-black/40 border-t-1 border-default-600 dark:border-default-100">
<div className="flex w-full items-center gap-2">
<p className="text-xs text-white/80">{talk.description}</p>
<Card.Footer className="absolute bottom-0 left-0 right-0 z-10 border-t border-white/20 bg-black/40 p-3 backdrop-blur-md">
<div className="flex min-h-10 w-full items-center gap-4">
<p className="min-w-0 flex-1 text-sm leading-snug text-white/80">{talk.description}</p>
<Button
variant="ghost"
color="warning"
size="sm"
className="ml-auto"
className={actionButtonClassName}
onPress={() => {
window.open(talk.url, "_blank", "noopener,noreferrer");
}}
@@ -154,13 +164,15 @@ const TalksIndexPage: NextPage = () => {
Watch <FontAwesomeIcon icon={faChevronRight} />
</Button>
</div>
</CardFooter>
</Card.Footer>
)}
</Card>
</div>
))}
</div>
</AccordionItem>
</Accordion.Body>
</Accordion.Panel>
</Accordion.Item>
))}
</Accordion>
</div>
+47 -55
View File
@@ -3,30 +3,24 @@ import LoadingState from "@/components/loading-state";
import { Tutorials } from "@/util/tutorials";
import { PREBUILD_VERSION } from "@/util/__generated__/prebuild-version";
import { fetchTutorials as fetchTutorialsContent } from "@/util/content-fetchers";
import { Themes } from "@/util/themes";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Card,
CardBody,
CardHeader,
Divider,
Input,
Listbox,
ListboxItem,
ListBox,
ScrollShadow,
SearchField,
Separator,
} from "@heroui/react";
import { useQuery } from "@tanstack/react-query";
import Fuse from "fuse.js";
import { NextPage } from "next";
import { useTheme } from "next-themes";
import Head from "next/head";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
import React from "react";
const TutorialsIndexPage: NextPage = () => {
const { theme } = useTheme();
const router = useRouter();
const { data: tutorials, isLoading } = useQuery({
@@ -75,13 +69,28 @@ const TutorialsIndexPage: NextPage = () => {
return selectedTutorial ? [selectedTutorial, ...visibleTutorials] : visibleTutorials;
}, [name, tutorials, visibleTutorials]);
const listboxClasses = React.useMemo(() => {
if (theme === Themes.DARK) {
return "p-0 gap-0 divide-y divide-default-300/50 dark:divide-default-100/80 bg-content1 overflow-visible shadow-small rounded-large";
} else {
return "p-0 gap-0 divide-y divide-default-300/50 dark:divide-default-100/80 bg-content1 overflow-visible rounded-large";
}
}, [theme]);
const listboxClasses =
"p-0 gap-0 divide-y divide-separator bg-surface overflow-visible rounded-lg shadow-sm";
const renderFilterInput = (className?: string) => (
<SearchField
aria-label="Filter tutorials"
className={className}
fullWidth
value={filterValue}
onChange={setFilterValue}
>
<SearchField.Group>
<SearchField.SearchIcon>
<FontAwesomeIcon icon={faSearch} />
</SearchField.SearchIcon>
<SearchField.Input placeholder="Filter..." />
{filterValue.length > 0 ? (
<SearchField.ClearButton aria-label="Clear tutorial filter" />
) : null}
</SearchField.Group>
</SearchField>
);
if (isLoading || !tutorials || (hasNameQueryInPath && !name)) {
return <LoadingState />;
@@ -99,19 +108,10 @@ const TutorialsIndexPage: NextPage = () => {
>
Select a tutorial
</label>
<div className="mt-2">
<Input
placeholder="Filter..."
startContent={<FontAwesomeIcon icon={faSearch} />}
value={filterValue}
onChange={(e) => setFilterValue(e.target.value)}
isClearable={true}
onClear={() => setFilterValue("")}
/>
</div>
<div className="mt-2">{renderFilterInput()}</div>
<select
id="tutorials-mobile-selector"
className="mt-3 w-full rounded-lg border border-default-200 bg-content1 p-2 text-sm dark:border-default-100/60"
className="mt-3 w-full rounded-lg border border-separator bg-surface p-2 text-sm"
value={name}
onChange={(event) => {
const selectedName = event.target.value;
@@ -132,58 +132,50 @@ const TutorialsIndexPage: NextPage = () => {
<div className="grid grid-cols-1 gap-6 lg:grid-cols-12 lg:gap-8">
<aside className="hidden lg:block lg:col-span-3">
<div className="sticky top-16 ml-4 flex flex-col gap-3">
<Input
className="mt-2"
placeholder="Filter..."
startContent={<FontAwesomeIcon icon={faSearch} />}
value={filterValue}
onChange={(e) => setFilterValue(e.target.value)}
isClearable={true}
onClear={() => setFilterValue("")}
/>
<ScrollShadow className="max-h-[calc(100vh-6rem)] sliver-scrollbar overflow-y-auto pr-1 rounded-large">
<Listbox
{renderFilterInput("mt-2")}
<ScrollShadow className="max-h-[calc(100vh-6rem)] sliver-scrollbar overflow-y-auto pr-1 rounded-lg">
<ListBox
aria-label="Toolbox Menu"
className={listboxClasses}
itemClasses={{
base: "px-3 first:rounded-t-large last:rounded-b-large rounded-none gap-3 h-12 data-[hover=true]:bg-default-100/80",
onAction={(key) => {
router.push({
pathname: "/tutorials",
query: { name: String(key) },
});
}}
>
{visibleTutorials.map((tutorial) => (
<ListboxItem
<ListBox.Item
key={tutorial.name}
onClick={() => {
router.push({
pathname: "/tutorials",
query: { name: tutorial.name },
});
}}
id={tutorial.name}
textValue={tutorial.name}
className="h-12 rounded-none px-3 first:rounded-t-lg last:rounded-b-lg"
>
{tutorial.name}
</ListboxItem>
</ListBox.Item>
))}
</Listbox>
</ListBox>
</ScrollShadow>
</div>
</aside>
<div className="px-4 pb-8 lg:col-span-9 lg:px-8">
{name !== "" ? (
<Card className="mt-2">
<CardHeader>
<Card.Header>
<span className="text-3xl">{name}</span>
</CardHeader>
<Divider />
<CardBody>
</Card.Header>
<Separator />
<Card.Content>
<MarkdownViewer
key={name}
markdown={markdown || ""}
/>
</CardBody>
</Card.Content>
</Card>
) : (
<div className="mt-8 text-center text-2xl text-foreground/90">
Welcome to the Sliver Tutorials!
<div className="mt-2 text-xl text-default-500">
<div className="mt-2 text-xl text-muted">
Please select a chapter
</div>
</div>
+36 -4
View File
@@ -42,6 +42,34 @@ echo "Running from $(pwd)"
echo "Using Minisign public key..."
stop_existing_sliver_daemon() {
local existing_sliver_server=""
if test -x /root/sliver-server; then
existing_sliver_server="/root/sliver-server"
elif command -v sliver-server &> /dev/null; then
existing_sliver_server="$(command -v sliver-server)"
fi
if [[ -z "$existing_sliver_server" ]]; then
return 0
fi
echo "Existing Sliver server install detected at $existing_sliver_server"
if command -v systemctl &> /dev/null && test -f /etc/systemd/system/sliver.service; then
if systemctl is-active --quiet sliver; then
echo "Stopping the Sliver systemd service before upgrade..."
systemctl stop sliver
fi
fi
if pgrep -f "${existing_sliver_server} daemon" > /dev/null 2>&1; then
echo "Stopping the running Sliver daemon before upgrade..."
pkill -f "${existing_sliver_server} daemon"
fi
}
# Download and Unpack Sliver Server
ARCH="$(uname -m)"
case "$ARCH" in
@@ -79,6 +107,8 @@ echo "Verifying signatures ..."
minisign -Vm "/root/$SLIVER_SERVER" -x "/root/$SLIVER_SERVER.minisig" -P "$SLIVER_MINISIGN_PUB_KEY"
minisign -Vm "/root/$SLIVER_CLIENT" -x "/root/$SLIVER_CLIENT.minisig" -P "$SLIVER_MINISIGN_PUB_KEY"
stop_existing_sliver_daemon
if test -f "/root/$SLIVER_SERVER"; then
echo "Moving the Sliver server executable to /root/sliver-server..."
mv "/root/$SLIVER_SERVER" /root/sliver-server
@@ -128,8 +158,6 @@ WantedBy=multi-user.target
EOF
chown root:root /etc/systemd/system/sliver.service
chmod 600 /etc/systemd/system/sliver.service
echo "Starting the Sliver service..."
systemctl start sliver # Start the service now
# Generate local configs
echo "Generating local configs ..."
@@ -137,7 +165,7 @@ echo "Generating local configs ..."
# Generate local configs
echo "Generating operator configs ..."
mkdir -p /root/.sliver-client/configs
/root/sliver-server operator --name root --lhost localhost --permissions all --save /root/.sliver-client/configs
/root/sliver-server operator --name root --lhost 127.0.0.1 --permissions all --save /root/.sliver-client/configs
chown -R root:root /root/.sliver-client/
USER_DIRS=(/home/*)
@@ -146,7 +174,11 @@ for USER_DIR in "${USER_DIRS[@]}"; do
if id -u "$USER" >/dev/null 2>&1; then
echo "Generating operator configs for user $USER..."
mkdir -p "$USER_DIR/.sliver-client/configs"
/root/sliver-server operator --name "$USER" --lhost localhost --permissions all --save "$USER_DIR/.sliver-client/configs"
/root/sliver-server operator --name "$USER" --lhost 127.0.0.1 --permissions all --save "$USER_DIR/.sliver-client/configs"
chown -R "$USER":"$(id -gn "$USER")" "$USER_DIR/.sliver-client/"
fi
done
echo "Reloading systemd and starting the Sliver service..."
systemctl daemon-reload
systemctl start sliver
+16 -6
View File
@@ -1,4 +1,5 @@
@import "tailwindcss";
@import "@heroui/styles";
@config "../tailwind.config.js";
@@ -7,12 +8,6 @@
Consolas, "Liberation Mono", "Courier New", monospace;
}
/* Keep layout width stable when page content toggles vertical scrolling. */
html,
body {
scrollbar-gutter: stable both-edges;
}
/*
Keep html as the single scrolling element. Setting overflow on both html
and body breaks sticky sidebar behavior on docs/tutorial pages.
@@ -68,6 +63,21 @@ pre {
background-clip: content-box;
}
.sliver-navbar-glass {
width: 100%;
border-bottom: 1px solid var(--separator);
background-color: color-mix(in oklab, var(--surface) 72%, transparent);
-webkit-backdrop-filter: blur(18px) saturate(1.18);
backdrop-filter: blur(18px) saturate(1.18);
}
.sliver-armory-ghost {
--button-bg: transparent;
--button-bg-hover: rgb(109 40 217 / 0.16);
--button-bg-pressed: rgb(109 40 217 / 0.24);
--button-fg: #a78bfa;
}
.dark .sliver-scrollbar {
scrollbar-color: rgba(79, 97, 125, 0.8) transparent;
}
+2 -4
View File
@@ -1,11 +1,9 @@
const { heroui } = require("@heroui/theme");
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
@@ -16,5 +14,5 @@ module.exports = {
},
},
darkMode: "class",
plugins: [heroui()],
plugins: [],
};
+19 -11
View File
@@ -840,22 +840,30 @@ func servicesListHandler(data []byte, resp RPCResponse) {
}
serviceInfo, err := service.ListServices(servicesReq.Hostname)
/*
Errors from listing the services are not fatal. The client can
display a message to the user about the issue
We still want other errors like timeouts to be handled in the
normal way.
*/
servicesResp := &sliverpb.Services{
Details: serviceInfo,
Error: err.Error(),
Response: &commonpb.Response{},
}
servicesResp := buildServicesResp(serviceInfo, err)
data, err = proto.Marshal(servicesResp)
resp(data, err)
}
// buildServicesResp packages the result of service.ListServices into a
// sliverpb.Services response. Errors from listing services are not fatal
// (partial results may still be useful to the operator), so a non-nil error
// is reported via the Error string field rather than failing the RPC.
// The nil-check is load-bearing: callers previously called err.Error()
// unconditionally, crashing the implant when ListServices succeeded cleanly.
func buildServicesResp(details []*sliverpb.ServiceDetails, err error) *sliverpb.Services {
errStr := ""
if err != nil {
errStr = err.Error()
}
return &sliverpb.Services{
Details: details,
Error: errStr,
Response: &commonpb.Response{},
}
}
func serviceDetailHandler(data []byte, resp RPCResponse) {
serviceDetailReq := &sliverpb.ServiceDetailReq{}
err := proto.Unmarshal(data, serviceDetailReq)
+5 -2
View File
@@ -119,17 +119,20 @@ func pivotStopListenerHandler(envelope *pb.Envelope, connection *transports.Conn
}
func pivotPeerEnvelopeHandler(envelope *pb.Envelope, connection *transports.Connection) {
sent, err := pivots.SendToPeer(envelope)
nextPeerID, sent, err := pivots.SendToPeer(envelope)
if !sent {
// {{if .Config.Debug}}
log.Printf("Send to peer failed, report peer failure upstream ...")
// {{end}}
if nextPeerID == 0 {
return
}
errStr := ""
if err != nil {
errStr = err.Error()
}
data, _ := proto.Marshal(&pb.PivotPeerFailure{
PeerID: pivots.MyPeerID,
PeerID: nextPeerID,
Type: pb.PeerFailureType_SEND_FAILURE,
Err: errStr,
})
+5 -5
View File
@@ -145,14 +145,14 @@ func StopListener(id uint32) {
}
// SendToPeer - Forward an envelope to a peer
func SendToPeer(envelope *pb.Envelope) (bool, error) {
func SendToPeer(envelope *pb.Envelope) (int64, bool, error) {
pivotPeerEnvelope := &pb.PivotPeerEnvelope{}
err := proto.Unmarshal(envelope.Data, pivotPeerEnvelope)
if err != nil {
// {{if .Config.Debug}}
log.Printf("Failed to unmarshal peer envelope: %s", err)
// {{end}}
return false, err
return 0, false, err
}
// {{if .Config.Debug}}
@@ -164,7 +164,7 @@ func SendToPeer(envelope *pb.Envelope) (bool, error) {
// {{if .Config.Debug}}
log.Printf("Failed to find next peer id: %s", err)
// {{end}}
return false, err
return 0, false, err
}
sent := false // Controls iteration of outer loop
@@ -183,9 +183,9 @@ func SendToPeer(envelope *pb.Envelope) (bool, error) {
// {{if .Config.Debug}}
log.Printf("Failed to find peer with id %d", nextPeerID)
// {{end}}
return false, errors.New("peer not found")
return nextPeerID, false, errors.New("peer not found")
}
return sent, nil
return nextPeerID, sent, nil
}
func findNextPeerID(pivotPeerEnvelope *pb.PivotPeerEnvelope) (int64, error) {
+48 -9
View File
@@ -34,21 +34,60 @@ import (
"unsafe"
)
// LocalTask - Run a shellcode in the current process
// Will hang the process until shellcode completion
// TODO: actually test this code
// Adapted/stolen from: https://github.com/lesnuages/hershell/blob/master/shell/shell_default.go#L48
//go:linkname localTaskBeforeFork syscall.runtime_BeforeFork
func localTaskBeforeFork()
//go:linkname localTaskAfterFork syscall.runtime_AfterFork
func localTaskAfterFork()
//go:linkname localTaskAfterForkInChild syscall.runtime_AfterForkInChild
func localTaskAfterForkInChild()
// LocalTask - Run shellcode in a forked child; blocks until the child exits.
// Forking isolates the beacon from payloads that exit/execve (issue #2237).
func LocalTask(data []byte, rwxPages bool) error {
dataAddr := uintptr(unsafe.Pointer(&data[0]))
page := getPage(dataAddr)
syscall.Mprotect(page, syscall.PROT_READ|syscall.PROT_EXEC)
pageAddr := uintptr(unsafe.Pointer(&page[0]))
pageLen := uintptr(len(page))
dataPtr := unsafe.Pointer(&data)
// funcPtr trick from hershell (https://github.com/lesnuages/hershell)
funcPtr := *(*func())(unsafe.Pointer(&dataPtr))
runtime.LockOSThread()
defer runtime.UnlockOSThread()
go func(fPtr func()) {
fPtr()
}(funcPtr)
localTaskBeforeFork()
// Raw SYS_FORK on Darwin: r0 holds child's pid in BOTH processes; r1==1
// flags the child (libSystem's fork() wrapper hides this).
r0, isChild, errno := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if errno != 0 {
localTaskAfterFork()
runtime.UnlockOSThread()
return errno
}
if isChild == 1 {
localTaskAfterForkInChild()
for fd := uintptr(3); fd < 1024; fd++ {
syscall.RawSyscall(syscall.SYS_CLOSE, fd, 0, 0)
}
syscall.RawSyscall(syscall.SYS_MPROTECT, pageAddr, pageLen, uintptr(syscall.PROT_READ|syscall.PROT_EXEC))
funcPtr()
for {
syscall.RawSyscall(syscall.SYS_EXIT, 0, 0, 0)
}
}
localTaskAfterFork()
var ws syscall.WaitStatus
_, err := syscall.Wait4(int(r0), &ws, 0, nil)
runtime.UnlockOSThread()
if err != nil {
return err
}
if ws.Signaled() {
return fmt.Errorf("shellcode child killed by signal %v", ws.Signal())
}
if ws.ExitStatus() != 0 {
return fmt.Errorf("shellcode child exited %d", ws.ExitStatus())
}
return nil
}
@@ -0,0 +1,127 @@
//go:build darwin
package taskrunner
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"fmt"
"os"
"os/exec"
"runtime"
"testing"
"time"
"unsafe"
)
const localTaskHelperEnv = "SLIVER_LOCALTASK_HELPER"
const localTaskSentinel = "PARENT_ALIVE_AFTER_LOCALTASK"
// darwin/amd64 mov eax,0x2000001 ; xor edi,edi ; syscall — exit(0)
var exitShellcodeDarwinAmd64 = []byte{0xb8, 0x01, 0x00, 0x00, 0x02, 0x31, 0xff, 0x0f, 0x05}
// darwin/amd64 mov eax,0x2000001 ; mov edi,42 ; syscall — exit(42)
var exit42ShellcodeDarwinAmd64 = []byte{0xb8, 0x01, 0x00, 0x00, 0x02, 0xbf, 0x2a, 0x00, 0x00, 0x00, 0x0f, 0x05}
// darwin/arm64 movz x0,#0 ; movz x16,#1 ; svc #0x80 — exit(0)
// Stored as [N]uint32 so the backing storage is 4-byte aligned (ARM64 SIGBUS
// otherwise).
var exitShellcodeDarwinArm64Words = [3]uint32{0xd2800000, 0xd2800030, 0xd4001001}
// darwin/arm64 movz x0,#42 ; movz x16,#1 ; svc #0x80 — exit(42)
var exit42ShellcodeDarwinArm64Words = [3]uint32{0xd2800540, 0xd2800030, 0xd4001001}
func asBytes[T any](words *T) []byte {
return unsafe.Slice((*byte)(unsafe.Pointer(words)), unsafe.Sizeof(*words))
}
func exitShellcode() []byte {
switch runtime.GOARCH {
case "amd64":
return exitShellcodeDarwinAmd64
case "arm64":
return asBytes(&exitShellcodeDarwinArm64Words)
}
return nil
}
func exit42Shellcode() []byte {
switch runtime.GOARCH {
case "amd64":
return exit42ShellcodeDarwinAmd64
case "arm64":
return asBytes(&exit42ShellcodeDarwinArm64Words)
}
return nil
}
func TestMain(m *testing.M) {
switch os.Getenv(localTaskHelperEnv) {
case "exit0":
_ = LocalTask(exitShellcode(), false)
time.Sleep(500 * time.Millisecond)
fmt.Println(localTaskSentinel)
os.Exit(0)
case "exit42":
err := LocalTask(exit42Shellcode(), false)
if err != nil {
fmt.Printf("LOCALTASK_ERR=%s\n", err.Error())
} else {
fmt.Println("LOCALTASK_ERR=<nil>")
}
os.Exit(0)
}
os.Exit(m.Run())
}
func runHelper(t *testing.T, mode string) []byte {
t.Helper()
if exitShellcode() == nil {
t.Skipf("no exit shellcode for GOARCH=%s", runtime.GOARCH)
}
cmd := exec.Command(os.Args[0])
cmd.Env = append(os.Environ(), localTaskHelperEnv+"="+mode)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("helper subprocess (%s) exited abnormally: %v\noutput: %s", mode, err, out)
}
return out
}
func TestLocalTask_ParentSurvives(t *testing.T) {
out := runHelper(t, "exit0")
if !bytes.Contains(out, []byte(localTaskSentinel)) {
t.Fatalf("expected sentinel %q in helper output:\n%s", localTaskSentinel, out)
}
}
// Accepts signal-kill as well as clean non-zero exit: macOS Apple Silicon
// W^X faults mprotected-page execution with SIGBUS regardless of the
// shellcode bytes, which still exercises LocalTask's error path.
func TestLocalTask_ReportsChildFailure(t *testing.T) {
out := runHelper(t, "exit42")
if bytes.Contains(out, []byte("LOCALTASK_ERR=shellcode child exited 42")) {
return
}
if bytes.Contains(out, []byte("LOCALTASK_ERR=shellcode child killed by signal")) {
return
}
t.Fatalf("expected LOCALTASK_ERR for exit-42 or signal kill:\n%s", out)
}
+47 -7
View File
@@ -34,19 +34,59 @@ import (
//{{end}}
)
// LocalTask - Run a shellcode in the current process
// Will hang the process until shellcode completion
//go:linkname localTaskBeforeFork syscall.runtime_BeforeFork
func localTaskBeforeFork()
//go:linkname localTaskAfterFork syscall.runtime_AfterFork
func localTaskAfterFork()
//go:linkname localTaskAfterForkInChild syscall.runtime_AfterForkInChild
func localTaskAfterForkInChild()
// LocalTask - Run shellcode in a forked child; blocks until the child exits.
// Forking isolates the beacon from payloads that exit/execve (issue #2237).
func LocalTask(data []byte, rwxPages bool) error {
dataAddr := uintptr(unsafe.Pointer(&data[0]))
page := getPage(dataAddr)
syscall.Mprotect(page, syscall.PROT_READ|syscall.PROT_EXEC)
pageAddr := uintptr(unsafe.Pointer(&page[0]))
pageLen := uintptr(len(page))
dataPtr := unsafe.Pointer(&data)
// funcPtr trick from hershell (https://github.com/lesnuages/hershell)
funcPtr := *(*func())(unsafe.Pointer(&dataPtr))
runtime.LockOSThread()
defer runtime.UnlockOSThread()
go func(fPtr func()) {
fPtr()
}(funcPtr)
localTaskBeforeFork()
// SYS_CLONE(SIGCHLD) = fork(). linux/arm64 has no SYS_FORK.
pid, _, errno := syscall.RawSyscall6(syscall.SYS_CLONE, uintptr(syscall.SIGCHLD), 0, 0, 0, 0, 0)
if errno != 0 {
localTaskAfterFork()
runtime.UnlockOSThread()
return errno
}
if pid == 0 {
localTaskAfterForkInChild()
for fd := uintptr(3); fd < 1024; fd++ {
syscall.RawSyscall(syscall.SYS_CLOSE, fd, 0, 0)
}
syscall.RawSyscall(syscall.SYS_MPROTECT, pageAddr, pageLen, uintptr(syscall.PROT_READ|syscall.PROT_EXEC))
funcPtr()
for {
syscall.RawSyscall(syscall.SYS_EXIT_GROUP, 0, 0, 0)
}
}
localTaskAfterFork()
var ws syscall.WaitStatus
_, err := syscall.Wait4(int(pid), &ws, 0, nil)
runtime.UnlockOSThread()
if err != nil {
return err
}
if ws.Signaled() {
return fmt.Errorf("shellcode child killed by signal %v", ws.Signal())
}
if ws.ExitStatus() != 0 {
return fmt.Errorf("shellcode child exited %d", ws.ExitStatus())
}
return nil
}
@@ -0,0 +1,87 @@
//go:build linux
package taskrunner
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"fmt"
"os"
"os/exec"
"runtime"
"testing"
"time"
)
const localTaskHelperEnv = "SLIVER_LOCALTASK_HELPER"
const localTaskSentinel = "PARENT_ALIVE_AFTER_LOCALTASK"
// linux/amd64: xor eax,eax ; xor edi,edi ; mov al,0x3c ; syscall — exit(0)
var exitShellcodeAmd64 = []byte{0x31, 0xc0, 0x31, 0xff, 0xb0, 0x3c, 0x0f, 0x05}
// linux/amd64: xor eax,eax ; mov al,0x3c ; mov edi,42 ; syscall — exit(42)
var exit42ShellcodeAmd64 = []byte{0x31, 0xc0, 0xb0, 0x3c, 0xbf, 0x2a, 0x00, 0x00, 0x00, 0x0f, 0x05}
func TestMain(m *testing.M) {
switch os.Getenv(localTaskHelperEnv) {
case "exit0":
_ = LocalTask(exitShellcodeAmd64, false)
time.Sleep(500 * time.Millisecond)
fmt.Println(localTaskSentinel)
os.Exit(0)
case "exit42":
err := LocalTask(exit42ShellcodeAmd64, false)
if err != nil {
fmt.Printf("LOCALTASK_ERR=%s\n", err.Error())
} else {
fmt.Println("LOCALTASK_ERR=<nil>")
}
os.Exit(0)
}
os.Exit(m.Run())
}
func runHelper(t *testing.T, mode string) []byte {
t.Helper()
if runtime.GOARCH != "amd64" {
t.Skipf("exit shellcode is amd64-specific; GOARCH=%s", runtime.GOARCH)
}
cmd := exec.Command(os.Args[0])
cmd.Env = append(os.Environ(), localTaskHelperEnv+"="+mode)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("helper subprocess (%s) exited abnormally: %v\noutput: %s", mode, err, out)
}
return out
}
func TestLocalTask_ParentSurvives(t *testing.T) {
out := runHelper(t, "exit0")
if !bytes.Contains(out, []byte(localTaskSentinel)) {
t.Fatalf("expected sentinel %q in helper output:\n%s", localTaskSentinel, out)
}
}
func TestLocalTask_ReportsChildFailure(t *testing.T) {
out := runHelper(t, "exit42")
if !bytes.Contains(out, []byte("LOCALTASK_ERR=shellcode child exited 42")) {
t.Fatalf("expected exit-42 error in helper output:\n%s", out)
}
}
@@ -0,0 +1,139 @@
package version
/*
Sliver Implant Framework
Copyright (C) 2021 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"fmt"
"os"
"strings"
)
type linuxVersionInfo struct {
Sysname string
Release string
Version string
Machine string
}
func readLinuxOSRelease() string {
paths := []string{"/etc/os-release", "/usr/lib/os-release"}
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
continue
}
if osRelease := buildLinuxOSRelease(parseLinuxOSRelease(string(data))); osRelease != "" {
return osRelease
}
}
return ""
}
func parseLinuxOSRelease(content string) map[string]string {
values := make(map[string]string)
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok || key == "" {
continue
}
key = strings.TrimSpace(key)
value = unescapeLinuxOSReleaseValue(unquoteLinuxOSReleaseValue(strings.TrimSpace(value)))
values[key] = value
}
return values
}
func unquoteLinuxOSReleaseValue(s string) string {
if len(s) < 2 {
return s
}
if (s[0] == '"' || s[0] == '\'') && s[0] == s[len(s)-1] {
return s[1 : len(s)-1]
}
return s
}
func unescapeLinuxOSReleaseValue(s string) string {
return strings.NewReplacer(
`\$`, `$`,
`\"`, `"`,
`\'`, `'`,
`\\`, `\`,
"\\`", "`",
).Replace(s)
}
func buildLinuxOSRelease(values map[string]string) string {
name := values["NAME"]
version := values["VERSION"]
if version == "" {
version = values["VERSION_ID"]
}
if name != "" && version != "" {
return fmt.Sprintf("%s %s", name, version)
}
if values["PRETTY_NAME"] != "" {
return values["PRETTY_NAME"]
}
return name
}
func normalizeLinuxArch(arch string) string {
arch = strings.TrimSpace(arch)
if arch == "" {
return ""
}
switch strings.ToLower(arch) {
case "amd64":
return "x86_64"
case "i386", "i486", "i586", "i686", "x86":
return "x86"
default:
return arch
}
}
func formatLinuxDetailedVersion(osRelease string, versionInfo linuxVersionInfo) string {
parts := make([]string, 0, 3)
if osRelease != "" {
parts = append(parts, osRelease)
} else if versionInfo.Sysname != "" {
parts = append(parts, versionInfo.Sysname)
}
kernelParts := make([]string, 0, 2)
if versionInfo.Release != "" {
kernelParts = append(kernelParts, versionInfo.Release)
}
if versionInfo.Version != "" {
kernelParts = append(kernelParts, versionInfo.Version)
}
if len(kernelParts) > 0 {
parts = append(parts, fmt.Sprintf("kernel %s", strings.Join(kernelParts, " ")))
}
if arch := normalizeLinuxArch(versionInfo.Machine); arch != "" {
parts = append(parts, arch)
}
return strings.Join(parts, " ")
}
@@ -0,0 +1,100 @@
package version
import "testing"
func TestParseLinuxOSRelease(t *testing.T) {
content := "# comment\n" +
"NAME=\"Ubuntu\"\n" +
"VERSION=\"24.04.2 LTS (Noble Numbat)\"\n" +
"PRETTY_NAME=\"Ubuntu 24.04.2 LTS\"\n" +
"SPECIAL=\"quoted \\\"value\\\" \\$HOME \\`uname\\`\"\n"
values := parseLinuxOSRelease(content)
if got, want := values["NAME"], "Ubuntu"; got != want {
t.Fatalf("NAME = %q, want %q", got, want)
}
if got, want := values["VERSION"], "24.04.2 LTS (Noble Numbat)"; got != want {
t.Fatalf("VERSION = %q, want %q", got, want)
}
if got, want := values["PRETTY_NAME"], "Ubuntu 24.04.2 LTS"; got != want {
t.Fatalf("PRETTY_NAME = %q, want %q", got, want)
}
if got, want := values["SPECIAL"], "quoted \"value\" $HOME `uname`"; got != want {
t.Fatalf("SPECIAL = %q, want %q", got, want)
}
}
func TestBuildLinuxOSRelease(t *testing.T) {
testCases := []struct {
name string
values map[string]string
want string
}{
{
name: "prefers name and version",
values: map[string]string{
"NAME": "Ubuntu",
"VERSION": "24.04.2 LTS (Noble Numbat)",
"PRETTY_NAME": "Ubuntu 24.04.2 LTS",
},
want: "Ubuntu 24.04.2 LTS (Noble Numbat)",
},
{
name: "falls back to version id",
values: map[string]string{
"NAME": "Alpine Linux",
"VERSION_ID": "3.21.3",
},
want: "Alpine Linux 3.21.3",
},
{
name: "falls back to pretty name",
values: map[string]string{
"PRETTY_NAME": "Fedora Linux 41 (Workstation Edition)",
},
want: "Fedora Linux 41 (Workstation Edition)",
},
{
name: "falls back to name",
values: map[string]string{
"NAME": "Linux",
},
want: "Linux",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
if got := buildLinuxOSRelease(testCase.values); got != testCase.want {
t.Fatalf("buildLinuxOSRelease() = %q, want %q", got, testCase.want)
}
})
}
}
func TestFormatLinuxDetailedVersion(t *testing.T) {
version := formatLinuxDetailedVersion("Ubuntu 24.04.2 LTS (Noble Numbat)", linuxVersionInfo{
Release: "6.8.0-57-generic",
Version: "#59-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 14 18:29:04 UTC 2025",
Machine: "amd64",
})
want := "Ubuntu 24.04.2 LTS (Noble Numbat) kernel 6.8.0-57-generic #59-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 14 18:29:04 UTC 2025 x86_64"
if version != want {
t.Fatalf("formatLinuxDetailedVersion() = %q, want %q", version, want)
}
}
func TestFormatLinuxDetailedVersionFallback(t *testing.T) {
version := formatLinuxDetailedVersion("", linuxVersionInfo{
Sysname: "Linux",
Release: "6.12.0",
Machine: "i686",
})
want := "Linux kernel 6.12.0 x86"
if version != want {
t.Fatalf("formatLinuxDetailedVersion() = %q, want %q", version, want)
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !darwin && !(windows && (amd64 || 386)) && !(linux && (amd64 || 386))
//go:build !darwin && !linux && !(windows && (amd64 || 386))
package version
+18 -114
View File
@@ -1,4 +1,4 @@
//go:build amd64 || 386
//go:build linux
package version
@@ -21,132 +21,36 @@ package version
*/
import (
"fmt"
"bytes"
//{{if .Config.Debug}}
"log"
//{{end}}
"os"
"strings"
"syscall"
"golang.org/x/sys/unix"
)
func getString(input [65]int8) string {
var buf [65]byte
for i, b := range input {
buf[i] = byte(b)
func linuxNullTerminatedString(input []byte) string {
if index := bytes.IndexByte(input, 0); index >= 0 {
input = input[:index]
}
ver := string(buf[:])
if i := strings.Index(ver, "\x00"); i != -1 {
ver = ver[:i]
}
return ver
}
func readOSRelease() string {
paths := []string{"/etc/os-release", "/usr/lib/os-release"}
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
continue
}
return buildOSRelease(parseOSRelease(string(data)))
}
return ""
}
func parseOSRelease(content string) map[string]string {
values := make(map[string]string)
for _, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
if !ok || key == "" {
continue
}
key = strings.TrimSpace(key)
value = unescape(unquote(strings.TrimSpace(value)))
values[key] = value
}
return values
}
func unquote(s string) string {
if len(s) < 2 {
return s
}
if (s[0] == '"' || s[0] == '\'') && s[0] == s[len(s)-1] {
return s[1 : len(s)-1]
}
return s
}
func unescape(s string) string {
return strings.NewReplacer(
`\$`, `$`,
`\"`, `"`,
`\'`, `'`,
`\\`, `\`,
"\\`", "`",
).Replace(s)
}
func buildOSRelease(values map[string]string) string {
name := values["NAME"]
version := values["VERSION"]
if version == "" {
version = values["VERSION_ID"]
}
if name != "" && version != "" {
return fmt.Sprintf("%s %s", name, version)
}
return values["PRETTY_NAME"]
}
func normalizeArch(arch string) string {
arch = strings.TrimSpace(arch)
if arch == "" {
return ""
}
switch strings.ToLower(arch) {
case "amd64":
return "x86_64"
case "i386", "i486", "i586", "i686", "x86":
return "x86"
default:
return arch
}
}
func formatDetailedVersion(osRelease, kernel, arch string) string {
parts := make([]string, 0, 3)
if osRelease != "" {
parts = append(parts, osRelease)
}
if kernel != "" {
parts = append(parts, fmt.Sprintf("kernel %s", kernel))
}
if arch != "" {
parts = append(parts, arch)
}
return strings.Join(parts, " ")
return string(input)
}
// GetVersion returns the os version information
func GetVersion() string {
osRelease := readOSRelease()
var uname syscall.Utsname
if err := syscall.Uname(&uname); err != nil {
osRelease := readLinuxOSRelease()
var uname unix.Utsname
if err := unix.Uname(&uname); err != nil {
//{{if .Config.Debug}}
log.Printf("error getting OS version: %v", err)
//{{end}}
return osRelease
}
if osRelease == "" {
osRelease = getString(uname.Sysname)
}
kernel := getString(uname.Release)
arch := normalizeArch(getString(uname.Machine))
return formatDetailedVersion(osRelease, kernel, arch)
return formatLinuxDetailedVersion(osRelease, linuxVersionInfo{
Sysname: linuxNullTerminatedString(uname.Sysname[:]),
Release: linuxNullTerminatedString(uname.Release[:]),
Version: linuxNullTerminatedString(uname.Version[:]),
Machine: linuxNullTerminatedString(uname.Machine[:]),
})
}
+273 -151
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v7.34.0
// protoc v7.34.1
// source: clientpb/client.proto
package clientpb
@@ -11659,6 +11659,7 @@ type AIConfigSummary struct {
ThinkingLevel string `protobuf:"bytes,3,opt,name=ThinkingLevel,proto3" json:"ThinkingLevel,omitempty"`
Valid bool `protobuf:"varint,4,opt,name=Valid,proto3" json:"Valid,omitempty"`
Error string `protobuf:"bytes,5,opt,name=Error,proto3" json:"Error,omitempty"`
SystemPrompt string `protobuf:"bytes,6,opt,name=SystemPrompt,proto3" json:"SystemPrompt,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -11728,6 +11729,13 @@ func (x *AIConfigSummary) GetError() string {
return ""
}
func (x *AIConfigSummary) GetSystemPrompt() string {
if x != nil {
return x.SystemPrompt
}
return ""
}
type AIConversationReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"`
@@ -11824,29 +11832,107 @@ func (x *AIConversations) GetConversations() []*AIConversation {
return nil
}
type AIContextWindowUsage struct {
state protoimpl.MessageState `protogen:"open.v1"`
InputTokens int64 `protobuf:"varint,1,opt,name=InputTokens,proto3" json:"InputTokens,omitempty"`
OutputTokens int64 `protobuf:"varint,2,opt,name=OutputTokens,proto3" json:"OutputTokens,omitempty"`
TotalTokens int64 `protobuf:"varint,3,opt,name=TotalTokens,proto3" json:"TotalTokens,omitempty"`
ContextWindowTokens int64 `protobuf:"varint,4,opt,name=ContextWindowTokens,proto3" json:"ContextWindowTokens,omitempty"`
ContextWindowTokensEstimated bool `protobuf:"varint,5,opt,name=ContextWindowTokensEstimated,proto3" json:"ContextWindowTokensEstimated,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AIContextWindowUsage) Reset() {
*x = AIContextWindowUsage{}
mi := &file_clientpb_client_proto_msgTypes[131]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AIContextWindowUsage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AIContextWindowUsage) ProtoMessage() {}
func (x *AIContextWindowUsage) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[131]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AIContextWindowUsage.ProtoReflect.Descriptor instead.
func (*AIContextWindowUsage) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{131}
}
func (x *AIContextWindowUsage) GetInputTokens() int64 {
if x != nil {
return x.InputTokens
}
return 0
}
func (x *AIContextWindowUsage) GetOutputTokens() int64 {
if x != nil {
return x.OutputTokens
}
return 0
}
func (x *AIContextWindowUsage) GetTotalTokens() int64 {
if x != nil {
return x.TotalTokens
}
return 0
}
func (x *AIContextWindowUsage) GetContextWindowTokens() int64 {
if x != nil {
return x.ContextWindowTokens
}
return 0
}
func (x *AIContextWindowUsage) GetContextWindowTokensEstimated() bool {
if x != nil {
return x.ContextWindowTokensEstimated
}
return false
}
type AIConversation struct {
state protoimpl.MessageState `protogen:"open.v1"`
ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"`
CreatedAt int64 `protobuf:"varint,2,opt,name=CreatedAt,proto3" json:"CreatedAt,omitempty"`
UpdatedAt int64 `protobuf:"varint,3,opt,name=UpdatedAt,proto3" json:"UpdatedAt,omitempty"`
OperatorName string `protobuf:"bytes,4,opt,name=OperatorName,proto3" json:"OperatorName,omitempty"`
Provider string `protobuf:"bytes,5,opt,name=Provider,proto3" json:"Provider,omitempty"`
Model string `protobuf:"bytes,6,opt,name=Model,proto3" json:"Model,omitempty"`
Title string `protobuf:"bytes,7,opt,name=Title,proto3" json:"Title,omitempty"`
Summary string `protobuf:"bytes,8,opt,name=Summary,proto3" json:"Summary,omitempty"`
SystemPrompt string `protobuf:"bytes,9,opt,name=SystemPrompt,proto3" json:"SystemPrompt,omitempty"`
Messages []*AIConversationMessage `protobuf:"bytes,10,rep,name=Messages,proto3" json:"Messages,omitempty"`
ActiveTurnID string `protobuf:"bytes,11,opt,name=ActiveTurnID,proto3" json:"ActiveTurnID,omitempty"`
TurnState AIConversationTurnState `protobuf:"varint,12,opt,name=TurnState,proto3,enum=clientpb.AIConversationTurnState" json:"TurnState,omitempty"`
TargetSessionID string `protobuf:"bytes,13,opt,name=TargetSessionID,proto3" json:"TargetSessionID,omitempty"`
TargetBeaconID string `protobuf:"bytes,14,opt,name=TargetBeaconID,proto3" json:"TargetBeaconID,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
state protoimpl.MessageState `protogen:"open.v1"`
ID string `protobuf:"bytes,1,opt,name=ID,proto3" json:"ID,omitempty"`
CreatedAt int64 `protobuf:"varint,2,opt,name=CreatedAt,proto3" json:"CreatedAt,omitempty"`
UpdatedAt int64 `protobuf:"varint,3,opt,name=UpdatedAt,proto3" json:"UpdatedAt,omitempty"`
OperatorName string `protobuf:"bytes,4,opt,name=OperatorName,proto3" json:"OperatorName,omitempty"`
Provider string `protobuf:"bytes,5,opt,name=Provider,proto3" json:"Provider,omitempty"`
Model string `protobuf:"bytes,6,opt,name=Model,proto3" json:"Model,omitempty"`
Title string `protobuf:"bytes,7,opt,name=Title,proto3" json:"Title,omitempty"`
Summary string `protobuf:"bytes,8,opt,name=Summary,proto3" json:"Summary,omitempty"`
SystemPrompt string `protobuf:"bytes,9,opt,name=SystemPrompt,proto3" json:"SystemPrompt,omitempty"`
Messages []*AIConversationMessage `protobuf:"bytes,10,rep,name=Messages,proto3" json:"Messages,omitempty"`
ActiveTurnID string `protobuf:"bytes,11,opt,name=ActiveTurnID,proto3" json:"ActiveTurnID,omitempty"`
TurnState AIConversationTurnState `protobuf:"varint,12,opt,name=TurnState,proto3,enum=clientpb.AIConversationTurnState" json:"TurnState,omitempty"`
TargetSessionID string `protobuf:"bytes,13,opt,name=TargetSessionID,proto3" json:"TargetSessionID,omitempty"`
TargetBeaconID string `protobuf:"bytes,14,opt,name=TargetBeaconID,proto3" json:"TargetBeaconID,omitempty"`
ThinkingLevel string `protobuf:"bytes,15,opt,name=ThinkingLevel,proto3" json:"ThinkingLevel,omitempty"`
ContextWindowUsage *AIContextWindowUsage `protobuf:"bytes,16,opt,name=ContextWindowUsage,proto3" json:"ContextWindowUsage,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AIConversation) Reset() {
*x = AIConversation{}
mi := &file_clientpb_client_proto_msgTypes[131]
mi := &file_clientpb_client_proto_msgTypes[132]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -11858,7 +11944,7 @@ func (x *AIConversation) String() string {
func (*AIConversation) ProtoMessage() {}
func (x *AIConversation) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[131]
mi := &file_clientpb_client_proto_msgTypes[132]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -11871,7 +11957,7 @@ func (x *AIConversation) ProtoReflect() protoreflect.Message {
// Deprecated: Use AIConversation.ProtoReflect.Descriptor instead.
func (*AIConversation) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{131}
return file_clientpb_client_proto_rawDescGZIP(), []int{132}
}
func (x *AIConversation) GetID() string {
@@ -11972,6 +12058,20 @@ func (x *AIConversation) GetTargetBeaconID() string {
return ""
}
func (x *AIConversation) GetThinkingLevel() string {
if x != nil {
return x.ThinkingLevel
}
return ""
}
func (x *AIConversation) GetContextWindowUsage() *AIContextWindowUsage {
if x != nil {
return x.ContextWindowUsage
}
return nil
}
type AIConversationMessages struct {
state protoimpl.MessageState `protogen:"open.v1"`
ConversationID string `protobuf:"bytes,1,opt,name=ConversationID,proto3" json:"ConversationID,omitempty"`
@@ -11982,7 +12082,7 @@ type AIConversationMessages struct {
func (x *AIConversationMessages) Reset() {
*x = AIConversationMessages{}
mi := &file_clientpb_client_proto_msgTypes[132]
mi := &file_clientpb_client_proto_msgTypes[133]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -11994,7 +12094,7 @@ func (x *AIConversationMessages) String() string {
func (*AIConversationMessages) ProtoMessage() {}
func (x *AIConversationMessages) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[132]
mi := &file_clientpb_client_proto_msgTypes[133]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12007,7 +12107,7 @@ func (x *AIConversationMessages) ProtoReflect() protoreflect.Message {
// Deprecated: Use AIConversationMessages.ProtoReflect.Descriptor instead.
func (*AIConversationMessages) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{132}
return file_clientpb_client_proto_rawDescGZIP(), []int{133}
}
func (x *AIConversationMessages) GetConversationID() string {
@@ -12048,13 +12148,14 @@ type AIConversationMessage struct {
ToolArguments string `protobuf:"bytes,20,opt,name=ToolArguments,proto3" json:"ToolArguments,omitempty"`
ToolResult string `protobuf:"bytes,21,opt,name=ToolResult,proto3" json:"ToolResult,omitempty"`
ErrorText string `protobuf:"bytes,22,opt,name=ErrorText,proto3" json:"ErrorText,omitempty"`
IncludeInContext *bool `protobuf:"varint,23,opt,name=IncludeInContext,proto3,oneof" json:"IncludeInContext,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AIConversationMessage) Reset() {
*x = AIConversationMessage{}
mi := &file_clientpb_client_proto_msgTypes[133]
mi := &file_clientpb_client_proto_msgTypes[134]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12066,7 +12167,7 @@ func (x *AIConversationMessage) String() string {
func (*AIConversationMessage) ProtoMessage() {}
func (x *AIConversationMessage) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[133]
mi := &file_clientpb_client_proto_msgTypes[134]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12079,7 +12180,7 @@ func (x *AIConversationMessage) ProtoReflect() protoreflect.Message {
// Deprecated: Use AIConversationMessage.ProtoReflect.Descriptor instead.
func (*AIConversationMessage) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{133}
return file_clientpb_client_proto_rawDescGZIP(), []int{134}
}
func (x *AIConversationMessage) GetID() string {
@@ -12236,6 +12337,13 @@ func (x *AIConversationMessage) GetErrorText() string {
return ""
}
func (x *AIConversationMessage) GetIncludeInContext() bool {
if x != nil && x.IncludeInContext != nil {
return *x.IncludeInContext
}
return false
}
type AIConversationEvent struct {
state protoimpl.MessageState `protogen:"open.v1"`
EventType AIConversationEventType `protobuf:"varint,1,opt,name=EventType,proto3,enum=clientpb.AIConversationEventType" json:"EventType,omitempty"`
@@ -12250,7 +12358,7 @@ type AIConversationEvent struct {
func (x *AIConversationEvent) Reset() {
*x = AIConversationEvent{}
mi := &file_clientpb_client_proto_msgTypes[134]
mi := &file_clientpb_client_proto_msgTypes[135]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12262,7 +12370,7 @@ func (x *AIConversationEvent) String() string {
func (*AIConversationEvent) ProtoMessage() {}
func (x *AIConversationEvent) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[134]
mi := &file_clientpb_client_proto_msgTypes[135]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12275,7 +12383,7 @@ func (x *AIConversationEvent) ProtoReflect() protoreflect.Message {
// Deprecated: Use AIConversationEvent.ProtoReflect.Descriptor instead.
func (*AIConversationEvent) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{134}
return file_clientpb_client_proto_rawDescGZIP(), []int{135}
}
func (x *AIConversationEvent) GetEventType() AIConversationEventType {
@@ -12330,7 +12438,7 @@ type MonitoringProviders struct {
func (x *MonitoringProviders) Reset() {
*x = MonitoringProviders{}
mi := &file_clientpb_client_proto_msgTypes[135]
mi := &file_clientpb_client_proto_msgTypes[136]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12342,7 +12450,7 @@ func (x *MonitoringProviders) String() string {
func (*MonitoringProviders) ProtoMessage() {}
func (x *MonitoringProviders) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[135]
mi := &file_clientpb_client_proto_msgTypes[136]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12355,7 +12463,7 @@ func (x *MonitoringProviders) ProtoReflect() protoreflect.Message {
// Deprecated: Use MonitoringProviders.ProtoReflect.Descriptor instead.
func (*MonitoringProviders) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{135}
return file_clientpb_client_proto_rawDescGZIP(), []int{136}
}
func (x *MonitoringProviders) GetProviders() []*MonitoringProvider {
@@ -12377,7 +12485,7 @@ type MonitoringProvider struct {
func (x *MonitoringProvider) Reset() {
*x = MonitoringProvider{}
mi := &file_clientpb_client_proto_msgTypes[136]
mi := &file_clientpb_client_proto_msgTypes[137]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12389,7 +12497,7 @@ func (x *MonitoringProvider) String() string {
func (*MonitoringProvider) ProtoMessage() {}
func (x *MonitoringProvider) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[136]
mi := &file_clientpb_client_proto_msgTypes[137]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12402,7 +12510,7 @@ func (x *MonitoringProvider) ProtoReflect() protoreflect.Message {
// Deprecated: Use MonitoringProvider.ProtoReflect.Descriptor instead.
func (*MonitoringProvider) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{136}
return file_clientpb_client_proto_rawDescGZIP(), []int{137}
}
func (x *MonitoringProvider) GetID() string {
@@ -12446,7 +12554,7 @@ type ResourceID struct {
func (x *ResourceID) Reset() {
*x = ResourceID{}
mi := &file_clientpb_client_proto_msgTypes[137]
mi := &file_clientpb_client_proto_msgTypes[138]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12458,7 +12566,7 @@ func (x *ResourceID) String() string {
func (*ResourceID) ProtoMessage() {}
func (x *ResourceID) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[137]
mi := &file_clientpb_client_proto_msgTypes[138]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12471,7 +12579,7 @@ func (x *ResourceID) ProtoReflect() protoreflect.Message {
// Deprecated: Use ResourceID.ProtoReflect.Descriptor instead.
func (*ResourceID) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{137}
return file_clientpb_client_proto_rawDescGZIP(), []int{138}
}
func (x *ResourceID) GetID() string {
@@ -12512,7 +12620,7 @@ type CertificatesReq struct {
func (x *CertificatesReq) Reset() {
*x = CertificatesReq{}
mi := &file_clientpb_client_proto_msgTypes[138]
mi := &file_clientpb_client_proto_msgTypes[139]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12524,7 +12632,7 @@ func (x *CertificatesReq) String() string {
func (*CertificatesReq) ProtoMessage() {}
func (x *CertificatesReq) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[138]
mi := &file_clientpb_client_proto_msgTypes[139]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12537,7 +12645,7 @@ func (x *CertificatesReq) ProtoReflect() protoreflect.Message {
// Deprecated: Use CertificatesReq.ProtoReflect.Descriptor instead.
func (*CertificatesReq) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{138}
return file_clientpb_client_proto_rawDescGZIP(), []int{139}
}
func (x *CertificatesReq) GetCategoryFilters() uint32 {
@@ -12569,7 +12677,7 @@ type CertificateData struct {
func (x *CertificateData) Reset() {
*x = CertificateData{}
mi := &file_clientpb_client_proto_msgTypes[139]
mi := &file_clientpb_client_proto_msgTypes[140]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12581,7 +12689,7 @@ func (x *CertificateData) String() string {
func (*CertificateData) ProtoMessage() {}
func (x *CertificateData) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[139]
mi := &file_clientpb_client_proto_msgTypes[140]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12594,7 +12702,7 @@ func (x *CertificateData) ProtoReflect() protoreflect.Message {
// Deprecated: Use CertificateData.ProtoReflect.Descriptor instead.
func (*CertificateData) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{139}
return file_clientpb_client_proto_rawDescGZIP(), []int{140}
}
func (x *CertificateData) GetCN() string {
@@ -12655,7 +12763,7 @@ type CertificateInfo struct {
func (x *CertificateInfo) Reset() {
*x = CertificateInfo{}
mi := &file_clientpb_client_proto_msgTypes[140]
mi := &file_clientpb_client_proto_msgTypes[141]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12667,7 +12775,7 @@ func (x *CertificateInfo) String() string {
func (*CertificateInfo) ProtoMessage() {}
func (x *CertificateInfo) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[140]
mi := &file_clientpb_client_proto_msgTypes[141]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12680,7 +12788,7 @@ func (x *CertificateInfo) ProtoReflect() protoreflect.Message {
// Deprecated: Use CertificateInfo.ProtoReflect.Descriptor instead.
func (*CertificateInfo) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{140}
return file_clientpb_client_proto_rawDescGZIP(), []int{141}
}
func (x *CertificateInfo) GetInfo() []*CertificateData {
@@ -12705,7 +12813,7 @@ type CertificateAuthorityData struct {
func (x *CertificateAuthorityData) Reset() {
*x = CertificateAuthorityData{}
mi := &file_clientpb_client_proto_msgTypes[141]
mi := &file_clientpb_client_proto_msgTypes[142]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12717,7 +12825,7 @@ func (x *CertificateAuthorityData) String() string {
func (*CertificateAuthorityData) ProtoMessage() {}
func (x *CertificateAuthorityData) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[141]
mi := &file_clientpb_client_proto_msgTypes[142]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12730,7 +12838,7 @@ func (x *CertificateAuthorityData) ProtoReflect() protoreflect.Message {
// Deprecated: Use CertificateAuthorityData.ProtoReflect.Descriptor instead.
func (*CertificateAuthorityData) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{141}
return file_clientpb_client_proto_rawDescGZIP(), []int{142}
}
func (x *CertificateAuthorityData) GetCN() string {
@@ -12791,7 +12899,7 @@ type CertificateAuthorityInfo struct {
func (x *CertificateAuthorityInfo) Reset() {
*x = CertificateAuthorityInfo{}
mi := &file_clientpb_client_proto_msgTypes[142]
mi := &file_clientpb_client_proto_msgTypes[143]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -12803,7 +12911,7 @@ func (x *CertificateAuthorityInfo) String() string {
func (*CertificateAuthorityInfo) ProtoMessage() {}
func (x *CertificateAuthorityInfo) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[142]
mi := &file_clientpb_client_proto_msgTypes[143]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -12816,7 +12924,7 @@ func (x *CertificateAuthorityInfo) ProtoReflect() protoreflect.Message {
// Deprecated: Use CertificateAuthorityInfo.ProtoReflect.Descriptor instead.
func (*CertificateAuthorityInfo) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{142}
return file_clientpb_client_proto_rawDescGZIP(), []int{143}
}
func (x *CertificateAuthorityInfo) GetInfo() []*CertificateAuthorityData {
@@ -13801,18 +13909,25 @@ const file_clientpb_client_proto_rawDesc = "" +
"\x04Name\x18\x01 \x01(\tR\x04Name\x12\x1e\n" +
"\n" +
"Configured\x18\x02 \x01(\bR\n" +
"Configured\"\x95\x01\n" +
"Configured\"\xb9\x01\n" +
"\x0fAIConfigSummary\x12\x1a\n" +
"\bProvider\x18\x01 \x01(\tR\bProvider\x12\x14\n" +
"\x05Model\x18\x02 \x01(\tR\x05Model\x12$\n" +
"\rThinkingLevel\x18\x03 \x01(\tR\rThinkingLevel\x12\x14\n" +
"\x05Valid\x18\x04 \x01(\bR\x05Valid\x12\x14\n" +
"\x05Error\x18\x05 \x01(\tR\x05Error\"M\n" +
"\x05Error\x18\x05 \x01(\tR\x05Error\x12\"\n" +
"\fSystemPrompt\x18\x06 \x01(\tR\fSystemPrompt\"M\n" +
"\x11AIConversationReq\x12\x0e\n" +
"\x02ID\x18\x01 \x01(\tR\x02ID\x12(\n" +
"\x0fIncludeMessages\x18\x02 \x01(\bR\x0fIncludeMessages\"Q\n" +
"\x0fAIConversations\x12>\n" +
"\rConversations\x18\x01 \x03(\v2\x18.clientpb.AIConversationR\rConversations\"\xfa\x03\n" +
"\rConversations\x18\x01 \x03(\v2\x18.clientpb.AIConversationR\rConversations\"\xf4\x01\n" +
"\x14AIContextWindowUsage\x12 \n" +
"\vInputTokens\x18\x01 \x01(\x03R\vInputTokens\x12\"\n" +
"\fOutputTokens\x18\x02 \x01(\x03R\fOutputTokens\x12 \n" +
"\vTotalTokens\x18\x03 \x01(\x03R\vTotalTokens\x120\n" +
"\x13ContextWindowTokens\x18\x04 \x01(\x03R\x13ContextWindowTokens\x12B\n" +
"\x1cContextWindowTokensEstimated\x18\x05 \x01(\bR\x1cContextWindowTokensEstimated\"\xf0\x04\n" +
"\x0eAIConversation\x12\x0e\n" +
"\x02ID\x18\x01 \x01(\tR\x02ID\x12\x1c\n" +
"\tCreatedAt\x18\x02 \x01(\x03R\tCreatedAt\x12\x1c\n" +
@@ -13828,10 +13943,12 @@ const file_clientpb_client_proto_rawDesc = "" +
"\fActiveTurnID\x18\v \x01(\tR\fActiveTurnID\x12?\n" +
"\tTurnState\x18\f \x01(\x0e2!.clientpb.AIConversationTurnStateR\tTurnState\x12(\n" +
"\x0fTargetSessionID\x18\r \x01(\tR\x0fTargetSessionID\x12&\n" +
"\x0eTargetBeaconID\x18\x0e \x01(\tR\x0eTargetBeaconID\"}\n" +
"\x0eTargetBeaconID\x18\x0e \x01(\tR\x0eTargetBeaconID\x12$\n" +
"\rThinkingLevel\x18\x0f \x01(\tR\rThinkingLevel\x12N\n" +
"\x12ContextWindowUsage\x18\x10 \x01(\v2\x1e.clientpb.AIContextWindowUsageR\x12ContextWindowUsage\"}\n" +
"\x16AIConversationMessages\x12&\n" +
"\x0eConversationID\x18\x01 \x01(\tR\x0eConversationID\x12;\n" +
"\bMessages\x18\x02 \x03(\v2\x1f.clientpb.AIConversationMessageR\bMessages\"\x8d\x06\n" +
"\bMessages\x18\x02 \x03(\v2\x1f.clientpb.AIConversationMessageR\bMessages\"\xd3\x06\n" +
"\x15AIConversationMessage\x12\x0e\n" +
"\x02ID\x18\x01 \x01(\tR\x02ID\x12&\n" +
"\x0eConversationID\x18\x02 \x01(\tR\x0eConversationID\x12\x1c\n" +
@@ -13861,7 +13978,9 @@ const file_clientpb_client_proto_rawDesc = "" +
"\n" +
"ToolResult\x18\x15 \x01(\tR\n" +
"ToolResult\x12\x1c\n" +
"\tErrorText\x18\x16 \x01(\tR\tErrorText\"\xad\x02\n" +
"\tErrorText\x18\x16 \x01(\tR\tErrorText\x12/\n" +
"\x10IncludeInContext\x18\x17 \x01(\bH\x00R\x10IncludeInContext\x88\x01\x01B\x13\n" +
"\x11_IncludeInContext\"\xad\x02\n" +
"\x13AIConversationEvent\x12?\n" +
"\tEventType\x18\x01 \x01(\x0e2!.clientpb.AIConversationEventTypeR\tEventType\x12&\n" +
"\x0eConversationID\x18\x02 \x01(\tR\x0eConversationID\x12\x16\n" +
@@ -14154,7 +14273,7 @@ func file_clientpb_client_proto_rawDescGZIP() []byte {
}
var file_clientpb_client_proto_enumTypes = make([]protoimpl.EnumInfo, 18)
var file_clientpb_client_proto_msgTypes = make([]protoimpl.MessageInfo, 157)
var file_clientpb_client_proto_msgTypes = make([]protoimpl.MessageInfo, 158)
var file_clientpb_client_proto_goTypes = []any{
(OutputFormat)(0), // 0: clientpb.OutputFormat
(StageProtocol)(0), // 1: clientpb.StageProtocol
@@ -14305,35 +14424,36 @@ var file_clientpb_client_proto_goTypes = []any{
(*AIConfigSummary)(nil), // 146: clientpb.AIConfigSummary
(*AIConversationReq)(nil), // 147: clientpb.AIConversationReq
(*AIConversations)(nil), // 148: clientpb.AIConversations
(*AIConversation)(nil), // 149: clientpb.AIConversation
(*AIConversationMessages)(nil), // 150: clientpb.AIConversationMessages
(*AIConversationMessage)(nil), // 151: clientpb.AIConversationMessage
(*AIConversationEvent)(nil), // 152: clientpb.AIConversationEvent
(*MonitoringProviders)(nil), // 153: clientpb.MonitoringProviders
(*MonitoringProvider)(nil), // 154: clientpb.MonitoringProvider
(*ResourceID)(nil), // 155: clientpb.ResourceID
(*CertificatesReq)(nil), // 156: clientpb.CertificatesReq
(*CertificateData)(nil), // 157: clientpb.CertificateData
(*CertificateInfo)(nil), // 158: clientpb.CertificateInfo
(*CertificateAuthorityData)(nil), // 159: clientpb.CertificateAuthorityData
(*CertificateAuthorityInfo)(nil), // 160: clientpb.CertificateAuthorityInfo
nil, // 161: clientpb.TrafficEncoderMap.EncodersEntry
nil, // 162: clientpb.ExternalImplantConfig.EncodersEntry
nil, // 163: clientpb.ImplantBuilds.ConfigsEntry
nil, // 164: clientpb.ImplantBuilds.ResourceIDsEntry
nil, // 165: clientpb.ImplantBuilds.StagedEntry
nil, // 166: clientpb.WebsiteAddContent.ContentsEntry
nil, // 167: clientpb.Website.ContentsEntry
nil, // 168: clientpb.Host.ExtensionDataEntry
nil, // 169: clientpb.ShellcodeEncoderArchMap.EncodersEntry
nil, // 170: clientpb.ShellcodeEncoderArchMap.DescriptionsEntry
nil, // 171: clientpb.ShellcodeEncoderMap.EncodersEntry
nil, // 172: clientpb.CrackSyncStatus.ProgressEntry
nil, // 173: clientpb.CrackBenchmark.BenchmarksEntry
nil, // 174: clientpb.Crackstation.BenchmarksEntry
(*commonpb.File)(nil), // 175: commonpb.File
(*commonpb.Request)(nil), // 176: commonpb.Request
(*commonpb.Response)(nil), // 177: commonpb.Response
(*AIContextWindowUsage)(nil), // 149: clientpb.AIContextWindowUsage
(*AIConversation)(nil), // 150: clientpb.AIConversation
(*AIConversationMessages)(nil), // 151: clientpb.AIConversationMessages
(*AIConversationMessage)(nil), // 152: clientpb.AIConversationMessage
(*AIConversationEvent)(nil), // 153: clientpb.AIConversationEvent
(*MonitoringProviders)(nil), // 154: clientpb.MonitoringProviders
(*MonitoringProvider)(nil), // 155: clientpb.MonitoringProvider
(*ResourceID)(nil), // 156: clientpb.ResourceID
(*CertificatesReq)(nil), // 157: clientpb.CertificatesReq
(*CertificateData)(nil), // 158: clientpb.CertificateData
(*CertificateInfo)(nil), // 159: clientpb.CertificateInfo
(*CertificateAuthorityData)(nil), // 160: clientpb.CertificateAuthorityData
(*CertificateAuthorityInfo)(nil), // 161: clientpb.CertificateAuthorityInfo
nil, // 162: clientpb.TrafficEncoderMap.EncodersEntry
nil, // 163: clientpb.ExternalImplantConfig.EncodersEntry
nil, // 164: clientpb.ImplantBuilds.ConfigsEntry
nil, // 165: clientpb.ImplantBuilds.ResourceIDsEntry
nil, // 166: clientpb.ImplantBuilds.StagedEntry
nil, // 167: clientpb.WebsiteAddContent.ContentsEntry
nil, // 168: clientpb.Website.ContentsEntry
nil, // 169: clientpb.Host.ExtensionDataEntry
nil, // 170: clientpb.ShellcodeEncoderArchMap.EncodersEntry
nil, // 171: clientpb.ShellcodeEncoderArchMap.DescriptionsEntry
nil, // 172: clientpb.ShellcodeEncoderMap.EncodersEntry
nil, // 173: clientpb.CrackSyncStatus.ProgressEntry
nil, // 174: clientpb.CrackBenchmark.BenchmarksEntry
nil, // 175: clientpb.Crackstation.BenchmarksEntry
(*commonpb.File)(nil), // 176: commonpb.File
(*commonpb.Request)(nil), // 177: commonpb.Request
(*commonpb.Response)(nil), // 178: commonpb.Response
}
var file_clientpb_client_proto_depIdxs = []int32{
21, // 0: clientpb.Beacons.Beacons:type_name -> clientpb.Beacon
@@ -14343,7 +14463,7 @@ var file_clientpb_client_proto_depIdxs = []int32{
0, // 4: clientpb.ImplantConfig.Format:type_name -> clientpb.OutputFormat
27, // 5: clientpb.ImplantConfig.ShellcodeConfig:type_name -> clientpb.ShellcodeConfig
3, // 6: clientpb.ImplantConfig.ShellcodeEncoder:type_name -> clientpb.ShellcodeEncoder
175, // 7: clientpb.ImplantConfig.Assets:type_name -> commonpb.File
176, // 7: clientpb.ImplantConfig.Assets:type_name -> commonpb.File
29, // 8: clientpb.PESpoofMetadataConfig.Source:type_name -> clientpb.SpoofMetadataFile
29, // 9: clientpb.PESpoofMetadataConfig.Icon:type_name -> clientpb.SpoofMetadataFile
30, // 10: clientpb.PESpoofMetadataConfig.ResourceDirectory:type_name -> clientpb.IMAGE_RESOURCE_DIRECTORY
@@ -14351,18 +14471,18 @@ var file_clientpb_client_proto_depIdxs = []int32{
32, // 12: clientpb.PESpoofMetadataConfig.ResourceDataEntries:type_name -> clientpb.IMAGE_RESOURCE_DATA_ENTRY
33, // 13: clientpb.PESpoofMetadataConfig.ExportDirectory:type_name -> clientpb.IMAGE_EXPORT_DIRECTORY
34, // 14: clientpb.SpoofMetadataConfig.PE:type_name -> clientpb.PESpoofMetadataConfig
175, // 15: clientpb.TrafficEncoder.Wasm:type_name -> commonpb.File
161, // 16: clientpb.TrafficEncoderMap.Encoders:type_name -> clientpb.TrafficEncoderMap.EncodersEntry
176, // 15: clientpb.TrafficEncoder.Wasm:type_name -> commonpb.File
162, // 16: clientpb.TrafficEncoderMap.Encoders:type_name -> clientpb.TrafficEncoderMap.EncodersEntry
36, // 17: clientpb.TrafficEncoderTests.Encoder:type_name -> clientpb.TrafficEncoder
38, // 18: clientpb.TrafficEncoderTests.Tests:type_name -> clientpb.TrafficEncoderTest
28, // 19: clientpb.ExternalImplantConfig.Config:type_name -> clientpb.ImplantConfig
44, // 20: clientpb.ExternalImplantConfig.Build:type_name -> clientpb.ImplantBuild
119, // 21: clientpb.ExternalImplantConfig.HTTPC2:type_name -> clientpb.HTTPC2Config
162, // 22: clientpb.ExternalImplantConfig.encoders:type_name -> clientpb.ExternalImplantConfig.EncodersEntry
175, // 23: clientpb.ExternalImplantBinary.File:type_name -> commonpb.File
163, // 24: clientpb.ImplantBuilds.Configs:type_name -> clientpb.ImplantBuilds.ConfigsEntry
164, // 25: clientpb.ImplantBuilds.ResourceIDs:type_name -> clientpb.ImplantBuilds.ResourceIDsEntry
165, // 26: clientpb.ImplantBuilds.staged:type_name -> clientpb.ImplantBuilds.StagedEntry
163, // 22: clientpb.ExternalImplantConfig.encoders:type_name -> clientpb.ExternalImplantConfig.EncodersEntry
176, // 23: clientpb.ExternalImplantBinary.File:type_name -> commonpb.File
164, // 24: clientpb.ImplantBuilds.Configs:type_name -> clientpb.ImplantBuilds.ConfigsEntry
165, // 25: clientpb.ImplantBuilds.ResourceIDs:type_name -> clientpb.ImplantBuilds.ResourceIDsEntry
166, // 26: clientpb.ImplantBuilds.staged:type_name -> clientpb.ImplantBuilds.StagedEntry
0, // 27: clientpb.CompilerTarget.Format:type_name -> clientpb.OutputFormat
45, // 28: clientpb.Compiler.Targets:type_name -> clientpb.CompilerTarget
46, // 29: clientpb.Compiler.CrossCompilers:type_name -> clientpb.CrossCompiler
@@ -14377,24 +14497,24 @@ var file_clientpb_client_proto_depIdxs = []int32{
65, // 38: clientpb.ListenerJob.HTTPConf:type_name -> clientpb.HTTPListenerReq
61, // 39: clientpb.ListenerJob.MultiConf:type_name -> clientpb.MultiplayerListenerReq
78, // 40: clientpb.ListenerJob.TCPConf:type_name -> clientpb.StagerListenerReq
176, // 41: clientpb.NamedPipesReq.Request:type_name -> commonpb.Request
177, // 42: clientpb.NamedPipes.Response:type_name -> commonpb.Response
176, // 43: clientpb.TCPPivotReq.Request:type_name -> commonpb.Request
177, // 44: clientpb.TCPPivot.Response:type_name -> commonpb.Response
177, // 41: clientpb.NamedPipesReq.Request:type_name -> commonpb.Request
178, // 42: clientpb.NamedPipes.Response:type_name -> commonpb.Response
177, // 43: clientpb.TCPPivotReq.Request:type_name -> commonpb.Request
178, // 44: clientpb.TCPPivot.Response:type_name -> commonpb.Response
20, // 45: clientpb.Sessions.Sessions:type_name -> clientpb.Session
28, // 46: clientpb.GenerateReq.Config:type_name -> clientpb.ImplantConfig
175, // 47: clientpb.Generate.File:type_name -> commonpb.File
176, // 47: clientpb.Generate.File:type_name -> commonpb.File
35, // 48: clientpb.GenerateSpoofMetadataReq.SpoofMetadata:type_name -> clientpb.SpoofMetadataConfig
176, // 49: clientpb.MSFReq.Request:type_name -> commonpb.Request
176, // 50: clientpb.MSFRemoteReq.Request:type_name -> commonpb.Request
177, // 49: clientpb.MSFReq.Request:type_name -> commonpb.Request
177, // 50: clientpb.MSFRemoteReq.Request:type_name -> commonpb.Request
1, // 51: clientpb.StagerListenerReq.Protocol:type_name -> clientpb.StageProtocol
28, // 52: clientpb.GetSystemReq.Config:type_name -> clientpb.ImplantConfig
176, // 53: clientpb.GetSystemReq.Request:type_name -> commonpb.Request
177, // 53: clientpb.GetSystemReq.Request:type_name -> commonpb.Request
28, // 54: clientpb.MigrateReq.Config:type_name -> clientpb.ImplantConfig
3, // 55: clientpb.MigrateReq.Encoder:type_name -> clientpb.ShellcodeEncoder
176, // 56: clientpb.MigrateReq.Request:type_name -> commonpb.Request
176, // 57: clientpb.CreateTunnelReq.Request:type_name -> commonpb.Request
176, // 58: clientpb.CloseTunnelReq.Request:type_name -> commonpb.Request
177, // 56: clientpb.MigrateReq.Request:type_name -> commonpb.Request
177, // 57: clientpb.CreateTunnelReq.Request:type_name -> commonpb.Request
177, // 58: clientpb.CloseTunnelReq.Request:type_name -> commonpb.Request
20, // 59: clientpb.PivotGraphEntry.Session:type_name -> clientpb.Session
87, // 60: clientpb.PivotGraphEntry.Children:type_name -> clientpb.PivotGraphEntry
87, // 61: clientpb.PivotGraph.Children:type_name -> clientpb.PivotGraphEntry
@@ -14403,25 +14523,25 @@ var file_clientpb_client_proto_depIdxs = []int32{
55, // 64: clientpb.Event.Job:type_name -> clientpb.Job
89, // 65: clientpb.Event.Client:type_name -> clientpb.Client
92, // 66: clientpb.Operators.Operators:type_name -> clientpb.Operator
166, // 67: clientpb.WebsiteAddContent.Contents:type_name -> clientpb.WebsiteAddContent.ContentsEntry
167, // 68: clientpb.Website.Contents:type_name -> clientpb.Website.ContentsEntry
167, // 67: clientpb.WebsiteAddContent.Contents:type_name -> clientpb.WebsiteAddContent.ContentsEntry
168, // 68: clientpb.Website.Contents:type_name -> clientpb.Website.ContentsEntry
96, // 69: clientpb.Websites.Websites:type_name -> clientpb.Website
2, // 70: clientpb.Loot.FileType:type_name -> clientpb.FileType
175, // 71: clientpb.Loot.File:type_name -> commonpb.File
176, // 71: clientpb.Loot.File:type_name -> commonpb.File
99, // 72: clientpb.AllLoot.Loot:type_name -> clientpb.Loot
101, // 73: clientpb.Host.IOCs:type_name -> clientpb.IOC
168, // 74: clientpb.Host.ExtensionData:type_name -> clientpb.Host.ExtensionDataEntry
169, // 74: clientpb.Host.ExtensionData:type_name -> clientpb.Host.ExtensionDataEntry
103, // 75: clientpb.AllHosts.Hosts:type_name -> clientpb.Host
176, // 76: clientpb.DllHijackReq.Request:type_name -> commonpb.Request
177, // 77: clientpb.DllHijack.Response:type_name -> commonpb.Response
176, // 78: clientpb.BackdoorReq.Request:type_name -> commonpb.Request
177, // 79: clientpb.Backdoor.Response:type_name -> commonpb.Response
177, // 76: clientpb.DllHijackReq.Request:type_name -> commonpb.Request
178, // 77: clientpb.DllHijack.Response:type_name -> commonpb.Response
177, // 78: clientpb.BackdoorReq.Request:type_name -> commonpb.Request
178, // 79: clientpb.Backdoor.Response:type_name -> commonpb.Response
3, // 80: clientpb.ShellcodeEncodeReq.Encoder:type_name -> clientpb.ShellcodeEncoder
176, // 81: clientpb.ShellcodeEncodeReq.Request:type_name -> commonpb.Request
177, // 82: clientpb.ShellcodeEncode.Response:type_name -> commonpb.Response
169, // 83: clientpb.ShellcodeEncoderArchMap.Encoders:type_name -> clientpb.ShellcodeEncoderArchMap.EncodersEntry
170, // 84: clientpb.ShellcodeEncoderArchMap.Descriptions:type_name -> clientpb.ShellcodeEncoderArchMap.DescriptionsEntry
171, // 85: clientpb.ShellcodeEncoderMap.Encoders:type_name -> clientpb.ShellcodeEncoderMap.EncodersEntry
177, // 81: clientpb.ShellcodeEncodeReq.Request:type_name -> commonpb.Request
178, // 82: clientpb.ShellcodeEncode.Response:type_name -> commonpb.Response
170, // 83: clientpb.ShellcodeEncoderArchMap.Encoders:type_name -> clientpb.ShellcodeEncoderArchMap.EncodersEntry
171, // 84: clientpb.ShellcodeEncoderArchMap.Descriptions:type_name -> clientpb.ShellcodeEncoderArchMap.DescriptionsEntry
172, // 85: clientpb.ShellcodeEncoderMap.Encoders:type_name -> clientpb.ShellcodeEncoderMap.EncodersEntry
28, // 86: clientpb.ExternalGenerateReq.Config:type_name -> clientpb.ImplantConfig
115, // 87: clientpb.Builders.Builders:type_name -> clientpb.Builder
45, // 88: clientpb.Builder.Targets:type_name -> clientpb.CompilerTarget
@@ -14440,10 +14560,10 @@ var file_clientpb_client_proto_depIdxs = []int32{
133, // 101: clientpb.Crackstations.Crackstations:type_name -> clientpb.Crackstation
6, // 102: clientpb.CrackstationStatus.State:type_name -> clientpb.States
130, // 103: clientpb.CrackstationStatus.Syncing:type_name -> clientpb.CrackSyncStatus
172, // 104: clientpb.CrackSyncStatus.Progress:type_name -> clientpb.CrackSyncStatus.ProgressEntry
173, // 105: clientpb.CrackBenchmark.Benchmarks:type_name -> clientpb.CrackBenchmark.BenchmarksEntry
173, // 104: clientpb.CrackSyncStatus.Progress:type_name -> clientpb.CrackSyncStatus.ProgressEntry
174, // 105: clientpb.CrackBenchmark.Benchmarks:type_name -> clientpb.CrackBenchmark.BenchmarksEntry
137, // 106: clientpb.CrackTask.Command:type_name -> clientpb.CrackCommand
174, // 107: clientpb.Crackstation.Benchmarks:type_name -> clientpb.Crackstation.BenchmarksEntry
175, // 107: clientpb.Crackstation.Benchmarks:type_name -> clientpb.Crackstation.BenchmarksEntry
134, // 108: clientpb.Crackstation.CUDA:type_name -> clientpb.CUDABackendInfo
136, // 109: clientpb.Crackstation.Metal:type_name -> clientpb.MetalBackendInfo
135, // 110: clientpb.Crackstation.OpenCL:type_name -> clientpb.OpenCLBackendInfo
@@ -14461,32 +14581,33 @@ var file_clientpb_client_proto_depIdxs = []int32{
143, // 122: clientpb.CrackFile.Chunks:type_name -> clientpb.CrackFileChunk
145, // 123: clientpb.AIProviderConfigs.Providers:type_name -> clientpb.AIProviderConfig
146, // 124: clientpb.AIProviderConfigs.Config:type_name -> clientpb.AIConfigSummary
149, // 125: clientpb.AIConversations.Conversations:type_name -> clientpb.AIConversation
151, // 126: clientpb.AIConversation.Messages:type_name -> clientpb.AIConversationMessage
150, // 125: clientpb.AIConversations.Conversations:type_name -> clientpb.AIConversation
152, // 126: clientpb.AIConversation.Messages:type_name -> clientpb.AIConversationMessage
13, // 127: clientpb.AIConversation.TurnState:type_name -> clientpb.AIConversationTurnState
151, // 128: clientpb.AIConversationMessages.Messages:type_name -> clientpb.AIConversationMessage
14, // 129: clientpb.AIConversationMessage.Kind:type_name -> clientpb.AIConversationMessageKind
15, // 130: clientpb.AIConversationMessage.Visibility:type_name -> clientpb.AIConversationMessageVisibility
16, // 131: clientpb.AIConversationMessage.State:type_name -> clientpb.AIConversationMessageState
17, // 132: clientpb.AIConversationEvent.EventType:type_name -> clientpb.AIConversationEventType
149, // 133: clientpb.AIConversationEvent.Conversation:type_name -> clientpb.AIConversation
151, // 134: clientpb.AIConversationEvent.Message:type_name -> clientpb.AIConversationMessage
154, // 135: clientpb.MonitoringProviders.providers:type_name -> clientpb.MonitoringProvider
157, // 136: clientpb.CertificateInfo.info:type_name -> clientpb.CertificateData
159, // 137: clientpb.CertificateAuthorityInfo.info:type_name -> clientpb.CertificateAuthorityData
36, // 138: clientpb.TrafficEncoderMap.EncodersEntry.value:type_name -> clientpb.TrafficEncoder
28, // 139: clientpb.ImplantBuilds.ConfigsEntry.value:type_name -> clientpb.ImplantConfig
155, // 140: clientpb.ImplantBuilds.ResourceIDsEntry.value:type_name -> clientpb.ResourceID
93, // 141: clientpb.WebsiteAddContent.ContentsEntry.value:type_name -> clientpb.WebContent
93, // 142: clientpb.Website.ContentsEntry.value:type_name -> clientpb.WebContent
102, // 143: clientpb.Host.ExtensionDataEntry.value:type_name -> clientpb.ExtensionData
3, // 144: clientpb.ShellcodeEncoderArchMap.EncodersEntry.value:type_name -> clientpb.ShellcodeEncoder
111, // 145: clientpb.ShellcodeEncoderMap.EncodersEntry.value:type_name -> clientpb.ShellcodeEncoderArchMap
146, // [146:146] is the sub-list for method output_type
146, // [146:146] is the sub-list for method input_type
146, // [146:146] is the sub-list for extension type_name
146, // [146:146] is the sub-list for extension extendee
0, // [0:146] is the sub-list for field type_name
149, // 128: clientpb.AIConversation.ContextWindowUsage:type_name -> clientpb.AIContextWindowUsage
152, // 129: clientpb.AIConversationMessages.Messages:type_name -> clientpb.AIConversationMessage
14, // 130: clientpb.AIConversationMessage.Kind:type_name -> clientpb.AIConversationMessageKind
15, // 131: clientpb.AIConversationMessage.Visibility:type_name -> clientpb.AIConversationMessageVisibility
16, // 132: clientpb.AIConversationMessage.State:type_name -> clientpb.AIConversationMessageState
17, // 133: clientpb.AIConversationEvent.EventType:type_name -> clientpb.AIConversationEventType
150, // 134: clientpb.AIConversationEvent.Conversation:type_name -> clientpb.AIConversation
152, // 135: clientpb.AIConversationEvent.Message:type_name -> clientpb.AIConversationMessage
155, // 136: clientpb.MonitoringProviders.providers:type_name -> clientpb.MonitoringProvider
158, // 137: clientpb.CertificateInfo.info:type_name -> clientpb.CertificateData
160, // 138: clientpb.CertificateAuthorityInfo.info:type_name -> clientpb.CertificateAuthorityData
36, // 139: clientpb.TrafficEncoderMap.EncodersEntry.value:type_name -> clientpb.TrafficEncoder
28, // 140: clientpb.ImplantBuilds.ConfigsEntry.value:type_name -> clientpb.ImplantConfig
156, // 141: clientpb.ImplantBuilds.ResourceIDsEntry.value:type_name -> clientpb.ResourceID
93, // 142: clientpb.WebsiteAddContent.ContentsEntry.value:type_name -> clientpb.WebContent
93, // 143: clientpb.Website.ContentsEntry.value:type_name -> clientpb.WebContent
102, // 144: clientpb.Host.ExtensionDataEntry.value:type_name -> clientpb.ExtensionData
3, // 145: clientpb.ShellcodeEncoderArchMap.EncodersEntry.value:type_name -> clientpb.ShellcodeEncoder
111, // 146: clientpb.ShellcodeEncoderMap.EncodersEntry.value:type_name -> clientpb.ShellcodeEncoderArchMap
147, // [147:147] is the sub-list for method output_type
147, // [147:147] is the sub-list for method input_type
147, // [147:147] is the sub-list for extension type_name
147, // [147:147] is the sub-list for extension extendee
0, // [0:147] is the sub-list for field type_name
}
func init() { file_clientpb_client_proto_init() }
@@ -14494,13 +14615,14 @@ func file_clientpb_client_proto_init() {
if File_clientpb_client_proto != nil {
return
}
file_clientpb_client_proto_msgTypes[134].OneofWrappers = []any{}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_clientpb_client_proto_rawDesc), len(file_clientpb_client_proto_rawDesc)),
NumEnums: 18,
NumMessages: 157,
NumMessages: 158,
NumExtensions: 0,
NumServices: 0,
},
+12
View File
@@ -1426,6 +1426,7 @@ message AIConfigSummary {
string ThinkingLevel = 3;
bool Valid = 4;
string Error = 5;
string SystemPrompt = 6;
}
message AIConversationReq {
@@ -1472,6 +1473,14 @@ enum AIConversationEventType {
AI_CONVERSATION_EVENT_TYPE_MESSAGE_COMPLETED = 8;
}
message AIContextWindowUsage {
int64 InputTokens = 1;
int64 OutputTokens = 2;
int64 TotalTokens = 3;
int64 ContextWindowTokens = 4;
bool ContextWindowTokensEstimated = 5;
}
message AIConversation {
string ID = 1;
int64 CreatedAt = 2;
@@ -1487,6 +1496,8 @@ message AIConversation {
AIConversationTurnState TurnState = 12;
string TargetSessionID = 13;
string TargetBeaconID = 14;
string ThinkingLevel = 15;
AIContextWindowUsage ContextWindowUsage = 16;
}
message AIConversationMessages {
@@ -1517,6 +1528,7 @@ message AIConversationMessage {
string ToolArguments = 20;
string ToolResult = 21;
string ErrorText = 22;
optional bool IncludeInContext = 23;
}
message AIConversationEvent {
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v7.34.0
// protoc v7.34.1
// 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.36.11
// protoc v7.34.0
// protoc v7.34.1
// 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.36.11
// protoc v7.34.0
// protoc v7.34.1
// source: rpcpb/services.proto
package rpcpb
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
// - protoc v7.34.0
// - protoc v7.34.1
// 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.36.11
// protoc v7.34.0
// protoc v7.34.1
// source: sliverpb/sliver.proto
package sliverpb
+47 -9
View File
@@ -13,7 +13,7 @@ import (
"github.com/openai/openai-go/v2/shared"
)
const maxAgenticLoopIterations = 16
const maxAgenticLoopIterations = 100
// AgenticToolDefinition describes a custom function tool exposed to the model.
type AgenticToolDefinition struct {
@@ -30,11 +30,22 @@ type AgenticToolExecutor interface {
// AgenticEventSink persists and publishes non-context-window UI items.
type AgenticEventSink interface {
ChatMessage(context.Context, AgenticChatMessage) error
ReasoningItem(context.Context, AgenticReasoningItem) error
ToolCallStarted(context.Context, AgenticToolCall) error
ToolCallCompleted(context.Context, AgenticToolCallResult) error
}
// AgenticChatMessage is a provider-emitted assistant or system chat block.
type AgenticChatMessage struct {
ItemID string
Role string
Content string
Status string
UIOnly bool
IncludeInContext bool
}
// AgenticReasoningItem is a completed reasoning item emitted by the provider.
type AgenticReasoningItem struct {
ItemID string
@@ -103,8 +114,9 @@ func CompleteConversationAgentic(
client := newOpenAIClient(openAIRequestOptions(runtime)...)
currentInput := buildResponseInput(systemPrompt, messages)
toolParams := buildAgenticToolParams(tools)
toolParams := appendOpenAIResponseTools(runtime, buildAgenticToolParams(tools))
previousResponseID := ""
var maxUsage *ContextWindowUsage
for step := 0; step < maxAgenticLoopIterations; step++ {
params := openairesponses.ResponseNewParams{
@@ -129,8 +141,8 @@ func CompleteConversationAgentic(
if runtime.TopP != nil {
params.TopP = openai.Float(*runtime.TopP)
}
if effort, ok := reasoningEffortForThinkingLevel(runtime.ThinkingLevel); ok {
params.Reasoning = shared.ReasoningParam{Effort: effort}
if reasoning, ok := responseReasoningParam(runtime); ok {
params.Reasoning = reasoning
}
response, err := client.responses.New(ctx, params)
@@ -138,9 +150,18 @@ func CompleteConversationAgentic(
return nil, formatOpenAIError(runtime.Provider, err)
}
maxUsage = mergeContextWindowUsage(maxUsage, resolveContextWindowUsage(
ctx,
runtime,
fallbackString(response.Model, runtime.Model),
response.Usage.InputTokens,
response.Usage.OutputTokens,
response.Usage.TotalTokens,
))
previousResponseID = strings.TrimSpace(response.ID)
nextInput := make(openairesponses.ResponseInputParam, 0)
finalTexts := make([]string, 0, len(response.Output))
chatItems := make([]AgenticChatMessage, 0)
for _, item := range response.Output {
switch output := item.AsAny().(type) {
@@ -186,12 +207,28 @@ func CompleteConversationAgentic(
case openairesponses.ResponseOutputMessage:
if text := strings.TrimSpace(responseOutputMessageText(output)); text != "" {
chatItems = append(chatItems, AgenticChatMessage{
ItemID: strings.TrimSpace(output.ID),
Role: strings.TrimSpace(string(output.Role)),
Content: text,
Status: strings.TrimSpace(string(output.Status)),
IncludeInContext: true,
})
finalTexts = append(finalTexts, text)
}
}
}
if len(nextInput) > 0 {
if sink != nil {
for _, chatItem := range chatItems {
chatItem.UIOnly = true
chatItem.IncludeInContext = false
if err := sink.ChatMessage(ctx, chatItem); err != nil {
return nil, err
}
}
}
currentInput = nextInput
continue
}
@@ -205,11 +242,12 @@ func CompleteConversationAgentic(
}
return &Completion{
Provider: runtime.Provider,
Model: fallbackString(response.Model, runtime.Model),
Content: finalText,
ProviderMessageID: strings.TrimSpace(response.ID),
FinishReason: responseFinishReason(response),
Provider: runtime.Provider,
Model: fallbackString(response.Model, runtime.Model),
Content: finalText,
ProviderMessageID: strings.TrimSpace(response.ID),
FinishReason: responseFinishReason(response),
ContextWindowUsage: maxUsage,
}, nil
}
+71
View File
@@ -2,7 +2,12 @@ package ai
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/bishopfox/sliver/protobuf/clientpb"
)
type staticAgenticToolExecutor struct {
@@ -64,3 +69,69 @@ func TestBuildAgenticToolParamsNormalizesStrictOpenAISchemas(t *testing.T) {
}
}
}
func TestCompleteConversationAgenticRequestsReasoningSummaryForOpenAI(t *testing.T) {
type capturedRequest struct {
Body string
}
requests := make(chan capturedRequest, 1)
restoreClient := SetHTTPClientForTests(&http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
defer r.Body.Close()
payload, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
requests <- capturedRequest{Body: string(payload)}
return jsonResponse(http.StatusOK, `{
"id": "resp_123",
"model": "gpt-5.4",
"status": "completed",
"output": [
{
"type": "message",
"id": "msg_123",
"role": "assistant",
"content": [
{"type": "output_text", "text": "Done."}
]
}
]
}`), nil
}),
})
defer restoreClient()
completion, err := CompleteConversationAgentic(context.Background(), &RuntimeConfig{
Provider: ProviderOpenAI,
Model: "gpt-5.4",
UseResponsesAPI: true,
ThinkingLevel: "high",
APIKey: "openai-key",
}, &clientpb.AIConversation{
Messages: []*clientpb.AIConversationMessage{
{Role: "user", Content: "Say hi."},
},
}, nil, nil)
if err != nil {
t.Fatalf("complete agentic conversation: %v", err)
}
request := <-requests
for _, fragment := range []string{
`"type":"web_search"`,
`"search_context_size":"medium"`,
`"effort":"high"`,
`"summary":"auto"`,
} {
if !strings.Contains(request.Body, fragment) {
t.Fatalf("expected agentic request body to contain %q, got %s", fragment, request.Body)
}
}
if completion.Content != "Done." {
t.Fatalf("unexpected completion content: %q", completion.Content)
}
}
+2 -1
View File
@@ -130,12 +130,13 @@ func SafeConfigSummary() *clientpb.AIConfigSummary {
func SafeConfigSummaryFromConfig(cfg *configs.ServerConfig) *clientpb.AIConfigSummary {
summary := &clientpb.AIConfigSummary{}
if cfg != nil && cfg.AI != nil {
summary.Model = strings.TrimSpace(cfg.AI.Model)
summary.ThinkingLevel = strings.TrimSpace(cfg.AI.ThinkingLevel)
summary.SystemPrompt = strings.TrimSpace(cfg.AI.SystemPrompt)
}
provider, providerConfig := selectedProviderConfig(cfg)
summary.Provider = provider
summary.Model = configuredDefaultModel(provider, selectedAIConfig(cfg), providerConfig)
switch {
case cfg == nil || cfg.AI == nil:
+20 -2
View File
@@ -10,9 +10,9 @@ func TestSafeConfigSummaryFromConfigUsesExplicitConfiguredProvider(t *testing.T)
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAI,
Model: "gpt-test",
ThinkingLevel: "high",
OpenAI: &configs.AIProviderConfig{APIKey: "openai-key"},
SystemPrompt: "Stay concise.",
OpenAI: &configs.AIProviderConfig{APIKey: "openai-key", Models: []string{"gpt-test", "gpt-test-mini"}},
Anthropic: &configs.AIProviderConfig{APIKey: "anthropic-key"},
},
}
@@ -30,6 +30,24 @@ func TestSafeConfigSummaryFromConfigUsesExplicitConfiguredProvider(t *testing.T)
if summary.GetThinkingLevel() != "high" {
t.Fatalf("expected thinking level %q, got %q", "high", summary.GetThinkingLevel())
}
if summary.GetSystemPrompt() != "Stay concise." {
t.Fatalf("expected system prompt %q, got %q", "Stay concise.", summary.GetSystemPrompt())
}
}
func TestSafeConfigSummaryFromConfigFallsBackToLegacySharedModel(t *testing.T) {
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAI,
Model: "legacy-model",
OpenAI: &configs.AIProviderConfig{APIKey: "openai-key"},
},
}
summary := SafeConfigSummaryFromConfig(cfg)
if summary.GetModel() != "legacy-model" {
t.Fatalf("expected legacy model %q, got %q", "legacy-model", summary.GetModel())
}
}
func TestSafeConfigSummaryFromConfigFallsBackToConfiguredProvider(t *testing.T) {
+56 -17
View File
@@ -10,6 +10,7 @@ import (
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/util/clientpbutil"
)
const (
@@ -60,11 +61,12 @@ type RuntimeConfig struct {
// Completion contains the persisted assistant response details.
type Completion struct {
Provider string
Model string
Content string
ProviderMessageID string
FinishReason string
Provider string
Model string
Content string
ProviderMessageID string
FinishReason string
ContextWindowUsage *ContextWindowUsage
}
type providerMessage struct {
@@ -90,6 +92,9 @@ func ResolveRuntimeConfig(cfg *configs.ServerConfig, conversation *clientpb.AICo
if conversation != nil {
runtime.Provider = NormalizeProviderName(conversation.GetProvider())
runtime.Model = strings.TrimSpace(conversation.GetModel())
if thinkingLevel := NormalizeThinkingLevelValue(conversation.GetThinkingLevel()); thinkingLevel != "" {
runtime.ThinkingLevel = thinkingLevel
}
}
if runtime.Provider == "" {
@@ -105,11 +110,8 @@ func ResolveRuntimeConfig(cfg *configs.ServerConfig, conversation *clientpb.AICo
applyProviderRuntimeConfig(runtime, providerConfig)
}
if runtime.Model == "" && cfg != nil && cfg.AI != nil {
runtime.Model = strings.TrimSpace(cfg.AI.Model)
}
if runtime.Model == "" {
runtime.Model = defaultModelForProvider(runtime.Provider)
runtime.Model = configuredDefaultModel(runtime.Provider, selectedAIConfig(cfg), providerConfig)
}
runtime.UseResponsesAPI = useResponsesAPI(runtime.Provider, providerConfig)
@@ -121,7 +123,7 @@ func ResolveRuntimeConfig(cfg *configs.ServerConfig, conversation *clientpb.AICo
case !runtimeProviderConfigured(runtime):
return runtime, errors.New(missingProviderConfigError(runtime.Provider))
case runtime.Model == "":
return runtime, fmt.Errorf("server AI provider %q is missing a model; update `ai.model` or choose a provider default", runtime.Provider)
return runtime, fmt.Errorf("server AI provider %q is missing a model; update `ai.%s.models` or choose a provider default", runtime.Provider, providerConfigKey(runtime.Provider))
case !completionDriverAvailable(runtime):
return runtime, missingDriverError(runtime)
default:
@@ -165,7 +167,7 @@ func conversationHistory(conversation *clientpb.AIConversation) (string, []provi
if message == nil {
continue
}
if message.GetVisibility() == clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_UI_ONLY {
if !clientpbutil.AIConversationMessageIncludesContext(message) {
continue
}
if message.GetKind() != clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT {
@@ -218,6 +220,39 @@ func defaultModelForProvider(provider string) string {
}
}
func configuredDefaultModel(provider string, aiConfig *configs.AIConfig, providerConfig *configs.AIProviderConfig) string {
if providerConfig != nil {
for _, model := range providerConfig.Models {
model = strings.TrimSpace(model)
if model != "" {
return model
}
}
}
if aiConfig != nil {
if legacyModel := strings.TrimSpace(aiConfig.Model); legacyModel != "" {
return legacyModel
}
}
return defaultModelForProvider(provider)
}
func providerConfigKey(provider string) string {
switch NormalizeProviderName(provider) {
case ProviderOpenAICompat:
return "openai_compat"
default:
return NormalizeProviderName(provider)
}
}
func selectedAIConfig(cfg *configs.ServerConfig) *configs.AIConfig {
if cfg == nil {
return nil
}
return cfg.AI
}
func completionDriverAvailable(runtime *RuntimeConfig) bool {
_, err := selectCompletionDriver(runtime)
return err == nil
@@ -234,16 +269,20 @@ func missingDriverError(runtime *RuntimeConfig) error {
return nil
}
func NormalizeThinkingLevelValue(value string) string {
switch strings.ToLower(strings.TrimSpace(value)) {
case "low", "medium", "high", "xhigh", "disabled":
return strings.ToLower(strings.TrimSpace(value))
default:
return ""
}
}
func normalizeThinkingLevel(cfg *configs.ServerConfig) string {
if cfg == nil || cfg.AI == nil {
return ""
}
switch strings.ToLower(strings.TrimSpace(cfg.AI.ThinkingLevel)) {
case "low", "medium", "high", "disabled":
return strings.ToLower(strings.TrimSpace(cfg.AI.ThinkingLevel))
default:
return ""
}
return NormalizeThinkingLevelValue(cfg.AI.ThinkingLevel)
}
func applyProviderRuntimeConfig(runtime *RuntimeConfig, providerConfig *configs.AIProviderConfig) {
+306 -3
View File
@@ -9,6 +9,7 @@ import (
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/configs"
"github.com/openai/openai-go/v2/shared"
)
func TestCompleteConversationOpenAIUsesConfiguredCredentialsAndSettings(t *testing.T) {
@@ -38,6 +39,13 @@ func TestCompleteConversationOpenAIUsesConfiguredCredentialsAndSettings(t *testi
"id": "resp_123",
"model": "gpt-5.2",
"status": "completed",
"usage": {
"input_tokens": 12000,
"input_tokens_details": {},
"output_tokens": 6000,
"output_tokens_details": {},
"total_tokens": 18000
},
"output": [
{
"type": "message",
@@ -95,7 +103,10 @@ func TestCompleteConversationOpenAIUsesConfiguredCredentialsAndSettings(t *testi
}
for _, fragment := range []string{
`"model":"gpt-5.2"`,
`"type":"web_search"`,
`"search_context_size":"medium"`,
`"effort":"high"`,
`"summary":"auto"`,
`"Keep it brief."`,
`"Earlier answer."`,
`"Explain the workflow."`,
@@ -111,6 +122,15 @@ func TestCompleteConversationOpenAIUsesConfiguredCredentialsAndSettings(t *testi
if completion.ProviderMessageID != "resp_123" {
t.Fatalf("unexpected provider message id: %q", completion.ProviderMessageID)
}
if completion.ContextWindowUsage == nil {
t.Fatal("expected context window usage to be captured")
}
if completion.ContextWindowUsage.TotalTokens != 18000 {
t.Fatalf("unexpected total tokens: %d", completion.ContextWindowUsage.TotalTokens)
}
if completion.ContextWindowUsage.ContextWindowTokens != openAIFrontierContextWindowTokens {
t.Fatalf("unexpected context window tokens: %d", completion.ContextWindowUsage.ContextWindowTokens)
}
}
func TestCompleteConversationOpenAIUsesDefaultBaseURLWhenUnset(t *testing.T) {
@@ -157,8 +177,8 @@ func TestCompleteConversationOpenAIUsesDefaultBaseURLWhenUnset(t *testing.T) {
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAI,
Model: "gpt-5.4",
OpenAI: &configs.AIProviderConfig{
Models: []string{"gpt-5.4"},
APIKey: "openai-key",
UseResponsesAPI: boolPtr(true),
},
@@ -204,6 +224,118 @@ func TestCompleteConversationOpenAIUsesDefaultBaseURLWhenUnset(t *testing.T) {
}
}
func TestCompleteConversationOpenAIChatEnablesWebSearch(t *testing.T) {
type capturedRequest struct {
Path string
Authorization string
Body string
}
requests := make(chan capturedRequest, 1)
restoreClient := SetHTTPClientForTests(&http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
defer r.Body.Close()
payload, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read request body: %v", err)
}
requests <- capturedRequest{
Path: r.URL.Path,
Authorization: r.Header.Get("Authorization"),
Body: string(payload),
}
return jsonResponse(http.StatusOK, `{
"id": "chatcmpl_openai_123",
"object": "chat.completion",
"model": "gpt-5.4",
"usage": {
"prompt_tokens": 32000,
"completion_tokens": 4000,
"total_tokens": 36000
},
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "OpenAI chat reply"
}
}
]
}`), nil
}),
})
defer restoreClient()
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAI,
OpenAI: &configs.AIProviderConfig{
Models: []string{"gpt-5.4"},
APIKey: "openai-key",
UseResponsesAPI: boolPtr(false),
},
Anthropic: &configs.AIProviderConfig{},
},
}
conversation := &clientpb.AIConversation{
Provider: ProviderOpenAI,
Model: "gpt-5.4",
Messages: []*clientpb.AIConversationMessage{
{Role: "user", Content: "Say hi."},
},
}
runtime, err := ResolveRuntimeConfig(cfg, conversation)
if err != nil {
t.Fatalf("resolve runtime config: %v", err)
}
if runtime.UseResponsesAPI {
t.Fatal("expected openai runtime to use chat completions for this test")
}
completion, err := CompleteConversation(context.Background(), runtime, conversation)
if err != nil {
t.Fatalf("complete conversation: %v", err)
}
request := <-requests
if request.Path != "/v1/chat/completions" {
t.Fatalf("unexpected openai chat request path: got=%q want=%q", request.Path, "/v1/chat/completions")
}
if request.Authorization != "Bearer openai-key" {
t.Fatalf("unexpected authorization header: %q", request.Authorization)
}
for _, fragment := range []string{
`"model":"gpt-5.4"`,
`"web_search_options":{"search_context_size":"medium"}`,
`"Say hi."`,
} {
if !strings.Contains(request.Body, fragment) {
t.Fatalf("expected openai chat request body to contain %q, got %s", fragment, request.Body)
}
}
if completion.Content != "OpenAI chat reply" {
t.Fatalf("unexpected completion content: %q", completion.Content)
}
if completion.ProviderMessageID != "chatcmpl_openai_123" {
t.Fatalf("unexpected provider message id: %q", completion.ProviderMessageID)
}
if completion.ContextWindowUsage == nil {
t.Fatal("expected openai chat usage to be captured")
}
if completion.ContextWindowUsage.TotalTokens != 36000 {
t.Fatalf("unexpected openai chat total tokens: %d", completion.ContextWindowUsage.TotalTokens)
}
if completion.ContextWindowUsage.ContextWindowTokens != openAI5_4ContextWindowTokens {
t.Fatalf("unexpected openai chat context window tokens: %d", completion.ContextWindowUsage.ContextWindowTokens)
}
}
func TestResolveRuntimeConfigAnthropicRequiresAnInstalledDriver(t *testing.T) {
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
@@ -233,8 +365,8 @@ func TestResolveRuntimeConfigOpenAICompatAllowsBaseURLWithoutAPIKey(t *testing.T
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAICompat,
Model: "gpt-oss-120b",
OpenAICompat: &configs.AIProviderConfig{
Models: []string{"gpt-oss-120b"},
BaseURL: "http://127.0.0.1:8080/v1",
},
},
@@ -257,6 +389,58 @@ func TestResolveRuntimeConfigOpenAICompatAllowsBaseURLWithoutAPIKey(t *testing.T
}
}
func TestResolveRuntimeConfigUsesConversationThinkingOverride(t *testing.T) {
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAI,
ThinkingLevel: "high",
OpenAI: &configs.AIProviderConfig{
Models: []string{"gpt-5.4"},
APIKey: "openai-key",
UseResponsesAPI: boolPtr(true),
},
Anthropic: &configs.AIProviderConfig{},
},
}
runtime, err := ResolveRuntimeConfig(cfg, &clientpb.AIConversation{
Provider: ProviderOpenAI,
ThinkingLevel: "disabled",
})
if err != nil {
t.Fatalf("resolve runtime config: %v", err)
}
if runtime.ThinkingLevel != "disabled" {
t.Fatalf("expected conversation thinking override %q, got %q", "disabled", runtime.ThinkingLevel)
}
}
func TestReasoningEffortForThinkingLevelSupportsXHigh(t *testing.T) {
effort, ok := reasoningEffortForThinkingLevel("xhigh")
if !ok {
t.Fatal("expected xhigh reasoning effort to be supported")
}
if string(effort) != "xhigh" {
t.Fatalf("expected reasoning effort %q, got %q", "xhigh", effort)
}
}
func TestResponseReasoningParamSkipsSummaryForOpenAICompat(t *testing.T) {
reasoning, ok := responseReasoningParam(&RuntimeConfig{
Provider: ProviderOpenAICompat,
ThinkingLevel: "high",
})
if !ok {
t.Fatal("expected response reasoning params to be available")
}
if reasoning.Effort != shared.ReasoningEffortHigh {
t.Fatalf("expected reasoning effort %q, got %q", shared.ReasoningEffortHigh, reasoning.Effort)
}
if reasoning.Summary != "" {
t.Fatalf("expected openai-compatible runtime to skip reasoning summary, got %q", reasoning.Summary)
}
}
func TestCompleteConversationOpenAICompatUsesBaseURLWithoutAuth(t *testing.T) {
type capturedRequest struct {
Path string
@@ -307,8 +491,8 @@ func TestCompleteConversationOpenAICompatUsesBaseURLWithoutAuth(t *testing.T) {
cfg := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ProviderOpenAICompat,
Model: "gpt-oss-120b",
OpenAICompat: &configs.AIProviderConfig{
Models: []string{"gpt-oss-120b"},
BaseURL: "http://127.0.0.1:8080/v1",
},
},
@@ -375,6 +559,11 @@ func TestCompleteConversationOpenRouterUsesDefaultBaseURL(t *testing.T) {
"id": "chatcmpl_or_123",
"object": "chat.completion",
"model": "openai/gpt-5",
"usage": {
"prompt_tokens": 14000,
"completion_tokens": 2000,
"total_tokens": 16000
},
"choices": [
{
"index": 0,
@@ -440,6 +629,120 @@ func TestCompleteConversationOpenRouterUsesDefaultBaseURL(t *testing.T) {
if completion.ProviderMessageID != "chatcmpl_or_123" {
t.Fatalf("unexpected provider message id: %q", completion.ProviderMessageID)
}
if completion.ContextWindowUsage == nil {
t.Fatal("expected openrouter usage to be captured")
}
if completion.ContextWindowUsage.TotalTokens != 16000 {
t.Fatalf("unexpected openrouter total tokens: %d", completion.ContextWindowUsage.TotalTokens)
}
if completion.ContextWindowUsage.ContextWindowTokens != openAIFrontierContextWindowTokens {
t.Fatalf("unexpected openrouter context window tokens: %d", completion.ContextWindowUsage.ContextWindowTokens)
}
}
func TestConversationHistoryUsesExplicitContextFlagIndependentlyOfVisibility(t *testing.T) {
systemPrompt, messages, err := conversationHistory(&clientpb.AIConversation{
SystemPrompt: "Stay concise.",
Messages: []*clientpb.AIConversationMessage{
{
Role: "assistant",
Content: "Visible in the transcript but excluded from context.",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
IncludeInContext: boolPtr(false),
},
{
Role: "assistant",
Content: "UI-only but still included in context.",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_UI_ONLY,
IncludeInContext: boolPtr(true),
},
{
Role: "user",
Content: "What changed?",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
IncludeInContext: boolPtr(true),
},
},
})
if err != nil {
t.Fatalf("conversationHistory: %v", err)
}
if systemPrompt != "Stay concise." {
t.Fatalf("unexpected system prompt: %q", systemPrompt)
}
if len(messages) != 2 {
t.Fatalf("unexpected message count: got=%d want=%d", len(messages), 2)
}
if messages[0].Content != "UI-only but still included in context." {
t.Fatalf("unexpected retained assistant message: %+v", messages[0])
}
if messages[1].Role != "user" || messages[1].Content != "What changed?" {
t.Fatalf("unexpected trailing user message: %+v", messages[1])
}
}
func TestConversationHistoryTreatsLeadingSystemMessageAsSystemPrompt(t *testing.T) {
systemPrompt, messages, err := conversationHistory(&clientpb.AIConversation{
Messages: []*clientpb.AIConversationMessage{
{
Role: "system",
Content: "Stay concise.",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
IncludeInContext: boolPtr(true),
},
{
Role: "user",
Content: "What changed?",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
IncludeInContext: boolPtr(true),
},
},
})
if err != nil {
t.Fatalf("conversationHistory: %v", err)
}
if systemPrompt != "Stay concise." {
t.Fatalf("unexpected system prompt: %q", systemPrompt)
}
if len(messages) != 1 {
t.Fatalf("unexpected message count: got=%d want=%d", len(messages), 1)
}
if messages[0].Role != "user" || messages[0].Content != "What changed?" {
t.Fatalf("unexpected trailing user message: %+v", messages[0])
}
}
func TestConversationHistoryFallsBackToVisibilityWhenContextFlagIsUnset(t *testing.T) {
_, messages, err := conversationHistory(&clientpb.AIConversation{
Messages: []*clientpb.AIConversationMessage{
{
Role: "assistant",
Content: "Legacy context-visible message.",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
},
{
Role: "user",
Content: "Legacy prompt.",
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
},
},
})
if err != nil {
t.Fatalf("conversationHistory: %v", err)
}
if len(messages) != 2 {
t.Fatalf("unexpected legacy message count: got=%d want=%d", len(messages), 2)
}
if messages[0].Content != "Legacy context-visible message." {
t.Fatalf("unexpected legacy assistant message: %+v", messages[0])
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
+312
View File
@@ -0,0 +1,312 @@
package ai
import (
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
openAIFrontierContextWindowTokens = 400000
openAIChatContextWindowTokens = 128000
openAI4_1ContextWindowTokens = 1047576
openAI5_4ContextWindowTokens = 1050000
openAIReasoningContextWindowTokens = 200000
openAIRealtimeContextWindowTokens = 32000
openAIRealtimeMiniContextWindowTokens = 16000
openRouterContextWindowCacheTTL = 6 * time.Hour
)
// ContextWindowUsage captures the provider-reported token usage for a turn and,
// when available, the model context window used to render the client-side meter.
type ContextWindowUsage struct {
InputTokens int64
OutputTokens int64
TotalTokens int64
ContextWindowTokens int64
ContextWindowTokensEstimated bool
}
func newContextWindowUsage(inputTokens, outputTokens, totalTokens, windowTokens int64, estimated bool) *ContextWindowUsage {
if inputTokens == 0 && outputTokens == 0 && totalTokens == 0 {
return nil
}
return &ContextWindowUsage{
InputTokens: inputTokens,
OutputTokens: outputTokens,
TotalTokens: totalTokens,
ContextWindowTokens: windowTokens,
ContextWindowTokensEstimated: estimated,
}
}
func cloneContextWindowUsage(usage *ContextWindowUsage) *ContextWindowUsage {
if usage == nil {
return nil
}
cloned := *usage
return &cloned
}
func contextWindowUsageRank(usage *ContextWindowUsage) (int64, int64, int64) {
if usage == nil {
return 0, 0, 0
}
return usage.TotalTokens, usage.InputTokens, usage.OutputTokens
}
func mergeContextWindowUsage(current *ContextWindowUsage, candidate *ContextWindowUsage) *ContextWindowUsage {
if candidate == nil {
return cloneContextWindowUsage(current)
}
if current == nil {
return cloneContextWindowUsage(candidate)
}
result := cloneContextWindowUsage(current)
currentTotal, currentInput, currentOutput := contextWindowUsageRank(result)
candidateTotal, candidateInput, candidateOutput := contextWindowUsageRank(candidate)
if candidateTotal > currentTotal ||
(candidateTotal == currentTotal && candidateInput > currentInput) ||
(candidateTotal == currentTotal && candidateInput == currentInput && candidateOutput > currentOutput) {
result = cloneContextWindowUsage(candidate)
}
if result.ContextWindowTokens == 0 && candidate.ContextWindowTokens > 0 {
result.ContextWindowTokens = candidate.ContextWindowTokens
result.ContextWindowTokensEstimated = candidate.ContextWindowTokensEstimated
}
if result.ContextWindowTokens > 0 && result.ContextWindowTokensEstimated &&
candidate.ContextWindowTokens > 0 && !candidate.ContextWindowTokensEstimated {
result.ContextWindowTokens = candidate.ContextWindowTokens
result.ContextWindowTokensEstimated = false
}
return result
}
func resolveContextWindowUsage(ctx context.Context, runtime *RuntimeConfig, model string, inputTokens, outputTokens, totalTokens int64) *ContextWindowUsage {
windowTokens, estimated := resolveContextWindowTokens(ctx, runtime, model)
return newContextWindowUsage(inputTokens, outputTokens, totalTokens, windowTokens, estimated)
}
func resolveContextWindowTokens(ctx context.Context, runtime *RuntimeConfig, model string) (int64, bool) {
model = normalizeContextWindowModelID(model)
if model == "" {
return 0, false
}
if tokens := openAIKnownContextWindowTokens(model); tokens > 0 {
return tokens, true
}
if openRouterCompatibleRuntime(runtime) {
if tokens, ok := openRouterContextWindowTokens(ctx, runtime, model); ok {
return tokens, false
}
}
return 0, false
}
func openAIKnownContextWindowTokens(model string) int64 {
model = normalizeContextWindowModelID(model)
switch {
case model == "codex-mini-latest":
return openAIReasoningContextWindowTokens
case strings.HasPrefix(model, "o3"), strings.HasPrefix(model, "o4-"):
return openAIReasoningContextWindowTokens
case strings.HasPrefix(model, "gpt-5.4"):
return openAI5_4ContextWindowTokens
case strings.HasPrefix(model, "gpt-4.1"):
return openAI4_1ContextWindowTokens
case strings.HasPrefix(model, "gpt-5.1-chat"), strings.HasPrefix(model, "gpt-5-chat"):
return openAIChatContextWindowTokens
case strings.HasPrefix(model, "gpt-5"):
return openAIFrontierContextWindowTokens
case strings.HasPrefix(model, "gpt-4o-mini-realtime"):
return openAIRealtimeMiniContextWindowTokens
case strings.HasPrefix(model, "gpt-4o-realtime"):
return openAIRealtimeContextWindowTokens
case strings.HasPrefix(model, "gpt-4o"), strings.HasPrefix(model, "chatgpt-4o"):
return openAIChatContextWindowTokens
case strings.Contains(model, "gpt-4-turbo"):
return openAIChatContextWindowTokens
case strings.HasPrefix(model, "gpt-4"):
return 8192
default:
return 0
}
}
func normalizeContextWindowModelID(model string) string {
model = strings.ToLower(strings.TrimSpace(model))
if idx := strings.Index(model, "/"); idx >= 0 {
model = model[idx+1:]
}
if idx := strings.Index(model, ":"); idx >= 0 {
model = model[:idx]
}
return strings.TrimSpace(model)
}
func openRouterCompatibleRuntime(runtime *RuntimeConfig) bool {
if runtime == nil {
return false
}
switch NormalizeProviderName(runtime.Provider) {
case ProviderOpenRouter:
return true
case ProviderOpenAICompat:
baseURL := strings.ToLower(strings.TrimSpace(openAIBaseURL(runtime)))
return strings.Contains(baseURL, "openrouter.ai")
default:
return false
}
}
type openRouterModelsResponse struct {
Data []openRouterModel `json:"data"`
}
type openRouterModel struct {
ID string `json:"id"`
TopProvider struct {
ContextLength int64 `json:"context_length"`
} `json:"top_provider"`
}
type cachedOpenRouterContextWindow struct {
tokens int64
expiresAt time.Time
}
var openRouterContextWindowCache = struct {
sync.RWMutex
entries map[string]cachedOpenRouterContextWindow
}{
entries: map[string]cachedOpenRouterContextWindow{},
}
func openRouterContextWindowTokens(ctx context.Context, runtime *RuntimeConfig, model string) (int64, bool) {
model = normalizeContextWindowModelID(model)
if model == "" {
return 0, false
}
cacheKey := openRouterContextWindowCacheKey(runtime, model)
if tokens, ok := cachedOpenRouterContextWindowTokens(cacheKey); ok {
return tokens, true
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, openRouterModelsURL(runtime), nil)
if err != nil {
return 0, false
}
if runtime != nil && !runtime.SkipAuth && strings.TrimSpace(runtime.APIKey) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(runtime.APIKey))
}
for key, value := range providerHeaders(runtime) {
req.Header.Set(key, value)
}
resp, err := httpClient.Do(req)
if err != nil {
return 0, false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, false
}
payload := &openRouterModelsResponse{}
if err := json.NewDecoder(resp.Body).Decode(payload); err != nil {
return 0, false
}
for _, candidate := range payload.Data {
candidateID := normalizeContextWindowModelID(candidate.ID)
if candidateID != model {
continue
}
if candidate.TopProvider.ContextLength <= 0 {
return 0, false
}
storeOpenRouterContextWindowTokens(cacheKey, candidate.TopProvider.ContextLength)
return candidate.TopProvider.ContextLength, true
}
return 0, false
}
func openRouterModelsURL(runtime *RuntimeConfig) string {
baseURL := strings.TrimSpace(openAIBaseURL(runtime))
if baseURL == "" {
baseURL = defaultOpenRouterBaseURL
}
parsed, err := url.Parse(baseURL)
if err != nil || parsed == nil {
return defaultOpenRouterBaseURL + "/models"
}
path := strings.TrimRight(parsed.Path, "/")
switch {
case strings.HasSuffix(path, "/chat/completions"):
path = strings.TrimSuffix(path, "/chat/completions")
case strings.HasSuffix(path, "/responses"):
path = strings.TrimSuffix(path, "/responses")
case path == "":
path = "/api/v1"
}
if !strings.HasSuffix(path, "/models") {
path += "/models"
}
parsed.Path = path
parsed.RawQuery = ""
parsed.Fragment = ""
return parsed.String()
}
func openRouterContextWindowCacheKey(runtime *RuntimeConfig, model string) string {
return openRouterModelsURL(runtime) + "|" + normalizeContextWindowModelID(model)
}
func cachedOpenRouterContextWindowTokens(cacheKey string) (int64, bool) {
if cacheKey == "" {
return 0, false
}
now := time.Now()
openRouterContextWindowCache.RLock()
cached, ok := openRouterContextWindowCache.entries[cacheKey]
openRouterContextWindowCache.RUnlock()
if !ok || cached.tokens <= 0 || now.After(cached.expiresAt) {
if ok && now.After(cached.expiresAt) {
openRouterContextWindowCache.Lock()
delete(openRouterContextWindowCache.entries, cacheKey)
openRouterContextWindowCache.Unlock()
}
return 0, false
}
return cached.tokens, true
}
func storeOpenRouterContextWindowTokens(cacheKey string, tokens int64) {
if cacheKey == "" || tokens <= 0 {
return
}
openRouterContextWindowCache.Lock()
openRouterContextWindowCache.entries[cacheKey] = cachedOpenRouterContextWindow{
tokens: tokens,
expiresAt: time.Now().Add(openRouterContextWindowCacheTTL),
}
openRouterContextWindowCache.Unlock()
}
+50
View File
@@ -0,0 +1,50 @@
package ai
import (
"context"
"net/http"
"testing"
)
func TestResolveContextWindowUsageOpenRouterUsesModelsAPIForUnknownModels(t *testing.T) {
openRouterContextWindowCache.Lock()
openRouterContextWindowCache.entries = map[string]cachedOpenRouterContextWindow{}
openRouterContextWindowCache.Unlock()
requests := make(chan string, 1)
restoreClient := SetHTTPClientForTests(&http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
requests <- r.URL.Path
return jsonResponse(http.StatusOK, `{
"data": [
{
"id": "anthropic/claude-sonnet-4-0",
"top_provider": {
"context_length": 200000
}
}
]
}`), nil
}),
})
defer restoreClient()
usage := resolveContextWindowUsage(context.Background(), &RuntimeConfig{
Provider: ProviderOpenRouter,
APIKey: "openrouter-key",
}, "anthropic/claude-sonnet-4-0", 24000, 1000, 25000)
if usage == nil {
t.Fatal("expected context window usage")
}
if usage.ContextWindowTokens != 200000 {
t.Fatalf("unexpected context window tokens: %d", usage.ContextWindowTokens)
}
if usage.ContextWindowTokensEstimated {
t.Fatal("expected OpenRouter model lookup to be treated as exact")
}
requestPath := <-requests
if requestPath != "/api/v1/models" {
t.Fatalf("unexpected models lookup path: %q", requestPath)
}
}
+81 -4
View File
@@ -15,6 +15,7 @@ import (
const (
openAIDriverName = "openai-go"
defaultOpenRouterBaseURL = "https://openrouter.ai/api/v1"
openAIWebSearchContext = "medium"
)
type openAIDriver struct{}
@@ -115,6 +116,39 @@ func openAIBaseURL(runtime *RuntimeConfig) string {
return ""
}
func openAIWebSearchEnabled(runtime *RuntimeConfig) bool {
return runtime != nil && NormalizeProviderName(runtime.Provider) == ProviderOpenAI
}
func appendOpenAIResponseTools(runtime *RuntimeConfig, tools []openairesponses.ToolUnionParam) []openairesponses.ToolUnionParam {
if !openAIWebSearchEnabled(runtime) {
return tools
}
for _, tool := range tools {
if tool.OfWebSearch != nil || tool.OfWebSearchPreview != nil {
return tools
}
}
webSearch := openairesponses.ToolParamOfWebSearch(openairesponses.WebSearchToolTypeWebSearch)
if webSearch.OfWebSearch != nil {
webSearch.OfWebSearch.SearchContextSize = openairesponses.WebSearchToolSearchContextSizeMedium
}
return append(append([]openairesponses.ToolUnionParam{}, tools...), webSearch)
}
func applyOpenAIChatWebSearch(runtime *RuntimeConfig, params *openai.ChatCompletionNewParams) {
if params == nil || !openAIWebSearchEnabled(runtime) {
return
}
params.WebSearchOptions = openai.ChatCompletionNewParamsWebSearchOptions{
SearchContextSize: openAIWebSearchContext,
}
}
func (d *openAIDriver) completeResponses(ctx context.Context, client *openAIClient, runtime *RuntimeConfig, request *completionRequest) (*Completion, error) {
params := openairesponses.ResponseNewParams{
Input: openairesponses.ResponseNewParamsInputUnion{
@@ -122,6 +156,9 @@ func (d *openAIDriver) completeResponses(ctx context.Context, client *openAIClie
},
Model: shared.ResponsesModel(runtime.Model),
}
if tools := appendOpenAIResponseTools(runtime, nil); len(tools) > 0 {
params.Tools = tools
}
if runtime.MaxOutputTokens > 0 {
params.MaxOutputTokens = openai.Int(runtime.MaxOutputTokens)
}
@@ -131,8 +168,8 @@ func (d *openAIDriver) completeResponses(ctx context.Context, client *openAIClie
if runtime.TopP != nil {
params.TopP = openai.Float(*runtime.TopP)
}
if effort, ok := reasoningEffortForThinkingLevel(runtime.ThinkingLevel); ok {
params.Reasoning = shared.ReasoningParam{Effort: effort}
if reasoning, ok := responseReasoningParam(runtime); ok {
params.Reasoning = reasoning
}
response, err := client.responses.New(ctx, params)
@@ -145,12 +182,21 @@ func (d *openAIDriver) completeResponses(ctx context.Context, client *openAIClie
return nil, fmt.Errorf("%s response did not include assistant text", runtime.Provider)
}
model := fallbackString(response.Model, runtime.Model)
return &Completion{
Provider: runtime.Provider,
Model: fallbackString(response.Model, runtime.Model),
Model: model,
Content: content,
ProviderMessageID: strings.TrimSpace(response.ID),
FinishReason: responseFinishReason(response),
ContextWindowUsage: resolveContextWindowUsage(
ctx,
runtime,
model,
response.Usage.InputTokens,
response.Usage.OutputTokens,
response.Usage.TotalTokens,
),
}, nil
}
@@ -159,6 +205,7 @@ func (d *openAIDriver) completeChat(ctx context.Context, client *openAIClient, r
Messages: buildChatMessages(request.SystemPrompt, request.Messages),
Model: shared.ChatModel(runtime.Model),
}
applyOpenAIChatWebSearch(runtime, &params)
if runtime.MaxOutputTokens > 0 {
if NormalizeProviderName(runtime.Provider) == ProviderOpenAI {
params.MaxCompletionTokens = openai.Int(runtime.MaxOutputTokens)
@@ -192,12 +239,21 @@ func (d *openAIDriver) completeChat(ctx context.Context, client *openAIClient, r
return nil, fmt.Errorf("%s response did not include assistant text", runtime.Provider)
}
model := fallbackString(response.Model, runtime.Model)
return &Completion{
Provider: runtime.Provider,
Model: fallbackString(response.Model, runtime.Model),
Model: model,
Content: content,
ProviderMessageID: strings.TrimSpace(response.ID),
FinishReason: finishReason,
ContextWindowUsage: resolveContextWindowUsage(
ctx,
runtime,
model,
response.Usage.PromptTokens,
response.Usage.CompletionTokens,
response.Usage.TotalTokens,
),
}, nil
}
@@ -281,11 +337,32 @@ func reasoningEffortForThinkingLevel(thinkingLevel string) (shared.ReasoningEffo
return shared.ReasoningEffortMedium, true
case "high":
return shared.ReasoningEffortHigh, true
case "xhigh":
return shared.ReasoningEffort("xhigh"), true
default:
return "", false
}
}
func responseReasoningParam(runtime *RuntimeConfig) (shared.ReasoningParam, bool) {
effort, ok := reasoningEffortForThinkingLevel(runtime.ThinkingLevel)
if !ok {
return shared.ReasoningParam{}, false
}
reasoning := shared.ReasoningParam{Effort: effort}
switch NormalizeProviderName(runtime.Provider) {
case ProviderOpenAI, ProviderOpenRouter:
// Native OpenAI-style Responses backends can return a reasoning summary
// for UI-only transcript blocks. Use "auto" because summary modes are
// model-specific; hard-coding "concise" can suppress summaries on models
// that only expose a different summarizer.
reasoning.Summary = shared.ReasoningSummaryAuto
}
return reasoning, true
}
func formatOpenAIError(provider string, err error) error {
if err == nil {
return nil
+41
View File
@@ -0,0 +1,41 @@
package assets
import (
"os"
"path/filepath"
)
const (
// AIDirName stores server-side AI helper data under the Sliver root.
AIDirName = "ai"
// AIAliasesDirName stores aliases made available to the server-side AI agent.
AIAliasesDirName = "aliases"
// AIExtensionsDirName stores extensions made available to the server-side AI agent.
AIExtensionsDirName = "extensions"
)
// GetAIDir returns the server-side AI data directory: ~/.sliver/ai
func GetAIDir() string {
return ensureAIDir(filepath.Join(GetRootAppDir(), AIDirName))
}
// GetAIAliasesDir returns the server-side AI alias directory: ~/.sliver/ai/aliases
func GetAIAliasesDir() string {
return ensureAIDir(filepath.Join(GetAIDir(), AIAliasesDirName))
}
// GetAIExtensionsDir returns the server-side AI extension directory: ~/.sliver/ai/extensions
func GetAIExtensionsDir() string {
return ensureAIDir(filepath.Join(GetAIDir(), AIExtensionsDirName))
}
func ensureAIDir(dir string) string {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0o700); err != nil {
setupLog.Fatalf("Cannot create AI data dir %s", err)
}
}
return dir
}
+4 -4
View File
@@ -52,7 +52,7 @@ const (
outputFlagStr = "output"
permissionsFlagStr = "permissions"
tailscaleFlagStr = "tailscale"
disableWGFlagStr = "disable-wg"
enableWGFlagStr = "enable-wg"
// Cert flags
caTypeFlagStr = "type"
@@ -87,7 +87,7 @@ func init() {
operatorCmd.Flags().StringP(saveFlagStr, "s", "", "save file to ...")
operatorCmd.Flags().StringP(outputFlagStr, "o", "file", "output format (file, stdout)")
operatorCmd.Flags().StringSliceP(permissionsFlagStr, "P", []string{}, "grant permissions to the operator profile (all, builder, crackstation)")
operatorCmd.Flags().Bool(disableWGFlagStr, false, "omit WireGuard tunnel settings from the generated operator config")
operatorCmd.Flags().Bool(enableWGFlagStr, false, "include WireGuard tunnel settings in the generated operator config")
rootCmd.AddCommand(operatorCmd)
// Certs
@@ -104,7 +104,7 @@ func init() {
daemonCmd.Flags().Uint16P(lportFlagStr, "p", daemon.BlankPort, "multiplayer listener port")
daemonCmd.Flags().BoolP(forceFlagStr, "f", false, "force unpack and overwrite static assets")
daemonCmd.Flags().BoolP(tailscaleFlagStr, "t", false, "enable tailscale")
daemonCmd.Flags().Bool(disableWGFlagStr, false, "expose multiplayer directly instead of wrapping it in WireGuard")
daemonCmd.Flags().Bool(enableWGFlagStr, false, "wrap the multiplayer listener in WireGuard")
rootCmd.AddCommand(daemonCmd)
// Builder
@@ -153,7 +153,7 @@ var rootCmd = &cobra.Command{
fmt.Printf("[!] %s\n", err)
}
if serverConfig.DaemonMode {
daemon.Start(daemon.BlankHost, daemon.BlankPort, serverConfig.DaemonConfig.Tailscale, serverConfig.DaemonConfig.DisableWG)
daemon.Start(daemon.BlankHost, daemon.BlankPort, serverConfig.DaemonConfig.Tailscale, serverConfig.DaemonConfig.WireGuardEnabled())
} else {
rcScript, err := clientcli.ReadRCScript(cmd)
if err != nil {
+5 -5
View File
@@ -47,13 +47,13 @@ var daemonCmd = &cobra.Command{
fmt.Printf("Failed to parse --%s flag %s\n", tailscaleFlagStr, err)
return
}
disableWG, err := cmd.Flags().GetBool(disableWGFlagStr)
enableWG, err := cmd.Flags().GetBool(enableWGFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s\n", disableWGFlagStr, err)
fmt.Printf("Failed to parse --%s flag %s\n", enableWGFlagStr, err)
return
}
if !cmd.Flags().Changed(disableWGFlagStr) {
disableWG = configs.GetServerConfig().DaemonConfig.DisableWG
if !cmd.Flags().Changed(enableWGFlagStr) {
enableWG = configs.GetServerConfig().DaemonConfig.WireGuardEnabled()
}
appDir := assets.GetRootAppDir()
@@ -87,7 +87,7 @@ var daemonCmd = &cobra.Command{
fmt.Printf("[!] %s\n", err)
}
daemon.Start(lhost, uint16(lport), tailscale, disableWG)
daemon.Start(lhost, uint16(lport), tailscale, enableWG)
},
}
+4 -8
View File
@@ -99,14 +99,10 @@ var operatorCmd = &cobra.Command{
}
certs.SetupCAs()
includeWG := console.DefaultOperatorWireGuardEnabled()
if cmd.Flags().Changed(disableWGFlagStr) {
disableWG, err := cmd.Flags().GetBool(disableWGFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", disableWGFlagStr, err)
return
}
includeWG = !disableWG
includeWG, err := cmd.Flags().GetBool(enableWGFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", enableWGFlagStr, err)
return
}
configJSON, err := console.NewOperatorConfig(name, lhost, lport, permissions, includeWG)
+305 -30
View File
@@ -18,10 +18,62 @@ package configs
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "strings"
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/log"
"gopkg.in/yaml.v3"
)
const (
aiConfigFileName = "ai.yaml"
aiProviderAnthropic = "anthropic"
aiProviderGoogle = "google"
aiProviderOpenAI = "openai"
aiProviderOpenAICompat = "openai-compat"
aiProviderOpenRouter = "openrouter"
defaultAISystemPrompt = `You are Sliver's AI copilot for authorized security testing, detection engineering, lab work, and incident-response support in environments the operator is explicitly permitted to assess.
Your job is to help the operator make careful, high-signal decisions inside the Sliver workflow.
Operating rules:
- Assume all activity must stay within the operator's authorized scope. If a request is ambiguous, unusually risky, destructive, or inconsistent with the available context, pause, state the concern, and ask for confirmation or offer a safer alternative.
- Use the current conversation, target metadata, and Sliver context to tailor answers. If OS, privilege, transport, or session/beacon state matters, say so before recommending commands.
- Never fabricate command output, host state, credentials, files, loot, or tool results. When information is missing, say exactly what is unknown.
- Prefer the smallest next step that increases certainty. Start with low-noise, reversible discovery before collection, execution, or configuration changes.
- Highlight operational tradeoffs: stealth, telemetry, privilege requirements, target stability, cleanup burden, and chances of breaking access.
- Prefer actions that preserve operator access, host stability, and forensic defensibility. Avoid destructive, noisy, or irreversible steps unless the operator explicitly asks for them and the purpose is clear.
- Treat credentials, secrets, tokens, and loot as sensitive. Do not suggest unnecessary exposure, duplication, or broad collection.
- When troubleshooting, separate confirmed facts from hypotheses and propose the next diagnostic step rather than many speculative changes at once.
- When multiple approaches are possible, present the safest practical option first, then note faster or more aggressive alternatives only if they materially help.
- When suggesting Sliver commands, make them concrete, minimal, and easy to audit. Include assumptions and prerequisites when they matter.
- When asked to draft code, scripts, or one-liners, optimize for readability, explicitness, and minimal side effects.
Response style:
- Be concise, structured, and operator-focused.
- Prefer short checklists or step plans over long essays.
- Distinguish clearly between facts, assumptions, and recommendations.
- If the request appears outside authorized security work, refuse and redirect to safer high-level guidance.`
)
var (
aiConfigLog = log.NamedLogger("config", "ai")
supportedAIProviders = []string{
aiProviderAnthropic,
aiProviderGoogle,
aiProviderOpenAI,
aiProviderOpenAICompat,
aiProviderOpenRouter,
}
)
// AIProviderConfig - Shared AI provider configuration.
type AIProviderConfig struct {
Models []string `json:"models,omitempty" yaml:"models,omitempty"`
APIKey string `json:"api_key" yaml:"api_key"`
BaseURL string `json:"base_url" yaml:"base_url"`
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
@@ -37,8 +89,9 @@ type AIProviderConfig struct {
// AIConfig - Server-side AI provider configuration.
type AIConfig struct {
Provider string `json:"provider" yaml:"provider"`
Model string `json:"model" yaml:"model"`
Model string `json:"model,omitempty" yaml:"model,omitempty"` // Deprecated legacy shared model field; migrated into provider-specific models on save.
ThinkingLevel string `json:"thinking_level" yaml:"thinking_level"`
SystemPrompt string `json:"system_prompt" yaml:"system_prompt"`
MaxOutputTokens int64 `json:"max_output_tokens,omitempty" yaml:"max_output_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty" yaml:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty" yaml:"top_p,omitempty"`
@@ -52,6 +105,18 @@ type AIConfig struct {
OpenRouter *AIProviderConfig `json:"openrouter" yaml:"openrouter"`
}
type aiConfigEnvelope struct {
AI *AIConfig `json:"ai" yaml:"ai"`
}
// GetAIConfigPath - File path to ai.yaml.
func GetAIConfigPath() string {
appDir := assets.GetRootAppDir()
aiConfigPath := filepath.Join(appDir, "configs", aiConfigFileName)
aiConfigLog.Debugf("Loading config from %s", aiConfigPath)
return aiConfigPath
}
func defaultAIProviderConfig() *AIProviderConfig {
return &AIProviderConfig{
Headers: map[string]string{},
@@ -63,6 +128,7 @@ func defaultAIConfig() *AIConfig {
Provider: "",
Model: "",
ThinkingLevel: "",
SystemPrompt: defaultAISystemPrompt,
MaxOutputTokens: 0,
Temperature: nil,
TopP: nil,
@@ -77,47 +143,135 @@ func defaultAIConfig() *AIConfig {
}
}
func normalizeAIConfig(config *ServerConfig) {
if config.AI == nil {
config.AI = defaultAIConfig()
// Save - Save AI config file to disk.
func (c *AIConfig) Save() error {
config := normalizeAIConfig(c)
configPath := GetAIConfigPath()
configDir := filepath.Dir(configPath)
if _, err := os.Stat(configDir); os.IsNotExist(err) {
aiConfigLog.Debugf("Creating config dir %s", configDir)
err := os.MkdirAll(configDir, 0700)
if err != nil {
return err
}
}
config.AI.Provider = strings.ToLower(strings.TrimSpace(config.AI.Provider))
config.AI.Model = strings.TrimSpace(config.AI.Model)
config.AI.ThinkingLevel = strings.ToLower(strings.TrimSpace(config.AI.ThinkingLevel))
if config.AI.MaxOutputTokens < 0 {
config.AI.MaxOutputTokens = 0
data, err := yaml.Marshal(config)
if err != nil {
return err
}
config.AI.Temperature = normalizeOptionalFloat(config.AI.Temperature)
config.AI.TopP = normalizeOptionalFloat(config.AI.TopP)
config.AI.TopK = normalizeOptionalInt(config.AI.TopK)
config.AI.PresencePenalty = normalizeOptionalFloat(config.AI.PresencePenalty)
config.AI.FrequencyPenalty = normalizeOptionalFloat(config.AI.FrequencyPenalty)
if config.AI.Anthropic == nil {
config.AI.Anthropic = defaultAIProviderConfig()
aiConfigLog.Infof("Saving config to %s", configPath)
err = os.WriteFile(configPath, data, 0600)
if err != nil {
aiConfigLog.Errorf("Failed to write config %s", err)
}
normalizeAIProviderConfig(config.AI.Anthropic)
if config.AI.Google == nil {
config.AI.Google = defaultAIProviderConfig()
return err
}
// GetAIConfig - Get AI config value from ai.yaml.
func GetAIConfig() *AIConfig {
return getAIConfig(nil)
}
func getAIConfig(migratedConfig *AIConfig) *AIConfig {
configPath := GetAIConfigPath()
config := defaultAIConfig()
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
data, err := os.ReadFile(configPath)
if err != nil {
aiConfigLog.Errorf("Failed to read config file %s", err)
return config
}
err = yaml.Unmarshal(data, config)
if err != nil {
aiConfigLog.Errorf("Failed to parse config file %s", err)
return config
}
} else if migratedConfig != nil {
config = migratedConfig
aiConfigLog.Infof("Migrating embedded AI config to %s", configPath)
} else {
aiConfigLog.Warnf("Config file does not exist, using defaults")
}
normalizeAIProviderConfig(config.AI.Google)
if config.AI.OpenAI == nil {
config.AI.OpenAI = defaultAIProviderConfig()
config = normalizeAIConfig(config)
err := config.Save() // This updates the config with any missing fields
if err != nil {
aiConfigLog.Errorf("Failed to save default config %s", err)
return config
}
normalizeAIProviderConfig(config.AI.OpenAI)
if config.AI.OpenAICompat == nil {
config.AI.OpenAICompat = defaultAIProviderConfig()
return config
}
func aiConfigFromYAML(data []byte) *AIConfig {
envelope := &aiConfigEnvelope{}
if err := yaml.Unmarshal(data, envelope); err != nil {
aiConfigLog.Errorf("Failed to parse embedded AI config %s", err)
return nil
}
normalizeAIProviderConfig(config.AI.OpenAICompat)
if config.AI.OpenRouter == nil {
config.AI.OpenRouter = defaultAIProviderConfig()
if envelope.AI == nil {
return nil
}
normalizeAIProviderConfig(config.AI.OpenRouter)
return normalizeAIConfig(envelope.AI)
}
func aiConfigFromJSON(data []byte) *AIConfig {
envelope := &aiConfigEnvelope{}
if err := json.Unmarshal(data, envelope); err != nil {
aiConfigLog.Errorf("Failed to parse embedded AI config %s", err)
return nil
}
if envelope.AI == nil {
return nil
}
return normalizeAIConfig(envelope.AI)
}
func normalizeAIConfig(config *AIConfig) *AIConfig {
if config == nil {
config = defaultAIConfig()
}
config.Provider = normalizeAIProviderName(config.Provider)
config.Model = strings.TrimSpace(config.Model)
config.ThinkingLevel = strings.ToLower(strings.TrimSpace(config.ThinkingLevel))
config.SystemPrompt = strings.TrimSpace(config.SystemPrompt)
if config.MaxOutputTokens < 0 {
config.MaxOutputTokens = 0
}
config.Temperature = normalizeOptionalFloat(config.Temperature)
config.TopP = normalizeOptionalFloat(config.TopP)
config.TopK = normalizeOptionalInt(config.TopK)
config.PresencePenalty = normalizeOptionalFloat(config.PresencePenalty)
config.FrequencyPenalty = normalizeOptionalFloat(config.FrequencyPenalty)
if config.Anthropic == nil {
config.Anthropic = defaultAIProviderConfig()
}
normalizeAIProviderConfig(config.Anthropic)
if config.Google == nil {
config.Google = defaultAIProviderConfig()
}
normalizeAIProviderConfig(config.Google)
if config.OpenAI == nil {
config.OpenAI = defaultAIProviderConfig()
}
normalizeAIProviderConfig(config.OpenAI)
if config.OpenAICompat == nil {
config.OpenAICompat = defaultAIProviderConfig()
}
normalizeAIProviderConfig(config.OpenAICompat)
if config.OpenRouter == nil {
config.OpenRouter = defaultAIProviderConfig()
}
normalizeAIProviderConfig(config.OpenRouter)
migrateLegacyAIModel(config)
return config
}
func normalizeAIProviderConfig(provider *AIProviderConfig) {
if provider == nil {
return
}
provider.Models = normalizeStringSlice(provider.Models)
provider.APIKey = strings.TrimSpace(provider.APIKey)
provider.BaseURL = strings.TrimSpace(provider.BaseURL)
provider.UserAgent = strings.TrimSpace(provider.UserAgent)
@@ -174,3 +328,124 @@ func normalizeStringMap(values map[string]string) map[string]string {
}
return normalized
}
func migrateLegacyAIModel(config *AIConfig) {
if config == nil {
return
}
legacyModel := strings.TrimSpace(config.Model)
if legacyModel == "" {
return
}
provider := legacyAIModelProvider(config)
providerConfig := aiProviderConfigByName(config, provider)
if providerConfig != nil {
providerConfig.Models = normalizeStringSlice(append([]string{legacyModel}, providerConfig.Models...))
}
config.Model = ""
}
func legacyAIModelProvider(config *AIConfig) string {
if config == nil {
return aiProviderOpenAI
}
if provider := normalizeAIProviderName(config.Provider); isSupportedAIProvider(provider) {
return provider
}
for _, provider := range supportedAIProviders {
if aiProviderConfigured(provider, aiProviderConfigByName(config, provider)) {
return provider
}
}
return aiProviderOpenAI
}
func normalizeAIProviderName(name string) string {
normalized := strings.ToLower(strings.TrimSpace(name))
switch normalized {
case "gemini":
return aiProviderGoogle
case "openai_compat", "openaicompat", "openai-compatible":
return aiProviderOpenAICompat
default:
return normalized
}
}
func isSupportedAIProvider(provider string) bool {
switch normalizeAIProviderName(provider) {
case aiProviderAnthropic, aiProviderGoogle, aiProviderOpenAI, aiProviderOpenAICompat, aiProviderOpenRouter:
return true
default:
return false
}
}
func aiProviderConfigByName(config *AIConfig, provider string) *AIProviderConfig {
if config == nil {
return nil
}
switch normalizeAIProviderName(provider) {
case aiProviderAnthropic:
return config.Anthropic
case aiProviderGoogle:
return config.Google
case aiProviderOpenAI:
return config.OpenAI
case aiProviderOpenAICompat:
return config.OpenAICompat
case aiProviderOpenRouter:
return config.OpenRouter
default:
return nil
}
}
func aiProviderConfigured(provider string, providerConfig *AIProviderConfig) bool {
if providerConfig == nil {
return false
}
switch normalizeAIProviderName(provider) {
case aiProviderAnthropic:
return strings.TrimSpace(providerConfig.APIKey) != "" ||
providerConfig.UseBedrock ||
(strings.TrimSpace(providerConfig.Project) != "" && strings.TrimSpace(providerConfig.Location) != "")
case aiProviderGoogle:
return strings.TrimSpace(providerConfig.APIKey) != "" ||
(strings.TrimSpace(providerConfig.Project) != "" && strings.TrimSpace(providerConfig.Location) != "")
case aiProviderOpenAI:
return strings.TrimSpace(providerConfig.APIKey) != ""
case aiProviderOpenAICompat:
return strings.TrimSpace(providerConfig.BaseURL) != ""
case aiProviderOpenRouter:
return strings.TrimSpace(providerConfig.APIKey) != ""
default:
return false
}
}
func normalizeStringSlice(values []string) []string {
if len(values) == 0 {
return nil
}
normalized := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if _, exists := seen[value]; exists {
continue
}
seen[value] = struct{}{}
normalized = append(normalized, value)
}
if len(normalized) == 0 {
return nil
}
return normalized
}
+211
View File
@@ -0,0 +1,211 @@
package configs
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestAIConfigParsesYAML(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
configPath := GetAIConfigPath()
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
t.Fatalf("failed to create config dir: %v", err)
}
data := []byte(`provider: "openai"
thinking_level: "high"
system_prompt: "Stay concise."
max_output_tokens: 2048
temperature: 0.25
anthropic:
api_key: "anthropic-key"
base_url: "https://api.anthropic.example"
use_bedrock: true
openai:
models:
- "gpt-test"
- "gpt-mini-test"
api_key: "openai-key"
base_url: "https://api.openai.example"
organization: "org-test"
project: "proj-test"
use_responses_api: true
google:
api_key: "google-key"
project: "vertex-project"
location: "us-central1"
skip_auth: true
openai_compat:
base_url: "http://127.0.0.1:8080/v1"
openrouter:
api_key: "openrouter-key"
user_agent: "sliver-test/1.0"
`)
if err := os.WriteFile(configPath, data, 0600); err != nil {
t.Fatalf("failed to write yaml config: %v", err)
}
config := GetAIConfig()
if config.Provider != "openai" {
t.Fatalf("expected provider %q, got %q", "openai", config.Provider)
}
if config.Model != "" {
t.Fatalf("expected legacy model field to remain empty, got %q", config.Model)
}
if config.ThinkingLevel != "high" {
t.Fatalf("expected thinking level %q, got %q", "high", config.ThinkingLevel)
}
if config.SystemPrompt != "Stay concise." {
t.Fatalf("expected system prompt %q, got %q", "Stay concise.", config.SystemPrompt)
}
if config.MaxOutputTokens != 2048 {
t.Fatalf("expected max_output_tokens %d, got %d", 2048, config.MaxOutputTokens)
}
if config.Temperature == nil || *config.Temperature != 0.25 {
t.Fatalf("expected temperature %v, got %#v", 0.25, config.Temperature)
}
if config.Anthropic == nil || config.Anthropic.APIKey != "anthropic-key" || !config.Anthropic.UseBedrock {
t.Fatalf("expected anthropic config to load, got %#v", config.Anthropic)
}
if config.OpenAI == nil || config.OpenAI.APIKey != "openai-key" || config.OpenAI.Organization != "org-test" || config.OpenAI.Project != "proj-test" {
t.Fatalf("expected openai config to load, got %#v", config.OpenAI)
}
if config.OpenAI == nil || len(config.OpenAI.Models) != 2 || config.OpenAI.Models[0] != "gpt-test" || config.OpenAI.Models[1] != "gpt-mini-test" {
t.Fatalf("expected openai models to load, got %#v", config.OpenAI)
}
if config.OpenAI == nil || config.OpenAI.UseResponsesAPI == nil || !*config.OpenAI.UseResponsesAPI {
t.Fatalf("expected openai responses api flag to load")
}
if config.Google == nil || config.Google.APIKey != "google-key" || config.Google.Project != "vertex-project" || config.Google.Location != "us-central1" || !config.Google.SkipAuth {
t.Fatalf("expected google config to load, got %#v", config.Google)
}
if config.OpenAICompat == nil || config.OpenAICompat.BaseURL != "http://127.0.0.1:8080/v1" {
t.Fatalf("expected openai_compat config to load, got %#v", config.OpenAICompat)
}
if config.OpenRouter == nil || config.OpenRouter.APIKey != "openrouter-key" || config.OpenRouter.UserAgent != "sliver-test/1.0" {
t.Fatalf("expected openrouter config to load, got %#v", config.OpenRouter)
}
}
func TestAIConfigWritesDefault(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
config := GetAIConfig()
if config.Provider != "" || config.Model != "" || config.ThinkingLevel != "" {
t.Fatalf("expected empty default ai selections, got %#v", config)
}
if config.SystemPrompt != defaultAISystemPrompt {
t.Fatalf("expected default system prompt %q, got %q", defaultAISystemPrompt, config.SystemPrompt)
}
if config.Anthropic == nil || config.Google == nil || config.OpenAI == nil || config.OpenAICompat == nil || config.OpenRouter == nil {
t.Fatalf("expected default provider configs to exist, got %#v", config)
}
if _, err := os.Stat(GetAIConfigPath()); err != nil {
t.Fatalf("expected default ai config file to exist: %v", err)
}
data, err := os.ReadFile(GetAIConfigPath())
if err != nil {
t.Fatalf("failed to read default ai config: %v", err)
}
if !strings.Contains(string(data), "system_prompt:") {
t.Fatalf("expected default ai config to include system_prompt field, got %q", string(data))
}
if strings.Contains(string(data), "\nmodel:") || strings.HasPrefix(string(data), "model:") {
t.Fatalf("expected default ai config to omit legacy model field, got %q", string(data))
}
if !strings.Contains(string(data), "authorized security testing") {
t.Fatalf("expected default ai config to include the default system prompt, got %q", string(data))
}
}
func TestAIConfigMigratesLegacySharedModelToProviderModels(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
configPath := GetAIConfigPath()
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
t.Fatalf("failed to create config dir: %v", err)
}
data := []byte(`provider: "openai"
model: "gpt-test"
openai:
api_key: "openai-key"
`)
if err := os.WriteFile(configPath, data, 0600); err != nil {
t.Fatalf("failed to write legacy ai config: %v", err)
}
config := GetAIConfig()
if config.Model != "" {
t.Fatalf("expected legacy model field to be cleared, got %q", config.Model)
}
if config.OpenAI == nil || len(config.OpenAI.Models) != 1 || config.OpenAI.Models[0] != "gpt-test" {
t.Fatalf("expected legacy model to migrate into openai models, got %#v", config.OpenAI)
}
savedData, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("failed to read migrated ai config: %v", err)
}
if strings.Contains(string(savedData), "\nmodel:") || strings.HasPrefix(string(savedData), "model:") {
t.Fatalf("expected migrated ai config to omit legacy model field, got %q", string(savedData))
}
if !strings.Contains(string(savedData), "models:") {
t.Fatalf("expected migrated ai config to include provider models, got %q", string(savedData))
}
}
func TestServerConfigMigratesEmbeddedAIConfigFromYAML(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
serverConfigPath := GetServerConfigPath()
if err := os.MkdirAll(filepath.Dir(serverConfigPath), 0700); err != nil {
t.Fatalf("failed to create config dir: %v", err)
}
data := []byte(`daemon_mode: true
daemon:
host: "127.0.0.1"
port: 4444
ai:
provider: "openai"
model: "gpt-test"
system_prompt: "Stay concise."
openai:
api_key: "openai-key"
`)
if err := os.WriteFile(serverConfigPath, data, 0600); err != nil {
t.Fatalf("failed to write yaml config: %v", err)
}
config := GetServerConfig()
if !config.DaemonMode || config.DaemonConfig == nil || config.DaemonConfig.Port != 4444 {
t.Fatalf("expected daemon settings to load, got %#v", config.DaemonConfig)
}
if config.AI == nil || config.AI.Provider != "openai" || config.AI.SystemPrompt != "Stay concise." {
t.Fatalf("expected embedded AI config to migrate, got %#v", config.AI)
}
if config.AI == nil || config.AI.Model != "" {
t.Fatalf("expected embedded legacy ai model field to be cleared, got %#v", config.AI)
}
if config.AI == nil || config.AI.OpenAI == nil || len(config.AI.OpenAI.Models) != 1 || config.AI.OpenAI.Models[0] != "gpt-test" {
t.Fatalf("expected embedded ai model to migrate into openai models, got %#v", config.AI)
}
if config.AI.OpenAI == nil || config.AI.OpenAI.APIKey != "openai-key" {
t.Fatalf("expected embedded openai api key to migrate, got %#v", config.AI.OpenAI)
}
if _, err := os.Stat(GetAIConfigPath()); err != nil {
t.Fatalf("expected migrated ai config file to exist: %v", err)
}
serverData, err := os.ReadFile(GetServerConfigPath())
if err != nil {
t.Fatalf("failed to read migrated server config: %v", err)
}
if strings.Contains(string(serverData), "\nai:") || strings.HasPrefix(string(serverData), "ai:") {
t.Fatalf("expected migrated server config to drop embedded ai block, got %q", string(serverData))
}
}
+50 -6
View File
@@ -73,10 +73,32 @@ type GRPCConfig struct {
// DaemonConfig - Configure daemon mode
type DaemonConfig struct {
Host string `json:"host" yaml:"host"`
Port int `json:"port" yaml:"port"`
Tailscale bool `json:"tailscale" yaml:"tailscale"`
DisableWG bool `json:"disable_wg" yaml:"disable_wg"`
Host string `json:"host" yaml:"host"`
Port int `json:"port" yaml:"port"`
Tailscale bool `json:"tailscale" yaml:"tailscale"`
EnableWG *bool `json:"enable_wg,omitempty" yaml:"enable_wg,omitempty"`
LegacyDisableWG *bool `json:"disable_wg,omitempty" yaml:"disable_wg,omitempty"`
}
func (c *DaemonConfig) WireGuardEnabled() bool {
if c == nil {
return false
}
if c.EnableWG != nil {
return *c.EnableWG
}
if c.LegacyDisableWG != nil {
return !*c.LegacyDisableWG
}
return false
}
func (c *DaemonConfig) SetWireGuardEnabled(enabled bool) {
if c == nil {
return
}
c.EnableWG = &enabled
c.LegacyDisableWG = nil
}
// JobConfig - Restart Jobs on Load
@@ -197,7 +219,7 @@ type ServerConfig struct {
DaemonConfig *DaemonConfig `json:"daemon" yaml:"daemon"`
Logs *LogConfig `json:"logs" yaml:"logs"`
GRPC *GRPCConfig `json:"grpc" yaml:"grpc"`
AI *AIConfig `json:"ai" yaml:"ai"`
AI *AIConfig `json:"-" yaml:"-"`
Watchtower *WatchTowerConfig `json:"watch_tower" yaml:"watch_tower"`
GoProxy string `json:"go_proxy" yaml:"go_proxy"`
HTTPDefaults *HttpDefaultConfig `json:"http_default" yaml:"http_default"`
@@ -210,6 +232,14 @@ type ServerConfig struct {
// Save - Save config file to disk
func (c *ServerConfig) Save() error {
if c != nil {
c.AI = normalizeAIConfig(c.AI)
if err := c.AI.Save(); err != nil {
return err
}
normalizeServerConfig(c)
}
configPath := GetServerConfigPath()
configDir := filepath.Dir(configPath)
if _, err := os.Stat(configDir); os.IsNotExist(err) {
@@ -237,6 +267,7 @@ func GetServerConfig() *ServerConfig {
legacyPath := getServerLegacyConfigPath()
config := getDefaultServerConfig()
migratedLegacy := false
var migratedAIConfig *AIConfig
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
data, err := os.ReadFile(configPath)
if err != nil {
@@ -248,6 +279,7 @@ func GetServerConfig() *ServerConfig {
serverConfigLog.Errorf("Failed to parse config file %s", err)
return config
}
migratedAIConfig = aiConfigFromYAML(data)
} else if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
data, err := os.ReadFile(legacyPath)
if err != nil {
@@ -259,6 +291,7 @@ func GetServerConfig() *ServerConfig {
serverConfigLog.Errorf("Failed to parse legacy config file %s", err)
return config
}
migratedAIConfig = aiConfigFromJSON(data)
migratedLegacy = true
serverConfigLog.Infof("Migrating legacy config %s to %s", legacyPath, configPath)
} else {
@@ -286,7 +319,8 @@ func GetServerConfig() *ServerConfig {
defaultPermit := true
config.GRPC.Keepalive.PermitWithoutStream = &defaultPermit
}
normalizeAIConfig(config)
normalizeServerConfig(config)
config.AI = getAIConfig(migratedAIConfig)
err := config.Save() // This updates the config with any missing fields
if err != nil {
@@ -336,3 +370,13 @@ func getDefaultServerConfig() *ServerConfig {
CXX: map[string]string{},
}
}
func normalizeServerConfig(config *ServerConfig) {
if config == nil {
return
}
if config.DaemonConfig == nil {
config.DaemonConfig = &DaemonConfig{}
}
config.DaemonConfig.SetWireGuardEnabled(config.DaemonConfig.WireGuardEnabled())
}
+120 -29
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -20,37 +21,12 @@ daemon:
host: "127.0.0.1"
port: 4444
tailscale: true
enable_wg: true
logs:
level: 5
grpc_unary_payloads: true
grpc_stream_payloads: true
tls_key_logger: true
ai:
provider: "openai"
model: "gpt-test"
thinking_level: "high"
max_output_tokens: 2048
temperature: 0.25
anthropic:
api_key: "anthropic-key"
base_url: "https://api.anthropic.example"
use_bedrock: true
openai:
api_key: "openai-key"
base_url: "https://api.openai.example"
organization: "org-test"
project: "proj-test"
use_responses_api: true
google:
api_key: "google-key"
project: "vertex-project"
location: "us-central1"
skip_auth: true
openai_compat:
base_url: "http://127.0.0.1:8080/v1"
openrouter:
api_key: "openrouter-key"
user_agent: "sliver-test/1.0"
watch_tower:
vt_api_key: "vt"
xforce_api_key: "xforce"
@@ -84,6 +60,38 @@ cxx:
if err := os.WriteFile(configPath, data, 0600); err != nil {
t.Fatalf("failed to write yaml config: %v", err)
}
aiPath := GetAIConfigPath()
aiData := []byte(`provider: "openai"
thinking_level: "high"
max_output_tokens: 2048
temperature: 0.25
anthropic:
api_key: "anthropic-key"
base_url: "https://api.anthropic.example"
use_bedrock: true
openai:
models:
- "gpt-test"
- "gpt-mini-test"
api_key: "openai-key"
base_url: "https://api.openai.example"
organization: "org-test"
project: "proj-test"
use_responses_api: true
google:
api_key: "google-key"
project: "vertex-project"
location: "us-central1"
skip_auth: true
openai_compat:
base_url: "http://127.0.0.1:8080/v1"
openrouter:
api_key: "openrouter-key"
user_agent: "sliver-test/1.0"
`)
if err := os.WriteFile(aiPath, aiData, 0600); err != nil {
t.Fatalf("failed to write ai yaml config: %v", err)
}
config := GetServerConfig()
if !config.DaemonMode {
@@ -92,6 +100,9 @@ cxx:
if config.DaemonConfig == nil || config.DaemonConfig.Port != 4444 {
t.Fatalf("expected daemon port %d, got %v", 4444, config.DaemonConfig)
}
if !config.DaemonConfig.WireGuardEnabled() {
t.Fatalf("expected daemon enable_wg true")
}
if config.Logs == nil || config.Logs.Level != 5 {
t.Fatalf("expected logs level %d, got %v", 5, config.Logs)
}
@@ -113,8 +124,11 @@ cxx:
if config.AI == nil || config.AI.Provider != "openai" {
t.Fatalf("expected ai provider %q, got %#v", "openai", config.AI)
}
if config.AI == nil || config.AI.Model != "gpt-test" {
t.Fatalf("expected ai model %q, got %#v", "gpt-test", config.AI)
if config.AI == nil || config.AI.Model != "" {
t.Fatalf("expected legacy ai model field to remain empty, got %#v", config.AI)
}
if config.AI == nil || config.AI.OpenAI == nil || len(config.AI.OpenAI.Models) != 2 || config.AI.OpenAI.Models[0] != "gpt-test" || config.AI.OpenAI.Models[1] != "gpt-mini-test" {
t.Fatalf("expected ai openai models to load, got %#v", config.AI)
}
if config.AI == nil || config.AI.ThinkingLevel != "high" {
t.Fatalf("expected ai thinking level %q, got %#v", "high", config.AI)
@@ -192,6 +206,47 @@ cxx:
}
}
func TestServerConfigMigratesLegacyDisableWG(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
configPath := GetServerConfigPath()
if err := os.MkdirAll(filepath.Dir(configPath), 0700); err != nil {
t.Fatalf("failed to create config dir: %v", err)
}
data := []byte(`daemon_mode: true
daemon:
host: "127.0.0.1"
port: 4444
disable_wg: false
`)
if err := os.WriteFile(configPath, data, 0600); err != nil {
t.Fatalf("failed to write yaml config: %v", err)
}
config := GetServerConfig()
if config.DaemonConfig == nil {
t.Fatalf("expected daemon config")
}
if !config.DaemonConfig.WireGuardEnabled() {
t.Fatalf("expected legacy disable_wg:false to migrate to enable_wg:true")
}
if config.DaemonConfig.LegacyDisableWG != nil {
t.Fatalf("expected legacy disable_wg field to be cleared after normalization")
}
saved, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("failed to read migrated config: %v", err)
}
if !strings.Contains(string(saved), "enable_wg: true") {
t.Fatalf("expected migrated config to contain enable_wg: true, got:\n%s", string(saved))
}
if strings.Contains(string(saved), "disable_wg") {
t.Fatalf("expected migrated config to drop legacy disable_wg field, got:\n%s", string(saved))
}
}
func TestServerConfigWritesDefault(t *testing.T) {
t.Setenv("SLIVER_ROOT_DIR", t.TempDir())
@@ -205,9 +260,29 @@ func TestServerConfigWritesDefault(t *testing.T) {
if config.AI.Provider != "" || config.AI.Model != "" || config.AI.ThinkingLevel != "" {
t.Fatalf("expected empty default ai selections, got %#v", config.AI)
}
if config.AI.SystemPrompt != defaultAISystemPrompt {
t.Fatalf("expected default ai system prompt %q, got %q", defaultAISystemPrompt, config.AI.SystemPrompt)
}
if _, err := os.Stat(GetServerConfigPath()); err != nil {
t.Fatalf("expected default config file to exist: %v", err)
}
if _, err := os.Stat(GetAIConfigPath()); err != nil {
t.Fatalf("expected default ai config file to exist: %v", err)
}
aiData, err := os.ReadFile(GetAIConfigPath())
if err != nil {
t.Fatalf("failed to read default ai config: %v", err)
}
if strings.Contains(string(aiData), "\nmodel:") || strings.HasPrefix(string(aiData), "model:") {
t.Fatalf("expected default ai config to omit legacy model field, got %q", string(aiData))
}
data, err := os.ReadFile(GetServerConfigPath())
if err != nil {
t.Fatalf("failed to read default server config: %v", err)
}
if strings.Contains(string(data), "\nai:") || strings.HasPrefix(string(data), "ai:") {
t.Fatalf("expected default server config to exclude ai block, got %q", string(data))
}
}
func TestServerConfigMigratesLegacyJSON(t *testing.T) {
@@ -325,9 +400,15 @@ func TestServerConfigMigratesLegacyJSON(t *testing.T) {
if config.AI == nil || config.AI.OpenRouter == nil || config.AI.OpenRouter.APIKey != "openrouter-legacy" {
t.Fatalf("expected legacy ai openrouter config to load")
}
if config.AI == nil || config.AI.Provider != "anthropic" || config.AI.Model != "claude-test" || config.AI.ThinkingLevel != "medium" || config.AI.MaxOutputTokens != 1024 {
if config.AI == nil || config.AI.Provider != "anthropic" || config.AI.ThinkingLevel != "medium" || config.AI.MaxOutputTokens != 1024 {
t.Fatalf("expected legacy ai selections to load, got %#v", config.AI)
}
if config.AI == nil || config.AI.Model != "" {
t.Fatalf("expected legacy ai model field to be cleared, got %#v", config.AI)
}
if config.AI == nil || config.AI.Anthropic == nil || len(config.AI.Anthropic.Models) != 1 || config.AI.Anthropic.Models[0] != "claude-test" {
t.Fatalf("expected legacy model to migrate into anthropic models, got %#v", config.AI)
}
if config.Watchtower == nil || config.Watchtower.VTApiKey != "vt-legacy" {
t.Fatalf("expected legacy watch_tower to load")
}
@@ -340,12 +421,22 @@ func TestServerConfigMigratesLegacyJSON(t *testing.T) {
if _, err := os.Stat(GetServerConfigPath()); err != nil {
t.Fatalf("expected migrated yaml config file to exist: %v", err)
}
if _, err := os.Stat(GetAIConfigPath()); err != nil {
t.Fatalf("expected migrated ai yaml config file to exist: %v", err)
}
if _, err := os.Stat(legacyPath); !os.IsNotExist(err) {
t.Fatalf("expected legacy config to be renamed: %v", err)
}
if _, err := os.Stat(legacyBackupPath(legacyPath)); err != nil {
t.Fatalf("expected legacy backup file to exist: %v", err)
}
serverData, err := os.ReadFile(GetServerConfigPath())
if err != nil {
t.Fatalf("failed to read migrated server config: %v", err)
}
if strings.Contains(string(serverData), "\nai:") || strings.HasPrefix(string(serverData), "ai:") {
t.Fatalf("expected migrated server config to exclude ai block, got %q", string(serverData))
}
}
func boolPtr(value bool) *bool {
+3 -36
View File
@@ -39,7 +39,6 @@ import (
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/console/forms"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/db"
@@ -82,11 +81,7 @@ func newOperatorCmd(cmd *cobra.Command, _ []string) {
lport, _ := cmd.Flags().GetUint16("lport")
save, _ := cmd.Flags().GetString("save")
permissions, _ := cmd.Flags().GetStringSlice("permissions")
includeWG := DefaultOperatorWireGuardEnabled()
if cmd.Flags().Changed("disable-wg") {
disableWG, _ := cmd.Flags().GetBool("disable-wg")
includeWG = !disableWG
}
includeWG, _ := cmd.Flags().GetBool("enable-wg")
if save == "" {
save, _ = os.Getwd()
@@ -117,34 +112,6 @@ func newOperatorCmd(cmd *cobra.Command, _ []string) {
fmt.Printf(Info+"Saved new client config to: %s \n", saveTo)
}
// DefaultOperatorWireGuardEnabled returns the default wireguard mode for new
// operator configs based on the current server multiplayer exposure.
func DefaultOperatorWireGuardEnabled() bool {
serverConfig := configs.GetServerConfig()
if serverConfig != nil && serverConfig.DaemonMode && serverConfig.DaemonConfig != nil {
if serverConfig.DaemonConfig.Tailscale {
return false
}
return !serverConfig.DaemonConfig.DisableWG
}
listenerJobs, err := db.ListenerJobs()
if err != nil {
return true
}
for _, listenerJob := range listenerJobs {
if listenerJob == nil || listenerJob.Type != consts.MultiplayerModeStr {
continue
}
config, err := db.ListenerByJobID(listenerJob.JobID)
if err != nil || config == nil || config.MultiConf == nil {
continue
}
return config.MultiConf.WireGuard
}
return true
}
// NewOperatorConfig - Generate a new player/client/operator configuration
func NewOperatorConfig(operatorName string, lhost string, lport uint16, permissions []string, includeWG bool) ([]byte, error) {
if !namePattern.MatchString(operatorName) {
@@ -438,8 +405,8 @@ func startMultiplayerModeCmd(cmd *cobra.Command, _ []string) {
lhost, _ := cmd.Flags().GetString("lhost")
lport, _ := cmd.Flags().GetUint16("lport")
tailscale, _ := cmd.Flags().GetBool("tailscale")
disableWG, _ := cmd.Flags().GetBool("disable-wg")
useWireGuard := !disableWG && !tailscale
enableWG, _ := cmd.Flags().GetBool("enable-wg")
useWireGuard := enableWG && !tailscale
var err error
var jobID int
+244 -1
View File
@@ -4,17 +4,25 @@ import (
"context"
"encoding/json"
"errors"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
clientassets "github.com/bishopfox/sliver/client/assets"
clienttransport "github.com/bishopfox/sliver/client/transport"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
servertransport "github.com/bishopfox/sliver/server/transport"
"google.golang.org/grpc"
"gorm.io/gorm"
)
@@ -22,7 +30,7 @@ func TestNewOperatorConfigWithWireGuardConnectsToWrappedMultiplayer(t *testing.T
certs.SetupCAs()
certs.SetupWGKeys()
certs.SetupMultiplayerWGKeys()
clienttransport.SetMultiplayerConnectMode(clienttransport.MultiplayerConnectAuto)
clienttransport.SetMultiplayerConnectMode(clienttransport.MultiplayerConnectEnableWG)
operatorName := uniqueKickOperatorName(t)
t.Cleanup(func() {
@@ -116,6 +124,228 @@ func TestNewOperatorConfigWithWireGuardConnectsToWrappedMultiplayer(t *testing.T
}
}
func TestNewOperatorConfigWithWireGuardConnectsToWrappedMultiplayerRepeatedly(t *testing.T) {
certs.SetupCAs()
certs.SetupWGKeys()
certs.SetupMultiplayerWGKeys()
clienttransport.SetMultiplayerConnectMode(clienttransport.MultiplayerConnectEnableWG)
operatorName := uniqueKickOperatorName(t)
t.Cleanup(func() {
_ = removeOperator(operatorName)
_ = revokeOperatorClientCertificate(operatorName)
closeOperatorStreams(operatorName)
})
port := freeUDPPort(t)
configJSON, err := NewOperatorConfig(operatorName, "127.0.0.1", uint16(port), []string{"all"}, true)
if err != nil {
t.Fatalf("generate wireguard operator config: %v", err)
}
config := &clientassets.ClientConfig{}
if err := json.Unmarshal(configJSON, config); err != nil {
t.Fatalf("parse operator config: %v", err)
}
grpcServer, ln, err := servertransport.StartWGWrappedMtlsClientListener("127.0.0.1", uint16(port))
if err != nil {
if strings.Contains(err.Error(), "operation not permitted") {
t.Skipf("wireguard listener bind not permitted in this environment: %v", err)
}
t.Fatalf("start wrapped multiplayer listener: %v", err)
}
defer grpcServer.Stop()
defer ln.Close()
for attempt := 1; attempt <= 5; attempt++ {
rpcClient, conn, err := clienttransport.MTLSConnect(config)
if err != nil {
t.Fatalf("attempt %d: connect operator through wireguard wrapper: %v", attempt, err)
}
if _, err := rpcClient.GetVersion(context.Background(), &commonpb.Empty{}); err != nil {
_ = clienttransport.CloseGRPCConnection(conn)
t.Fatalf("attempt %d: GetVersion over wrapped multiplayer failed: %v", attempt, err)
}
if _, err := rpcClient.GetOperators(context.Background(), &commonpb.Empty{}); err != nil {
_ = clienttransport.CloseGRPCConnection(conn)
t.Fatalf("attempt %d: GetOperators over wrapped multiplayer failed: %v", attempt, err)
}
if err := clienttransport.CloseGRPCConnection(conn); err != nil {
t.Fatalf("attempt %d: close wrapped multiplayer connection: %v", attempt, err)
}
}
}
func TestWrappedMultiplayerWireGuardSupportsUnaryRPCsWithDedicatedCommandConnection(t *testing.T) {
t.Run("events-only", func(t *testing.T) {
runWrappedMultiplayerWireGuardUnaryWithBackgroundStreams(t, true, false)
})
t.Run("tunnel-only", func(t *testing.T) {
runWrappedMultiplayerWireGuardUnaryWithBackgroundStreams(t, false, true)
})
t.Run("events-and-tunnel", func(t *testing.T) {
runWrappedMultiplayerWireGuardUnaryWithBackgroundStreams(t, true, true)
})
}
func runWrappedMultiplayerWireGuardUnaryWithBackgroundStreams(t *testing.T, useEvents bool, useTunnel bool) {
certs.SetupCAs()
certs.SetupWGKeys()
certs.SetupMultiplayerWGKeys()
clienttransport.SetMultiplayerConnectMode(clienttransport.MultiplayerConnectEnableWG)
operatorName := uniqueKickOperatorName(t)
t.Cleanup(func() {
_ = removeOperator(operatorName)
_ = revokeOperatorClientCertificate(operatorName)
closeOperatorStreams(operatorName)
})
port := freeUDPPort(t)
configJSON, err := NewOperatorConfig(operatorName, "127.0.0.1", uint16(port), []string{"all"}, true)
if err != nil {
t.Fatalf("generate wireguard operator config: %v", err)
}
config := &clientassets.ClientConfig{}
if err := json.Unmarshal(configJSON, config); err != nil {
t.Fatalf("parse operator config: %v", err)
}
grpcServer, ln, err := servertransport.StartWGWrappedMtlsClientListener("127.0.0.1", uint16(port))
if err != nil {
if strings.Contains(err.Error(), "operation not permitted") {
t.Skipf("wireguard listener bind not permitted in this environment: %v", err)
}
t.Fatalf("start wrapped multiplayer listener: %v", err)
}
defer grpcServer.Stop()
defer ln.Close()
var streamClient rpcpb.SliverRPCClient
var streamConn *grpc.ClientConn
if useEvents || useTunnel {
streamClient, streamConn, err = clienttransport.MTLSConnect(config)
if err != nil {
t.Fatalf("connect dedicated background operator through wireguard wrapper: %v", err)
}
defer clienttransport.CloseGRPCConnection(streamConn)
}
streamCtx, streamCancel := context.WithCancel(context.Background())
defer streamCancel()
if useEvents {
events, err := streamClient.Events(streamCtx, &commonpb.Empty{})
if err != nil {
t.Fatalf("open events stream: %v", err)
}
go drainWGTestStream(t, "events", func() error {
_, err := events.Recv()
return err
})
}
if useTunnel {
tunnelData, err := streamClient.TunnelData(streamCtx)
if err != nil {
t.Fatalf("open tunnel data stream: %v", err)
}
go drainWGTestStream(t, "tunnel-data", func() error {
_, err := tunnelData.Recv()
return err
})
}
// Let the background streams settle before issuing the unary call. The
// interactive console opens these streams first and only later runs
// unary RPC-backed commands like "operators".
if useEvents || useTunnel {
time.Sleep(2 * time.Second)
}
rpcClient, conn, err := clienttransport.MTLSConnect(config)
if err != nil {
t.Fatalf("connect operator command channel through wireguard wrapper: %v", err)
}
defer clienttransport.CloseGRPCConnection(conn)
callCtx, callCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer callCancel()
if _, err := rpcClient.GetOperators(callCtx, &commonpb.Empty{}); err != nil {
t.Fatalf("GetOperators with dedicated command connection over wrapped multiplayer failed (events=%t tunnel=%t): %v", useEvents, useTunnel, err)
}
}
func TestOperatorCLIWireGuardConfigConnectsToWrappedMultiplayer(t *testing.T) {
certs.SetupCAs()
certs.SetupWGKeys()
certs.SetupMultiplayerWGKeys()
clienttransport.SetMultiplayerConnectMode(clienttransport.MultiplayerConnectEnableWG)
port := freeUDPPort(t)
grpcServer, ln, err := servertransport.StartWGWrappedMtlsClientListener("127.0.0.1", uint16(port))
if err != nil {
if strings.Contains(err.Error(), "operation not permitted") {
t.Skipf("wireguard listener bind not permitted in this environment: %v", err)
}
t.Fatalf("start wrapped multiplayer listener: %v", err)
}
defer grpcServer.Stop()
defer ln.Close()
operatorName := uniqueKickOperatorName(t)
t.Cleanup(func() {
_ = removeOperator(operatorName)
_ = revokeOperatorClientCertificate(operatorName)
closeOperatorStreams(operatorName)
})
wd, err := os.Getwd()
if err != nil {
t.Fatalf("get working directory: %v", err)
}
repoRoot := filepath.Clean(filepath.Join(wd, "..", ".."))
savePath := filepath.Join(t.TempDir(), operatorName+".cfg")
cmd := exec.Command(
"go", "run", "-tags=server,go_sqlite", "./server", "operator",
"--name", operatorName,
"--lhost", "127.0.0.1",
"--lport", strconv.Itoa(port),
"--permissions", "all",
"--enable-wg",
"--save", savePath,
)
cmd.Dir = repoRoot
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("generate operator config through CLI: %v\n%s", err, output)
}
configJSON, err := os.ReadFile(savePath)
if err != nil {
t.Fatalf("read generated operator config: %v", err)
}
config := &clientassets.ClientConfig{}
if err := json.Unmarshal(configJSON, config); err != nil {
t.Fatalf("parse operator config: %v", err)
}
if config.WG == nil {
t.Fatal("expected wireguard config block to be present")
}
rpcClient, conn, err := clienttransport.MTLSConnect(config)
if err != nil {
t.Fatalf("connect operator through wireguard wrapper after CLI generation: %v", err)
}
defer clienttransport.CloseGRPCConnection(conn)
if _, err := rpcClient.GetVersion(context.Background(), &commonpb.Empty{}); err != nil {
t.Fatalf("GetVersion over wrapped multiplayer failed: %v", err)
}
}
func TestKickOperatorReleasesWireGuardTunnelIPReservation(t *testing.T) {
certs.SetupCAs()
certs.SetupMultiplayerWGKeys()
@@ -167,3 +397,16 @@ func freeUDPPort(t *testing.T) int {
defer ln.Close()
return ln.LocalAddr().(*net.UDPAddr).Port
}
func drainWGTestStream(t *testing.T, name string, recv func() error) {
t.Helper()
err := recv()
if err == nil || errors.Is(err, io.EOF) || errors.Is(err, context.Canceled) {
return
}
if strings.Contains(err.Error(), "context canceled") {
return
}
t.Errorf("%s stream recv failed: %v", name, err)
}
+29 -5
View File
@@ -67,11 +67,11 @@ func aiConfigCmd(_ *cobra.Command, args []string) {
return
}
fmt.Printf(Info+"Saved AI configuration to %s\n", configs.GetServerConfigPath())
fmt.Printf(Info+"Saved AI configuration to %s\n", configs.GetAIConfigPath())
fmt.Printf(
Info+"Provider=%s, model=%s, thinking=%s, api_key=%s\n",
Info+"Provider=%s, default_model=%s, thinking=%s, api_key=%s\n",
formatAIValue(serverConfig.AI.Provider, ai.ProviderOpenAI),
formatAIValue(serverConfig.AI.Model, "provider default"),
formatAIValue(aiConfigDefaultModel(serverConfig.AI, serverConfig.AI.Provider), "provider default"),
formatAIValue(serverConfig.AI.ThinkingLevel, "provider default"),
apiKeyStatus(serverConfig.AI.Provider, aiProviderConfig(serverConfig.AI, serverConfig.AI.Provider)),
)
@@ -105,8 +105,9 @@ func currentAIConfigFormResultForProvider(serverConfig *configs.ServerConfig, pr
UseResponsesAPI: provider == ai.ProviderOpenAI,
}
if serverConfig.AI != nil {
result.Model = strings.TrimSpace(serverConfig.AI.Model)
result.Models = aiConfigFormModels(serverConfig.AI, provider)
result.ThinkingLevel = strings.TrimSpace(serverConfig.AI.ThinkingLevel)
result.SystemPrompt = strings.TrimSpace(serverConfig.AI.SystemPrompt)
}
if providerConfig != nil {
result.APIKey = strings.TrimSpace(providerConfig.APIKey)
@@ -142,13 +143,15 @@ func applyAIConfigFormResult(serverConfig *configs.ServerConfig, result *forms.A
provider := ai.NormalizeProviderName(result.Provider)
serverConfig.AI.Provider = provider
serverConfig.AI.Model = strings.TrimSpace(result.Model)
serverConfig.AI.Model = ""
serverConfig.AI.ThinkingLevel = strings.ToLower(strings.TrimSpace(result.ThinkingLevel))
serverConfig.AI.SystemPrompt = strings.TrimSpace(result.SystemPrompt)
providerConfig := aiProviderConfig(serverConfig.AI, provider)
if providerConfig == nil {
return
}
providerConfig.Models = append([]string(nil), result.Models...)
providerConfig.APIKey = strings.TrimSpace(result.APIKey)
providerConfig.BaseURL = strings.TrimSpace(result.BaseURL)
providerConfig.UserAgent = strings.TrimSpace(result.UserAgent)
@@ -160,6 +163,27 @@ func applyAIConfigFormResult(serverConfig *configs.ServerConfig, result *forms.A
providerConfig.UseBedrock = result.UseBedrock
}
func aiConfigFormModels(aiConfig *configs.AIConfig, provider string) []string {
if aiConfig == nil {
return nil
}
if providerConfig := aiProviderConfig(aiConfig, provider); providerConfig != nil && len(providerConfig.Models) > 0 {
return append([]string(nil), providerConfig.Models...)
}
if legacyModel := strings.TrimSpace(aiConfig.Model); legacyModel != "" {
return []string{legacyModel}
}
return nil
}
func aiConfigDefaultModel(aiConfig *configs.AIConfig, provider string) string {
models := aiConfigFormModels(aiConfig, provider)
if len(models) == 0 {
return ""
}
return strings.TrimSpace(models[0])
}
func boolPtr(value bool) *bool {
return &value
}
+35 -6
View File
@@ -35,11 +35,12 @@ func TestCurrentAIConfigFormResultForProviderLoadsRequestedProviderSettings(t *t
serverConfig := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ai.ProviderAnthropic,
Model: "shared-model",
ThinkingLevel: "medium",
SystemPrompt: "Stay concise.",
Anthropic: &configs.AIProviderConfig{APIKey: "anthropic-key"},
Google: &configs.AIProviderConfig{},
OpenAI: &configs.AIProviderConfig{
Models: []string{"gpt-test", "gpt-test-mini"},
APIKey: "openai-key",
BaseURL: "https://api.openai.test",
Organization: "org-test",
@@ -55,8 +56,11 @@ func TestCurrentAIConfigFormResultForProviderLoadsRequestedProviderSettings(t *t
if result.Provider != ai.ProviderOpenAI {
t.Fatalf("expected %q provider, got %q", ai.ProviderOpenAI, result.Provider)
}
if result.Model != "shared-model" {
t.Fatalf("expected shared model, got %q", result.Model)
if len(result.Models) != 2 || result.Models[0] != "gpt-test" || result.Models[1] != "gpt-test-mini" {
t.Fatalf("expected provider models to load, got %#v", result.Models)
}
if result.SystemPrompt != "Stay concise." {
t.Fatalf("expected shared system prompt, got %q", result.SystemPrompt)
}
if result.APIKey != "openai-key" {
t.Fatalf("expected openai API key, got %q", result.APIKey)
@@ -75,6 +79,23 @@ func TestCurrentAIConfigFormResultForProviderLoadsRequestedProviderSettings(t *t
}
}
func TestCurrentAIConfigFormResultForProviderFallsBackToLegacySharedModel(t *testing.T) {
serverConfig := &configs.ServerConfig{
AI: &configs.AIConfig{
Provider: ai.ProviderAnthropic,
Model: "legacy-model",
ThinkingLevel: "medium",
Anthropic: &configs.AIProviderConfig{APIKey: "anthropic-key"},
OpenAI: &configs.AIProviderConfig{APIKey: "openai-key"},
},
}
result := currentAIConfigFormResultForProvider(serverConfig, ai.ProviderOpenAI)
if len(result.Models) != 1 || result.Models[0] != "legacy-model" {
t.Fatalf("expected legacy shared model fallback, got %#v", result.Models)
}
}
func TestCurrentAIConfigFormResultForProviderDefaultsResponsesAPIForOpenAI(t *testing.T) {
result := currentAIConfigFormResultForProvider(&configs.ServerConfig{}, ai.ProviderOpenAI)
if result.Provider != ai.ProviderOpenAI {
@@ -91,6 +112,7 @@ func TestApplyAIConfigFormResultUpdatesOnlySelectedProvider(t *testing.T) {
Provider: ai.ProviderAnthropic,
Model: "old-model",
ThinkingLevel: "low",
SystemPrompt: "Existing default",
Anthropic: &configs.AIProviderConfig{APIKey: "anthropic-key"},
Google: &configs.AIProviderConfig{},
OpenAI: &configs.AIProviderConfig{APIKey: "openai-key", BaseURL: "https://api.openai.test"},
@@ -101,8 +123,9 @@ func TestApplyAIConfigFormResultUpdatesOnlySelectedProvider(t *testing.T) {
applyAIConfigFormResult(serverConfig, &forms.AIConfigFormResult{
Provider: ai.ProviderOpenAI,
Model: "gpt-test",
Models: []string{"gpt-test", "gpt-test-mini"},
ThinkingLevel: "high",
SystemPrompt: "Stay concise.",
APIKey: "new-openai-key",
BaseURL: "https://override.openai.test",
Organization: "org-test",
@@ -113,12 +136,18 @@ func TestApplyAIConfigFormResultUpdatesOnlySelectedProvider(t *testing.T) {
if serverConfig.AI.Provider != ai.ProviderOpenAI {
t.Fatalf("expected provider %q, got %q", ai.ProviderOpenAI, serverConfig.AI.Provider)
}
if serverConfig.AI.Model != "gpt-test" {
t.Fatalf("expected model %q, got %q", "gpt-test", serverConfig.AI.Model)
if serverConfig.AI.Model != "" {
t.Fatalf("expected legacy model field to be cleared, got %q", serverConfig.AI.Model)
}
if len(serverConfig.AI.OpenAI.Models) != 2 || serverConfig.AI.OpenAI.Models[0] != "gpt-test" || serverConfig.AI.OpenAI.Models[1] != "gpt-test-mini" {
t.Fatalf("expected models to update, got %#v", serverConfig.AI.OpenAI.Models)
}
if serverConfig.AI.ThinkingLevel != "high" {
t.Fatalf("expected thinking level %q, got %q", "high", serverConfig.AI.ThinkingLevel)
}
if serverConfig.AI.SystemPrompt != "Stay concise." {
t.Fatalf("expected system prompt %q, got %q", "Stay concise.", serverConfig.AI.SystemPrompt)
}
if serverConfig.AI.OpenAI.APIKey != "new-openai-key" {
t.Fatalf("expected updated openai api key, got %q", serverConfig.AI.OpenAI.APIKey)
}
+4 -5
View File
@@ -75,7 +75,7 @@ func serverOnlyCmds() (commands []*cobra.Command) {
f.StringP("lhost", "L", "", "interface to bind server to")
f.Uint16P("lport", "l", 31337, "tcp listen port")
f.BoolP("tailscale", "T", false, "only expose multiplayer interface over Tailscale (requires TS_AUTHKEY)")
f.Bool("disable-wg", false, "expose multiplayer directly instead of wrapping it in WireGuard")
f.Bool("enable-wg", false, "wrap the multiplayer listener in WireGuard")
})
commands = append(commands, startMultiplayer)
@@ -93,7 +93,7 @@ func serverOnlyCmds() (commands []*cobra.Command) {
f.StringP("save", "s", "", "directory/file in which to save config")
f.StringP("name", "n", "", "operator name")
f.StringSliceP("permissions", "P", []string{}, "grant permissions to the operator profile (all, builder, crackstation)")
f.Bool("disable-wg", false, "omit WireGuard tunnel settings from the generated operator config")
f.Bool("enable-wg", false, "include WireGuard tunnel settings in the generated operator config")
})
command.BindFlagCompletions(newOperator, func(comp *carapace.ActionMap) {
(*comp)["save"] = carapace.ActionDirectories()
@@ -133,9 +133,8 @@ Create a new operator config file, operator configuration files allow
remote machines to connect to the Sliver server. They are most commonly
used for allowing remote operators to connect in "Multiplayer Mode."
By default, operator configs now include a WireGuard wrapper for the
multiplayer listener; use --disable-wg if the listener is being exposed
directly instead.
Operator configs use direct multiplayer mTLS by default. Add --enable-wg
when the multiplayer listener is wrapped in WireGuard.
To generate a profile for a remote operator, you need to specify the
"all" permission to grant the profile access to all gRPC APIs:
+48 -8
View File
@@ -12,8 +12,9 @@ import (
// AIConfigFormResult captures the server-side AI configuration collected from the form.
type AIConfigFormResult struct {
Provider string
Model string
Models []string
ThinkingLevel string
SystemPrompt string
APIKey string
BaseURL string
UserAgent string
@@ -25,7 +26,7 @@ type AIConfigFormResult struct {
UseBedrock bool
}
// AIConfig prompts for the server-side AI configuration stored in server.yaml.
// AIConfig prompts for the server-side AI configuration stored in ai.yaml.
func AIConfig(result *AIConfigFormResult) error {
if result == nil {
return errors.New("AI config result is required")
@@ -57,7 +58,7 @@ func SelectAIProvider(result *AIConfigFormResult) error {
huh.NewGroup(
huh.NewSelect[string]().
Title("AI provider").
Description("Choose the default AI provider stored in server.yaml.").
Description("Choose the default AI provider stored in ai.yaml.").
Options(providerOptions...).
Height(listHeight(len(providerOptions))).
Value(&result.Provider).
@@ -92,6 +93,7 @@ func EditAIConfig(result *AIConfigFormResult) error {
huh.NewOption("Medium", "medium"),
huh.NewOption("High", "high"),
}
modelsValue := formatAIModelList(result.Models)
detailsForm := newConsoleForm(
huh.NewGroup(
@@ -104,16 +106,21 @@ func EditAIConfig(result *AIConfigFormResult) error {
)
}, &result.Provider),
huh.NewInput().
Title("Model").
Description("Optional default model identifier. Leave blank to let the provider choose.").
Title("Models").
Description("Optional ordered model identifiers. Separate entries with commas. The first entry is the default.").
Placeholder("provider default").
Value(&result.Model),
Value(&modelsValue),
huh.NewSelect[string]().
Title("Thinking level").
Description("Optional reasoning/thinking level to store in the ai block.").
Description("Optional reasoning/thinking level to store in ai.yaml.").
Options(thinkingOptions...).
Height(listHeight(len(thinkingOptions))).
Value(&result.ThinkingLevel),
huh.NewInput().
Title("System prompt").
Description("Optional default system prompt for new AI conversations.").
Placeholder("leave blank for no default system prompt").
Value(&result.SystemPrompt),
huh.NewInput().
TitleFunc(func() string {
return fmt.Sprintf("%s API key", providerDisplayName(result.Provider))
@@ -144,6 +151,7 @@ func EditAIConfig(result *AIConfigFormResult) error {
if err := runConsoleForm(detailsForm); err != nil {
return err
}
result.Models = parseAIModelList(modelsValue)
if err := providerSpecificAIConfig(result); err != nil {
return err
@@ -244,8 +252,9 @@ func normalizeAIConfigResult(result *AIConfigFormResult) {
if !ai.IsSupportedProvider(result.Provider) {
result.Provider = ai.ProviderOpenAI
}
result.Model = strings.TrimSpace(result.Model)
result.Models = parseAIModelList(formatAIModelList(result.Models))
result.ThinkingLevel = strings.ToLower(strings.TrimSpace(result.ThinkingLevel))
result.SystemPrompt = strings.TrimSpace(result.SystemPrompt)
switch result.ThinkingLevel {
case "", "disabled", "low", "medium", "high":
default:
@@ -279,6 +288,37 @@ func normalizeAIConfigResult(result *AIConfigFormResult) {
}
}
func formatAIModelList(models []string) string {
return strings.Join(parseAIModelList(strings.Join(models, ",")), ", ")
}
func parseAIModelList(value string) []string {
fields := strings.FieldsFunc(value, func(r rune) bool {
return r == ',' || r == '\n' || r == '\r'
})
if len(fields) == 0 {
return nil
}
models := make([]string, 0, len(fields))
seen := make(map[string]struct{}, len(fields))
for _, field := range fields {
field = strings.TrimSpace(field)
if field == "" {
continue
}
if _, exists := seen[field]; exists {
continue
}
seen[field] = struct{}{}
models = append(models, field)
}
if len(models) == 0 {
return nil
}
return models
}
func providerDisplayName(provider string) string {
switch ai.NormalizeProviderName(provider) {
case ai.ProviderAnthropic:
+6 -3
View File
@@ -28,7 +28,8 @@ const (
)
// Event - An event is fired when there's a state change involving a
// session, job, or client.
//
// session, job, or client.
type Event struct {
Session *Session
Job *Job
@@ -62,7 +63,10 @@ func (broker *eventBroker) Start() {
case sub := <-broker.subscribe:
subscribers[sub] = struct{}{}
case sub := <-broker.unsubscribe:
delete(subscribers, sub)
if _, ok := subscribers[sub]; ok {
delete(subscribers, sub)
close(sub)
}
case event := <-broker.publish:
for sub := range subscribers {
sub <- event
@@ -86,7 +90,6 @@ func (broker *eventBroker) Subscribe() chan Event {
// Unsubscribe - Remove a subscription channel
func (broker *eventBroker) Unsubscribe(events chan Event) {
broker.unsubscribe <- events
close(events)
}
// Publish - Push a message to all subscribers
+2 -2
View File
@@ -41,7 +41,7 @@ var (
)
// Start - Start as daemon process
func Start(host string, port uint16, tailscale bool, disableWG bool) {
func Start(host string, port uint16, tailscale bool, enableWG bool) {
var (
ln net.Listener
err error
@@ -59,7 +59,7 @@ func Start(host string, port uint16, tailscale bool, disableWG bool) {
daemonLog.Infof("Starting Sliver daemon %s:%d ...", host, port)
if tailscale {
_, ln, err = transport.StartTsNetClientListener(host, port)
} else if !disableWG {
} else if enableWG {
_, ln, err = transport.StartWGWrappedMtlsClientListener(host, port)
} else {
_, ln, err = transport.StartMtlsClientListener(host, port)
+62 -1
View File
@@ -1407,7 +1407,59 @@ func AIConversationByID(id string, operatorName string, includeMessages bool) (*
if err != nil {
return nil, err
}
return conversation.ToProtobuf(), nil
pbConversation := conversation.ToProtobuf()
if includeMessages {
pbConversation = aiConversationWithSystemPromptMessage(pbConversation)
}
return pbConversation, nil
}
func aiConversationWithSystemPromptMessage(conversation *clientpb.AIConversation) *clientpb.AIConversation {
if conversation == nil {
return nil
}
systemPrompt := strings.TrimSpace(conversation.GetSystemPrompt())
if systemPrompt == "" {
return conversation
}
for _, message := range conversation.GetMessages() {
if message == nil {
continue
}
if message.GetKind() != clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT {
continue
}
if strings.EqualFold(strings.TrimSpace(message.GetRole()), "system") &&
strings.TrimSpace(message.GetContent()) == systemPrompt {
return conversation
}
}
includeInContext := true
systemMessageID := "system-prompt"
if conversationID := strings.TrimSpace(conversation.GetID()); conversationID != "" {
systemMessageID = conversationID + "-system-prompt"
}
systemMessage := &clientpb.AIConversationMessage{
ID: systemMessageID,
ConversationID: strings.TrimSpace(conversation.GetID()),
CreatedAt: conversation.GetCreatedAt(),
UpdatedAt: conversation.GetUpdatedAt(),
OperatorName: strings.TrimSpace(conversation.GetOperatorName()),
Provider: strings.TrimSpace(conversation.GetProvider()),
Model: strings.TrimSpace(conversation.GetModel()),
Sequence: 0,
Role: "system",
Content: systemPrompt,
Kind: clientpb.AIConversationMessageKind_AI_MESSAGE_KIND_CHAT,
Visibility: clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT,
State: clientpb.AIConversationMessageState_AI_MESSAGE_STATE_COMPLETED,
IncludeInContext: &includeInContext,
}
conversation.Messages = append([]*clientpb.AIConversationMessage{systemMessage}, conversation.GetMessages()...)
return conversation
}
// SaveAIConversation - Create or update an AI conversation thread.
@@ -1435,6 +1487,7 @@ func SaveAIConversation(conversation *clientpb.AIConversation, operatorName stri
}
existing.Provider = dbConversation.Provider
existing.Model = dbConversation.Model
existing.ThinkingLevel = dbConversation.ThinkingLevel
existing.Title = dbConversation.Title
existing.Summary = dbConversation.Summary
existing.SystemPrompt = dbConversation.SystemPrompt
@@ -1442,6 +1495,11 @@ func SaveAIConversation(conversation *clientpb.AIConversation, operatorName stri
existing.TurnState = dbConversation.TurnState
existing.TargetSessionID = dbConversation.TargetSessionID
existing.TargetBeaconID = dbConversation.TargetBeaconID
existing.ContextInputTokens = dbConversation.ContextInputTokens
existing.ContextOutputTokens = dbConversation.ContextOutputTokens
existing.ContextTotalTokens = dbConversation.ContextTotalTokens
existing.ContextWindowTokens = dbConversation.ContextWindowTokens
existing.ContextWindowTokensEstimated = dbConversation.ContextWindowTokensEstimated
if err := dbSession.Save(existing).Error; err != nil {
return nil, err
@@ -1582,6 +1640,9 @@ func SaveAIConversationMessage(message *clientpb.AIConversationMessage, operator
existing.ToolArguments = dbMessage.ToolArguments
existing.ToolResult = dbMessage.ToolResult
existing.ErrorText = dbMessage.ErrorText
if dbMessage.IncludeInContext != nil {
existing.IncludeInContext = dbMessage.IncludeInContext
}
if err := tx.Save(existing).Error; err != nil {
return err
+76 -24
View File
@@ -28,19 +28,25 @@ import (
// AIConversation - A server-side AI conversation thread.
type AIConversation struct {
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
UpdatedAt time.Time
OperatorName string `gorm:"index"`
Provider string `gorm:"index"`
Model string
Title string
Summary string
SystemPrompt string `gorm:"type:text;"`
ActiveTurnID string `gorm:"index"`
TurnState int32
TargetSessionID string `gorm:"index"`
TargetBeaconID string `gorm:"index"`
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
UpdatedAt time.Time
OperatorName string `gorm:"index"`
Provider string `gorm:"index"`
Model string
ThinkingLevel string
Title string
Summary string
SystemPrompt string `gorm:"type:text;"`
ActiveTurnID string `gorm:"index"`
TurnState int32
TargetSessionID string `gorm:"index"`
TargetBeaconID string `gorm:"index"`
ContextInputTokens int64
ContextOutputTokens int64
ContextTotalTokens int64
ContextWindowTokens int64
ContextWindowTokensEstimated bool
Messages []AIConversationMessage `gorm:"foreignKey:ConversationID;constraint:OnDelete:CASCADE;"`
}
@@ -71,6 +77,7 @@ func (a *AIConversation) ToProtobuf() *clientpb.AIConversation {
OperatorName: a.OperatorName,
Provider: a.Provider,
Model: a.Model,
ThinkingLevel: a.ThinkingLevel,
Title: a.Title,
Summary: a.Summary,
SystemPrompt: a.SystemPrompt,
@@ -79,6 +86,13 @@ func (a *AIConversation) ToProtobuf() *clientpb.AIConversation {
TurnState: clientpb.AIConversationTurnState(a.TurnState),
TargetSessionID: a.TargetSessionID,
TargetBeaconID: a.TargetBeaconID,
ContextWindowUsage: aiContextWindowUsageToProtobuf(
a.ContextInputTokens,
a.ContextOutputTokens,
a.ContextTotalTokens,
a.ContextWindowTokens,
a.ContextWindowTokensEstimated,
),
}
}
@@ -91,17 +105,36 @@ func AIConversationFromProtobuf(pbConversation *clientpb.AIConversation) *AIConv
id, _ := uuid.FromString(pbConversation.ID)
return &AIConversation{
ID: id,
OperatorName: pbConversation.OperatorName,
Provider: pbConversation.Provider,
Model: pbConversation.Model,
Title: pbConversation.Title,
Summary: pbConversation.Summary,
SystemPrompt: pbConversation.SystemPrompt,
ActiveTurnID: pbConversation.ActiveTurnID,
TurnState: int32(pbConversation.TurnState),
TargetSessionID: pbConversation.TargetSessionID,
TargetBeaconID: pbConversation.TargetBeaconID,
ID: id,
OperatorName: pbConversation.OperatorName,
Provider: pbConversation.Provider,
Model: pbConversation.Model,
ThinkingLevel: pbConversation.ThinkingLevel,
Title: pbConversation.Title,
Summary: pbConversation.Summary,
SystemPrompt: pbConversation.SystemPrompt,
ActiveTurnID: pbConversation.ActiveTurnID,
TurnState: int32(pbConversation.TurnState),
TargetSessionID: pbConversation.TargetSessionID,
TargetBeaconID: pbConversation.TargetBeaconID,
ContextInputTokens: pbConversation.GetContextWindowUsage().GetInputTokens(),
ContextOutputTokens: pbConversation.GetContextWindowUsage().GetOutputTokens(),
ContextTotalTokens: pbConversation.GetContextWindowUsage().GetTotalTokens(),
ContextWindowTokens: pbConversation.GetContextWindowUsage().GetContextWindowTokens(),
ContextWindowTokensEstimated: pbConversation.GetContextWindowUsage().GetContextWindowTokensEstimated(),
}
}
func aiContextWindowUsageToProtobuf(inputTokens, outputTokens, totalTokens, windowTokens int64, estimated bool) *clientpb.AIContextWindowUsage {
if inputTokens == 0 && outputTokens == 0 && totalTokens == 0 && windowTokens == 0 && !estimated {
return nil
}
return &clientpb.AIContextWindowUsage{
InputTokens: inputTokens,
OutputTokens: outputTokens,
TotalTokens: totalTokens,
ContextWindowTokens: windowTokens,
ContextWindowTokensEstimated: estimated,
}
}
@@ -129,6 +162,7 @@ type AIConversationMessage struct {
ToolArguments string `gorm:"type:text;"`
ToolResult string `gorm:"type:text;"`
ErrorText string `gorm:"type:text;"`
IncludeInContext *bool
}
// BeforeCreate - GORM hook.
@@ -168,6 +202,7 @@ func (a *AIConversationMessage) ToProtobuf() *clientpb.AIConversationMessage {
ToolArguments: a.ToolArguments,
ToolResult: a.ToolResult,
ErrorText: a.ErrorText,
IncludeInContext: resolveAIConversationMessageIncludeInContext(a.IncludeInContext, a.Visibility),
}
}
@@ -201,5 +236,22 @@ func AIConversationMessageFromProtobuf(pbMessage *clientpb.AIConversationMessage
ToolArguments: pbMessage.ToolArguments,
ToolResult: pbMessage.ToolResult,
ErrorText: pbMessage.ErrorText,
IncludeInContext: cloneOptionalBool(pbMessage.IncludeInContext),
}
}
func resolveAIConversationMessageIncludeInContext(value *bool, visibility int32) *bool {
if value != nil {
return cloneOptionalBool(value)
}
include := clientpb.AIConversationMessageVisibility(visibility) == clientpb.AIConversationMessageVisibility_AI_MESSAGE_VISIBILITY_CONTEXT
return &include
}
func cloneOptionalBool(value *bool) *bool {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
+42 -19
View File
@@ -143,36 +143,59 @@ func pivotPeerFailureHandler(implantConn *core.ImplantConnection, data []byte) *
}
pivotLog.Errorf("pivot peer failure received: %v", peerFailure)
reportingSession := core.Sessions.FromImplantConnection(implantConn)
if reportingSession == nil {
pivotLog.Warn("ignoring pivot peer failure from unknown session")
return nil
}
targetSessionIDs := map[string]struct{}{}
targetPivotIDs := map[string]struct{}{}
core.PivotSessions.Range(func(key, value interface{}) bool {
pivot := value.(*core.Pivot)
found := pivot.OriginID == peerFailure.PeerID
if !found {
pivotLog.Warnf("Filed peer not found by OriginID, searching by Peers instead")
for _, peer := range pivot.Peers {
if peer.PeerID == peerFailure.PeerID {
pivotLog.Warnf("Found session with needed peer!")
found = true
}
}
reporterIdx := pivotPeerIndex(pivot.Peers, reportingSession.PeerID)
if reporterIdx <= 0 {
return true
}
if pivot.Peers[reporterIdx-1].PeerID != peerFailure.PeerID {
return true
}
if found {
session := core.Sessions.FromImplantConnection(pivot.ImplantConn)
targetPivotIDs[pivot.ID] = struct{}{}
if pivot.OriginID != peerFailure.PeerID {
return true
}
if session != nil {
core.Sessions.Remove(session.ID)
}
defer core.PivotSessions.Delete(pivot.ID)
return false
session := core.Sessions.FromImplantConnection(pivot.ImplantConn)
if session != nil {
targetSessionIDs[session.ID] = struct{}{}
}
return true
})
if len(targetSessionIDs) == 0 {
pivotLog.Warnf("ignoring unauthorized pivot peer failure from %d for %d", reportingSession.PeerID, peerFailure.PeerID)
return nil
}
for sessionID := range targetSessionIDs {
core.Sessions.Remove(sessionID)
}
for pivotID := range targetPivotIDs {
core.PivotSessions.Delete(pivotID)
}
return nil
}
func pivotPeerIndex(peers []*sliverpb.PivotPeer, peerID int64) int {
for idx, peer := range peers {
if peer.PeerID == peerID {
return idx
}
}
return -1
}
func pivotServerPingHandler(pivot *core.Pivot) {
pivot.ImplantConn.UpdateLastMessage()
pivot.ImmediateImplantConn.UpdateLastMessage()
+145
View File
@@ -0,0 +1,145 @@
package handlers
import (
"fmt"
"testing"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/core"
"google.golang.org/protobuf/proto"
)
func TestPivotPeerFailureHandlerRemovesAuthorizedImmediateChild(t *testing.T) {
resetPivotFailureTestState(t)
reporterConn, reporterSession := addPivotFailureTestSession(t, 300, "wg")
_, unrelatedSession := addPivotFailureTestSession(t, 900, "wg")
childSession, childPivot := addPivotFailureTestPivotSession(t, 200, 200, 300)
grandchildSession, grandchildPivot := addPivotFailureTestPivotSession(t, 100, 100, 200, 300)
unrelatedChildSession, unrelatedChildPivot := addPivotFailureTestPivotSession(t, 800, 800, 900)
pivotPeerFailureHandler(reporterConn, mustMarshalPivotPeerFailure(t, 200))
if got := core.Sessions.Get(reporterSession.ID); got == nil {
t.Fatalf("reporting session was removed")
}
if got := core.Sessions.Get(childSession.ID); got != nil {
t.Fatalf("child session still present after authorized failure")
}
if got := core.Sessions.Get(grandchildSession.ID); got != nil {
t.Fatalf("grandchild session still present after authorized failure")
}
if got := core.Sessions.Get(unrelatedSession.ID); got == nil {
t.Fatalf("unrelated direct session was removed")
}
if got := core.Sessions.Get(unrelatedChildSession.ID); got == nil {
t.Fatalf("unrelated pivot session was removed")
}
if pivotSessionExists(childPivot.ID) {
t.Fatalf("child pivot session still present after authorized failure")
}
if pivotSessionExists(grandchildPivot.ID) {
t.Fatalf("grandchild pivot session still present after authorized failure")
}
if !pivotSessionExists(unrelatedChildPivot.ID) {
t.Fatalf("unrelated pivot session was removed")
}
}
func TestPivotPeerFailureHandlerRejectsNonImmediateChild(t *testing.T) {
resetPivotFailureTestState(t)
reporterConn, _ := addPivotFailureTestSession(t, 300, "wg")
childSession, childPivot := addPivotFailureTestPivotSession(t, 200, 200, 300)
grandchildSession, grandchildPivot := addPivotFailureTestPivotSession(t, 100, 100, 200, 300)
pivotPeerFailureHandler(reporterConn, mustMarshalPivotPeerFailure(t, 100))
if got := core.Sessions.Get(childSession.ID); got == nil {
t.Fatalf("child session was removed by non-immediate failure report")
}
if got := core.Sessions.Get(grandchildSession.ID); got == nil {
t.Fatalf("grandchild session was removed by non-immediate failure report")
}
if !pivotSessionExists(childPivot.ID) {
t.Fatalf("child pivot session was removed by non-immediate failure report")
}
if !pivotSessionExists(grandchildPivot.ID) {
t.Fatalf("grandchild pivot session was removed by non-immediate failure report")
}
}
func addPivotFailureTestSession(t *testing.T, peerID int64, transport string) (*core.ImplantConnection, *core.Session) {
t.Helper()
conn := core.NewImplantConnection(transport, fmt.Sprintf("peer-%d", peerID))
session := core.NewSession(conn)
session.Name = fmt.Sprintf("peer-%d", peerID)
session.PeerID = peerID
core.Sessions.Add(session)
return conn, session
}
func addPivotFailureTestPivotSession(t *testing.T, originID int64, chain ...int64) (*core.Session, *core.Pivot) {
t.Helper()
peers := make([]*sliverpb.PivotPeer, 0, len(chain))
for _, peerID := range chain {
peers = append(peers, &sliverpb.PivotPeer{
PeerID: peerID,
Name: fmt.Sprintf("peer-%d", peerID),
})
}
pivot := core.NewPivotSession(peers)
pivot.OriginID = originID
pivot.ImplantConn = core.NewImplantConnection(core.PivotTransportName, fmt.Sprintf("pivot-%d", originID))
core.PivotSessions.Store(pivot.ID, pivot)
session := core.NewSession(pivot.ImplantConn)
session.Name = fmt.Sprintf("peer-%d", originID)
session.PeerID = originID
core.Sessions.Add(session)
return session, pivot
}
func mustMarshalPivotPeerFailure(t *testing.T, peerID int64) []byte {
t.Helper()
data, err := proto.Marshal(&sliverpb.PivotPeerFailure{
PeerID: peerID,
Type: sliverpb.PeerFailureType_SEND_FAILURE,
})
if err != nil {
t.Fatalf("marshal peer failure: %v", err)
}
return data
}
func pivotSessionExists(pivotID string) bool {
_, ok := core.PivotSessions.Load(pivotID)
return ok
}
func resetPivotFailureTestState(t *testing.T) {
t.Helper()
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
core.PivotSessions.Range(func(key, value interface{}) bool {
core.PivotSessions.Delete(key)
return true
})
t.Cleanup(func() {
for _, session := range core.Sessions.All() {
core.Sessions.Remove(session.ID)
}
core.PivotSessions.Range(func(key, value interface{}) bool {
core.PivotSessions.Delete(key)
return true
})
})
}
+3 -3
View File
@@ -169,10 +169,10 @@ func tunnelCloseHandler(implantConn *core.ImplantConnection, data []byte) *slive
}
} else {
rtunnel := rtunnels.GetRTunnel(tunnelData.TunnelID)
if rtunnel != nil && session.ID == tunnel.SessionID {
if rtunnel != nil && session.ID == rtunnel.SessionID {
rtunnel.Close()
rtunnels.RemoveRTunnel(rtunnel.ID)
} else if rtunnel != nil && session.ID != tunnel.SessionID {
} else if rtunnel != nil && session.ID != rtunnel.SessionID {
sessionHandlerLog.Warnf("Warning: Session %s attempted to send data on reverse tunnel it did not own", session.ID)
} else {
sessionHandlerLog.Warnf("Close sent on nil tunnel %d", tunnelData.TunnelID)
@@ -206,7 +206,7 @@ func socksDataHandler(implantConn *core.ImplantConnection, data []byte) *sliverp
// core.SocksTunnels.Close(socksData.TunnelID)
// return nil
//}
sessionHandlerLog.Debugf("socksDataHandler:", len(socksData.Data), socksData.Data)
sessionHandlerLog.Debugf("socksDataHandler: %d bytes: %v", len(socksData.Data), socksData.Data)
socksTunnel := core.SocksTunnels.Get(socksData.TunnelID)
if socksTunnel != nil {
if session.ID == socksTunnel.SessionID {
+115
View File
@@ -0,0 +1,115 @@
package handlers
import (
"testing"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/core/rtunnels"
"google.golang.org/protobuf/proto"
)
type testWriteCloser struct {
closed bool
}
func (t *testWriteCloser) Write(data []byte) (int, error) {
return len(data), nil
}
func (t *testWriteCloser) Close() error {
t.closed = true
return nil
}
func addTestSession(t *testing.T) (*core.ImplantConnection, *core.Session) {
t.Helper()
conn := core.NewImplantConnection("test", "n/a")
session := core.NewSession(conn)
core.Sessions.Add(session)
t.Cleanup(func() {
core.Sessions.Remove(session.ID)
})
return conn, session
}
func marshalTunnelCloseData(t *testing.T, tunnelID uint64) []byte {
t.Helper()
data, err := proto.Marshal(&sliverpb.TunnelData{
TunnelID: tunnelID,
Closed: true,
})
if err != nil {
t.Fatalf("marshal tunnel close data: %v", err)
}
return data
}
func assertNoPanic(t *testing.T, fn func()) {
t.Helper()
defer func() {
if recovered := recover(); recovered != nil {
t.Fatalf("unexpected panic: %v", recovered)
}
}()
fn()
}
func TestTunnelCloseHandlerClosesOwnedReverseTunnel(t *testing.T) {
conn, session := addTestSession(t)
tunnelID := core.NewTunnelID()
writer := &testWriteCloser{}
rtunnels.AddRTunnel(rtunnels.NewRTunnel(tunnelID, session.ID, writer))
t.Cleanup(func() {
rtunnels.RemoveRTunnel(tunnelID)
})
assertNoPanic(t, func() {
tunnelCloseHandler(conn, marshalTunnelCloseData(t, tunnelID))
})
if rtunnel := rtunnels.GetRTunnel(tunnelID); rtunnel != nil {
t.Fatalf("expected reverse tunnel %d to be removed", tunnelID)
}
if !writer.closed {
t.Fatal("expected reverse tunnel writer to be closed")
}
}
func TestTunnelCloseHandlerKeepsUnownedReverseTunnel(t *testing.T) {
ownerConn, ownerSession := addTestSession(t)
_ = ownerConn
attackerConn, attackerSession := addTestSession(t)
tunnelID := core.NewTunnelID()
writer := &testWriteCloser{}
rtunnels.AddRTunnel(rtunnels.NewRTunnel(tunnelID, ownerSession.ID, writer))
t.Cleanup(func() {
rtunnels.RemoveRTunnel(tunnelID)
})
assertNoPanic(t, func() {
tunnelCloseHandler(attackerConn, marshalTunnelCloseData(t, tunnelID))
})
rtunnel := rtunnels.GetRTunnel(tunnelID)
if rtunnel == nil {
t.Fatalf("expected reverse tunnel %d to remain for owner %s", tunnelID, ownerSession.ID)
}
if rtunnel.SessionID != ownerSession.ID {
t.Fatalf("expected reverse tunnel owner %s, got %s", ownerSession.ID, rtunnel.SessionID)
}
if attackerSession.ID == ownerSession.ID {
t.Fatal("expected distinct owner and attacker sessions")
}
if writer.closed {
t.Fatal("expected unowned reverse tunnel writer to remain open")
}
}
+361
View File
@@ -0,0 +1,361 @@
package aitools
import (
"context"
stdbase32 "encoding/base32"
stdbase64 "encoding/base64"
"fmt"
"strings"
"unicode/utf8"
serverai "github.com/bishopfox/sliver/server/ai"
utilencoders "github.com/bishopfox/sliver/util/encoders"
)
const aiEncodingDefaultMaxBytes = 64 * 1024
type encodingInputArgs struct {
Text *string `json:"text,omitempty"`
DataBase64 *string `json:"data_base64,omitempty"`
}
type encodedValueArgs struct {
Value *string `json:"value,omitempty"`
MaxBytes *int64 `json:"max_bytes,omitempty"`
}
type gzipDecodeArgs struct {
DataBase64 *string `json:"data_base64,omitempty"`
MaxBytes *int64 `json:"max_bytes,omitempty"`
}
type encodingValueResult struct {
Encoding string `json:"encoding"`
Operation string `json:"operation"`
Variant string `json:"variant,omitempty"`
Value string `json:"value"`
ByteLen int `json:"byte_len"`
}
type encodingBytesResult struct {
Encoding string `json:"encoding"`
Operation string `json:"operation"`
Variant string `json:"variant,omitempty"`
ByteLen int `json:"byte_len"`
SHA256 string `json:"sha256,omitempty"`
DataBase64 string `json:"data_base64,omitempty"`
Text string `json:"text,omitempty"`
}
type standardBase32Encoder struct{}
type standardBase64Encoder struct{}
func encodingToolDefinitions() []serverai.AgenticToolDefinition {
return []serverai.AgenticToolDefinition{
{
Name: "base32_encode",
Description: "Encode bytes using standard RFC 4648 base32 with padding. Provide either text or data_base64 input.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"data_base64": map[string]any{"type": "string", "description": "Optional standard base64 wrapper for arbitrary input bytes."},
"text": map[string]any{"type": "string", "description": "Optional UTF-8 text to encode."},
},
"additionalProperties": false,
},
},
{
Name: "base32_decode",
Description: "Decode standard RFC 4648 base32. Returns the decoded bytes as standard data_base64 plus UTF-8 text when valid.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"max_bytes": map[string]any{"type": "integer", "description": "Optional maximum decoded byte length. Defaults to 65536."},
"value": map[string]any{"type": "string", "description": "Base32 value to decode."},
},
"required": []string{"value"},
"additionalProperties": false,
},
},
{
Name: "base64_encode",
Description: "Encode bytes using standard RFC 4648 base64 with padding. Provide either text or data_base64 input.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"data_base64": map[string]any{"type": "string", "description": "Optional standard base64 wrapper for arbitrary input bytes."},
"text": map[string]any{"type": "string", "description": "Optional UTF-8 text to encode."},
},
"additionalProperties": false,
},
},
{
Name: "base64_decode",
Description: "Decode standard RFC 4648 base64. Returns the decoded bytes as standard data_base64 plus UTF-8 text when valid.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"max_bytes": map[string]any{"type": "integer", "description": "Optional maximum decoded byte length. Defaults to 65536."},
"value": map[string]any{"type": "string", "description": "Base64 value to decode."},
},
"required": []string{"value"},
"additionalProperties": false,
},
},
{
Name: "hex_encode",
Description: "Encode bytes as lowercase hexadecimal. Provide either text or data_base64 input.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"data_base64": map[string]any{"type": "string", "description": "Optional standard base64 wrapper for arbitrary input bytes."},
"text": map[string]any{"type": "string", "description": "Optional UTF-8 text to encode."},
},
"additionalProperties": false,
},
},
{
Name: "hex_decode",
Description: "Decode a hexadecimal string. Returns the decoded bytes as standard data_base64 plus UTF-8 text when valid.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"max_bytes": map[string]any{"type": "integer", "description": "Optional maximum decoded byte length. Defaults to 65536."},
"value": map[string]any{"type": "string", "description": "Hexadecimal value to decode."},
},
"required": []string{"value"},
"additionalProperties": false,
},
},
{
Name: "gzip_encode",
Description: "Compress bytes with gzip. Provide either text or data_base64 input. Returns the compressed bytes as standard data_base64.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"data_base64": map[string]any{"type": "string", "description": "Optional standard base64 wrapper for arbitrary input bytes."},
"text": map[string]any{"type": "string", "description": "Optional UTF-8 text to compress."},
},
"additionalProperties": false,
},
},
{
Name: "gzip_decode",
Description: "Decompress gzip bytes supplied as standard data_base64. Returns the decoded bytes as standard data_base64 plus UTF-8 text when valid.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"data_base64": map[string]any{"type": "string", "description": "Standard base64 wrapper for gzip-compressed bytes."},
"max_bytes": map[string]any{"type": "integer", "description": "Optional maximum decoded byte length. Defaults to 65536."},
},
"required": []string{"data_base64"},
"additionalProperties": false,
},
},
}
}
func (e *executor) callEncodingTool(_ context.Context, name string, arguments string) (string, bool, error) {
switch strings.TrimSpace(name) {
case "base32_encode":
var args encodingInputArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callEncodeValueTool("base32", "standard", args, standardBase32Encoder{})
return result, true, err
case "base32_decode":
var args encodedValueArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callDecodeValueTool("base32", "standard", args, standardBase32Encoder{})
return result, true, err
case "base64_encode":
var args encodingInputArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callEncodeValueTool("base64", "standard", args, standardBase64Encoder{})
return result, true, err
case "base64_decode":
var args encodedValueArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callDecodeValueTool("base64", "standard", args, standardBase64Encoder{})
return result, true, err
case "hex_encode":
var args encodingInputArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callEncodeValueTool("hex", "", args, utilencoders.Hex{})
return result, true, err
case "hex_decode":
var args encodedValueArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
result, err := callDecodeValueTool("hex", "", args, utilencoders.Hex{})
return result, true, err
case "gzip_encode":
var args encodingInputArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
input, err := resolveEncodingInput(args)
if err != nil {
return "", true, err
}
output, err := new(utilencoders.Gzip).Encode(input)
if err != nil {
return "", true, err
}
result, err := marshalToolResult(newEncodingBytesResult("gzip", "encode", "", output))
return result, true, err
case "gzip_decode":
var args gzipDecodeArgs
if err := decodeToolArgs(arguments, &args); err != nil {
return "", true, err
}
data, err := requireStandardBase64(args.DataBase64, "data_base64")
if err != nil {
return "", true, err
}
output, err := new(utilencoders.Gzip).DecodeWithMaxLen(data, resolveMaxBytes(args.MaxBytes))
if err != nil {
return "", true, err
}
result, err := marshalToolResult(newEncodingBytesResult("gzip", "decode", "", output))
return result, true, err
default:
return "", false, nil
}
}
func callEncodeValueTool(name string, variant string, args encodingInputArgs, encoder utilencoders.Encoder) (string, error) {
input, err := resolveEncodingInput(args)
if err != nil {
return "", err
}
output, err := encoder.Encode(input)
if err != nil {
return "", err
}
return marshalToolResult(encodingValueResult{
Encoding: name,
Operation: "encode",
Variant: variant,
Value: string(output),
ByteLen: len(output),
})
}
func (standardBase32Encoder) Encode(data []byte) ([]byte, error) {
return []byte(stdbase32.StdEncoding.EncodeToString(data)), nil
}
func (standardBase32Encoder) Decode(data []byte) ([]byte, error) {
value := strings.TrimSpace(string(data))
decoded, err := stdbase32.StdEncoding.DecodeString(value)
if err == nil {
return decoded, nil
}
return stdbase32.StdEncoding.WithPadding(stdbase32.NoPadding).DecodeString(value)
}
func (standardBase64Encoder) Encode(data []byte) ([]byte, error) {
return []byte(stdbase64.StdEncoding.EncodeToString(data)), nil
}
func (standardBase64Encoder) Decode(data []byte) ([]byte, error) {
return decodeStandardBase64(strings.TrimSpace(string(data)))
}
func callDecodeValueTool(name string, variant string, args encodedValueArgs, encoder utilencoders.Encoder) (string, error) {
value, err := requireString(args.Value, "value")
if err != nil {
return "", err
}
output, err := encoder.Decode([]byte(value))
if err != nil {
return "", err
}
maxBytes := resolveMaxBytes(args.MaxBytes)
if int64(len(output)) > maxBytes {
return "", fmt.Errorf("%s decoded payload exceeds %d bytes", name, maxBytes)
}
return marshalToolResult(newEncodingBytesResult(name, "decode", variant, output))
}
func resolveEncodingInput(args encodingInputArgs) ([]byte, error) {
hasText := args.Text != nil
hasData := args.DataBase64 != nil
switch {
case hasText && hasData:
return nil, fmt.Errorf("provide only one of text or data_base64")
case hasText:
return []byte(*args.Text), nil
case hasData:
return decodeStandardBase64(*args.DataBase64)
default:
return nil, fmt.Errorf("text or data_base64 is required")
}
}
func requireString(value *string, field string) (string, error) {
if value == nil {
return "", fmt.Errorf("%s is required", field)
}
return *value, nil
}
func requireStandardBase64(value *string, field string) ([]byte, error) {
if value == nil {
return nil, fmt.Errorf("%s is required", field)
}
data, err := decodeStandardBase64(*value)
if err != nil {
return nil, fmt.Errorf("invalid %s: %w", field, err)
}
return data, nil
}
func decodeStandardBase64(value string) ([]byte, error) {
value = strings.TrimSpace(value)
data, err := stdbase64.StdEncoding.DecodeString(value)
if err == nil {
return data, nil
}
return stdbase64.RawStdEncoding.DecodeString(value)
}
func resolveMaxBytes(maxBytes *int64) int64 {
if maxBytes != nil && *maxBytes > 0 {
return *maxBytes
}
return aiEncodingDefaultMaxBytes
}
func newEncodingBytesResult(name string, operation string, variant string, data []byte) encodingBytesResult {
result := encodingBytesResult{
Encoding: name,
Operation: operation,
Variant: variant,
ByteLen: len(data),
DataBase64: stdbase64.StdEncoding.EncodeToString(data),
}
if len(data) > 0 {
result.SHA256 = sha256Hex(data)
if utf8.Valid(data) {
result.Text = string(data)
}
}
return result
}
+119
View File
@@ -0,0 +1,119 @@
package aitools
import (
"context"
stdbase32 "encoding/base32"
stdbase64 "encoding/base64"
stdhex "encoding/hex"
"encoding/json"
"testing"
)
func TestValueEncodingToolsRoundTrip(t *testing.T) {
exec := &executor{}
ctx := context.Background()
cases := []struct {
encodeTool string
decodeTool string
expected string
variant string
}{
{encodeTool: "base32_encode", decodeTool: "base32_decode", expected: stdbase32.StdEncoding.EncodeToString([]byte("hello world")), variant: "standard"},
{encodeTool: "base64_encode", decodeTool: "base64_decode", expected: stdbase64.StdEncoding.EncodeToString([]byte("hello world")), variant: "standard"},
{encodeTool: "hex_encode", decodeTool: "hex_decode", expected: stdhex.EncodeToString([]byte("hello world")), variant: ""},
}
for _, tc := range cases {
t.Run(tc.encodeTool, func(t *testing.T) {
encodedRaw, err := exec.CallTool(ctx, tc.encodeTool, `{"text":"hello world"}`)
if err != nil {
t.Fatalf("encode with %s: %v", tc.encodeTool, err)
}
var encoded encodingValueResult
if err := json.Unmarshal([]byte(encodedRaw), &encoded); err != nil {
t.Fatalf("decode encode result: %v", err)
}
if encoded.Value == "" {
t.Fatalf("expected encoded value from %s", tc.encodeTool)
}
if encoded.Value != tc.expected {
t.Fatalf("unexpected encoded value: got=%q want=%q", encoded.Value, tc.expected)
}
if encoded.Variant != tc.variant {
t.Fatalf("unexpected variant: got=%q want=%q", encoded.Variant, tc.variant)
}
decodedRaw, err := exec.CallTool(ctx, tc.decodeTool, `{"value":"`+encoded.Value+`"}`)
if err != nil {
t.Fatalf("decode with %s: %v", tc.decodeTool, err)
}
var decoded encodingBytesResult
if err := json.Unmarshal([]byte(decodedRaw), &decoded); err != nil {
t.Fatalf("decode decode result: %v", err)
}
if decoded.Text != "hello world" {
t.Fatalf("unexpected decoded text: %+v", decoded)
}
if decoded.Variant != tc.variant {
t.Fatalf("unexpected decoded variant: got=%q want=%q", decoded.Variant, tc.variant)
}
})
}
}
func TestGzipEncodingToolsRoundTrip(t *testing.T) {
exec := &executor{}
ctx := context.Background()
encodedRaw, err := exec.CallTool(ctx, "gzip_encode", `{"text":"hello world"}`)
if err != nil {
t.Fatalf("gzip encode: %v", err)
}
var encoded encodingBytesResult
if err := json.Unmarshal([]byte(encodedRaw), &encoded); err != nil {
t.Fatalf("decode gzip encode result: %v", err)
}
if encoded.DataBase64 == "" {
t.Fatalf("expected gzip output bytes, got %+v", encoded)
}
decodedRaw, err := exec.CallTool(ctx, "gzip_decode", `{"data_base64":"`+encoded.DataBase64+`"}`)
if err != nil {
t.Fatalf("gzip decode: %v", err)
}
var decoded encodingBytesResult
if err := json.Unmarshal([]byte(decodedRaw), &decoded); err != nil {
t.Fatalf("decode gzip decode result: %v", err)
}
if decoded.Text != "hello world" {
t.Fatalf("unexpected gzip decode text: %+v", decoded)
}
}
func TestValueDecodingToolsRespectMaxBytes(t *testing.T) {
exec := &executor{}
ctx := context.Background()
encoded := stdbase64.StdEncoding.EncodeToString([]byte("abc"))
if _, err := exec.CallTool(ctx, "gzip_decode", `{"data_base64":"`+encoded+`","max_bytes":2}`); err == nil {
t.Fatal("expected gzip decode to reject invalid compressed data")
}
hexEncodedRaw, err := exec.CallTool(ctx, "hex_encode", `{"text":"abc"}`)
if err != nil {
t.Fatalf("hex encode: %v", err)
}
var hexEncoded encodingValueResult
if err := json.Unmarshal([]byte(hexEncodedRaw), &hexEncoded); err != nil {
t.Fatalf("decode hex encode result: %v", err)
}
if _, err := exec.CallTool(ctx, "hex_decode", `{"value":"`+hexEncoded.Value+`","max_bytes":2}`); err == nil {
t.Fatal("expected hex decode max_bytes limit to be enforced")
}
}
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more