Compare commits

...
Author SHA1 Message Date
moloch-- b3429f5f88 Fix err nil deref 2023-11-18 13:31:47 -07:00
moloch-- 04d8d2aac7 Add missing builder permissions 2023-11-18 12:39:34 -07:00
moloch-- b71759f3b2 Add basic methods 2023-11-18 12:33:06 -07:00
moloch-- 13c68a7f50 Implement method checks 2023-11-18 12:27:39 -07:00
moloch-- 1f894f50ff Add permissions to operator config 2023-11-18 12:14:33 -07:00
moloch-- 33ea66de58 Add production 'slim' Docker stage 2023-11-18 10:19:14 -07:00
moloch-- 9a432f583d Add missing libs to docker test 2023-11-18 10:09:32 -07:00
moloch-- cbcd948c83 Add comments to Dockerfile 2023-11-18 09:24:21 -07:00
Joe 2ada8bf8ed Merge pull request #1465 from BishopFox/vendor/ssh
Update ssh and garble
2023-11-18 08:16:16 -08:00
moloch-- 02a4657d14 Additional tweaks to dockerfile 2023-11-18 08:53:46 -07:00
Joe b7cef9a07c Merge branch 'master' into vendor/ssh 2023-11-18 07:06:53 -08:00
moloch-- 49606ba753 Update ssh and garble 2023-11-18 07:49:03 -07:00
Joe 116431a049 Merge pull request #1421 from BishopFox/upload-dir
Adding the ability to upload directories
2023-11-17 10:03:09 -08:00
Joe ae5ac2af0f Merge branch 'master' into upload-dir 2023-11-17 09:34:45 -08:00
Joe b03c2ca6cd Merge pull request #1464 from BishopFox/vendor/gorilla
Update deps
2023-11-16 17:55:34 -08:00
Joe 6a4276e1e2 Merge pull request #1463 from BishopFox/http/default-config
Update default http c2 config
2023-11-16 17:55:17 -08:00
moloch-- c7358f8e63 Remove uneeded rand seeding 2023-11-16 18:32:54 -07:00
moloch-- de2fb65ee0 Improve cert randomization 2023-11-16 18:28:48 -07:00
moloch-- c52ca054a0 Update default http c2 config 2023-11-16 18:22:50 -07:00
moloch-- ffdbaba982 Update default http c2 config 2023-11-16 18:17:04 -07:00
moloch-- d23d814368 Update deps 2023-11-16 17:20:33 -07:00
Joe a57a67b6e0 Merge pull request #1461 from BishopFox/vendor/sqlite
Update sqlite deps
2023-11-16 15:59:35 -08:00
Ronan Kervella 8c1194283b Merge branch 'master' into upload-dir 2023-11-10 14:05:05 -08:00
Raf 8ebd7da9a8 Merge branch 'master' into upload-dir 2023-11-08 08:15:02 -05:00
Raf a511af6fd2 Merge branch 'master' into upload-dir 2023-11-01 10:52:23 -04:00
Raf 97a22bb8eb Merging master into this branch and making some tweaks to upload. 2023-11-01 10:38:34 -04:00
Ronan Kervella 6b88a01fad Merge branch 'master' into upload-dir 2023-10-19 15:31:56 -07:00
Raf 7747df7b96 Addressing potential zip slip issue, fixing bug when uploading directories without a filter 2023-10-04 11:11:49 -04:00
Raf efe747b8aa Adding the ability to upload directories 2023-10-04 10:13:04 -04:00
91 changed files with 2754 additions and 1388 deletions

No files matched your search

