You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.9 KiB

4 years ago
4 years ago
4 years ago
4 years ago
  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/glog"
  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.V(1).Infof("load cert/key error: %v", err)
  19. return nil
  20. }
  21. caCert, err := ioutil.ReadFile(config.GetString(component + ".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 *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. 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. }