Skip to content

Commit

Permalink
Merge pull request #334 from BishopFox/stage
Browse files Browse the repository at this point in the history
Improved logging
  • Loading branch information
moloch-- authored Mar 3, 2021
2 parents 6d2fbf2 + c0aa592 commit 424e700
Show file tree
Hide file tree
Showing 10 changed files with 92 additions and 17 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.16rc1
FROM golang:1.16

#
# IMPORTANT: This Dockerfile is used for testing, I do not recommend deploying
Expand Down
2 changes: 1 addition & 1 deletion client/command/bind-commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ func BindCommands(app *grumble.App, rpc rpcpb.SliverRPCClient) {
Flags: func(f *grumble.Flags) {
f.String("o", "os", "windows", "operating system")
f.String("a", "arch", "amd64", "cpu architecture")
f.String("n", "name", "", "agent name")
f.String("N", "name", "", "agent name")
f.Bool("d", "debug", false, "enable debug features")
f.Bool("e", "evasion", false, "enable evasion features")
f.Bool("b", "skip-symbols", false, "skip symbol obfuscation")
Expand Down
4 changes: 2 additions & 2 deletions client/core/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func TunnelLoop(rpc rpcpb.SliverRPCClient) error {
}
for {

log.Printf("Waiting for TunnelData ...")
// log.Printf("Waiting for TunnelData ...")
incoming, err := stream.Recv()
log.Printf("Recv stream msg: %v", incoming)
if err == io.EOF {
Expand All @@ -155,7 +155,7 @@ func TunnelLoop(rpc rpcpb.SliverRPCClient) error {
log.Printf("Tunnel data read error: %s", err)
return err
}
log.Printf("Received TunnelData for tunnel %d", incoming.TunnelID)
// log.Printf("Received TunnelData for tunnel %d", incoming.TunnelID)
tunnel := Tunnels.Get(incoming.TunnelID)
if tunnel != nil {
if !incoming.Closed {
Expand Down
6 changes: 3 additions & 3 deletions server/certs/operators.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ func OperatorClientRemoveCertificate(operator string) error {
return RemoveCertificate(OperatorCA, ECCKey, fmt.Sprintf("%s.%s", clientNamespace, operator))
}

// OperatorServerGetCertificate - Helper function to fetch a client cert
func OperatorServerGetCertificate(operator string) ([]byte, []byte, error) {
return GetECCCertificate(OperatorCA, fmt.Sprintf("%s.%s", serverNamespace, operator))
// OperatorServerGetCertificate - Helper function to fetch a server cert
func OperatorServerGetCertificate(hostname string) ([]byte, []byte, error) {
return GetECCCertificate(OperatorCA, fmt.Sprintf("%s.%s", serverNamespace, hostname))
}

// OperatorServerGenerateCertificate - Generate a certificate signed with a given CA
Expand Down
9 changes: 9 additions & 0 deletions server/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"log"
"os"
"path"
"runtime/debug"
"strings"

"github.com/bishopfox/sliver/client/version"
Expand Down Expand Up @@ -109,6 +110,14 @@ var rootCmd = &cobra.Command{
logFile := initLogging(appDir)
defer logFile.Close()

defer func() {
if r := recover(); r != nil {
log.Printf("panic:\n%s", debug.Stack())
fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
os.Exit(99)
}
}()

assets.Setup(false)
certs.SetupCAs()

Expand Down
29 changes: 23 additions & 6 deletions server/handlers/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ package handlers
*/

import (
"encoding/json"
"sync"

"github.com/bishopfox/sliver/protobuf/clientpb"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/server/core"
"github.com/bishopfox/sliver/server/log"
Expand Down Expand Up @@ -68,23 +70,20 @@ func registerSessionHandler(session *core.Session, data []byte) {
return
}

handlerLog.Warnf("%v", session)
handlerLog.Warnf("%v", register)

if session.ID == 0 {
session.ID = core.NextSessionID()
}

// Parse Register UUID
session_uuid, err := uuid.Parse(register.Uuid)
sessionUUID, err := uuid.Parse(register.Uuid)
if err != nil {
// Generate Random UUID
session_uuid = uuid.New()
sessionUUID = uuid.New()
}

session.Name = register.Name
session.Hostname = register.Hostname
session.UUID = session_uuid.String()
session.UUID = sessionUUID.String()
session.Username = register.Username
session.UID = register.Uid
session.GID = register.Gid
Expand All @@ -97,6 +96,24 @@ func registerSessionHandler(session *core.Session, data []byte) {
session.ReconnectInterval = register.ReconnectInterval
session.ProxyURL = register.ProxyURL
core.Sessions.Add(session)
go auditLogSession(session, register)
}

type auditLogNewSessionMsg struct {
Session *clientpb.Session
Register *sliverpb.Register
}

func auditLogSession(session *core.Session, register *sliverpb.Register) {
msg, err := json.Marshal(auditLogNewSessionMsg{
Session: session.ToProtobuf(),
Register: register,
})
if err != nil {
handlerLog.Errorf("Failed to log new session to audit log %s", err)
} else {
log.AuditLogger.Warn(string(msg))
}
}

// The handler mutex prevents a send on a closed channel, without it
Expand Down
2 changes: 1 addition & 1 deletion server/log/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func newAuditLogger() *logrus.Logger {
auditLogger := logrus.New()
auditLogger.Formatter = &logrus.JSONFormatter{}
jsonFilePath := path.Join(GetLogDir(), "audit.json")
jsonFile, err := os.OpenFile(jsonFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
jsonFile, err := os.OpenFile(jsonFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
panic(fmt.Sprintf("Failed to open log file %v", err))
}
Expand Down
16 changes: 13 additions & 3 deletions server/transport/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package transport
*/

import (
"runtime/debug"

"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/server/log"
"github.com/bishopfox/sliver/server/rpc"
Expand All @@ -29,13 +31,13 @@ import (
const bufSize = 2 * mb

var (
pipeLog = log.NamedLogger("transport", "local")
bufConnLog = log.NamedLogger("transport", "local")
)

// LocalListener - Bind gRPC server to an in-memory listener, which is
// typically used for unit testing, but ... it should be fine
func LocalListener() (*grpc.Server, *bufconn.Listener, error) {
pipeLog.Infof("Binding gRPC to listener ...")
bufConnLog.Infof("Binding gRPC to listener ...")
ln := bufconn.Listen(bufSize)
options := []grpc.ServerOption{
grpc.MaxRecvMsgSize(ServerMaxMessageSize),
Expand All @@ -45,8 +47,16 @@ func LocalListener() (*grpc.Server, *bufconn.Listener, error) {
grpcServer := grpc.NewServer(options...)
rpcpb.RegisterSliverRPCServer(grpcServer, rpc.NewServer())
go func() {
panicked := true
defer func() {
if panicked {
bufConnLog.Errorf("stacktrace from panic: %s", string(debug.Stack()))
}
}()
if err := grpcServer.Serve(ln); err != nil {
pipeLog.Fatalf("gRPC local listener error: %v", err)
bufConnLog.Fatalf("gRPC local listener error: %v", err)
} else {
panicked = false
}
}()
return grpcServer, ln, nil
Expand Down
30 changes: 30 additions & 0 deletions server/transport/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package transport

import (
"context"
"encoding/json"
"fmt"

"github.com/bishopfox/sliver/server/configs"
"github.com/bishopfox/sliver/server/log"
Expand All @@ -44,6 +46,7 @@ func initLoggerMiddleware() []grpc.ServerOption {
grpc_logrus.ReplaceGrpcLogger(logrusEntry)
return []grpc.ServerOption{
grpc_middleware.WithUnaryServerChain(
auditLogUnaryServerInterceptor(),
grpc_tags.UnaryServerInterceptor(grpc_tags.WithFieldExtractor(grpc_tags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry, logrusOpts...),
grpc_logrus.PayloadUnaryServerInterceptor(logrusEntry, deciderUnary),
Expand Down Expand Up @@ -105,3 +108,30 @@ func codeToLevel(code codes.Code) logrus.Level {
return logrus.ErrorLevel
}
}

type auditUnaryLogMsg struct {
Request string `json:"request"`
Method string `json:"method"`
}

func auditLogUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
var request string
rawRequest, err := json.Marshal(req)
if err != nil {
log.AuditLogger.Errorf("Failed to serialize %s", err)
request = fmt.Sprintf("%v", req)
} else {
request = string(rawRequest)
}

msg, _ := json.Marshal(&auditUnaryLogMsg{
Request: request,
Method: info.FullMethod,
})
log.AuditLogger.Info(string(msg))

resp, err := handler(ctx, req)
return resp, err
}
}
9 changes: 9 additions & 0 deletions server/transport/mtls.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"crypto/x509"
"fmt"
"net"
"runtime/debug"

"github.com/bishopfox/sliver/protobuf/rpcpb"
"github.com/bishopfox/sliver/server/certs"
Expand Down Expand Up @@ -65,8 +66,16 @@ func StartClientListener(host string, port uint16) (*grpc.Server, net.Listener,
grpcServer := grpc.NewServer(options...)
rpcpb.RegisterSliverRPCServer(grpcServer, rpc.NewServer())
go func() {
panicked := true
defer func() {
if panicked {
mtlsLog.Errorf("stacktrace from panic: %s", string(debug.Stack()))
}
}()
if err := grpcServer.Serve(ln); err != nil {
mtlsLog.Warnf("gRPC server exited with error: %v", err)
} else {
panicked = false
}
}()
return grpcServer, ln, nil
Expand Down

0 comments on commit 424e700

Please sign in to comment.