tls.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package security
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "github.com/chrislusf/seaweedfs/weed/util"
  6. "io/ioutil"
  7. "google.golang.org/grpc"
  8. "google.golang.org/grpc/credentials"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  10. )
  11. func LoadServerTLS(config *util.ViperProxy, component string) grpc.ServerOption {
  12. if config == nil {
  13. return nil
  14. }
  15. // load cert/key, ca cert
  16. cert, err := tls.LoadX509KeyPair(config.GetString(component+".cert"), config.GetString(component+".key"))
  17. if err != nil {
  18. glog.V(1).Infof("load cert/key error: %v", err)
  19. return nil
  20. }
  21. caCert, err := ioutil.ReadFile(config.GetString("grpc.ca"))
  22. if err != nil {
  23. glog.V(1).Infof("read ca cert file error: %v", err)
  24. return nil
  25. }
  26. caCertPool := x509.NewCertPool()
  27. caCertPool.AppendCertsFromPEM(caCert)
  28. ta := credentials.NewTLS(&tls.Config{
  29. Certificates: []tls.Certificate{cert},
  30. ClientCAs: caCertPool,
  31. ClientAuth: tls.RequireAndVerifyClientCert,
  32. })
  33. return grpc.Creds(ta)
  34. }
  35. func LoadClientTLS(config *util.ViperProxy, component string) grpc.DialOption {
  36. if config == nil {
  37. return grpc.WithInsecure()
  38. }
  39. certFileName, keyFileName, caFileName := config.GetString(component+".cert"), config.GetString(component+".key"), config.GetString("grpc.ca")
  40. if certFileName == "" || keyFileName == "" || caFileName == "" {
  41. return grpc.WithInsecure()
  42. }
  43. // load cert/key, cacert
  44. cert, err := tls.LoadX509KeyPair(certFileName, keyFileName)
  45. if err != nil {
  46. glog.V(1).Infof("load cert/key error: %v", err)
  47. return grpc.WithInsecure()
  48. }
  49. caCert, err := ioutil.ReadFile(caFileName)
  50. if err != nil {
  51. glog.V(1).Infof("read ca cert file error: %v", err)
  52. return grpc.WithInsecure()
  53. }
  54. caCertPool := x509.NewCertPool()
  55. caCertPool.AppendCertsFromPEM(caCert)
  56. ta := credentials.NewTLS(&tls.Config{
  57. Certificates: []tls.Certificate{cert},
  58. RootCAs: caCertPool,
  59. InsecureSkipVerify: true,
  60. })
  61. return grpc.WithTransportCredentials(ta)
  62. }