tls.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package security
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "io/ioutil"
  6. "github.com/spf13/viper"
  7. "google.golang.org/grpc"
  8. "google.golang.org/grpc/credentials"
  9. "github.com/chrislusf/seaweedfs/weed/util/log"
  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. log.Debugf("load cert/key error: %v", err)
  19. return nil
  20. }
  21. caCert, err := ioutil.ReadFile(config.GetString(component + ".ca"))
  22. if err != nil {
  23. log.Debugf("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. certFileName, keyFileName, caFileName := config.GetString(component+".cert"), config.GetString(component+".key"), config.GetString(component+".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. log.Debugf("load cert/key error: %v", err)
  47. return grpc.WithInsecure()
  48. }
  49. caCert, err := ioutil.ReadFile(caFileName)
  50. if err != nil {
  51. log.Debugf("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. }