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.

68 lines
1.7 KiB

  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. // load cert/key, cacert
  40. cert, err := tls.LoadX509KeyPair(config.GetString(component+".cert"), config.GetString(component+".key"))
  41. if err != nil {
  42. glog.V(1).Infof("load cert/key error: %v", err)
  43. return grpc.WithInsecure()
  44. }
  45. caCert, err := ioutil.ReadFile(config.GetString(component + ".ca"))
  46. if err != nil {
  47. glog.V(1).Infof("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. }