seaweedfs/weed/security/tls.go

73 lines
1.9 KiB
Go
Raw Normal View History

2019-02-18 20:11:52 +00:00
package security
import (
"crypto/tls"
"crypto/x509"
2021-01-12 10:28:13 +00:00
"github.com/chrislusf/seaweedfs/weed/util"
2019-02-18 20:11:52 +00:00
"io/ioutil"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
2020-02-23 05:23:30 +00:00
"github.com/chrislusf/seaweedfs/weed/glog"
2019-02-18 20:11:52 +00:00
)
2021-01-12 10:28:13 +00:00
func LoadServerTLS(config *util.ViperProxy, component string) grpc.ServerOption {
2019-02-18 20:11:52 +00:00
if config == nil {
return nil
}
// load cert/key, ca cert
cert, err := tls.LoadX509KeyPair(config.GetString(component+".cert"), config.GetString(component+".key"))
if err != nil {
2020-02-23 05:23:30 +00:00
glog.V(1).Infof("load cert/key error: %v", err)
2019-02-18 20:11:52 +00:00
return nil
}
2020-11-22 12:27:15 +00:00
caCert, err := ioutil.ReadFile(config.GetString("grpc.ca"))
2019-02-18 20:11:52 +00:00
if err != nil {
2020-02-23 05:23:30 +00:00
glog.V(1).Infof("read ca cert file error: %v", err)
2019-02-18 20:11:52 +00:00
return nil
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
ta := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
})
return grpc.Creds(ta)
}
2021-01-12 10:28:13 +00:00
func LoadClientTLS(config *util.ViperProxy, component string) grpc.DialOption {
2019-02-18 20:11:52 +00:00
if config == nil {
return grpc.WithInsecure()
}
2020-11-22 12:27:15 +00:00
certFileName, keyFileName, caFileName := config.GetString(component+".cert"), config.GetString(component+".key"), config.GetString("grpc.ca")
2020-09-20 22:40:49 +00:00
if certFileName == "" || keyFileName == "" || caFileName == "" {
2020-09-20 22:38:59 +00:00
return grpc.WithInsecure()
}
2019-02-18 20:11:52 +00:00
// load cert/key, cacert
2020-09-20 22:38:59 +00:00
cert, err := tls.LoadX509KeyPair(certFileName, keyFileName)
2019-02-18 20:11:52 +00:00
if err != nil {
2020-02-23 05:23:30 +00:00
glog.V(1).Infof("load cert/key error: %v", err)
2019-02-18 20:11:52 +00:00
return grpc.WithInsecure()
}
2020-09-20 22:40:49 +00:00
caCert, err := ioutil.ReadFile(caFileName)
2019-02-18 20:11:52 +00:00
if err != nil {
2020-02-23 05:23:30 +00:00
glog.V(1).Infof("read ca cert file error: %v", err)
2019-02-18 20:11:52 +00:00
return grpc.WithInsecure()
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
ta := credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
InsecureSkipVerify: true,
})
return grpc.WithTransportCredentials(ta)
}