forked from BishopFox/sliver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binaries.go
518 lines (450 loc) · 15.1 KB
/
binaries.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
package generate
/*
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 (
"bytes"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"text/template"
clientpb "github.com/bishopfox/sliver/protobuf/client"
"github.com/bishopfox/sliver/server/assets"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/gobfuscate"
"github.com/bishopfox/sliver/server/gogo"
"github.com/bishopfox/sliver/server/log"
"github.com/gobuffalo/packr"
)
var (
buildLog = log.NamedLogger("generate", "build")
// Fix #67: use an arch specific compiler
defaultMingwPath = map[string]string{
"386": "/usr/bin/i686-w64-mingw32-gcc",
"amd64": "/usr/bin/x86_64-w64-mingw32-gcc",
}
)
const (
// WINDOWS OS
WINDOWS = "windows"
// DARWIN / MacOS
DARWIN = "darwin"
// LINUX OS
LINUX = "linux"
clientsDirName = "clients"
sliversDirName = "slivers"
encryptKeySize = 16
// DefaultReconnectInterval - In seconds
DefaultReconnectInterval = 60
// DefaultMTLSLPort - Default listen port
DefaultMTLSLPort = 8888
// DefaultHTTPLPort - Default HTTP listen port
DefaultHTTPLPort = 443 // Assume SSL, it'll fallback
// SliverCC64EnvVar - Environment variable that can specify the 64 bit mingw path
SliverCC64EnvVar = "SLIVER_CC_64"
// SliverCC32EnvVar - Environment variable that can specify the 32 bit mingw path
SliverCC32EnvVar = "SLIVER_CC_32"
)
// SliverConfig - Parameters when generating a implant
type SliverConfig struct {
// Go
GOOS string `json:"go_os"`
GOARCH string `json:"go_arch"`
// Standard
Name string `json:"name"`
CACert string `json:"ca_cert"`
Cert string `json:"cert"`
Key string `json:"key"`
Debug bool `json:"debug"`
ObfuscateSymbols bool `json:"obfuscate_symbols"`
ReconnectInterval int `json:"reconnect_interval"`
MaxConnectionErrors int `json:"max_connection_errors"`
C2 []SliverC2 `json:"c2s"`
MTLSc2Enabled bool `json:"c2_mtls_enabled"`
HTTPc2Enabled bool `json:"c2_http_enabled"`
DNSc2Enabled bool `json:"c2_dns_enabled"`
CanaryDomains []string `json:"canary_domains"`
// Limits
LimitDomainJoined bool `json:"limit_domainjoined"`
LimitHostname string `json:"limit_hostname"`
LimitUsername string `json:"limit_username"`
LimitDatetime string `json:"limit_datetime"`
// Output Format
Format clientpb.SliverConfig_OutputFormat `json:"format"`
// For IsSharedLib bool `json:"is_shared_lib"`
IsSharedLib bool `json:"is_shared_lib"`
FileName string
}
// ToProtobuf - Convert SliverConfig to protobuf equiv
func (c *SliverConfig) ToProtobuf() *clientpb.SliverConfig {
config := &clientpb.SliverConfig{
GOOS: c.GOOS,
GOARCH: c.GOARCH,
Name: c.Name,
CACert: c.CACert,
Cert: c.Cert,
Key: c.Key,
Debug: c.Debug,
ObfuscateSymbols: c.ObfuscateSymbols,
CanaryDomains: c.CanaryDomains,
ReconnectInterval: uint32(c.ReconnectInterval),
MaxConnectionErrors: uint32(c.MaxConnectionErrors),
LimitDatetime: c.LimitDatetime,
LimitDomainJoined: c.LimitDomainJoined,
LimitHostname: c.LimitHostname,
LimitUsername: c.LimitUsername,
IsSharedLib: c.IsSharedLib,
Format: c.Format,
FileName: c.FileName,
}
config.C2 = []*clientpb.SliverC2{}
for _, c2 := range c.C2 {
config.C2 = append(config.C2, c2.ToProtobuf())
}
return config
}
// SliverConfigFromProtobuf - Create a native config struct from Protobuf
func SliverConfigFromProtobuf(pbConfig *clientpb.SliverConfig) *SliverConfig {
cfg := &SliverConfig{}
cfg.GOOS = pbConfig.GOOS
cfg.GOARCH = pbConfig.GOARCH
cfg.Name = pbConfig.Name
cfg.CACert = pbConfig.CACert
cfg.Cert = pbConfig.Cert
cfg.Key = pbConfig.Key
cfg.Debug = pbConfig.Debug
cfg.ObfuscateSymbols = pbConfig.ObfuscateSymbols
cfg.CanaryDomains = pbConfig.CanaryDomains
cfg.ReconnectInterval = int(pbConfig.ReconnectInterval)
cfg.MaxConnectionErrors = int(pbConfig.MaxConnectionErrors)
cfg.LimitDomainJoined = pbConfig.LimitDomainJoined
cfg.LimitDatetime = pbConfig.LimitDatetime
cfg.LimitUsername = pbConfig.LimitUsername
cfg.LimitHostname = pbConfig.LimitHostname
cfg.Format = pbConfig.Format
cfg.IsSharedLib = pbConfig.IsSharedLib
cfg.C2 = copyC2List(pbConfig.C2)
cfg.MTLSc2Enabled = isC2Enabled([]string{"mtls"}, cfg.C2)
cfg.HTTPc2Enabled = isC2Enabled([]string{"http", "https"}, cfg.C2)
cfg.DNSc2Enabled = isC2Enabled([]string{"dns"}, cfg.C2)
cfg.FileName = pbConfig.FileName
return cfg
}
func copyC2List(src []*clientpb.SliverC2) []SliverC2 {
c2s := []SliverC2{}
for _, srcC2 := range src {
c2URL, err := url.Parse(srcC2.URL)
if err != nil {
buildLog.Warnf("Failed to parse c2 url %v", err)
continue
}
c2s = append(c2s, SliverC2{
Priority: srcC2.Priority,
URL: c2URL.String(),
Options: srcC2.Options,
})
}
return c2s
}
func isC2Enabled(schemes []string, c2s []SliverC2) bool {
for _, c2 := range c2s {
c2URL, err := url.Parse(c2.URL)
if err != nil {
buildLog.Warnf("Failed to parse c2 url %v", err)
continue
}
for _, scheme := range schemes {
if scheme == c2URL.Scheme {
return true
}
}
}
buildLog.Debugf("No %v URLs found in %v", schemes, c2s)
return false
}
// SliverC2 - C2 struct
type SliverC2 struct {
Priority uint32 `json:"priority"`
URL string `json:"url"`
Options string `json:"options"`
}
// ToProtobuf - Convert to protobuf version
func (s SliverC2) ToProtobuf() *clientpb.SliverC2 {
return &clientpb.SliverC2{
Priority: s.Priority,
URL: s.URL,
Options: s.Options,
}
}
func (s SliverC2) String() string {
return s.URL
}
// GetSliversDir - Get the binary directory
func GetSliversDir() string {
appDir := assets.GetRootAppDir()
sliversDir := path.Join(appDir, sliversDirName)
if _, err := os.Stat(sliversDir); os.IsNotExist(err) {
buildLog.Infof("Creating bin directory: %s", sliversDir)
err = os.MkdirAll(sliversDir, os.ModePerm)
if err != nil {
buildLog.Fatal(err)
}
}
return sliversDir
}
// SliverEgg - Generates a sliver egg (stager) binary
func SliverEgg(config SliverConfig) (string, error) {
return "", nil
}
// -----------------------
// Sliver Generation Code
// -----------------------
// SliverSharedLibrary - Generates a sliver shared library (DLL/dylib/so) binary
func SliverSharedLibrary(config *SliverConfig) (string, error) {
// Compile go code
appDir := assets.GetRootAppDir()
crossCompiler := getCCompiler(config.GOARCH)
if crossCompiler == "" {
return "", errors.New("No cross-compiler (mingw) found")
}
goConfig := &gogo.GoConfig{
CGO: "1",
CC: crossCompiler,
GOOS: config.GOOS,
GOARCH: config.GOARCH,
GOROOT: gogo.GetGoRootDir(appDir),
}
pkgPath, err := renderSliverGoCode(config, goConfig)
if err != nil {
return "", err
}
dest := path.Join(goConfig.GOPATH, "bin", config.Name)
if goConfig.GOOS == WINDOWS {
dest += ".dll"
}
if goConfig.GOOS == DARWIN {
dest += ".dylib"
}
if goConfig.GOOS == LINUX {
dest += ".so"
}
tags := []string{"netgo"}
ldflags := []string{"-s -w"}
if !config.Debug && goConfig.GOOS == WINDOWS {
ldflags[0] += " -H=windowsgui"
}
gcflags := fmt.Sprintf("-trimpath=%s", pkgPath)
asmflags := fmt.Sprintf("-trimpath=%s", pkgPath)
_, err = gogo.GoBuild(*goConfig, pkgPath, dest, "c-shared", tags, ldflags, gcflags, asmflags)
config.FileName = path.Base(dest)
saveFileErr := SliverFileSave(config.Name, dest)
saveCfgErr := SliverConfigSave(config)
if saveFileErr != nil || saveCfgErr != nil {
buildLog.Errorf("Failed to save file to db %s %s", saveFileErr, saveCfgErr)
}
return dest, err
}
// SliverExecutable - Generates a sliver executable binary
func SliverExecutable(config *SliverConfig) (string, error) {
// Compile go code
appDir := assets.GetRootAppDir()
goConfig := &gogo.GoConfig{
CGO: "0",
GOOS: config.GOOS,
GOARCH: config.GOARCH,
GOROOT: gogo.GetGoRootDir(appDir),
}
pkgPath, err := renderSliverGoCode(config, goConfig)
if err != nil {
return "", err
}
dest := path.Join(goConfig.GOPATH, "bin", config.Name)
if goConfig.GOOS == WINDOWS {
dest += ".exe"
}
tags := []string{"netgo"}
ldflags := []string{"-s -w -buildid="}
if !config.Debug && goConfig.GOOS == WINDOWS {
ldflags[0] += " -H=windowsgui"
}
gcflags := fmt.Sprintf("-trimpath=%s", pkgPath)
asmflags := fmt.Sprintf("-trimpath=%s", pkgPath)
_, err = gogo.GoBuild(*goConfig, pkgPath, dest, "", tags, ldflags, gcflags, asmflags)
config.FileName = path.Base(dest)
saveFileErr := SliverFileSave(config.Name, dest)
saveCfgErr := SliverConfigSave(config)
if saveFileErr != nil || saveCfgErr != nil {
buildLog.Errorf("Failed to save file to db %s %s", saveFileErr, saveCfgErr)
}
return dest, err
}
// This function is a little too long, we should probably refactor it as some point
func renderSliverGoCode(config *SliverConfig, goConfig *gogo.GoConfig) (string, error) {
target := fmt.Sprintf("%s/%s", config.GOOS, config.GOARCH)
if _, ok := gogo.ValidCompilerTargets[target]; !ok {
return "", fmt.Errorf("Invalid compiler target: %s", target)
}
if config.Name == "" {
config.Name = GetCodename()
}
buildLog.Infof("Generating new sliver binary '%s'", config.Name)
config.MTLSc2Enabled = isC2Enabled([]string{"mtls"}, config.C2)
config.HTTPc2Enabled = isC2Enabled([]string{"http", "https"}, config.C2)
config.DNSc2Enabled = isC2Enabled([]string{"dns"}, config.C2)
sliversDir := GetSliversDir() // ~/.sliver/slivers
projectGoPathDir := path.Join(sliversDir, config.GOOS, config.GOARCH, config.Name)
os.MkdirAll(projectGoPathDir, os.ModePerm)
goConfig.GOPATH = projectGoPathDir
// Cert PEM encoded certificates
serverCACert, _, _ := certs.GetCertificateAuthorityPEM(certs.ServerCA)
sliverCert, sliverKey, err := certs.SliverGenerateECCCertificate(config.Name)
if err != nil {
return "", err
}
config.CACert = string(serverCACert)
config.Cert = string(sliverCert)
config.Key = string(sliverKey)
// binDir - ~/.sliver/slivers/<os>/<arch>/<name>/bin
binDir := path.Join(projectGoPathDir, "bin")
os.MkdirAll(binDir, os.ModePerm)
// srcDir - ~/.sliver/slivers/<os>/<arch>/<name>/src
srcDir := path.Join(projectGoPathDir, "src")
assets.SetupGoPath(srcDir) // Extract GOPATH dependancy files
sliverPkgDir := path.Join(srcDir, "github.com", "bishopfox", "sliver") // "main"
os.MkdirAll(sliverPkgDir, os.ModePerm)
// Load code template
sliverBox := packr.NewBox("../../sliver")
for index, boxName := range srcFiles {
// Gobfuscate doesn't handle all the platform specific code
// well and the renamer can get confused when symbols for a
// different OS don't show up. So we just filter out anything
// we're not actually going to compile into the final binary
suffix := ".go"
if strings.Contains(boxName, "_") {
fileNameParts := strings.Split(boxName, "_")
suffix = "_" + fileNameParts[len(fileNameParts)-1]
if strings.HasSuffix(boxName, "_test.go") {
buildLog.Infof("Skipping (test): %s", boxName)
continue
}
osSuffix := fmt.Sprintf("_%s.go", strings.ToLower(config.GOOS))
archSuffix := fmt.Sprintf("_%s.go", strings.ToLower(config.GOARCH))
if !strings.HasSuffix(boxName, osSuffix) && !strings.HasSuffix(boxName, archSuffix) {
buildLog.Infof("Skipping file wrong os/arch: %s", boxName)
continue
}
}
sliverGoCode, _ := sliverBox.FindString(boxName)
// We need to correct for the "github.com/bishopfox/sliver/sliver/foo" imports, since Go
// doesn't allow relative imports and "sliver" is a subdirectory of
// the main "sliver" repo we need to fake this when coping the code
// to our per-compile "GOPATH"
var sliverCodePath string
dirName := filepath.Dir(boxName)
var fileName string
if config.Debug {
fileName = filepath.Base(boxName)
} else {
fileName = fmt.Sprintf("s%d%s", index, suffix)
}
if dirName != "." {
// Add an extra "sliver" dir
dirPath := path.Join(sliverPkgDir, "sliver", dirName)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
buildLog.Infof("[mkdir] %#v", dirPath)
os.MkdirAll(dirPath, os.ModePerm)
}
sliverCodePath = path.Join(dirPath, fileName)
} else {
sliverCodePath = path.Join(sliverPkgDir, fileName)
}
fSliver, _ := os.Create(sliverCodePath)
buf := bytes.NewBuffer([]byte{})
buildLog.Infof("[render] %s", sliverCodePath)
// Render code
sliverCodeTmpl, _ := template.New("sliver").Parse(sliverGoCode)
sliverCodeTmpl.Execute(buf, config)
// Render canaries
buildLog.Infof("Canary domain(s): %v", config.CanaryDomains)
canaryTempl := template.New("canary").Delims("[[", "]]")
canaryGenerator := &CanaryGenerator{
SliverName: config.Name,
ParentDomains: config.CanaryDomains,
}
canaryTempl, err := canaryTempl.Funcs(template.FuncMap{
"GenerateCanary": canaryGenerator.GenerateCanary,
}).Parse(buf.String())
canaryTempl.Execute(fSliver, canaryGenerator)
if err != nil {
buildLog.Infof("Failed to render go code: %s", err)
return "", err
}
}
if !config.Debug {
buildLog.Infof("Obfuscating source code ...")
obfgoPath := path.Join(projectGoPathDir, "obfuscated")
pkgName := "github.com/bishopfox/sliver"
obfSymbols := config.ObfuscateSymbols
obfuscatedPkg, err := gobfuscate.Gobfuscate(*goConfig, randomObfuscationKey(), pkgName, obfgoPath, obfSymbols)
if err != nil {
buildLog.Infof("Error while obfuscating sliver %v", err)
return "", err
}
goConfig.GOPATH = obfgoPath
buildLog.Infof("Obfuscated GOPATH = %s", obfgoPath)
buildLog.Infof("Obfuscated sliver package: %s", obfuscatedPkg)
sliverPkgDir = path.Join(obfgoPath, "src", obfuscatedPkg) // new "main"
}
if err != nil {
buildLog.Errorf("Failed to save sliver config %s", err)
}
return sliverPkgDir, nil
}
func getCCompiler(arch string) string {
var found bool // meh, ugly
var compiler string
if arch == "amd64" {
compiler = os.Getenv(SliverCC64EnvVar)
}
if arch == "386" {
compiler = os.Getenv(SliverCC32EnvVar)
}
if compiler == "" {
if compiler, found = defaultMingwPath[arch]; !found {
compiler = defaultMingwPath["amd64"] // should not happen, but just in case ...
}
}
if _, err := os.Stat(compiler); os.IsNotExist(err) {
buildLog.Warnf("CC path %v does not exist", compiler)
return ""
}
if runtime.GOOS == "windows" {
compiler = "" // TODO: Add windows mingw support
}
buildLog.Infof("CC = %v", compiler)
return compiler
}
func randomObfuscationKey() string {
randBuf := make([]byte, 64) // 64 bytes of randomness
rand.Read(randBuf)
digest := sha256.Sum256(randBuf)
return fmt.Sprintf("%x", digest[:encryptKeySize])
}