-
Notifications
You must be signed in to change notification settings - Fork 10
/
mtls.go
67 lines (55 loc) · 2.27 KB
/
mtls.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
package utils
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"github.com/flomesh-io/fsm/pkg/certificate"
)
func setupMutualTLS(insecure bool, serverName string, certPem []byte, keyPem []byte, ca []byte) (grpc.ServerOption, error) {
certif, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return nil, fmt.Errorf("[grpc][mTLS][%s] Failed loading Certificate (%+v) and Key (%+v) PEM files", serverName, certPem, keyPem)
}
certPool := x509.NewCertPool()
// Load the set of Root CAs
if ok := certPool.AppendCertsFromPEM(ca); !ok {
return nil, fmt.Errorf("[grpc][mTLS][%s] Failed to append client certs", serverName)
}
// #nosec G402
tlsConfig := tls.Config{
InsecureSkipVerify: insecure,
ServerName: serverName,
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{certif},
ClientCAs: certPool,
MinVersion: tls.VersionTLS13,
}
return grpc.Creds(credentials.NewTLS(&tlsConfig)), nil
}
// ValidateClient ensures that the connected client is authorized to connect to the gRPC server.
func ValidateClient(ctx context.Context) (certificate.CommonName, certificate.SerialNumber, error) {
mtlsPeer, ok := peer.FromContext(ctx)
if !ok {
log.Error().Msg("[grpc][mTLS] No peer found")
return "", "", status.Error(codes.Unauthenticated, "no peer found")
}
tlsAuth, ok := mtlsPeer.AuthInfo.(credentials.TLSInfo)
if !ok {
log.Error().Msg("[grpc][mTLS] Unexpected peer transport credentials")
return "", "", status.Error(codes.Unauthenticated, "unexpected peer transport credentials")
}
if len(tlsAuth.State.VerifiedChains) == 0 || len(tlsAuth.State.VerifiedChains[0]) == 0 {
log.Error().Msgf("[grpc][mTLS] Could not verify peer certificate")
return "", "", status.Error(codes.Unauthenticated, "could not verify peer certificate")
}
// Check whether the subject common name is one that is allowed to connect.
cn := tlsAuth.State.VerifiedChains[0][0].Subject.CommonName
certificateSerialNumber := tlsAuth.State.VerifiedChains[0][0].SerialNumber.String()
return certificate.CommonName(cn), certificate.SerialNumber(certificateSerialNumber), nil
}