tls.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package security
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "github.com/spf13/viper"
  6. "io/ioutil"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/credentials"
  10. )
  11. func LoadServerTLS(config *viper.Viper, 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.Errorf("load cert/key error: %v", err)
  19. return nil
  20. }
  21. caCert, err := ioutil.ReadFile(config.GetString("ca"))
  22. if err != nil {
  23. glog.Errorf("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 *viper.Viper, component string) grpc.DialOption {
  36. if config == nil {
  37. return grpc.WithInsecure()
  38. }
  39. // load cert/key, cacert
  40. cert, err := tls.LoadX509KeyPair(config.GetString(component+".cert"), config.GetString(component+".key"))
  41. if err != nil {
  42. glog.Errorf("load cert/key error: %v", err)
  43. return grpc.WithInsecure()
  44. }
  45. caCert, err := ioutil.ReadFile(config.GetString("ca"))
  46. if err != nil {
  47. glog.Errorf("read ca cert file error: %v", err)
  48. return grpc.WithInsecure()
  49. }
  50. caCertPool := x509.NewCertPool()
  51. caCertPool.AppendCertsFromPEM(caCert)
  52. ta := credentials.NewTLS(&tls.Config{
  53. Certificates: []tls.Certificate{cert},
  54. RootCAs: caCertPool,
  55. InsecureSkipVerify: true,
  56. })
  57. return grpc.WithTransportCredentials(ta)
  58. }