+82 -24
View File
@@ -1,3 +1,12 @@
#
# For production:
# docker build --target production -t sliver .
# docker run -it --rm -v $HOME/.sliver:/home/sliver/.sliver sliver
#
# For unit testing:
# docker build --target test .
#
# STAGE: base
## Compiles Sliver for use
FROM --platform=linux/amd64 golang:1.21.4 as base
@@ -22,25 +31,10 @@ RUN cp -vv sliver-server /opt/sliver-server
## Use `--target test` in the docker build command to run this stage
FROM --platform=linux/amd64 base as test
### Install testing packages
RUN apt-get update --fix-missing && apt-get -y install \
libxml2 libxml2-dev libxslt-dev locate curl \
libreadline6-dev libcurl4-openssl-dev git-core \
libssl-dev libyaml-dev openssl autoconf libtool \
ncurses-dev bison curl xsel postgresql \
postgresql-contrib postgresql-client libpq-dev \
libapr1 libaprutil1 libsvn1 \
libpcap-dev libsqlite3-dev libgmp3-dev \
mingw-w64 binutils-mingw-w64 g++-mingw-w64 \
nasm gcc-multilib
### Install MSF for testing
RUN curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall \
&& chmod 755 msfinstall \
&& ./msfinstall
RUN mkdir -p ~/.msf4/ \
&& touch ~/.msf4/initial_setup_complete \
&& su -l sliver -c 'mkdir -p ~/.msf4/ && touch ~/.msf4/initial_setup_complete'
RUN apt-get update --fix-missing \
&& apt-get -y upgrade \
&& apt-get -y install \
curl gcc-multilib build-essential mingw-w64 binutils-mingw-w64 g++-mingw-w64
RUN /opt/sliver-server unpack --force
@@ -51,17 +45,81 @@ RUN /go/src/github.com/bishopfox/sliver/go-tests.sh
## Final dockerized form of Sliver
FROM --platform=linux/amd64 debian:bookworm-slim as production
### Install production packages
RUN apt-get update --fix-missing \
&& apt-get -y upgrade \
&& apt-get -y install \
libxml2 libxml2-dev libxslt-dev locate gnupg \
libreadline6-dev libcurl4-openssl-dev git-core \
libssl-dev libyaml-dev openssl autoconf libtool \
ncurses-dev bison curl xsel postgresql \
postgresql-contrib postgresql-client libpq-dev \
curl libapr1 libaprutil1 libsvn1 \
libpcap-dev libsqlite3-dev libgmp3-dev \
mingw-w64 binutils-mingw-w64 g++-mingw-w64 \
nasm gcc-multilib
### Install MSF for stager generation
RUN curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall \
&& chmod 755 msfinstall \
&& ./msfinstall \
&& mkdir -p ~/.msf4/ \
&& touch ~/.msf4/initial_setup_complete
### Cleanup unneeded packages
RUN apt-get remove -y curl gnupg \
&& apt-get autoremove -y \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
### Add sliver user
RUN groupadd -g 999 sliver \
&& useradd -r -u 999 -g sliver sliver \
&& mkdir -p /home/sliver/ \
&& chown -R sliver:sliver /home/sliver \
&& su -l sliver -c 'mkdir -p ~/.msf4/ && touch ~/.msf4/initial_setup_complete'
### Copy compiled binary
COPY --from=base /opt/sliver-server /opt/sliver-server
### Add sliver user
RUN groupadd -g 999 sliver && useradd -r -u 999 -g sliver sliver
RUN mkdir -p /home/sliver/ && chown -R sliver:sliver /home/sliver
### Unpack Sliver:
USER sliver
RUN /opt/sliver-server unpack --force
WORKDIR /home/sliver/
VOLUME [ "/home/sliver/.sliver" ]
ENTRYPOINT [ "/opt/sliver-server" ]
# STAGE: production-slim (about 1Gb smaller)
### Slim production image, i.e. without MSF and assoicated libraries
### Still include GCC and MinGW for cross-platform generation
FROM --platform=linux/amd64 debian:bookworm-slim as production-slim
### Install production packages
RUN apt-get update --fix-missing \
&& apt-get -y upgrade \
&& apt-get -y install \
build-essential mingw-w64 binutils-mingw-w64 g++-mingw-w64 gcc-multilib
### Cleanup unneeded packages
RUN apt-get autoremove -y \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
### Add sliver user
RUN groupadd -g 999 sliver \
&& useradd -r -u 999 -g sliver sliver \
&& mkdir -p /home/sliver/ \
&& chown -R sliver:sliver /home/sliver
### Copy compiled binary
COPY --from=base /opt/sliver-server /opt/sliver-server
### Unpack Sliver:
USER sliver
RUN /opt/sliver-server unpack --force
USER sliver
WORKDIR /home/sliver/
VOLUME [ "/home/sliver/.sliver" ]
ENTRYPOINT [ "/opt/sliver-server" ]
+349 -19
View File
@@ -19,23 +19,261 @@ package filesystem
*/
import (
"archive/tar"
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"google.golang.org/protobuf/proto"
"github.com/spf13/cobra"
"github.com/bishopfox/sliver/client/console"
"github.com/bishopfox/sliver/implant/sliver/handlers/matcher"
"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/util/encoders"
)
func determineDirPathFilter(targetPath string) (string, string) {
// The filter
filter := ""
// The path the filter applies to
path := ""
/*
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 targetPath != "." {
// Check if the path contains a filter
// Test on a standardized version of the path (change any \ to /)
testPath := strings.Replace(targetPath, "\\", "/", -1)
/*
Cannot use the path or filepath libraries because the OS
of the client does not necessarily match the OS of the
implant
*/
lastSeparatorOccurrence := strings.LastIndex(testPath, "/")
if lastSeparatorOccurrence == -1 {
// Then this is only a filter
filter = targetPath
path = "."
} else {
// Then we need to test for a filter on the end of the string
// The indices should be the same because we did not change the length of the string
path = targetPath[:lastSeparatorOccurrence+1]
filter = targetPath[lastSeparatorOccurrence+1:]
}
} else {
path = targetPath
// filter remains blank
}
return path, filter
}
func standarizeArchiveFileName(path string, uploadPathSpecified string) string {
// Change all backslashes to forward slashes
var standardFilePath string = strings.ReplaceAll(path, "\\", "/")
var standardUploadPath string = strings.ReplaceAll(uploadPathSpecified, "\\", "/")
/*
Remove the volume / root from the directory
path. This makes it so that files on the
system where the archive is extracted to
will not be clobbered.
Tried with filepath.VolumeName, but that function
does not work reliably with Windows paths
*/
if strings.HasPrefix(standardFilePath, "//") {
// If this a UNC path, filepath.Rel is not going to work
return standardFilePath[2:]
} else {
beginningOfUploadPath, _, _ := strings.Cut(standardUploadPath, "/")
if index := strings.Index(standardFilePath, beginningOfUploadPath); index != -1 {
// Add a / in front to make the specified upload path the root
standardFilePath = "/" + standardFilePath[index:]
}
// Calculate a path relative to the root
pathParts := strings.SplitN(standardFilePath, "/", 2)
if len(pathParts) < 2 {
// Then something is wrong with this path
return standardFilePath
}
basePath := pathParts[0]
fileRelPath := pathParts[1]
if basePath == "" {
// If base path is blank, that means it started with / and / is the root
return fileRelPath
} else {
/*
Then this is almost certainly Windows, and we will set the archive up
so that it preserves the path but without the colon.
Something like:
c/windows/system32/file.whatever
Colons are not legal in Windows filenames, so let's get rid of them.
*/
basePath = strings.ReplaceAll(basePath, ":", "")
basePath = strings.ToLower(basePath)
return basePath + "/" + fileRelPath
}
}
}
func tarDirectory(sourcePath string, pathAsSpecified string, sourceFilter string, recurse bool, preserveDirStructure bool) ([]byte, int, int, error) {
readFiles := 0
unreadableFiles := 0
var matchingFiles []string
var buffer bytes.Buffer
tarWriter := tar.NewWriter(&buffer)
/*
Build the list of files to include in the archive.
Walking the directory can take a long time and do a lot of unnecessary work
if we do not need to recurse through subdirectories.
If we are not recursing, then read the directory without worrying about
subdirectories.
*/
if !recurse {
testPath := strings.ReplaceAll(sourcePath, "\\", "/")
directory, err := os.Open(sourcePath)
if err != nil {
return nil, readFiles, unreadableFiles, err
}
directoryFiles, err := directory.Readdirnames(0)
directory.Close()
if err != nil {
return nil, readFiles, unreadableFiles, err
}
for _, fileName := range directoryFiles {
standardFileName := strings.ReplaceAll(testPath+fileName, "\\", "/")
if sourceFilter != "" {
match, err := matcher.Match(sourcePath+sourceFilter, standardFileName)
if err == nil && match {
matchingFiles = append(matchingFiles, standardFileName)
}
} else {
matchingFiles = append(matchingFiles, standardFileName)
}
}
} else {
filepath.WalkDir(sourcePath, func(file string, d os.DirEntry, err error) error {
filePath := strings.ReplaceAll(file, "\\", "/")
if sourceFilter != "" {
// Normalize paths
testPath := strings.ReplaceAll(filepath.Dir(file), "\\", "/") + "/"
match, matchErr := matcher.Match(testPath+sourceFilter, filePath)
if !match || matchErr != nil {
// If there is an error, it is because the filter is bad, so it is not a match
return nil
}
matchingFiles = append(matchingFiles, file)
} else {
matchingFiles = append(matchingFiles, file)
}
return nil
})
}
var fileName string
for _, file := range matchingFiles {
fi, err := os.Stat(file)
if err != nil {
// Cannot get info on the file, so skip it
unreadableFiles += 1
continue
}
if preserveDirStructure {
fileName = standarizeArchiveFileName(file, pathAsSpecified)
} else {
fileName = fi.Name()
}
// If the file is a SymLink replace fileInfo and path with the symlink destination.
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
file, err = filepath.EvalSymlinks(file)
if err != nil {
unreadableFiles += 1
continue
}
fi, err = os.Lstat(file)
if err != nil {
unreadableFiles += 1
continue
}
}
header, err := tar.FileInfoHeader(fi, file)
if err != nil {
unreadableFiles += 1
continue
}
// Keep the symlink file path for the header name.
header.Name = filepath.ToSlash(fileName)
// Check that we can open the file before we try to write it to the archive
if !fi.IsDir() {
data, err := os.Open(file)
if err != nil {
// Skip this file and do not write it to the archive.
unreadableFiles += 1
continue
}
if err := tarWriter.WriteHeader(header); err != nil {
unreadableFiles += 1
data.Close()
continue
}
if _, err := io.Copy(tarWriter, data); err != nil {
unreadableFiles += 1
data.Close()
continue
}
data.Close()
readFiles += 1
} else {
if err := tarWriter.WriteHeader(header); err != nil {
unreadableFiles += 1
continue
}
}
}
if err := tarWriter.Close(); err != nil {
return buffer.Bytes(), readFiles, unreadableFiles, err
}
return buffer.Bytes(), readFiles, unreadableFiles, nil
}
// UploadCmd - Upload a file to the remote system
func UploadCmd(cmd *cobra.Command, con *console.SliverConsoleClient, args []string) {
readFiles := 0
unreadableFiles := 0
var isDirectory bool
var fileName string
var sourceInfomation fs.FileInfo
var uploadData []byte
session, beacon := con.ActiveTarget.GetInteractive()
if session == nil && beacon == nil {
return
@@ -48,9 +286,10 @@ func UploadCmd(cmd *cobra.Command, con *console.SliverConsoleClient, args []stri
remotePath = args[1]
}
// localPath := ctx.Args.String("local-path")
// remotePath := ctx.Args.String("remote-path")
recurse, _ := cmd.Flags().GetBool("recurse")
preserve, _ := cmd.Flags().GetBool("preserve")
isIOC, _ := cmd.Flags().GetBool("ioc")
overwrite, _ := cmd.Flags().GetBool("overwrite")
if localPath == "" {
con.PrintErrorf("Missing parameter, see `help upload`\n")
@@ -58,12 +297,6 @@ func UploadCmd(cmd *cobra.Command, con *console.SliverConsoleClient, args []stri
}
src, _ := filepath.Abs(localPath)
_, err := os.Stat(src)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
fileName := filepath.Base(src)
if remotePath == "" {
remotePath = fileName
@@ -71,22 +304,103 @@ func UploadCmd(cmd *cobra.Command, con *console.SliverConsoleClient, args []stri
dst := remotePath
fileBuf, err := os.ReadFile(src)
// Get information on the source - is it a directory?
srcPath, srcFilter := determineDirPathFilter(src)
sourceInfomation, err := os.Stat(src)
if err == nil && sourceInfomation.IsDir() {
if !strings.HasSuffix(src, string(os.PathSeparator)) {
src += string(os.PathSeparator)
}
srcPath = src
srcFilter = ""
}
if err != nil {
con.PrintErrorf("%s\n", err)
if errors.Is(err, fs.ErrNotExist) {
// Check to see if src ends with a filter
sourceInfomation, err = os.Stat(srcPath)
if errors.Is(err, fs.ErrNotExist) {
con.PrintErrorf("The source %s does not exist.\n", src)
return
} else if errors.Is(err, fs.ErrPermission) {
con.PrintErrorf("Permissions error when trying to read %s.\n", src)
return
}
}
if errors.Is(err, fs.ErrPermission) {
con.PrintErrorf("Permissions error when trying to read %s.\n", src)
return
}
}
// If we still do not have information about the source at this point, bail.
if sourceInfomation == nil {
con.PrintErrorf("Could not get information about the upload source %s\n", src)
return
}
uploadGzip, _ := new(encoders.Gzip).Encode(fileBuf)
if sourceInfomation.IsDir() {
// tar the directory and send it over
uploadData, readFiles, unreadableFiles, err = tarDirectory(srcPath, localPath, srcFilter, recurse, preserve)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
if readFiles == 0 {
con.PrintErrorf("Could not find any files matching %s\n", src)
return
}
isDirectory = true
fileName = ""
} else {
uploadData, err = os.ReadFile(src)
if err != nil {
con.PrintErrorf("%s\n", err)
return
}
readFiles = 1
unreadableFiles = 0
isDirectory = false
fileName = filepath.Base(src)
}
uploadGzip, _ := new(encoders.Gzip).Encode(uploadData)
var readFilesQualifier string
var unsuccessfulFiles string
if readFiles == 1 {
readFilesQualifier = ""
} else {
readFilesQualifier = "s"
}
if unreadableFiles > 0 {
if unreadableFiles == 1 {
unsuccessfulFiles = fmt.Sprintf(" (could not read %d file)", unreadableFiles)
} else {
unsuccessfulFiles = fmt.Sprintf(" (could not read %d files)", unreadableFiles)
}
} else {
unsuccessfulFiles = ""
}
ctrl := make(chan bool)
con.SpinUntil(fmt.Sprintf("%s -> %s", src, dst), ctrl)
con.SpinUntil(fmt.Sprintf("Uploading %d file%s %sfrom %s to %s", readFiles,
readFilesQualifier,
unsuccessfulFiles,
src,
dst), ctrl)
upload, err := con.Rpc.Upload(context.Background(), &sliverpb.UploadReq{
Request: con.ActiveTarget.Request(cmd),
Path: dst,
Data: uploadGzip,
Encoder: "gzip",
IsIOC: isIOC,
FileName: fileName,
Request: con.ActiveTarget.Request(cmd),
Path: dst,
Data: uploadGzip,
Encoder: "gzip",
IsIOC: isIOC,
FileName: fileName,
IsDirectory: isDirectory,
Overwrite: overwrite,
})
ctrl <- true
<-ctrl
@@ -115,5 +429,21 @@ func PrintUpload(upload *sliverpb.Upload, con *console.SliverConsoleClient) {
con.PrintErrorf("%s\n", upload.Response.Err)
return
}
con.PrintInfof("Wrote file to %s\n", upload.Path)
writtenFileQualifier := "s"
if upload.WrittenFiles == 1 {
writtenFileQualifier = ""
}
unwrittenFileQualifier := "s"
if upload.UnwriteableFiles == 1 {
unwrittenFileQualifier = ""
}
if upload.WrittenFiles > 0 {
if upload.UnwriteableFiles > 0 {
con.PrintInfof("Wrote %d file%s successfully (%d file%s not written) to %s\n", upload.WrittenFiles, writtenFileQualifier, upload.UnwriteableFiles, unwrittenFileQualifier, upload.Path)
} else {
con.PrintInfof("Wrote %d file%s successfully to %s\n", upload.WrittenFiles, writtenFileQualifier, upload.Path)
}
} else {
con.PrintInfof("Could not write %d file%s to %s: the files already exist on the target\n", upload.UnwriteableFiles, unwrittenFileQualifier, upload.Path)
}
}
+25 -1
View File
@@ -334,7 +334,31 @@ On Windows, escaping is disabled. Instead, '\\' is treated as path separator.`
[[.Bold]]About:[[.Normal]] Fetch the last number of bytes or lines from a remote file and display it to stdout.`
uploadHelp = `[[.Bold]]Command:[[.Normal]] upload [local src] <remote dst>
[[.Bold]]About:[[.Normal]] Upload a file to the remote system.`
[[.Bold]]About:[[.Normal]] Upload a file or directory to the remote system.
[[.Bold]][[.Underline]]Paths[[.Normal]]
You can preserve directory structures using the -p switch. Directories will be preserved as they are specified in the source path.
For example, the command upload -p /home/me/docs /tmp will upload the files in /home/me/docs to /tmp/home/me/docs on the target.
However, if you are in the local directory /home/me, and issue the command upload -p docs /tmp, the files in /home/me/docs will
be uploaded to /tmp/docs on the target. This is equivalent to upload /home/me/docs /tmp/docs (notice the lack of the -p switch).
[[.Bold]][[.Underline]]Filters[[.Normal]]
Filters are a way to limit uploads to file names matching given criteria. Filters DO NOT apply to directory names.
Filters are specified after the path. A blank path will filter on names in the current directory. For example:
upload /etc/*.conf will upload all files from /etc whose names end in .conf. /etc/ is the path, *.conf is the filter.
Uploads can be filtered using the following patterns:
'*': Wildcard, matches any sequence of non-path separators (slashes)
Example: n*.txt will match all file 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 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 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.`
procdumpHelp = `[[.Bold]]Command:[[.Normal]] procdump [pid]
[[.Bold]]About:[[.Normal]] Dumps the process memory given a process identifier (pid)`
+4 -1
View File
@@ -1026,7 +1026,7 @@ func SliverCommands(con *client.SliverConsoleClient) console.Commands {
uploadCmd := &cobra.Command{
Use: consts.UploadStr,
Short: "Upload a file",
Short: "Upload a file or directory",
Long: help.GetHelpFor([]string{consts.UploadStr}),
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
@@ -1037,6 +1037,9 @@ func SliverCommands(con *client.SliverConsoleClient) console.Commands {
sliver.AddCommand(uploadCmd)
Flags("", false, uploadCmd, func(f *pflag.FlagSet) {
f.BoolP("ioc", "i", false, "track uploaded file as an ioc")
f.BoolP("recurse", "r", false, "recursively upload a directory")
f.BoolP("overwrite", "o", false, "overwrite files that exist in the destination")
f.BoolP("preserve", "p", false, "preserve directory structure when uploading a directory")
f.Int64P("timeout", "t", defaultTimeout, "grpc timeout in seconds")
})
carapace.Gen(uploadCmd).PositionalCompletion(
+1 -1
View File
@@ -21,7 +21,7 @@ set -e
# Creates the static go asset archives
GO_VER="1.21.4"
GARBLE_VER="1.21.4a"
GARBLE_VER="1.21.4b"
SGN_VER="0.0.3"
BLOAT_FILES="AUTHORS CONTRIBUTORS PATENTS VERSION favicon.ico robots.txt SECURITY.md CONTRIBUTING.md LICENSE README.md ./doc ./test ./api ./misc"
+4 -4
View File
@@ -22,7 +22,7 @@ require (
github.com/glebarez/sqlite v1.10.0
github.com/gofrs/uuid v4.4.0+incompatible
github.com/google/uuid v1.3.1
github.com/gorilla/mux v1.8.0
github.com/gorilla/mux v1.8.1
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
github.com/jedib0t/go-pretty/v6 v6.4.6
github.com/kbinani/screenshot v0.0.0-20191211154542-3a185f1ce18f
@@ -45,8 +45,9 @@ require (
github.com/things-go/go-socks5 v0.0.3
github.com/xlab/treeprint v1.2.0
github.com/yiya1989/sshkrb5 v0.0.0-20201110125252-a1455b75a35e
golang.org/x/crypto v0.14.0
golang.org/x/crypto v0.15.0
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
golang.org/x/net v0.17.0
golang.org/x/sys v0.14.0
golang.org/x/term v0.14.0
golang.org/x/text v0.14.0
@@ -59,6 +60,7 @@ require (
gorm.io/driver/postgres v1.5.2
gorm.io/driver/sqlite v1.5.2
gorm.io/gorm v1.25.5
gvisor.dev/gvisor v0.0.0-20231116203655-c480f66679e6
modernc.org/sqlite v1.27.0
tailscale.com v1.54.0
)
@@ -165,7 +167,6 @@ require (
go4.org/mem v0.0.0-20220726221520-4f986261bf13 // indirect
go4.org/netipx v0.0.0-20230824141953-6213f710f925 // indirect
golang.org/x/mod v0.13.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sync v0.4.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.14.0 // indirect
@@ -178,7 +179,6 @@ require (
gopkg.in/jcmturner/gokrb5.v7 v7.5.0 // indirect
gopkg.in/jcmturner/rpc.v1 v1.1.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gvisor.dev/gvisor v0.0.0-20231116203655-c480f66679e6 // indirect
inet.af/peercred v0.0.0-20210906144145-0893ea02156a // indirect
lukechampine.com/uint128 v1.2.0 // indirect
modernc.org/cc/v3 v3.40.0 // indirect
+4 -17
View File
@@ -135,12 +135,8 @@ github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=
github.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo=
github.com/glebarez/go-sqlite v1.21.1 h1:7MZyUPh2XTrHS7xNEHQbrhfMZuPSzhkm2A1qgg0y5NY=
github.com/glebarez/go-sqlite v1.21.1/go.mod h1:ISs8MF6yk5cL4n/43rSOmVMGJJjHYr7L2MbZZ5Q4E2E=
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
github.com/glebarez/sqlite v1.8.0 h1:02X12E2I/4C1n+v90yTqrjRa8yuo7c3KeHI3FRznCvc=
github.com/glebarez/sqlite v1.8.0/go.mod h1:bpET16h1za2KOOMb8+jCp6UBP/iahDpfPQqSaYLTLx8=
github.com/glebarez/sqlite v1.10.0 h1:u4gt8y7OND/cCei/NMHmfbLxF6xP2wgKcT/BJf2pYkc=
github.com/glebarez/sqlite v1.10.0/go.mod h1:IJ+lfSOmiekhQsFTJRx/lHtGYmCdtAiTaf5wI9u5uHA=
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
@@ -204,8 +200,8 @@ github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/csrf v1.7.1 h1:Ir3o2c1/Uzj6FBxMlAUB6SivgVMy1ONXwYgXn+/aHPE=
github.com/gorilla/csrf v1.7.1/go.mod h1:+a/4tCmqhG6/w4oafeAZ9pEa3/NZOWYVbD9fV0FwIQA=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
@@ -357,7 +353,6 @@ github.com/reeflective/console v0.1.6 h1:BhhvQU/m8QOpaIRzrXfwcbtkGQJX9jVR5qIqAy/
github.com/reeflective/console v0.1.6/go.mod h1:7owTBE9k2lg2QpVw7g4DrK1HxEgr/5DQCmA3O2Znoek=
github.com/reeflective/readline v1.0.8 h1:VuDGI82lAwl1H5by+hpW4OQgM+9ikh6EuOySQUGP3sI=
github.com/reeflective/readline v1.0.8/go.mod h1:5JgnHb/ZCvp/6RUA59HEansPBxWTkyBO4hJ5LL9Fp1Y=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
@@ -453,6 +448,8 @@ golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20220208050332-20e1d8d225ab/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
@@ -626,8 +623,6 @@ gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBp
gorm.io/driver/sqlite v1.5.2 h1:TpQ+/dqCY4uCigCFyrfnrJnrW9zjpelWVoEVNy5qJkc=
gorm.io/driver/sqlite v1.5.2/go.mod h1:qxAuCol+2r6PannQDpOP1FP6ag3mKi4esLnB/jHed+4=
gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.2 h1:gs1o6Vsa+oVKG/a9ElL3XgyGfghFfkKA2SInQaCyMho=
gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
gorm.io/gorm v1.25.5 h1:zR9lOiiYf09VNh5Q1gphfyia1JpiClIWG9hQaxB/mls=
gorm.io/gorm v1.25.5/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gvisor.dev/gvisor v0.0.0-20231116203655-c480f66679e6 h1:QYF5D47yyyibiD9otaga9OZu9JK/epGfDfJckWn3TAI=
@@ -652,22 +647,14 @@ modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
modernc.org/libc v1.29.0 h1:tTFRFq69YKCF2QyGNuRUQxKBm1uZZLubf6Cjh/pVHXs=
modernc.org/libc v1.29.0/go.mod h1:DaG/4Q3LRRdqpiLyP0C2m1B8ZMGkQ+cCgOIjEtQlYhQ=
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
modernc.org/sqlite v1.27.0 h1:MpKAHoyYB7xqcwnUwkuD+npwEa0fojF0B5QRbN+auJ8=
modernc.org/sqlite v1.27.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0=
modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=
+155 -23
View File
@@ -830,6 +830,74 @@ func grepHandler(data []byte, resp RPCResponse) {
resp(data, err)
}
func extractFiles(data []byte, path string, overwrite bool) (int, int, error) {
reader := tar.NewReader(bytes.NewReader(data))
filesSkipped := 0
filesWritten := 0
for {
header, err := reader.Next()
switch {
case err == io.EOF:
// Then we are done
return filesWritten, filesSkipped, nil
case err != nil:
// We should return the up to the caller
return filesWritten, filesSkipped, err
case header == nil:
// Just in case the error is nil, skip it
continue
}
// Validate file path
fileName := filepath.Join(path, header.Name)
if !strings.HasPrefix(fileName, filepath.Clean(path)+string(os.PathSeparator)) {
// Invalid path
continue
}
_, err = os.Stat(fileName)
// Take different actions based on whether this header entry is a directory or a file
switch header.Typeflag {
case tar.TypeDir:
if err != nil {
if err := os.MkdirAll(fileName, 0750); err != nil {
return filesWritten, filesSkipped, err
}
}
case tar.TypeReg:
if err == nil {
// Then the file exists
if !overwrite {
// If we are not overwriting files, then skip this entry
filesSkipped += 1
continue
}
}
// Check to make sure the destination directory exists, and if it does not, create it
destinationDir := filepath.Dir(fileName)
if _, err = os.Stat(destinationDir); errors.Is(err, fs.ErrNotExist) {
if err = os.MkdirAll(destinationDir, 0750); err != nil {
return filesWritten, filesSkipped, err
}
}
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
file.Close()
return filesWritten, filesSkipped, err
}
if _, err := io.Copy(file, reader); err != nil {
file.Close()
return filesWritten, filesSkipped, err
}
file.Close()
filesWritten += 1
}
}
}
func uploadHandler(data []byte, resp RPCResponse) {
uploadReq := &sliverpb.UploadReq{}
err := proto.Unmarshal(data, uploadReq)
@@ -847,47 +915,111 @@ func uploadHandler(data []byte, resp RPCResponse) {
log.Printf("upload path error: %v", err)
// {{end}}
resp([]byte{}, err)
return
}
// Process Upload
upload := &sliverpb.Upload{Path: uploadPath}
uploadPathInfo, err := os.Stat(uploadPath)
if err != nil && !os.IsNotExist(err) {
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
} else if errors.Is(err, fs.ErrNotExist) {
if uploadReq.IsDirectory {
// We need to make a directory for the files
err = os.MkdirAll(uploadPath, 0750)
if err != nil && !errors.Is(err, fs.ErrExist) {
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
}
} else {
// If the file does not exist, that is fine because we will create it.
err = nil
}
}
} else if uploadPathInfo.IsDir() {
if !strings.HasSuffix(uploadPath, string(os.PathSeparator)) {
uploadPath += string(os.PathSeparator)
upload.Path = uploadPath
}
if !uploadReq.IsDirectory {
uploadPath += uploadReq.FileName
uploadPathInfo, err = os.Stat(uploadPath)
upload.Path = uploadPath
// We will deal with any error in a bit.
if err != nil && errors.Is(err, fs.ErrNotExist) {
// If the file does not exist, that is fine because we will create it.
err = nil
}
}
}
if uploadPathInfo != nil && !uploadPathInfo.IsDir() && !uploadReq.Overwrite {
// Then we are trying to overwrite a file that exists and
// the overwrite flag was not specified
err = fmt.Errorf("%s exists, but the overwrite flag was not set", uploadPath)
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
}
if !os.IsNotExist(err) && uploadPathInfo.IsDir() {
if !strings.HasSuffix(uploadPath, string(os.PathSeparator)) {
uploadPath += string(os.PathSeparator)
}
uploadPath += uploadReq.FileName
// If we have not resolved the error by now, then bail.
if err != nil {
data, _ = proto.Marshal(upload)
resp(data, err)
return
}
f, err := os.Create(uploadPath)
var uploadData []byte
if uploadReq.Encoder == "gzip" {
uploadData, err = gzipRead(uploadReq.Data)
} else {
uploadData = uploadReq.Data
}
// Check for decode errors
if err != nil {
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
} else {
// Create file, write data to file system
defer f.Close()
var uploadData []byte
var err error
if uploadReq.Encoder == "gzip" {
uploadData, err = gzipRead(uploadReq.Data)
} else {
uploadData = uploadReq.Data
}
// Check for decode errors
if err != nil {
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
if uploadReq.IsDirectory {
filesWritten, filesSkipped, err := extractFiles(uploadData, uploadPath, uploadReq.Overwrite)
if err != nil {
writtenQualifer := "s"
if filesWritten == 1 {
writtenQualifer = ""
}
skippedQualifier := "s"
if filesSkipped == 1 {
skippedQualifier = ""
}
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%d file%s written, %d file%s skipped: %v", filesWritten, writtenQualifer, filesSkipped, skippedQualifier, err),
}
upload.WrittenFiles = int32(filesWritten)
upload.UnwriteableFiles = int32(filesSkipped)
}
upload.WrittenFiles = int32(filesWritten)
upload.UnwriteableFiles = int32(filesSkipped)
} else {
f.Write(uploadData)
f, err := os.Create(uploadPath)
if err != nil {
upload.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
upload.UnwriteableFiles = 1
upload.WrittenFiles = 0
} else {
// Create file, write data to file system
f.Write(uploadData)
f.Close()
upload.WrittenFiles = 1
upload.UnwriteableFiles = 0
}
}
}
@@ -1119,7 +1251,7 @@ func gzipWrite(w io.Writer, data []byte) error {
}
func gzipRead(data []byte) ([]byte, error) {
bytes.NewReader(data)
//bytes.NewReader(data)
reader, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
-9
View File
@@ -25,8 +25,6 @@ import "C"
// {{end}}
import (
"crypto/rand"
"encoding/binary"
"errors"
insecureRand "math/rand"
@@ -69,13 +67,6 @@ var (
)
func init() {
buf := make([]byte, 8)
n, err := rand.Read(buf)
if err != nil || n != len(buf) {
insecureRand.Seed(time.Now().Unix())
} else {
insecureRand.Seed(int64(binary.LittleEndian.Uint64(buf)))
}
id, err := uuid.NewV4()
if err != nil {
buf := make([]byte, 16) // NewV4 fails if secure rand fails
File diff suppressed because it is too large. Load diff
+4
View File
@@ -278,12 +278,16 @@ message UploadReq {
bytes Data = 3;
bool IsIOC = 4;
string FileName = 5;
bool IsDirectory = 6;
bool Overwrite = 7;
commonpb.Request Request = 9;
}
message Upload {
string Path = 1;
int32 WrittenFiles = 2;
int32 UnwriteableFiles = 3;
commonpb.Response Response = 9;
}
-15
View File
@@ -17,21 +17,6 @@ package c2
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------
We've put a little effort to making the server at least not super easily fingerprintable,
though I'm guessing it's also still not super hard to do. The server must receive a valid
TOTP code before we start returning any non-error records. All requests must be formatted
as valid protobuf and contain a 24-bit "dns session ID" (16777216 possible values), and a
8 bit "message ID." The server only responds to non-TOTP queries with valid dns session IDs
16,777,216 can probably be bruteforced but it'll at least be slow.
DNS command and control outline:
1. Implant sends TOTP encoded message to DNS server, server checks validity
2. DNS server responds with the "DNS Session ID" which is just some random value
3. Requests with valid DNS session IDs enable the server to respond with CRC32 responses
4. Implant establishes encrypted session
*/
import (
"log"
+1 -1
View File
@@ -272,7 +272,7 @@ func listenAndServeTLS(srv *http.Server, certPEMBlock, keyPEMBlock []byte) error
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
config = srv.TLSConfig
}
if certs.TLSKeyLogger != nil {
config.KeyLogWriter = certs.TLSKeyLogger
+59 -5
View File
@@ -25,6 +25,8 @@ import (
"strings"
"github.com/bishopfox/sliver/server/codenames"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
@@ -267,8 +269,8 @@ func randomSubject(commonName string) *pkix.Name {
func randomPostalCode(country []string) []string {
// 1 in `n` will include a postal code
// From my cursory view of a few TLS certs it seems uncommon to include this
// in the distinguished name so right now it's set to 1/5
const postalProbability = 5
// in the distinguished name so right now it's set to 1/20
const postalProbability = 20
if len(country) == 0 {
return []string{}
@@ -367,6 +369,50 @@ var (
"limited",
"corporation",
"company",
"GmbH",
"AG",
"S.A.",
"B.V.",
"LLP",
"Pte Ltd",
"Sdn Bhd",
"KG",
"Limited",
"Partnership",
"Associates",
"Group",
"Holdings",
"Enterprises",
"Industries",
"Ventures",
"International",
"Systems",
"Technologies",
"Incorporated",
"Services",
"Solutions",
"Enterprises",
"Global",
"Trading",
"Manufacturing",
"Development",
"Management",
"Consulting",
"Logistics",
"Communications",
"Finance",
"Electronics",
"Pharmaceuticals",
"Automotive",
"Energy",
"Healthcare",
"Technology",
"Biotech",
"Media",
"Software",
"Hardware",
"Entertainment",
"Construction",
}
)
@@ -375,6 +421,14 @@ func randomOrganization() []string {
noun, _ := codenames.RandomNoun()
suffix := orgSuffixes[insecureRand.Intn(len(orgSuffixes))]
// Not exactly sure this even matters much, but hey its fun to add more randomness
caseTitles := []cases.Caser{
cases.Title(language.English),
cases.Title(language.AmericanEnglish),
cases.Title(language.BritishEnglish),
}
caseTitle := caseTitles[insecureRand.Intn(len(caseTitles))]
var orgName string
switch insecureRand.Intn(8) {
case 0:
@@ -384,13 +438,13 @@ func randomOrganization() []string {
case 2:
orgName = strings.TrimSpace(fmt.Sprintf("%s, %s", noun, suffix))
case 3:
orgName = strings.TrimSpace(strings.Title(fmt.Sprintf("%s %s, %s", adjective, noun, suffix)))
orgName = strings.TrimSpace(caseTitle.String(fmt.Sprintf("%s %s, %s", adjective, noun, suffix)))
case 4:
orgName = strings.TrimSpace(strings.Title(fmt.Sprintf("%s %s", adjective, noun)))
orgName = strings.TrimSpace(caseTitle.String(fmt.Sprintf("%s %s", adjective, noun)))
case 5:
orgName = strings.TrimSpace(strings.ToLower(fmt.Sprintf("%s %s", adjective, noun)))
case 6:
orgName = strings.TrimSpace(strings.Title(fmt.Sprintf("%s", noun)))
orgName = strings.TrimSpace(caseTitle.String(fmt.Sprintf("%s", noun)))
case 7:
noun2, _ := codenames.RandomNoun()
orgName = strings.TrimSpace(strings.ToLower(fmt.Sprintf("%s-%s", noun, noun2)))
+5 -4
View File
@@ -44,10 +44,11 @@ const (
forceFlagStr = "force"
// Operator flags
nameFlagStr = "name"
lhostFlagStr = "lhost"
lportFlagStr = "lport"
saveFlagStr = "save"
nameFlagStr = "name"
lhostFlagStr = "lhost"
lportFlagStr = "lport"
saveFlagStr = "save"
permissionsFlagStr = "permissions"
// Cert flags
caTypeFlagStr = "type"
+4 -4
View File
@@ -71,10 +71,10 @@ var daemonCmd = &cobra.Command{
},
}
func StartPersistentJobs(listenerJobs *[]clientpb.ListenerJob) error {
if len(*listenerJobs) > 0 {
func StartPersistentJobs(listenerJobs []*clientpb.ListenerJob) error {
if len(listenerJobs) > 0 {
// StartPersistentJobs - Start persistent jobs
for _, j := range *listenerJobs {
for _, j := range listenerJobs {
listenerJob, err := db.ListenerByJobID(j.JobID)
if err != nil {
return err
@@ -117,7 +117,7 @@ func StartPersistentJobs(listenerJobs *[]clientpb.ListenerJob) error {
}
j.JobID = uint32(id)
}
db.UpdateHTTPC2Listener(&j)
db.UpdateHTTPC2Listener(j)
}
}
+20 -11
View File
@@ -33,54 +33,63 @@ var operatorCmd = &cobra.Command{
Short: "Generate operator configuration files",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
name, err := cmd.Flags().GetString(nameFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", nameFlagStr, err)
os.Exit(1)
return
}
if name == "" {
fmt.Printf("Must specify --%s", nameFlagStr)
os.Exit(1)
return
}
lhost, err := cmd.Flags().GetString(lhostFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", lhostFlagStr, err)
os.Exit(1)
return
}
if lhost == "" {
fmt.Printf("Must specify --%s", lhostFlagStr)
os.Exit(1)
return
}
lport, err := cmd.Flags().GetUint16(lportFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", lportFlagStr, err)
os.Exit(1)
return
}
save, err := cmd.Flags().GetString(saveFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", saveFlagStr, err)
os.Exit(1)
return
}
if save == "" {
save, _ = os.Getwd()
}
permissions, err := cmd.Flags().GetStringSlice(permissionsFlagStr)
if err != nil {
fmt.Printf("Failed to parse --%s flag %s", permissionsFlagStr, err)
return
}
if len(permissions) == 0 {
fmt.Printf("Must specify --%s", permissionsFlagStr)
return
}
certs.SetupCAs()
configJSON, err := console.NewOperatorConfig(name, lhost, lport)
configJSON, err := console.NewOperatorConfig(name, lhost, lport, permissions)
if err != nil {
fmt.Printf("Failed: %s\n", err)
os.Exit(1)
return
}
saveTo, _ := filepath.Abs(save)
fi, err := os.Stat(saveTo)
if !os.IsNotExist(err) && !fi.IsDir() {
fmt.Printf("File already exists: %s\n", err)
os.Exit(1)
return
}
if !os.IsNotExist(err) && fi.IsDir() {
filename := fmt.Sprintf("%s_%s.cfg", filepath.Base(name), filepath.Base(lhost))
@@ -89,7 +98,7 @@ var operatorCmd = &cobra.Command{
err = os.WriteFile(saveTo, configJSON, 0600)
if err != nil {
fmt.Printf("Write failed: %s (%s)\n", saveTo, err)
os.Exit(1)
return
}
},
}
+557 -2
View File
@@ -188,9 +188,9 @@ func GenerateDefaultHTTPC2Config() *clientpb.HTTPC2Config {
NonceQueryArgChars: "abcdefghijklmnopqrstuvwxyz",
ExtraURLParameters: httpC2UrlParameters,
Headers: httpC2Headers,
MaxFiles: 8,
MaxFiles: 4,
MinFiles: 2,
MaxPaths: 8,
MaxPaths: 4,
MinPaths: 2,
StagerFileExtension: "woff",
PollFileExtension: "js",
@@ -318,7 +318,83 @@ func GenerateHTTPC2DefaultPathSegment() []*clientpb.HTTPC2PathSegment {
var (
httpC2ConfigLog = log.NamedLogger("config", "http-c2")
// Pro-tip: You can use ChatGPT to generate this stuff for you!
Cookies = []string{
"JSESSIONID",
"rememberMe",
"authToken",
"userId",
"userName",
"language",
"theme",
"locale",
"currency",
"lastVisited",
"loggedIn",
"userRole",
"cartId",
"accessToken",
"refreshToken",
"consent",
"notificationPreference",
"userSettings",
"sessionTimeout",
"error",
"errorMessage",
"successMessage",
"infoMessage",
"warningMessage",
"errorMessageKey",
"successMessageKey",
"infoMessageKey",
"warningMessageKey",
"sessionID",
"userID",
"username",
"authToken",
"rememberMe",
"language",
"theme",
"locale",
"currency",
"lastVisit",
"loggedIn",
"userRole",
"cartID",
"accessToken",
"refreshToken",
"consent",
"notificationPref",
"userSettings",
"sessionTimeout",
"visitedPages",
"favoriteItems",
"searchHistory",
"basketID",
"promoCode",
"campaignID",
"referrer",
"source",
"utmCampaign",
"utmSource",
"utmMedium",
"utmContent",
"utmTerm",
"deviceType",
"OSVersion",
"browser",
"screenResolution",
"timezone",
"firstVisit",
"feedbackGiven",
"surveyID",
"errorAlerts",
"successAlerts",
"infoAlerts",
"warningAlerts",
"darkMode",
"emailSubscription",
"privacyConsent",
"PHPSESSID",
"SID",
"SSID",
@@ -338,6 +414,104 @@ var (
"backbone",
"script",
"email",
"main",
"index",
"utils",
"jquery.min",
"bootstrap",
"angular",
"react",
"vue",
"lodash",
"moment",
"axios",
"underscore",
"d3",
"chart",
"map",
"validation",
"animation",
"slider",
"modal",
"form",
"ajax",
"cookie",
"dom",
"events",
"navigation",
"menu",
"dropdown",
"carousel",
"scroll",
"pagination",
"tabs",
"accordion",
"tooltip",
"popover",
"alert",
"notification",
"progress",
"loader",
"countdown",
"lazyload",
"parallax",
"video",
"audio",
"slideshow",
"gallery",
"lightbox",
"share",
"social",
"analytics",
"tracking",
"search",
"autocomplete",
"filter",
"sort",
"table",
"chart",
"graph",
"calendar",
"datepicker",
"timepicker",
"dropdown",
"multi-select",
"form-validation",
"tooltip",
"popover",
"modal",
"sidebar",
"drawer",
"sticky",
"scrollspy",
"smoothscroll",
"anchor",
"slideshow",
"testimonial",
"newsletter",
"login",
"registration",
"cart",
"checkout",
"payment",
"validation",
"maps",
"geolocation",
"geocoding",
"canvas",
"webgl",
"particles",
"barcode",
"qr-code",
"encryption",
"decryption",
"localization",
"translation",
"i18n",
"routing",
"router",
"storage",
"offline",
}
PollPaths = []string{
"js",
@@ -350,6 +524,62 @@ var (
"javascripts",
"javascript",
"jscript",
"js",
"scripts",
"assets",
"src",
"lib",
"public",
"static",
"app",
"www",
"dist",
"frontend",
"client",
"server",
"resources",
"jsfiles",
"javascript",
"jslib",
"jslibraries",
"jsdir",
"jsfolder",
"jsfilesdir",
"jsfilesfolder",
"scriptsdir",
"assetsjs",
"srcjs",
"srcscripts",
"libjs",
"libscripts",
"publicjs",
"publicscripts",
"staticjs",
"staticscripts",
"appjs",
"appscripts",
"distjs",
"distscripts",
"frontendjs",
"frontendscripts",
"clientjs",
"clientscripts",
"serverjs",
"resourcesjs",
"jsfilesjs",
"jsfilesscripts",
"javascriptjs",
"jslibscripts",
"assetsjs",
"assetsjsscripts",
"assetsjs",
"assetsscripts",
"srcjs",
"srcjsscripts",
"srcscripts",
"srcscripts",
"libjs",
"libjsscripts",
}
SessionFiles = []string{
"login",
@@ -361,6 +591,97 @@ var (
"admin",
"register",
"sign-up",
"index",
"config",
"functions",
"database",
"header",
"footer",
"login",
"register",
"logout",
"profile",
"dashboard",
"home",
"about",
"contact",
"services",
"utils",
"common",
"init",
"auth",
"session",
"error",
"handler",
"api",
"ajax",
"form",
"validation",
"upload",
"download",
"report",
"admin",
"user",
"account",
"settings",
"utility",
"script",
"mailer",
"cron",
"cache",
"template",
"page",
"model",
"view",
"controller",
"middleware",
"router",
"route",
"helper",
"library",
"plugin",
"widget",
"widgetized",
"search",
"filter",
"sort",
"pagination",
"backup",
"restore",
"upgrade",
"install",
"uninstall",
"upgrade",
"maintenance",
"sitemap",
"rss",
"atom",
"xml",
"json",
"rss",
"log",
"debug",
"test",
"mock",
"stub",
"mockup",
"mockdata",
"temp",
"tmp",
"backup",
"old",
"new",
"demo",
"example",
"sample",
"prototype",
"backup",
"import",
"export",
"sync",
"async",
"validate",
"authenticate",
}
SessionPaths = []string{
"php",
@@ -377,8 +698,193 @@ var (
"database",
"db",
"namespaces",
"home",
"about",
"contact",
"services",
"products",
"blog",
"news",
"events",
"gallery",
"portfolio",
"shop",
"store",
"login",
"register",
"profile",
"dashboard",
"account",
"settings",
"faq",
"help",
"support",
"download",
"upload",
"subscribe",
"unsubscribe",
"search",
"sitemap",
"privacy",
"terms",
"conditions",
"policy",
"cookie",
"checkout",
"cart",
"order",
"payment",
"confirmation",
"feedback",
"survey",
"testimonial",
"newsletter",
"membership",
"forum",
"signin",
"signup",
"forum",
"contact-us",
"pricing",
"donate",
"partners",
"team",
"career",
"join-us",
"downloads",
"events",
"explore",
"insights",
"newsroom",
"press",
"media",
"blog",
"articles",
"research",
"library",
"resources",
"inspiration",
"academy",
"labs",
"developers",
"api",
"integration",
"status",
"changelog",
"roadmap",
"solutions",
"clients",
"testimonials",
"success-stories",
"clients",
"partners",
"404",
"500",
"error",
"maintenance",
"upgrade",
}
CloseFiles = []string{
"image",
"logo",
"icon",
"background",
"banner",
"button",
"avatar",
"photo",
"picture",
"header",
"footer",
"thumbnail",
"screenshot",
"cover",
"badge",
"illustration",
"graphic",
"map",
"diagram",
"chart",
"emoji",
"flag",
"arrow",
"social",
"media",
"document",
"product",
"menu",
"navigation",
"search",
"result",
"loading",
"progress",
"error",
"success",
"warning",
"info",
"question",
"exclamation",
"play",
"pause",
"stop",
"next",
"previous",
"rewind",
"forward",
"volume",
"mute",
"speaker",
"microphone",
"camera",
"video",
"audio",
"file",
"folder",
"download",
"upload",
"share",
"like",
"heart",
"star",
"comment",
"chat",
"speech bubble",
"message",
"envelope",
"mail",
"clock",
"calendar",
"location",
"pin",
"home",
"settings",
"gear",
"tools",
"user",
"profile",
"login",
"logout",
"register",
"lock",
"unlock",
"shield",
"security",
"privacy",
"checkmark",
"cross",
"delete",
"trash",
"restore",
"recycle",
"favorite",
"bookmark",
"star",
"eye",
"magnifier",
"question mark",
"information",
"exclamationmark",
"help",
"favicon",
"sample",
"example",
@@ -392,6 +898,55 @@ var (
"image",
"icon",
"png",
"images",
"photos",
"pictures",
"pics",
"gallery",
"media",
"uploads",
"assets",
"img",
"graphics",
"visuals",
"media-library",
"artwork",
"design",
"diagrams",
"icons",
"logos",
"banners",
"thumbnails",
"avatars",
"screenshots",
"headers",
"footers",
"backgrounds",
"buttons",
"illustrations",
"diagrams",
"photoshoots",
"picoftheday",
"imagebank",
"album",
"memories",
"memes",
"snapshots",
"portraits",
"posters",
"renders",
"cover-photos",
"wallpapers",
"photography",
"visualizations",
"moodboard",
"infographics",
"renders",
"icons",
"layers",
"picgallery",
"picdump",
"imagelibrary",
}
StagerFiles = []string{
"attribute_text_w01_regular", "ZillaSlab-Regular.subset.bbc33fb47cf6",
+20 -4
View File
@@ -24,7 +24,6 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
@@ -86,13 +85,14 @@ func newOperatorCmd(cmd *cobra.Command, _ []string) {
lhost, _ := cmd.Flags().GetString("lhost")
lport, _ := cmd.Flags().GetUint16("lport")
save, _ := cmd.Flags().GetString("save")
permissions, _ := cmd.Flags().GetStringSlice("permissions")
if save == "" {
save, _ = os.Getwd()
}
fmt.Printf(Info + "Generating new client certificate, please wait ... \n")
configJSON, err := NewOperatorConfig(name, lhost, lport)
configJSON, err := NewOperatorConfig(name, lhost, lport, permissions)
if err != nil {
fmt.Printf(Warn+"%s\n", err)
return
@@ -108,7 +108,7 @@ func newOperatorCmd(cmd *cobra.Command, _ []string) {
filename := fmt.Sprintf("%s_%s.cfg", filepath.Base(name), filepath.Base(lhost))
saveTo = filepath.Join(saveTo, filename)
}
err = ioutil.WriteFile(saveTo, configJSON, 0o600)
err = os.WriteFile(saveTo, configJSON, 0o600)
if err != nil {
fmt.Printf(Warn+"Failed to write config to: %s (%s) \n", saveTo, err)
return
@@ -117,7 +117,7 @@ func newOperatorCmd(cmd *cobra.Command, _ []string) {
}
// NewOperatorConfig - Generate a new player/client/operator configuration
func NewOperatorConfig(operatorName string, lhost string, lport uint16) ([]byte, error) {
func NewOperatorConfig(operatorName string, lhost string, lport uint16, permissions []string) ([]byte, error) {
if !namePattern.MatchString(operatorName) {
return nil, errors.New("invalid operator name (alphanumerics only)")
}
@@ -127,6 +127,9 @@ func NewOperatorConfig(operatorName string, lhost string, lport uint16) ([]byte,
if lhost == "" {
return nil, errors.New("invalid lhost")
}
if len(permissions) == 0 {
return nil, errors.New("must specify at least one permission")
}
rawToken := models.GenerateOperatorToken()
digest := sha256.Sum256([]byte(rawToken))
@@ -134,6 +137,19 @@ func NewOperatorConfig(operatorName string, lhost string, lport uint16) ([]byte,
Name: operatorName,
Token: hex.EncodeToString(digest[:]),
}
for _, permission := range permissions {
switch permission {
case "all":
dbOperator.PermissionAll = true
break
case "builder":
dbOperator.PermissionBuilder = true
case "crackstation":
dbOperator.PermissionCrackstation = true
default:
return nil, fmt.Errorf("invalid permission: %s", permission)
}
}
err := db.Session().Save(dbOperator).Error
if err != nil {
return nil, err
+1 -1
View File
@@ -12,7 +12,7 @@ import (
func TestRootOnlyVerifyCertificate(t *testing.T) {
certs.SetupCAs()
data, err := NewOperatorConfig("zerocool", "localhost", uint16(1337))
data, err := NewOperatorConfig("zerocool", "localhost", uint16(1337), []string{"all"})
if err != nil {
t.Fatalf("failed to generate test player profile %s", err)
}
+22 -1
View File
@@ -85,7 +85,7 @@ func serverOnlyCmds() (commands []*cobra.Command) {
newOperator := &cobra.Command{
Use: consts.NewOperatorStr,
Short: "Create a new operator config file",
Long: help.GetHelpFor([]string{consts.NewOperatorStr}),
Long: newOperatorLongHelp,
Run: newOperatorCmd,
GroupID: consts.MultiplayerHelpGroup,
}
@@ -94,6 +94,7 @@ func serverOnlyCmds() (commands []*cobra.Command) {
f.Uint16P("lport", "p", 31337, "listen port")
f.StringP("save", "s", "", "directory/file in which to save config")
f.StringP("name", "n", "", "operator name")
f.StringSliceP("permissions", "P", []string{}, "grant permissions to the operator profile (all, builder, crackstation)")
})
command.FlagComps(newOperator, func(comp *carapace.ActionMap) {
(*comp)["save"] = carapace.ActionDirectories()
@@ -115,3 +116,23 @@ func serverOnlyCmds() (commands []*cobra.Command) {
return
}
const newOperatorLongHelp = `
Create a new operator config file, operator configuration files allow
remote machines to connect to the Sliver server. They are most commonly
used for allowing remote operators to connect in "Multiplayer Mode."
To generate a profile for a remote operator, you need to specify the
the "all" permission to grant the profile access to all gRPC APIs:
new-operator --name <operator name> --lhost <sliver server> --permissions all
Operator profiles can also be used to allow remote machines to connect to
the Sliver server for other purposes, such as a "Remote Builder" or a
"Crackstation."
You can restrict profiles' permissions by using the --permissions flag, for
example, to create a profile that can only be used as a "Remote Builder":
new-operator --name <operator name> --lhost <sliver server> --permissions builder
`
+1 -1
View File
@@ -31,11 +31,11 @@ type ImplantConnection struct {
ID string
Send chan *sliverpb.Envelope
RespMutex *sync.RWMutex
LastMessageMutex *sync.RWMutex
Resp map[int64]chan *sliverpb.Envelope
Transport string
RemoteAddress string
LastMessage time.Time
LastMessageMutex *sync.RWMutex
Cleanup func()
}
+4 -4
View File
@@ -525,15 +525,15 @@ func ListenerByJobID(JobID uint32) (*clientpb.ListenerJob, error) {
return listenerJob.ToProtobuf(), err
}
func ListenerJobs() (*[]clientpb.ListenerJob, error) {
func ListenerJobs() ([]*clientpb.ListenerJob, error) {
listenerJobs := []models.ListenerJob{}
err := Session().Where(&models.ListenerJob{}).Find(&listenerJobs).Error
pbListenerJobs := []clientpb.ListenerJob{}
pbListenerJobs := []*clientpb.ListenerJob{}
for _, listenerJob := range listenerJobs {
pbListenerJobs = append(pbListenerJobs, *listenerJob.ToProtobuf())
pbListenerJobs = append(pbListenerJobs, listenerJob.ToProtobuf())
}
return &pbListenerJobs, err
return pbListenerJobs, err
}
func DeleteListener(JobID uint32) error {
+8 -5
View File
@@ -28,12 +28,15 @@ import (
"gorm.io/gorm"
)
// Operator - Colletions of content to serve from HTTP(S)
// Operator - Collections of content to serve from HTTP(S)
type Operator struct {
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
Name string
Token string `gorm:"uniqueIndex"`
ID uuid.UUID `gorm:"primaryKey;->;<-:create;type:uuid;"`
CreatedAt time.Time `gorm:"->;<-:create;"`
Name string
Token string `gorm:"uniqueIndex"` // NOTE: This is the SHA256 of the token
PermissionAll bool `gorm:"default:false"` // Access all gRPC APIs
PermissionBuilder bool `gorm:"default:false"` // Access Builder gRPC APIs
PermissionCrackstation bool `gorm:"default:false"` // Access Crackstation gRPC APIs
}
// BeforeCreate - GORM hook
-17
View File
@@ -21,26 +21,9 @@ package main
*/
import (
"crypto/rand"
"encoding/binary"
insecureRand "math/rand"
"time"
"github.com/bishopfox/sliver/server/cli"
)
// Attempt to seed insecure rand with secure rand, but we really
// don't care that much if it fails since it's insecure anyways
func init() {
buf := make([]byte, 8)
_, err := rand.Read(buf)
if err != nil {
insecureRand.Seed(int64(time.Now().Unix()))
} else {
insecureRand.Seed(int64(binary.LittleEndian.Uint64(buf)))
}
}
func main() {
cli.Execute()
}
+1 -1
View File
@@ -283,7 +283,7 @@ func PortInUse(newPort uint32) error {
return err
}
var port uint32
for _, job := range *listenerJobs {
for _, job := range listenerJobs {
listener, err := db.ListenerByJobID(job.JobID)
if err != nil {
return err
+79 -6
View File
@@ -29,6 +29,7 @@ import (
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/db"
"github.com/bishopfox/sliver/server/db/models"
"github.com/bishopfox/sliver/server/log"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
@@ -64,6 +65,7 @@ func initMiddleware(remoteAuth bool) []grpc.ServerOption {
return []grpc.ServerOption{
grpc.ChainUnaryInterceptor(
grpc_auth.UnaryServerInterceptor(tokenAuthFunc),
permissionsUnaryServerInterceptor(),
auditLogUnaryServerInterceptor(),
grpc_tags.UnaryServerInterceptor(grpc_tags.WithFieldExtractor(grpc_tags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry, logrusOpts...),
@@ -71,6 +73,7 @@ func initMiddleware(remoteAuth bool) []grpc.ServerOption {
),
grpc.ChainStreamInterceptor(
grpc_auth.StreamServerInterceptor(tokenAuthFunc),
permissionsStreamServerInterceptor(),
grpc_tags.StreamServerInterceptor(grpc_tags.WithFieldExtractor(grpc_tags.CodeGenRequestFieldExtractor)),
grpc_logrus.StreamServerInterceptor(logrusEntry, logrusOpts...),
grpc_logrus.PayloadStreamServerInterceptor(logrusEntry, deciderStream),
@@ -123,23 +126,93 @@ func tokenAuthFunc(ctx context.Context) (context.Context, error) {
digest := sha256.Sum256([]byte(rawToken))
token := hex.EncodeToString(digest[:])
newCtx := context.WithValue(ctx, Transport, "mtls")
if name, ok := tokenCache.Load(token); ok {
if op, ok := tokenCache.Load(token); ok {
mtlsLog.Debugf("Token in cache!")
newCtx = context.WithValue(newCtx, Operator, name.(string))
newCtx = context.WithValue(newCtx, Operator, op.(*models.Operator))
return newCtx, nil
}
operator, err := db.OperatorByToken(token)
if err != nil || operator == nil {
mtlsLog.Errorf("Authentication failure: %s", err)
mtlsLog.Errorf("Authentication failure: %v", err)
return nil, status.Error(codes.Unauthenticated, "Authentication failure")
}
mtlsLog.Debugf("Valid user token for %s", operator.Name)
tokenCache.Store(token, operator.Name)
mtlsLog.Debugf("Valid token for %s", operator.Name)
tokenCache.Store(token, operator)
newCtx = context.WithValue(newCtx, Operator, operator.Name)
newCtx = context.WithValue(newCtx, Operator, operator)
return newCtx, nil
}
var (
// Builder - Allowed methods
builderMethods = map[string]bool{
"/rpcpb.SliverRPC/GetVersion": true,
"/rpcpb.SliverRPC/GenerateExternalGetBuildConfig": true,
"/rpcpb.SliverRPC/GenerateExternalSaveBuild": true,
"/rpcpb.SliverRPC/BuilderRegister": true,
"/rpcpb.SliverRPC/BuilderTrigger": true,
"/rpcpb.SliverRPC/Builders": true,
}
// Crackstation - Allowed methods
crackstationMethods = map[string]bool{
"/rpcpb.SliverRPC/GetVersion": true,
"/rpcpb.SliverRPC/CrackstationRegister": true,
"/rpcpb.SliverRPC/CrackstationTrigger": true,
"/rpcpb.SliverRPC/CrackstationBenchmark": true,
"/rpcpb.SliverRPC/Crackstations": true,
"/rpcpb.SliverRPC/CrackTaskByID": true,
"/rpcpb.SliverRPC/CrackTaskUpdate": true,
"/rpcpb.SliverRPC/CrackFilesList": true,
"/rpcpb.SliverRPC/CrackFileCreate": true,
"/rpcpb.SliverRPC/CrackFileChunkUpload": true,
"/rpcpb.SliverRPC/CrackFileChunkDownload": true,
"/rpcpb.SliverRPC/CrackFileComplete": true,
"/rpcpb.SliverRPC/CrackFileDelete": true,
}
)
func permissionsUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
operator := ctx.Value(Operator).(*models.Operator)
if operator.PermissionAll {
return handler(ctx, req)
}
if operator.PermissionBuilder {
if ok, _ := builderMethods[info.FullMethod]; ok {
return handler(ctx, req)
}
}
if operator.PermissionCrackstation {
if ok, _ := crackstationMethods[info.FullMethod]; ok {
return handler(ctx, req)
}
}
mtlsLog.Warnf("Permission denied for %s attempting to access %s", operator.Name, info.FullMethod)
return nil, status.Error(codes.PermissionDenied, "Permission denied")
}
}
func permissionsStreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
operator := ss.Context().Value(Operator).(*models.Operator)
if operator.PermissionAll {
return handler(srv, ss)
}
if operator.PermissionBuilder {
if ok, _ := builderMethods[info.FullMethod]; ok {
return handler(srv, ss)
}
}
if operator.PermissionCrackstation {
if ok, _ := crackstationMethods[info.FullMethod]; ok {
return handler(srv, ss)
}
}
mtlsLog.Warnf("Permission denied for %s attempting to access %s", operator.Name, info.FullMethod)
return status.Error(codes.PermissionDenied, "Permission denied")
}
}
func deciderUnary(_ context.Context, _ string, _ interface{}) bool {
return serverConfig.Logs.GRPCUnaryPayloads
}
+20
View File
@@ -0,0 +1,20 @@
; https://editorconfig.org/
root = true
[*]
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
indent_style = space
indent_size = 2
[{Makefile,go.mod,go.sum,*.go,.gitmodules}]
indent_style = tab
indent_size = 4
[*.md]
indent_size = 4
trim_trailing_whitespace = false
eclint_indent_style = unset
+1
View File
@@ -0,0 +1 @@
coverage.coverprofile
-8
View File
@@ -1,8 +0,0 @@
# This is the official list of gorilla/mux authors for copyright purposes.
#
# Please keep the list sorted.
Google LLC (https://opensource.google.com/)
Kamil Kisielk <[email protected]>
Matt Silverlock <[email protected]>
Rodrigo Moraes (https://github.com/moraes)
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.
Copyright (c) 2023 The Gorilla Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
+34
View File
@@ -0,0 +1,34 @@
GO_LINT=$(shell which golangci-lint 2> /dev/null || echo '')
GO_LINT_URI=github.com/golangci/golangci-lint/cmd/golangci-lint@latest
GO_SEC=$(shell which gosec 2> /dev/null || echo '')
GO_SEC_URI=github.com/securego/gosec/v2/cmd/gosec@latest
GO_VULNCHECK=$(shell which govulncheck 2> /dev/null || echo '')
GO_VULNCHECK_URI=golang.org/x/vuln/cmd/govulncheck@latest
.PHONY: golangci-lint
golangci-lint:
$(if $(GO_LINT), ,go install $(GO_LINT_URI))
@echo "##### Running golangci-lint"
golangci-lint run -v
.PHONY: gosec
gosec:
$(if $(GO_SEC), ,go install $(GO_SEC_URI))
@echo "##### Running gosec"
gosec ./...
.PHONY: govulncheck
govulncheck:
$(if $(GO_VULNCHECK), ,go install $(GO_VULNCHECK_URI))
@echo "##### Running govulncheck"
govulncheck ./...
.PHONY: verify
verify: golangci-lint gosec govulncheck
.PHONY: test
test:
@echo "##### Running tests"
go test -race -cover -coverprofile=coverage.coverprofile -covermode=atomic -v ./...
+35 -28
View File
@@ -1,12 +1,12 @@
# gorilla/mux
[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
[![CircleCI](https://circleci.com/gh/gorilla/mux.svg?style=svg)](https://circleci.com/gh/gorilla/mux)
[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
![testing](https://github.com/gorilla/mux/actions/workflows/test.yml/badge.svg)
[![codecov](https://codecov.io/github/gorilla/mux/branch/main/graph/badge.svg)](https://codecov.io/github/gorilla/mux)
[![godoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
[![sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
![Gorilla Logo](https://cloud-cdn.questionable.services/gorilla-icon-64.png)
https://www.gorillatoolkit.org/pkg/mux
![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5)
Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
their respective handler.
@@ -247,32 +247,25 @@ type spaHandler struct {
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Join internally call path.Clean to prevent directory traversal
path := filepath.Join(h.staticPath, r.URL.Path)
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
// check whether a file exists or is a directory at the given path
fi, err := os.Stat(path)
if os.IsNotExist(err) || fi.IsDir() {
// file does not exist or path is a directory, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static file
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
@@ -375,6 +368,19 @@ url, err := r.Get("article").URL("subdomain", "news",
"id", "42")
```
To find all the required variables for a given route when calling `URL()`, the method `GetVarNames()` is available:
```go
r := mux.NewRouter()
r.Host("{domain}").
Path("/{group}/{item_id}").
Queries("some_data1", "{some_data1}").
Queries("some_data2", "{some_data2}").
Name("article")
// Will print [domain group item_id some_data1 some_data2] <nil>
fmt.Println(r.Get("article").GetVarNames())
```
### Walking Routes
The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
@@ -572,7 +578,7 @@ func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler
r := mux.NewRouter()
r.HandleFunc("/", handler)
amw := authenticationMiddleware{}
amw := authenticationMiddleware{tokenUsers: make(map[string]string)}
amw.Populate()
r.Use(amw.Middleware)
@@ -758,7 +764,8 @@ func TestMetricsHandler(t *testing.T) {
rr := httptest.NewRecorder()
// Need to create a router that we can pass the request through so that the vars will be added to the context
// To add the vars to the context,
// we need to create a router through which we can pass the request.
router := mux.NewRouter()
router.HandleFunc("/metrics/{type}", MetricsHandler)
router.ServeHTTP(rr, req)
+12 -13
View File
@@ -10,18 +10,18 @@ http.ServeMux, mux.Router matches incoming requests against a list of
registered routes and calls a handler for the route that matches the URL
or other conditions. The main features are:
* Requests can be matched based on URL host, path, path prefix, schemes,
header and query values, HTTP methods or using custom matchers.
* URL hosts, paths and query values can have variables with an optional
regular expression.
* Registered URLs can be built, or "reversed", which helps maintaining
references to resources.
* Routes can be used as subrouters: nested routes are only tested if the
parent route matches. This is useful to define groups of routes that
share common conditions like a host, a path prefix or other repeated
attributes. As a bonus, this optimizes request matching.
* It implements the http.Handler interface so it is compatible with the
standard http.ServeMux.
- Requests can be matched based on URL host, path, path prefix, schemes,
header and query values, HTTP methods or using custom matchers.
- URL hosts, paths and query values can have variables with an optional
regular expression.
- Registered URLs can be built, or "reversed", which helps maintaining
references to resources.
- Routes can be used as subrouters: nested routes are only tested if the
parent route matches. This is useful to define groups of routes that
share common conditions like a host, a path prefix or other repeated
attributes. As a bonus, this optimizes request matching.
- It implements the http.Handler interface so it is compatible with the
standard http.ServeMux.
Let's start registering a couple of URL paths and handlers:
@@ -301,6 +301,5 @@ A more complex authentication middleware, which maps session token to users, cou
r.Use(amw.Middleware)
Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to.
*/
package mux
+9 -7
View File
@@ -31,24 +31,26 @@ func NewRouter() *Router {
// It implements the http.Handler interface, so it can be registered to serve
// requests:
//
// var router = mux.NewRouter()
// var router = mux.NewRouter()
//
// func main() {
// http.Handle("/", router)
// }
// func main() {
// http.Handle("/", router)
// }
//
// Or, for Google App Engine, register it in a init() function:
//
// func init() {
// http.Handle("/", router)
// }
// func init() {
// http.Handle("/", router)
// }
//
// This will send all incoming requests to the router.
type Router struct {
// Configurable Handler to be used when no route matches.
// This can be used to render your own 404 Not Found errors.
NotFoundHandler http.Handler
// Configurable Handler to be used when the request method does not match the route.
// This can be used to render your own 405 Method Not Allowed errors.
MethodNotAllowedHandler http.Handler
// Routes to be matched, in order.
+5 -5
View File
@@ -22,10 +22,10 @@ type routeRegexpOptions struct {
type regexpType int
const (
regexpTypePath regexpType = 0
regexpTypeHost regexpType = 1
regexpTypePrefix regexpType = 2
regexpTypeQuery regexpType = 3
regexpTypePath regexpType = iota
regexpTypeHost
regexpTypePrefix
regexpTypeQuery
)
// newRouteRegexp parses a route template and returns a routeRegexp,
@@ -195,7 +195,7 @@ func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
// url builds a URL part using the given values.
func (r *routeRegexp) url(values map[string]string) (string, error) {
urlValues := make([]interface{}, len(r.varsN), len(r.varsN))
urlValues := make([]interface{}, len(r.varsN))
for k, v := range r.varsN {
value, ok := values[v]
if !ok {
+69 -40
View File
@@ -64,8 +64,18 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
match.MatchErr = nil
}
matchErr = nil
matchErr = nil // nolint:ineffassign
return false
} else {
// Multiple routes may share the same path but use different HTTP methods. For instance:
// Route 1: POST "/users/{id}".
// Route 2: GET "/users/{id}", parameters: "id": "[0-9]+".
//
// The router must handle these cases correctly. For a GET request to "/users/abc" with "id" as "-2",
// The router should return a "Not Found" error as no route fully matches this request.
if match.MatchErr == ErrMethodMismatch {
match.MatchErr = nil
}
}
}
@@ -230,9 +240,9 @@ func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
// Headers adds a matcher for request header values.
// It accepts a sequence of key/value pairs to be matched. For example:
//
// r := mux.NewRouter()
// r.Headers("Content-Type", "application/json",
// "X-Requested-With", "XMLHttpRequest")
// r := mux.NewRouter().NewRoute()
// r.Headers("Content-Type", "application/json",
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both request header values match.
// If the value is an empty string, it will match any value if the key is set.
@@ -255,9 +265,9 @@ func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
// support. For example:
//
// r := mux.NewRouter()
// r.HeadersRegexp("Content-Type", "application/(text|json)",
// "X-Requested-With", "XMLHttpRequest")
// r := mux.NewRouter().NewRoute()
// r.HeadersRegexp("Content-Type", "application/(text|json)",
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both the request header matches both regular expressions.
// If the value is an empty string, it will match any value if the key is set.
@@ -283,10 +293,10 @@ func (r *Route) HeadersRegexp(pairs ...string) *Route {
//
// For example:
//
// r := mux.NewRouter()
// r.Host("www.example.com")
// r.Host("{subdomain}.domain.com")
// r.Host("{subdomain:[a-z]+}.domain.com")
// r := mux.NewRouter().NewRoute()
// r.Host("www.example.com")
// r.Host("{subdomain}.domain.com")
// r.Host("{subdomain:[a-z]+}.domain.com")
//
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
@@ -342,11 +352,11 @@ func (r *Route) Methods(methods ...string) *Route {
//
// For example:
//
// r := mux.NewRouter()
// r.Path("/products/").Handler(ProductsHandler)
// r.Path("/products/{key}").Handler(ProductsHandler)
// r.Path("/articles/{category}/{id:[0-9]+}").
// Handler(ArticleHandler)
// r := mux.NewRouter().NewRoute()
// r.Path("/products/").Handler(ProductsHandler)
// r.Path("/products/{key}").Handler(ProductsHandler)
// r.Path("/articles/{category}/{id:[0-9]+}").
// Handler(ArticleHandler)
//
// Variable names must be unique in a given route. They can be retrieved
// calling mux.Vars(request).
@@ -377,8 +387,8 @@ func (r *Route) PathPrefix(tpl string) *Route {
// It accepts a sequence of key/value pairs. Values may define variables.
// For example:
//
// r := mux.NewRouter()
// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
// r := mux.NewRouter().NewRoute()
// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
//
// The above route will only match if the URL contains the defined queries
// values, e.g.: ?foo=bar&id=42.
@@ -473,11 +483,11 @@ func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
//
// It will test the inner routes only if the parent route matched. For example:
//
// r := mux.NewRouter()
// s := r.Host("www.example.com").Subrouter()
// s.HandleFunc("/products/", ProductsHandler)
// s.HandleFunc("/products/{key}", ProductHandler)
// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
// r := mux.NewRouter().NewRoute()
// s := r.Host("www.example.com").Subrouter()
// s.HandleFunc("/products/", ProductsHandler)
// s.HandleFunc("/products/{key}", ProductHandler)
// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
//
// Here, the routes registered in the subrouter won't be tested if the host
// doesn't match.
@@ -497,36 +507,36 @@ func (r *Route) Subrouter() *Router {
// It accepts a sequence of key/value pairs for the route variables. For
// example, given this route:
//
// r := mux.NewRouter()
// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
// Name("article")
// r := mux.NewRouter()
// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
// Name("article")
//
// ...a URL for it can be built using:
//
// url, err := r.Get("article").URL("category", "technology", "id", "42")
// url, err := r.Get("article").URL("category", "technology", "id", "42")
//
// ...which will return an url.URL with the following path:
//
// "/articles/technology/42"
// "/articles/technology/42"
//
// This also works for host variables:
//
// r := mux.NewRouter()
// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
// Host("{subdomain}.domain.com").
// Name("article")
// r := mux.NewRouter()
// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
// Host("{subdomain}.domain.com").
// Name("article")
//
// // url.String() will be "http://news.domain.com/articles/technology/42"
// url, err := r.Get("article").URL("subdomain", "news",
// "category", "technology",
// "id", "42")
// // url.String() will be "http://news.domain.com/articles/technology/42"
// url, err := r.Get("article").URL("subdomain", "news",
// "category", "technology",
// "id", "42")
//
// The scheme of the resulting url will be the first argument that was passed to Schemes:
//
// // url.String() will be "https://example.com"
// r := mux.NewRouter()
// url, err := r.Host("example.com")
// .Schemes("https", "http").URL()
// // url.String() will be "https://example.com"
// r := mux.NewRouter().NewRoute()
// url, err := r.Host("example.com")
// .Schemes("https", "http").URL()
//
// All variables defined in the route are required, and their values must
// conform to the corresponding patterns.
@@ -718,6 +728,25 @@ func (r *Route) GetHostTemplate() (string, error) {
return r.regexp.host.template, nil
}
// GetVarNames returns the names of all variables added by regexp matchers
// These can be used to know which route variables should be passed into r.URL()
func (r *Route) GetVarNames() ([]string, error) {
if r.err != nil {
return nil, r.err
}
var varNames []string
if r.regexp.host != nil {
varNames = append(varNames, r.regexp.host.varsN...)
}
if r.regexp.path != nil {
varNames = append(varNames, r.regexp.path.varsN...)
}
for _, regx := range r.regexp.queries {
varNames = append(varNames, regx.varsN...)
}
return varNames, nil
}
// prepareVars converts the route variable pairs into a map. If the route has a
// BuildVarsFunc, it is invoked.
func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.12
// +build go1.12
package acme
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package argon2
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
// +build !amd64 purego !gc
package argon2
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.7 && amd64 && gc && !purego
// +build go1.7,amd64,gc,!purego
package blake2b
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.7 && amd64 && gc && !purego
// +build go1.7,amd64,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !go1.7 && amd64 && gc && !purego
// +build !go1.7,amd64,gc,!purego
package blake2b
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
// +build !amd64 purego !gc
package blake2b
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.9
// +build go1.9
package blake2b
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build 386 && gc && !purego
// +build 386,gc,!purego
package blake2s
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build 386 && gc && !purego
// +build 386,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package blake2s
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build (!amd64 && !386) || !gc || purego
// +build !amd64,!386 !gc purego
package blake2s
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.9
// +build go1.9
package blake2s
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build (!arm64 && !s390x && !ppc64le) || !gc || purego
// +build !arm64,!s390x,!ppc64le !gc purego
package chacha20
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20
-1
View File
@@ -20,7 +20,6 @@
// due to the calling conventions and initialization of constants.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "go_asm.h"
#include "textflag.h"
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package chacha20poly1305
+22 -3
View File
@@ -5,7 +5,6 @@
// This file was originally from https://golang.org/cl/24717 by Vlad Krasnov of CloudFlare.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
// General register allocation
@@ -184,11 +183,31 @@ GLOBL ·andMask<>(SB), (NOPTR+RODATA), $240
#define shiftD1Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xd2; BYTE $0x04 // PALIGNR $4, X10, X10
#define shiftD2Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xdb; BYTE $0x04 // PALIGNR $4, X11, X11
#define shiftD3Right BYTE $0x66; BYTE $0x45; BYTE $0x0f; BYTE $0x3a; BYTE $0x0f; BYTE $0xff; BYTE $0x04 // PALIGNR $4, X15, X15
// Some macros
// ROL rotates the uint32s in register R left by N bits, using temporary T.
#define ROL(N, R, T) \
MOVO R, T; PSLLL $(N), T; PSRLL $(32-(N)), R; PXOR T, R
// ROL16 rotates the uint32s in register R left by 16, using temporary T if needed.
#ifdef GOAMD64_v2
#define ROL16(R, T) PSHUFB ·rol16<>(SB), R
#else
#define ROL16(R, T) ROL(16, R, T)
#endif
// ROL8 rotates the uint32s in register R left by 8, using temporary T if needed.
#ifdef GOAMD64_v2
#define ROL8(R, T) PSHUFB ·rol8<>(SB), R
#else
#define ROL8(R, T) ROL(8, R, T)
#endif
#define chachaQR(A, B, C, D, T) \
PADDD B, A; PXOR A, D; PSHUFB ·rol16<>(SB), D \
PADDD B, A; PXOR A, D; ROL16(D, T) \
PADDD D, C; PXOR C, B; MOVO B, T; PSLLL $12, T; PSRLL $20, B; PXOR T, B \
PADDD B, A; PXOR A, D; PSHUFB ·rol8<>(SB), D \
PADDD B, A; PXOR A, D; ROL8(D, T) \
PADDD D, C; PXOR C, B; MOVO B, T; PSLLL $7, T; PSRLL $25, B; PXOR T, B
#define chachaQR_AVX2(A, B, C, D, T) \
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || !gc || purego
// +build !amd64 !gc purego
package chacha20poly1305
-1
View File
@@ -1,7 +1,6 @@
// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
package field
-1
View File
@@ -1,7 +1,6 @@
// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT.
//go:build amd64 && gc && !purego
// +build amd64,gc,!purego
#include "textflag.h"
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || !gc || purego
// +build !amd64 !gc purego
package field
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build arm64 && gc && !purego
// +build arm64,gc,!purego
package field
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build arm64 && gc && !purego
// +build arm64,gc,!purego
#include "textflag.h"
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !arm64 || !gc || purego
// +build !arm64 !gc purego
package field
+3 -1
View File
@@ -56,7 +56,9 @@ func (f *hkdf) Read(p []byte) (int, error) {
// Fill the rest of the buffer
for len(p) > 0 {
f.expander.Reset()
if f.counter > 1 {
f.expander.Reset()
}
f.expander.Write(f.prev)
f.expander.Write(f.info)
f.expander.Write([]byte{f.counter})
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !purego
// +build !purego
// Package alias implements memory aliasing tests.
package alias
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build purego
// +build purego
// Package alias implements memory aliasing tests.
package alias
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !go1.13
// +build !go1.13
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build go1.13
// +build go1.13
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build (!amd64 && !ppc64le && !s390x) || !gc || purego
// +build !amd64,!ppc64le,!s390x !gc purego
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
package poly1305
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build gc && !purego
// +build gc,!purego
#include "textflag.h"
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && !purego && gc
// +build amd64,!purego,gc
package salsa
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build amd64 && !purego && gc
// +build amd64,!purego,gc
// This code was translated into a form compatible with 6a from the public
// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html
-1
View File
@@ -3,7 +3,6 @@
// license that can be found in the LICENSE file.
//go:build !amd64 || purego || !gc
// +build !amd64 purego !gc
package salsa
+9 -4
View File
@@ -141,9 +141,14 @@ const (
agentAddSmartcardKeyConstrained = 26
// 3.7 Key constraint identifiers
agentConstrainLifetime = 1
agentConstrainConfirm = 2
agentConstrainExtension = 3
agentConstrainLifetime = 1
agentConstrainConfirm = 2
// Constraint extension identifier up to version 2 of the protocol. A
// backward incompatible change will be required if we want to add support
// for SSH_AGENT_CONSTRAIN_MAXSIGN which uses the same ID.
agentConstrainExtensionV00 = 3
// Constraint extension identifier in version 3 and later of the protocol.
agentConstrainExtension = 255
)
// maxAgentResponseBytes is the maximum agent reply size that is accepted. This
@@ -205,7 +210,7 @@ type constrainLifetimeAgentMsg struct {
}
type constrainExtensionAgentMsg struct {
ExtensionName string `sshtype:"3"`
ExtensionName string `sshtype:"255|3"`
ExtensionDetails []byte
// Rest is a field used for parsing, not part of message
+1 -1
View File
@@ -208,7 +208,7 @@ func parseConstraints(constraints []byte) (lifetimeSecs uint32, confirmBeforeUse
case agentConstrainConfirm:
confirmBeforeUse = true
constraints = constraints[1:]
case agentConstrainExtension:
case agentConstrainExtension, agentConstrainExtensionV00:
var msg constrainExtensionAgentMsg
if err = ssh.Unmarshal(constraints, &msg); err != nil {
return 0, false, nil, err
-3
View File
@@ -10,7 +10,6 @@ import (
"fmt"
"io"
"math"
"strings"
"sync"
_ "crypto/sha1"
@@ -140,8 +139,6 @@ var supportedPubKeyAuthAlgos = []string{
KeyAlgoDSA,
}
var supportedPubKeyAuthAlgosList = strings.Join(supportedPubKeyAuthAlgos, ",")
// unexpectedMessageError results when the SSH message that we received didn't
// match what we wanted.
func unexpectedMessageError(expected, got uint8) error {
+7
View File
@@ -11,6 +11,7 @@ import (
"io"
"log"
"net"
"strings"
"sync"
)
@@ -50,6 +51,10 @@ type handshakeTransport struct {
// connection.
hostKeys []Signer
// publicKeyAuthAlgorithms is non-empty if we are the server. In that case,
// it contains the supported client public key authentication algorithms.
publicKeyAuthAlgorithms []string
// hostKeyAlgorithms is non-empty if we are the client. In that case,
// we accept these key types from the server as host key.
hostKeyAlgorithms []string
@@ -141,6 +146,7 @@ func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byt
func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
t.hostKeys = config.hostKeys
t.publicKeyAuthAlgorithms = config.PublicKeyAuthAlgorithms
go t.readLoop()
go t.kexLoop()
return t
@@ -649,6 +655,7 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
// message with the server-sig-algs extension if the client supports it. See
// RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9.
if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") {
supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",")
extInfo := &extInfoMsg{
NumExtensions: 2,
Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)+4+16+4+1),
+15 -4
View File
@@ -1232,16 +1232,27 @@ func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{},
return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
}
var result interface{}
switch block.Type {
case "RSA PRIVATE KEY":
return x509.ParsePKCS1PrivateKey(buf)
result, err = x509.ParsePKCS1PrivateKey(buf)
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(buf)
result, err = x509.ParseECPrivateKey(buf)
case "DSA PRIVATE KEY":
return ParseDSAPrivateKey(buf)
result, err = ParseDSAPrivateKey(buf)
default:
return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
err = fmt.Errorf("ssh: unsupported key type %q", block.Type)
}
// Because of deficiencies in the format, DecryptPEMBlock does not always
// detect an incorrect password. In these cases decrypted DER bytes is
// random noise. If the parsing of the key returns an asn1.StructuralError
// we return x509.IncorrectPasswordError.
if _, ok := err.(asn1.StructuralError); ok {
return nil, x509.IncorrectPasswordError
}
return result, err
}
// ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
+18 -2
View File
@@ -64,6 +64,13 @@ type ServerConfig struct {
// Config contains configuration shared between client and server.
Config
// PublicKeyAuthAlgorithms specifies the supported client public key
// authentication algorithms. Note that this should not include certificate
// types since those use the underlying algorithm. This list is sent to the
// client if it supports the server-sig-algs extension. Order is irrelevant.
// If unspecified then a default set of algorithms is used.
PublicKeyAuthAlgorithms []string
hostKeys []Signer
// NoClientAuth is true if clients are allowed to connect without
@@ -201,6 +208,15 @@ func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewCha
if fullConf.MaxAuthTries == 0 {
fullConf.MaxAuthTries = 6
}
if len(fullConf.PublicKeyAuthAlgorithms) == 0 {
fullConf.PublicKeyAuthAlgorithms = supportedPubKeyAuthAlgos
} else {
for _, algo := range fullConf.PublicKeyAuthAlgorithms {
if !contains(supportedPubKeyAuthAlgos, algo) {
return nil, nil, nil, fmt.Errorf("ssh: unsupported public key authentication algorithm %s", algo)
}
}
}
// Check if the config contains any unsupported key exchanges
for _, kex := range fullConf.KeyExchanges {
if _, ok := serverForbiddenKexAlgos[kex]; ok {
@@ -524,7 +540,7 @@ userAuthLoop:
return nil, parseError(msgUserAuthRequest)
}
algo := string(algoBytes)
if !contains(supportedPubKeyAuthAlgos, underlyingAlgo(algo)) {
if !contains(config.PublicKeyAuthAlgorithms, underlyingAlgo(algo)) {
authErr = fmt.Errorf("ssh: algorithm %q not accepted", algo)
break
}
@@ -591,7 +607,7 @@ userAuthLoop:
// algorithm name that corresponds to algo with
// sig.Format. This is usually the same, but
// for certs, the names differ.
if !contains(supportedPubKeyAuthAlgos, sig.Format) {
if !contains(config.PublicKeyAuthAlgorithms, sig.Format) {
authErr = fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
break
}
+4 -4
View File
@@ -360,8 +360,8 @@ github.com/google/uuid
# github.com/gorilla/csrf v1.7.1
## explicit; go 1.13
github.com/gorilla/csrf
# github.com/gorilla/mux v1.8.0
## explicit; go 1.12
# github.com/gorilla/mux v1.8.1
## explicit; go 1.20
github.com/gorilla/mux
# github.com/gorilla/securecookie v1.1.1
## explicit
@@ -736,8 +736,8 @@ go4.org/mem
# go4.org/netipx v0.0.0-20230824141953-6213f710f925
## explicit; go 1.18
go4.org/netipx
# golang.org/x/crypto v0.14.0
## explicit; go 1.17
# golang.org/x/crypto v0.15.0
## explicit; go 1.18
golang.org/x/crypto/acme
golang.org/x/crypto/acme/autocert
golang.org/x/crypto/argon2