Skip to content

Commit 12b887e

Browse files
committed
fix tls insecure connection between agent and master
1 parent 1bbda29 commit 12b887e

File tree

6 files changed

+84
-105
lines changed

6 files changed

+84
-105
lines changed

agent-manager/main.go

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ package main
22

33
import (
44
"context"
5+
"crypto/tls"
56
"net"
67

7-
"net/http"
88
_ "net/http/pprof"
99

1010
pb "github.com/utmstack/UTMStack/agent-manager/agent"
@@ -14,17 +14,13 @@ import (
1414
"github.com/utmstack/UTMStack/agent-manager/util"
1515
"google.golang.org/grpc"
1616
"google.golang.org/grpc/codes"
17+
"google.golang.org/grpc/credentials"
1718
"google.golang.org/grpc/health"
1819
"google.golang.org/grpc/health/grpc_health_v1"
1920
"google.golang.org/grpc/status"
2021
)
2122

2223
func main() {
23-
go func() {
24-
// http://localhost:6060/debug/pprof/
25-
http.ListenAndServe("0.0.0.0:6060", nil)
26-
}()
27-
2824
h := util.GetLogger()
2925

3026
defer func() {
@@ -38,20 +34,28 @@ func main() {
3834
migration.MigrateDatabase(h)
3935

4036
s, err := pb.InitGrpc()
41-
4237
if err != nil {
4338
h.Fatal("Failed to inititialize gRPC: %v", err)
4439
}
4540

46-
lis, err := net.Listen("tcp", "0.0.0.0:50051")
41+
cert, err := tls.LoadX509KeyPair("/cert/utm.crt", "/cert/utm.key")
4742
if err != nil {
48-
h.Fatal("Failed to listen: %v", err)
43+
h.Fatal("failed to load server certificates: %v", err)
44+
}
45+
46+
tlsConfig := &tls.Config{
47+
MinVersion: tls.VersionTLS13,
48+
Certificates: []tls.Certificate{cert},
4949
}
5050

51-
// Create a gRPC server with the authInterceptor.
52-
grpcServer := grpc.NewServer(grpc.UnaryInterceptor(recoverInterceptor),
51+
creds := credentials.NewTLS(tlsConfig)
52+
53+
grpcServer := grpc.NewServer(
54+
grpc.Creds(creds),
55+
grpc.UnaryInterceptor(recoverInterceptor),
5356
grpc.ChainUnaryInterceptor(auth.UnaryInterceptor),
54-
grpc.StreamInterceptor(auth.StreamInterceptor))
57+
grpc.StreamInterceptor(auth.StreamInterceptor),
58+
)
5559

5660
pb.RegisterAgentServiceServer(grpcServer, s)
5761
pb.RegisterPanelServiceServer(grpcServer, s)
@@ -72,6 +76,11 @@ func main() {
7276
s.InitPingSync()
7377

7478
// Start the gRPC server
79+
lis, err := net.Listen("tcp", "0.0.0.0:50051")
80+
if err != nil {
81+
h.Fatal("Failed to listen: %v", err)
82+
}
83+
7584
h.Info("Starting gRPC server on 0.0.0.0:50051")
7685
if err := grpcServer.Serve(lis); err != nil {
7786
h.Fatal("Failed to serve: %v", err)

agent/agent/configuration/const.go

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -109,16 +109,6 @@ var (
109109
ProhibitedPortsChange = []LogType{LogTypeCiscoGeneric, LogTypeNetflow}
110110
)
111111

112-
func GetCertPath() string {
113-
path, _ := utils.GetMyPath()
114-
return filepath.Join(path, "certs", "utm.crt")
115-
}
116-
117-
func GetKeyPath() string {
118-
path, _ := utils.GetMyPath()
119-
return filepath.Join(path, "certs", "utm.key")
120-
}
121-
122112
func GetCaPath() string {
123113
path, _ := utils.GetMyPath()
124114
return filepath.Join(path, "certs", "ca.crt")

agent/agent/conn/conn.go

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package conn
22

33
import (
4+
"crypto/tls"
45
"fmt"
56
"time"
67

78
"github.com/threatwinds/logger"
89
"github.com/utmstack/UTMStack/agent/agent/configuration"
910
"github.com/utmstack/UTMStack/agent/agent/utils"
1011
grpc "google.golang.org/grpc"
11-
"google.golang.org/grpc/credentials/insecure"
12+
"google.golang.org/grpc/credentials"
1213
)
1314

1415
const (
@@ -33,29 +34,26 @@ func ConnectToServer(cnf *configuration.Config, h *logger.Logger, addrs, port st
3334
}
3435

3536
h.Info("trying to connect to Server...")
36-
37-
if cnf.SkipCertValidation {
38-
conn, err = grpc.Dial(serverAddress, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMessageSize)))
37+
var opts grpc.DialOption
38+
if !cnf.SkipCertValidation {
39+
creds, err := credentials.NewClientTLSFromFile(configuration.GetCaPath(), "")
3940
if err != nil {
40-
connectionAttemps++
41-
h.Info("error connecting to Server, trying again in %.0f seconds", reconnectDelay.Seconds())
42-
time.Sleep(reconnectDelay)
43-
reconnectDelay = utils.IncrementReconnectDelay(reconnectDelay, maxReconnectDelay)
44-
continue
41+
return nil, fmt.Errorf("failed to load CA trust certificate: %v", err)
4542
}
43+
opts = grpc.WithTransportCredentials(creds)
4644
} else {
47-
tlsCredentials, err := utils.LoadTLSCredentials(configuration.GetCertPath())
48-
if err != nil {
49-
return nil, fmt.Errorf("failed to load TLS credentials: %v", err)
50-
}
51-
conn, err = grpc.Dial(serverAddress, grpc.WithTransportCredentials(tlsCredentials), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMessageSize)))
52-
if err != nil {
53-
connectionAttemps++
54-
h.Info("error connecting to Server, trying again in %.0f seconds", reconnectDelay.Seconds())
55-
time.Sleep(reconnectDelay)
56-
reconnectDelay = utils.IncrementReconnectDelay(reconnectDelay, maxReconnectDelay)
57-
continue
58-
}
45+
tlsConfig := &tls.Config{InsecureSkipVerify: true}
46+
creds := credentials.NewTLS(tlsConfig)
47+
opts = grpc.WithTransportCredentials(creds)
48+
}
49+
50+
conn, err = grpc.NewClient(serverAddress, opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMessageSize)))
51+
if err != nil {
52+
connectionAttemps++
53+
h.Info("error connecting to Server, trying again in %.0f seconds", reconnectDelay.Seconds())
54+
time.Sleep(reconnectDelay)
55+
reconnectDelay = utils.IncrementReconnectDelay(reconnectDelay, maxReconnectDelay)
56+
continue
5957
}
6058

6159
break

agent/agent/utils/certs.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ func GenerateCerts(folder string) error {
8282
Locality: []string{"Coral Springs"},
8383
},
8484
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
85+
DNSNames: []string{"localhost"},
8586
NotBefore: time.Now(),
8687
NotAfter: time.Now().AddDate(10, 0, 0),
8788
SubjectKeyId: []byte{1, 2, 3, 4, 6},

agent/agent/utils/tls.go

Lines changed: 0 additions & 29 deletions
This file was deleted.

log-auth-proxy/main.go

Lines changed: 43 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,94 +1,104 @@
11
package main
22

33
import (
4-
"fmt"
4+
"crypto/tls"
55
"net"
6-
"os"
7-
"path/filepath"
6+
"net/http"
87

98
"github.com/gin-gonic/gin"
10-
"github.com/utmstack/UTMStack/log-auth-proxy/config"
119
"github.com/utmstack/UTMStack/log-auth-proxy/handlers"
1210
"github.com/utmstack/UTMStack/log-auth-proxy/logservice"
1311
"github.com/utmstack/UTMStack/log-auth-proxy/middleware"
1412
"github.com/utmstack/UTMStack/log-auth-proxy/utils"
1513
"google.golang.org/grpc"
14+
"google.golang.org/grpc/credentials"
1615
"google.golang.org/grpc/health"
1716
"google.golang.org/grpc/health/grpc_health_v1"
1817
)
1918

2019
func main() {
21-
h := utils.GetLogger()
2220
autService := logservice.NewLogAuthService()
2321
go autService.SyncAuth()
2422
authInterceptor := middleware.NewLogAuthInterceptor(autService)
2523

26-
cert, key, err := loadCerts()
27-
if err != nil {
28-
h.Fatal("Failed to load certificates: %v", err)
29-
}
30-
3124
logOutputService := logservice.NewLogOutputService()
3225
go logOutputService.SyncOutputs()
3326

34-
go startHTTPServer(authInterceptor, logOutputService, cert, key)
27+
go startHTTPServer(authInterceptor, logOutputService)
3528
go startGRPCServer(authInterceptor, logOutputService)
3629

37-
// Block the main thread until an interrupt is received
3830
select {}
3931
}
4032

41-
func startHTTPServer(interceptor *middleware.LogAuthInterceptor, logOutputService *logservice.LogOutputService, cert string, key string) {
33+
func startHTTPServer(interceptor *middleware.LogAuthInterceptor, logOutputService *logservice.LogOutputService) {
4234
h := utils.GetLogger()
35+
4336
gin.SetMode(gin.ReleaseMode)
4437
router := gin.Default()
4538
router.POST("/v1/log", interceptor.HTTPAuthInterceptor(), handlers.HttpLog(logOutputService))
4639
router.POST("/v1/logs", interceptor.HTTPAuthInterceptor(), handlers.HttpBulkLog(logOutputService))
4740
router.POST("/v1/github-webhook", interceptor.HTTPGitHubAuthInterceptor(), handlers.HttpGitHubHandler(logOutputService))
4841
router.GET("/v1/ping", handlers.HttpPing)
49-
err := router.RunTLS(":8080", cert, key)
50-
h.Info("Starting HTTP server on 0.0.0.0:8080")
42+
43+
cert, err := tls.LoadX509KeyPair("/cert/utm.crt", "/cert/utm.key")
5144
if err != nil {
52-
h.ErrorF("Failed to start HTTP server: %v", err)
53-
return
45+
h.Fatal("failed to load server certificates: %v", err)
5446
}
55-
}
5647

57-
func loadCerts() (string, string, error) {
58-
certsLocation := os.Getenv(config.UTMCertsLocationEnv)
59-
certPath := filepath.Join(certsLocation, config.UTMCertFileName)
60-
keyPath := filepath.Join(certsLocation, config.UTMCertFileKey)
48+
tlsConfig := &tls.Config{
49+
MinVersion: tls.VersionTLS13,
50+
Certificates: []tls.Certificate{cert},
51+
}
6152

62-
if _, err := os.Stat(certPath); os.IsNotExist(err) {
63-
return "", "", fmt.Errorf("certificate file does not exist: %s", certPath)
53+
server := &http.Server{
54+
Addr: ":8080",
55+
Handler: router,
56+
TLSConfig: tlsConfig,
6457
}
65-
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
66-
return "", "", fmt.Errorf("key file does not exist: %s", keyPath)
58+
59+
h.Info("Starting HTTP server on 0.0.0.0:8080")
60+
err = server.ListenAndServeTLS("", "")
61+
if err != nil {
62+
h.Fatal("Failed to start HTTP server: %v", err)
6763
}
68-
return certPath, keyPath, nil
6964
}
7065

7166
func startGRPCServer(interceptor *middleware.LogAuthInterceptor, logOutputService *logservice.LogOutputService) {
7267
h := utils.GetLogger()
73-
lis, err := net.Listen("tcp", "0.0.0.0:50051")
68+
69+
cert, err := tls.LoadX509KeyPair("/cert/utm.crt", "/cert/utm.key")
7470
if err != nil {
75-
h.Fatal("failed to listen grpc server: %v", err)
71+
h.Fatal("failed to load server certificates: %v", err)
7672
}
7773

74+
tlsConfig := &tls.Config{
75+
MinVersion: tls.VersionTLS13,
76+
Certificates: []tls.Certificate{cert},
77+
}
78+
79+
creds := credentials.NewTLS(tlsConfig)
80+
7881
s := &logservice.Grpc{
7982
OutputService: logOutputService,
8083
}
8184

82-
grpcServer := grpc.NewServer(grpc.UnaryInterceptor(interceptor.GrpcRecoverInterceptor),
83-
grpc.ChainUnaryInterceptor(interceptor.GrpcAuthInterceptor))
85+
grpcServer := grpc.NewServer(
86+
grpc.Creds(creds),
87+
grpc.UnaryInterceptor(interceptor.GrpcRecoverInterceptor),
88+
grpc.ChainUnaryInterceptor(interceptor.GrpcAuthInterceptor),
89+
)
90+
8491
logservice.RegisterLogServiceServer(grpcServer, s)
8592

86-
// Register the health check service
8793
healthServer := health.NewServer()
8894
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
8995
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
9096

91-
// Start the gRPC server
97+
lis, err := net.Listen("tcp", "0.0.0.0:50051")
98+
if err != nil {
99+
h.Fatal("failed to listen grpc server: %v", err)
100+
}
101+
92102
h.Info("Starting gRPC server on 0.0.0.0:50051")
93103
if err := grpcServer.Serve(lis); err != nil {
94104
h.Fatal("Failed to serve grpc: %v", err)

0 commit comments

Comments
 (0)