tls.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package inbound
  2. import (
  3. "crypto/tls"
  4. "os"
  5. "github.com/sagernet/sing-box/option"
  6. E "github.com/sagernet/sing/common/exceptions"
  7. )
  8. func NewTLSConfig(options option.InboundTLSOptions) (*tls.Config, error) {
  9. if !options.Enabled {
  10. return nil, nil
  11. }
  12. var tlsConfig tls.Config
  13. if options.ServerName != "" {
  14. tlsConfig.ServerName = options.ServerName
  15. }
  16. if len(options.ALPN) > 0 {
  17. tlsConfig.NextProtos = options.ALPN
  18. }
  19. if options.MinVersion != "" {
  20. minVersion, err := option.ParseTLSVersion(options.MinVersion)
  21. if err != nil {
  22. return nil, E.Cause(err, "parse min_version")
  23. }
  24. tlsConfig.MinVersion = minVersion
  25. }
  26. if options.MaxVersion != "" {
  27. maxVersion, err := option.ParseTLSVersion(options.MaxVersion)
  28. if err != nil {
  29. return nil, E.Cause(err, "parse max_version")
  30. }
  31. tlsConfig.MaxVersion = maxVersion
  32. }
  33. if options.CipherSuites != nil {
  34. find:
  35. for _, cipherSuite := range options.CipherSuites {
  36. for _, tlsCipherSuite := range tls.CipherSuites() {
  37. if cipherSuite == tlsCipherSuite.Name {
  38. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  39. continue find
  40. }
  41. }
  42. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  43. }
  44. }
  45. var certificate []byte
  46. if options.Certificate != "" {
  47. certificate = []byte(options.Certificate)
  48. } else if options.CertificatePath != "" {
  49. content, err := os.ReadFile(options.CertificatePath)
  50. if err != nil {
  51. return nil, E.Cause(err, "read certificate")
  52. }
  53. certificate = content
  54. }
  55. var key []byte
  56. if options.Key != "" {
  57. key = []byte(options.Key)
  58. } else if options.KeyPath != "" {
  59. content, err := os.ReadFile(options.KeyPath)
  60. if err != nil {
  61. return nil, E.Cause(err, "read key")
  62. }
  63. key = content
  64. }
  65. if certificate == nil {
  66. return nil, E.New("missing certificate")
  67. }
  68. if key == nil {
  69. return nil, E.New("missing key")
  70. }
  71. keyPair, err := tls.X509KeyPair(certificate, key)
  72. if err != nil {
  73. return nil, E.Cause(err, "parse x509 key pair")
  74. }
  75. tlsConfig.Certificates = []tls.Certificate{keyPair}
  76. return &tlsConfig, nil
  77. }