cert.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package cert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "os"
  6. "github.com/lf-edge/ekuiper/internal/conf"
  7. )
  8. type TlsConfigurationOptions struct {
  9. SkipCertVerify bool
  10. CertFile string
  11. KeyFile string
  12. CaFile string
  13. }
  14. func GenerateTLSForClient(
  15. Opts TlsConfigurationOptions,
  16. ) (*tls.Config, error) {
  17. tlsConfig := &tls.Config{
  18. InsecureSkipVerify: Opts.SkipCertVerify,
  19. }
  20. if len(Opts.CertFile) <= 0 && len(Opts.KeyFile) <= 0 {
  21. tlsConfig.Certificates = nil
  22. } else {
  23. if cert, err := certLoader(Opts.CertFile, Opts.KeyFile); err != nil {
  24. return nil, err
  25. } else {
  26. tlsConfig.Certificates = []tls.Certificate{cert}
  27. }
  28. }
  29. if len(Opts.CaFile) > 0 {
  30. root, err := caLoader(Opts.CaFile)
  31. if err != nil {
  32. return nil, err
  33. }
  34. tlsConfig.RootCAs = root
  35. }
  36. return tlsConfig, nil
  37. }
  38. func certLoader(certFilePath, keyFilePath string) (tls.Certificate, error) {
  39. if cp, err := conf.ProcessPath(certFilePath); err == nil {
  40. if kp, err1 := conf.ProcessPath(keyFilePath); err1 == nil {
  41. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  42. return tls.Certificate{}, err2
  43. } else {
  44. return cer, nil
  45. }
  46. } else {
  47. return tls.Certificate{}, err1
  48. }
  49. } else {
  50. return tls.Certificate{}, err
  51. }
  52. }
  53. func caLoader(caFilePath string) (*x509.CertPool, error) {
  54. if cp, err := conf.ProcessPath(caFilePath); err == nil {
  55. pool := x509.NewCertPool()
  56. caCrt, err1 := os.ReadFile(cp)
  57. if err1 != nil {
  58. return nil, err1
  59. }
  60. pool.AppendCertsFromPEM(caCrt)
  61. return pool, err1
  62. } else {
  63. return nil, err
  64. }
  65. }