config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package qlight
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "github.com/ethereum/go-ethereum/plugin/security"
  9. )
  10. type TLSConfig struct {
  11. CACertFileName string
  12. ClientCACertFileName string
  13. ClientAuth int
  14. CertFileName string
  15. KeyFileName string
  16. InsecureSkipVerify bool
  17. CipherSuites string
  18. ServerName string
  19. }
  20. func NewTLSConfig(config *TLSConfig) (*tls.Config, error) {
  21. if config.InsecureSkipVerify {
  22. return &tls.Config{
  23. InsecureSkipVerify: true,
  24. }, nil
  25. }
  26. var (
  27. CA_Pool *x509.CertPool
  28. err error
  29. )
  30. if len(config.CACertFileName) > 0 {
  31. CA_Pool, err = x509.SystemCertPool()
  32. if err != nil {
  33. CA_Pool = x509.NewCertPool()
  34. }
  35. cert, err := os.ReadFile(config.CACertFileName)
  36. if err != nil {
  37. return nil, err
  38. }
  39. CA_Pool.AppendCertsFromPEM(cert)
  40. }
  41. var (
  42. ClientCA_Pool *x509.CertPool
  43. ClientAuth tls.ClientAuthType
  44. )
  45. if len(config.ClientCACertFileName) > 0 {
  46. ClientCA_Pool, err = x509.SystemCertPool()
  47. if err != nil {
  48. ClientCA_Pool = x509.NewCertPool()
  49. }
  50. cert, err := os.ReadFile(config.ClientCACertFileName)
  51. if err != nil {
  52. return nil, err
  53. }
  54. ClientCA_Pool.AppendCertsFromPEM(cert)
  55. if config.ClientAuth < 0 || config.ClientAuth > 4 {
  56. return nil, fmt.Errorf("Invalid ClientAuth value: %d", config.ClientAuth)
  57. }
  58. ClientAuth = tls.ClientAuthType(config.ClientAuth)
  59. }
  60. var certificates []tls.Certificate
  61. if len(config.CertFileName) > 0 && len(config.KeyFileName) > 0 {
  62. cert, err := tls.LoadX509KeyPair(config.CertFileName, config.KeyFileName)
  63. if err != nil {
  64. return nil, err
  65. }
  66. certificates = []tls.Certificate{cert}
  67. }
  68. var CipherSuites []uint16
  69. if len(config.CipherSuites) > 0 {
  70. cipherSuitesStrings := strings.FieldsFunc(config.CipherSuites, func(r rune) bool {
  71. return r == ','
  72. })
  73. if len(cipherSuitesStrings) > 0 {
  74. cipherSuiteList := make(security.CipherSuiteList, len(cipherSuitesStrings))
  75. for i, s := range cipherSuitesStrings {
  76. cipherSuiteList[i] = security.CipherSuite(strings.TrimSpace(s))
  77. }
  78. CipherSuites, err = cipherSuiteList.ToUint16Array()
  79. if err != nil {
  80. return nil, err
  81. }
  82. }
  83. }
  84. return &tls.Config{
  85. RootCAs: CA_Pool,
  86. Certificates: certificates,
  87. ServerName: config.ServerName,
  88. ClientCAs: ClientCA_Pool,
  89. ClientAuth: ClientAuth,
  90. CipherSuites: CipherSuites,
  91. }, nil
  92. }