Compare commits

...
Author SHA1 Message Date
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
24 changed files with 2425 additions and 1254 deletions

No files matched your search

+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(
+3 -3
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
@@ -47,6 +47,7 @@ require (
github.com/yiya1989/sshkrb5 v0.0.0-20201110125252-a1455b75a35e
golang.org/x/crypto v0.14.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
+2 -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=
@@ -626,8 +621,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 +645,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"
+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)))
+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",
-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()
}
+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) {
+2 -2
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