/
launcher.go
696 lines (593 loc) · 17.5 KB
/
launcher.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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// Package main.
package main
import (
obBufio "bufio"
obBytes "bytes"
obZlib "compress/zlib"
obAES "crypto/aes"
obCipher "crypto/cipher"
obSHA "crypto/sha512"
obBase64 "encoding/base64"
obBinary "encoding/binary"
obErrors "errors"
obUtilio "io/ioutil"
obMath "math"
obOS "os"
obExec "os/exec"
obSignal "os/signal"
obStrconv "strconv"
obStrings "strings"
obSync "sync"
obSyscall "syscall"
obTime "time"
obUnsafe "unsafe"
)
type obDependency struct {
obDepSize string
obDepName string
obDepBFD []float64
}
// Stdout variable will be overwritten during compilation.
var Stdout string = "ENABLESTDOUT"
const (
obErr = 1
obCorrelationLevel = 0.4
obStdLevel = 1
obFileSizeLevel = 15
)
func obExit() {
println("https://shorturl.at/crzEZ")
obOS.Exit(obErr)
}
// Breakpoint on linux are 0xCC and will be interpreted as a
// SIGTRAP, we will intercept them.
func obSigTrap(obInput chan obOS.Signal) {
obMySignal := <-obInput
switch obMySignal {
case obSyscall.SIGILL:
obExit()
case obSyscall.SIGTRAP:
obExit()
default:
return
}
}
// attach to PTRACE, register if successful
// attach A G A I N , register if unsuccessful
// this protects against custom ptrace (always returning 0)
// against NOP attacks and LD_PRELOAD attacks.
//
// keep attached to avoid late attaching.
func obPtraceDetect(pid int, father bool) {
obOffset := 0
obProc, _ := obOS.FindProcess(pid)
obErr := obSyscall.PtraceAttach(obProc.Pid)
if obErr == nil {
obOffset = 5
}
// continuously check for ptrace on passed pid
for {
obErr = obSyscall.PtraceAttach(obProc.Pid)
if obErr != nil {
obOffset *= 3
}
obErr = obProc.Signal(obSyscall.SIGCONT)
if obErr != nil {
// we cannot send sigcont to out pid
// we should exit.
if father {
obExit()
} else {
obErr = obProc.Signal(obSyscall.SIGTRAP)
if obErr != nil {
obExit()
}
}
}
if obOffset != (3 * 5) {
if father {
obExit()
} else {
obErr = obProc.Signal(obSyscall.SIGTRAP)
if obErr != nil {
obExit()
}
}
}
obTime.Sleep(250 * obTime.Millisecond)
obOffset /= 3
}
}
// Check the process cmdline to spot if a debugger is inline.
func obParentCmdLineDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/cmdline"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
// Check the process status to spot if a debugger is active using the TracePid key.
func obParentTracerDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/status"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
obStatLines := obStrings.Split(string(obStatParent), "\n")
for _, obValue := range obStatLines {
if obStrings.Contains(obValue, "TracerPid") {
obSplitArray := obStrings.Split(obValue, ":")
obSplitValue := obStrings.Replace(obSplitArray[1], "\t", "", -1)
if obSplitValue != "0" {
obExit()
}
}
}
}
// Check the process cmdline to spot if a debugger is the PPID of our process.
func obParentDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/stat"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
// Check the process cmdline to spot if a debugger is launcher
// "_" and Args[0] should match otherwise.
func obEnvArgsDetect() {
obLines, _ := obOS.LookupEnv("_")
if obLines != obOS.Args[0] {
obExit()
}
}
// Check the process cmdline to spot if a debugger is inline
// "_" should not contain the name of any debugger.
func obEnvParentDetect() {
obLines, _ := obOS.LookupEnv("_")
if obStrings.Contains(obLines, "gdb") ||
obStrings.Contains(obLines, "dlv") ||
obStrings.Contains(obLines, "edb") ||
obStrings.Contains(obLines, "frida") ||
obStrings.Contains(obLines, "ghidra") ||
obStrings.Contains(obLines, "godebug") ||
obStrings.Contains(obLines, "ida") ||
obStrings.Contains(obLines, "lldb") ||
obStrings.Contains(obLines, "ltrace") ||
obStrings.Contains(obLines, "strace") ||
obStrings.Contains(obLines, "valgrind") {
obExit()
}
}
// Check the process cmdline to spot if a debugger is active
// most debuggers (like GDB) will set LINE,COLUMNS or LD_PRELOAD
// to function, we try to spot this.
func obEnvDetect() {
_, obLines := obOS.LookupEnv("LINES")
_, obColumns := obOS.LookupEnv("COLUMNS")
_, obLineLdPreload := obOS.LookupEnv("LD_PRELOAD")
if obLines || obColumns || obLineLdPreload {
obExit()
}
}
// Check the process is launcher with a LD_PRELOAD set.
// This can be an injection attack (like on frida) to try and circumvent
// various restrictions (like ptrace checks).
func obLdPreloadDetect() {
obKey := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
obValue := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
obErr := obOS.Setenv(obKey, obValue)
if obErr != nil {
obExit()
}
obLineLdPreload, _ := obOS.LookupEnv(obKey)
if obLineLdPreload == obValue {
obErr := obOS.Unsetenv(obKey)
if obErr != nil {
obExit()
}
} else {
obExit()
}
}
// calculate BFD (byte frequency distribution) for the input dependency.
func obUtilBFDCalc(obInput string) []float64 {
obFile, _ := obUtilio.ReadFile(obInput)
obBfd := make([]float64, 256)
for _, obValue := range obFile {
obBfd[obValue]++
}
return obBfd
}
// Abs returns the absolute value of obInput.
func obUtilAbsCalc(obInput float64) float64 {
if obInput < 0 {
return -obInput
}
return obInput
}
// calculate the covariance of two input slices.
func obUtilCovarianceCalc(obDepInput []float64, obTargetInput []float64) float64 {
obMeanDepInput := 0.0
obMeanTargetInput := 0.0
for obIndex := 0; obIndex < 256; obIndex++ {
obMeanDepInput += obDepInput[obIndex]
obMeanTargetInput += obTargetInput[obIndex]
}
obMeanDepInput /= 256
obMeanTargetInput /= 256
obCovariance := 0.0
for obIndex := 0; obIndex < 256; obIndex++ {
obCovariance += (obDepInput[obIndex] - obMeanDepInput) * (obTargetInput[obIndex] - obMeanTargetInput)
}
obCovariance /= 255
return obCovariance
}
// calculate the standard deviation of the values in a slice.
func obUtilStandardDeviationCalc(obInput []float64) float64 {
obSums := 0.0
// calculate the array of rations between the values
for obIndex := 0; obIndex < 256; obIndex++ {
// increase obInstanceDep to calculate mean value of registered distribution
obSums += obInput[obIndex]
}
// calculate the mean
obMeanSums := obSums / float64(len(obInput))
obStdDev := 0.0
// calculate the standard deviation
for obIndex := 0; obIndex < 256; obIndex++ {
obStdDev += obMath.Pow(obInput[obIndex]-obMeanSums, 2)
}
obStdDev = (obMath.Sqrt(obStdDev / float64(len(obInput))))
return obStdDev
}
// calculate the standard deviation of the values of reference over
// retrieved values.
func obUtilCombinedStandardDeviationCalc(obDepBFD []float64, obTargetBFD []float64) float64 {
obDiffs := [256]float64{}
obSums := 0.0
obDepSums := 0.0
// calculate the array of rations between the values
for obIndex := 0; obIndex < 256; obIndex++ {
// add 1 to both to work aroung division by zero
obDiffs[obIndex] = obUtilAbsCalc(obDepBFD[obIndex] - obTargetBFD[obIndex])
obSums += obDiffs[obIndex]
// increase obInstanceDep to calculate mean value of registered distribution
obDepSums += obDepBFD[obIndex]
}
// calculate the mean
obDepSums /= float64(len(obDepBFD))
// calculate the mean
obMeanSums := obSums / float64(len(obDepBFD))
obStdDev := 0.0
// calculate the standard deviation
for obIndex := 0; obIndex < 256; obIndex++ {
obStdDev += obMath.Pow(obDiffs[obIndex]-obMeanSums, 2)
}
obStdDev = (obMath.Sqrt(obStdDev / float64(len(obDepBFD)))) / obDepSums
return obStdDev
}
func obDependencyCheck() {
obStrControl1 := "_DEP"
obStrControl2 := "_NAME"
obStrControl3 := "_SIZE"
obInstanceDep := obDependency{
obDepName: "DEPNAME1",
obDepSize: "DEPSIZE2",
obDepBFD: []float64{1, 2, 3, 4},
}
// control that we effectively want to control the dependencies
if (obInstanceDep.obDepName != obStrControl1[1:]+obStrControl2[1:]+"1") &&
(obInstanceDep.obDepSize != obStrControl1[1:]+obStrControl3[1:]+"2") {
// check if the file is a symbolic link
obLTargetStats, _ := obOS.Lstat(obInstanceDep.obDepName)
if (obLTargetStats.Mode() & obOS.ModeSymlink) != 0 {
obExit()
}
// open dependency in current environment and check it's size
obFile, obErr := obOS.Open(obInstanceDep.obDepName)
if obErr != nil {
obExit()
}
defer obFile.Close()
obStatsFile, _ := obFile.Stat()
obTargetDepSize, _ := obStrconv.ParseInt(obInstanceDep.obDepSize, 10, 64)
obTargetTreshold := (obTargetDepSize / 100) * obFileSizeLevel
// first check if file size is +/- 15% of registered size
if (obStatsFile.Size()-obTargetDepSize) < (-1*(obTargetTreshold)) ||
(obStatsFile.Size()-obTargetDepSize) > obTargetTreshold {
obExit()
}
// Calculate BFD (byte frequency distribution) of target file
// and calculate standard deviation from registered fingerprint.
obTargetBFD := obUtilBFDCalc(obInstanceDep.obDepName)
// Calculate covariance of the 2 dataset
obCovariance := obUtilCovarianceCalc(obInstanceDep.obDepBFD, obTargetBFD)
// calculate the correlation index of Bravais-Pearson to see if the
// two dataset are linearly correlated
obDepStdDev := obUtilStandardDeviationCalc(obInstanceDep.obDepBFD)
obTargetStdDev := obUtilStandardDeviationCalc(obTargetBFD)
obCorrelation := obCovariance / (obDepStdDev * obTargetStdDev)
if obCorrelation < obCorrelationLevel {
// not correlated, different nature
obExit()
}
obCombinedStdDev := obUtilCombinedStandardDeviationCalc(
obInstanceDep.obDepBFD,
obTargetBFD)
// standard deviation should not be greater than 1
if obCombinedStdDev > obStdLevel {
obExit()
}
}
}
// Reverse a slice of bytes.
func obReverseByteArray(obInput []byte) []byte {
obResult := []byte{}
for i := range obInput {
n := obInput[len(obInput)-1-i]
obResult = append(obResult, n)
}
return obResult
}
// Change byte endianess.
func obByteReverse(obBar byte) byte {
var obFoo byte
for obStart := 0; obStart < 8; obStart++ {
obFoo <<= 1
obFoo |= obBar & 1
obBar >>= 1
}
return obFoo
}
const (
obCloexec uint = 1
// allow seal operations to be performed.
obAllowSealing uint = 2
// memfd is now immutable.
obSealAll = 0x0001 | 0x0002 | 0x0004 | 0x0008
// amd64 specific.
obSysFCNTL = obSyscall.SYS_FCNTL
obSysMEMFDCreate = 319
)
func obGetFDPath(obPid int, obFD int, obPayload []byte) string {
// check if we are pakkering a script, if it's a script
// use specific pid path.
if string(obPayload[0:2]) == "#!" {
return "/proc/" +
obStrconv.Itoa(obPid) +
"/fd/" +
obStrconv.Itoa(obFD)
}
// else use self for elf files
return "/proc/self/fd/" + obStrconv.Itoa(obFD)
}
func obLauncher() {
// OB_CHECK
obNameFile, _ := obOS.Executable()
obFile, _ := obOS.Open(obNameFile)
defer obFile.Close()
// OB_CHECK
obOffset, _ := obStrconv.ParseInt("9999999", 10, 64)
obStatsFile, _ := obFile.Stat()
// calculate final padding
obArrayFinalPadding := make([]byte, obBinary.MaxVarintLen64)
obByteFinalPadding := obArrayFinalPadding[:obBinary.PutVarint(obArrayFinalPadding, obOffset)]
for obIndex := range obByteFinalPadding {
obByteFinalPadding[obIndex] = obByteReverse(obByteFinalPadding[obIndex])
}
obFinalPadding, _ := obBinary.Varint(obByteFinalPadding)
// make it positive!
if obFinalPadding < 0 {
obFinalPadding *= -1
}
// read the complete executable
obKey := make([]byte, obOffset)
_, obErr := obFile.Read(obKey)
if obErr != nil {
obExit()
}
// OB_CHECK
obSizeFile := obStatsFile.Size() - obOffset
// OB_CHECK
_, obErr = obFile.Seek(obOffset, 0)
if obErr != nil {
obExit()
}
obCiphertext := make([]byte, obSizeFile)
// OB_CHECK
_, obErr = obFile.Read(obCiphertext)
if obErr != nil {
obExit()
}
obCiphertext = obCiphertext[:int64(len(obCiphertext))-obFinalPadding]
// OB_CHECK
// the payload was reversed!
obCiphertext = obReverseByteArray(obCiphertext)
// OB_CHECK
// restore endianess
for obIndex := range obCiphertext {
obCiphertext[obIndex] = obByteReverse(obCiphertext[obIndex])
}
// OB_CHECK
// the aes-256 psk is the sha512_256 sum of the whole executable
// this is also useful to protect against NOP attacks to the anti-debug
// features in the binary.
// This doubles also as anti-tamper measure.
obPassword := obSHA.Sum512_256(obKey)
// OB_CHECK
obCipherBlock, _ := obAES.NewCipher(obPassword[:])
// OB_CHECK
obGCM, _ := obCipher.NewGCM(obCipherBlock)
// OB_CHECK
obSizeNonce := obGCM.NonceSize()
// OB_CHECK
// decrypt!!!
obNonce, obCiphertext := obCiphertext[:obSizeNonce], obCiphertext[obSizeNonce:]
obCompressedPlaintext, _ := obGCM.Open(nil, obNonce, obCiphertext, nil)
// OB_CHECK
// the payload was compressed!
obBufferPlaintext := obBytes.NewReader(obCompressedPlaintext)
// OB_CHECK
obZlibReader, obErr := obZlib.NewReader(obBufferPlaintext)
if obErr != nil {
obExit()
}
// OB_CHECK
obPlaintext, _ := obUtilio.ReadAll(obZlibReader)
obZlibReader.Close()
// OB_CHECK
// payload was in b64
obPayload, _ := obBase64.StdEncoding.DecodeString(string(obPlaintext))
// OB_CHECK
obFDName := ""
obFileDescriptor, _, _ := obSyscall.Syscall(obSysMEMFDCreate,
uintptr(obUnsafe.Pointer(&obFDName)),
uintptr(obCloexec|obAllowSealing), 0)
// OB_CHECK
// write payload to FD
_, obErr = obSyscall.Write(int(obFileDescriptor), obPayload)
if obErr != nil {
obExit()
}
// OB_CHECK
// make it immutable
_, _, obErr = obSyscall.Syscall(obSysFCNTL,
obFileDescriptor,
uintptr(1024+9),
uintptr(obSealAll))
if !obErrors.Is(obErr, obSyscall.Errno(0)) {
obExit()
}
// OB_CHECK
obFDPath := obGetFDPath(obOS.Getpid(), int(obFileDescriptor), obPayload)
// OB_CHECK
obCommand := obExec.Command(obFDPath)
// OB_CHECK
obCommand.Args = obOS.Args
obCommand.Stdin = obOS.Stdin
// OB_CHECK
obStdoutIn, _ := obCommand.StdoutPipe()
defer obStdoutIn.Close()
obStderrIn, _ := obCommand.StderrPipe()
defer obStderrIn.Close()
obStdout, obErr := obStrconv.ParseBool(Stdout)
if obErr != nil {
obExit()
}
if obStdout {
// OB_CHECK
// launch and remain attached
obErr = obCommand.Start()
if obErr != nil {
obExit()
}
var obWaitGroup obSync.WaitGroup
obWaitGroup.Add(2)
obStdoutScan := obBufio.NewScanner(obStdoutIn)
obStderrScan := obBufio.NewScanner(obStderrIn)
// OB_CHECK
// async fetch stdout
go func() {
defer obWaitGroup.Done()
for obStdoutScan.Scan() {
println(obStdoutScan.Text())
}
}()
// OB_CHECK
// async fetch stderr
go func() {
defer obWaitGroup.Done()
for obStderrScan.Scan() {
println(obStderrScan.Text())
}
}()
// OB_CHECK
obWaitGroup.Wait()
} else {
// launch and forget
obCommand.SysProcAttr = &obSyscall.SysProcAttr{Setpgid: true, Noctty: true}
// OB_CHECK
obErr = obCommand.Start()
if obErr != nil {
obExit()
}
obTime.Sleep(2 * obTime.Second)
}
}
// obIsForked returns wether we are a forked process of ourself, or a new spawn.
func obIsForked() bool {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/cmdline"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
return obStrings.Contains(string(obStatParent), obOS.Args[0])
}
func main() {
// Prepare to intercept SIGTRAP
obChannel := make(chan obOS.Signal, 1)
obSignal.Notify(obChannel, obSyscall.SIGTRAP, obSyscall.SIGILL)
go obSigTrap(obChannel)
// OB_CHECK
obDependencyCheck()
// OB_CHECK
obEnvArgsDetect()
// OB_CHECK
obParentTracerDetect()
// OB_CHECK
obParentCmdLineDetect()
// OB_CHECK
obEnvDetect()
// OB_CHECK
obEnvParentDetect()
// OB_CHECK
obLdPreloadDetect()
// OB_CHECK
obParentDetect()
// check if we are a forked process, if not, fork
// and ptrace ourself, else exit gracefully and continue
// with normal execution.
//
// this workaround is because go does not support traditional fork()
// and calling ptrace in the main thread of execution will neuter
// any possibility of calling "exec" afterwards.
if obIsForked() {
// we are a child process, let's ptrace
obPtraceDetect(obOS.Getppid(), false)
} else {
// simulate for self, launch ourself in another
// process to ptrace ourself
obCommand := obExec.Command(obOS.Args[0], obOS.Args[1:]...)
obErr := obCommand.Start()
if obErr != nil {
println(obErr.Error())
obExit()
}
go obPtraceDetect(obCommand.Process.Pid, true)
// Ok we are set to go! Let's execute the payload
// OB_CHECK
obLauncher()
}
}