std_client.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package tls
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "net"
  10. "os"
  11. "strings"
  12. "time"
  13. "github.com/sagernet/sing-box/adapter"
  14. "github.com/sagernet/sing-box/common/tlsfragment"
  15. "github.com/sagernet/sing-box/common/tlsspoof"
  16. C "github.com/sagernet/sing-box/constant"
  17. "github.com/sagernet/sing-box/option"
  18. E "github.com/sagernet/sing/common/exceptions"
  19. "github.com/sagernet/sing/common/logger"
  20. "github.com/sagernet/sing/common/ntp"
  21. )
  22. type STDClientConfig struct {
  23. ctx context.Context
  24. config *tls.Config
  25. serverName string
  26. disableSNI bool
  27. verifyServerName bool
  28. handshakeTimeout time.Duration
  29. fragment bool
  30. fragmentFallbackDelay time.Duration
  31. recordFragment bool
  32. spoof string
  33. spoofMethod tlsspoof.Method
  34. }
  35. func (c *STDClientConfig) ServerName() string {
  36. return c.serverName
  37. }
  38. func (c *STDClientConfig) SetServerName(serverName string) {
  39. c.serverName = serverName
  40. if c.disableSNI {
  41. c.config.ServerName = ""
  42. if c.verifyServerName {
  43. c.config.VerifyConnection = verifyConnection(c.config.RootCAs, c.config.Time, serverName)
  44. } else {
  45. c.config.VerifyConnection = nil
  46. }
  47. return
  48. }
  49. c.config.ServerName = serverName
  50. }
  51. func (c *STDClientConfig) NextProtos() []string {
  52. return c.config.NextProtos
  53. }
  54. func (c *STDClientConfig) SetNextProtos(nextProto []string) {
  55. c.config.NextProtos = nextProto
  56. }
  57. func (c *STDClientConfig) HandshakeTimeout() time.Duration {
  58. return c.handshakeTimeout
  59. }
  60. func (c *STDClientConfig) SetHandshakeTimeout(timeout time.Duration) {
  61. c.handshakeTimeout = timeout
  62. }
  63. func (c *STDClientConfig) STDConfig() (*STDConfig, error) {
  64. return c.config, nil
  65. }
  66. func (c *STDClientConfig) Client(conn net.Conn) (Conn, error) {
  67. if c.fragment || c.recordFragment {
  68. conn = tf.NewConn(conn, c.ctx, c.fragment, c.recordFragment, c.fragmentFallbackDelay)
  69. }
  70. conn, err := applyTLSSpoof(conn, c.spoof, c.spoofMethod)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return tls.Client(conn, c.config), nil
  75. }
  76. func (c *STDClientConfig) Clone() Config {
  77. cloned := &STDClientConfig{
  78. ctx: c.ctx,
  79. config: c.config.Clone(),
  80. serverName: c.serverName,
  81. disableSNI: c.disableSNI,
  82. verifyServerName: c.verifyServerName,
  83. handshakeTimeout: c.handshakeTimeout,
  84. fragment: c.fragment,
  85. fragmentFallbackDelay: c.fragmentFallbackDelay,
  86. recordFragment: c.recordFragment,
  87. spoof: c.spoof,
  88. spoofMethod: c.spoofMethod,
  89. }
  90. cloned.SetServerName(cloned.serverName)
  91. return cloned
  92. }
  93. func (c *STDClientConfig) ECHConfigList() []byte {
  94. return c.config.EncryptedClientHelloConfigList
  95. }
  96. func (c *STDClientConfig) SetECHConfigList(EncryptedClientHelloConfigList []byte) {
  97. c.config.EncryptedClientHelloConfigList = EncryptedClientHelloConfigList
  98. }
  99. func NewSTDClient(ctx context.Context, logger logger.ContextLogger, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
  100. return newSTDClient(ctx, logger, serverAddress, options, false)
  101. }
  102. func newSTDClient(ctx context.Context, logger logger.ContextLogger, serverAddress string, options option.OutboundTLSOptions, allowEmptyServerName bool) (Config, error) {
  103. var serverName string
  104. if options.ServerName != "" {
  105. serverName = options.ServerName
  106. } else if serverAddress != "" {
  107. serverName = serverAddress
  108. }
  109. if serverName == "" && !options.Insecure && !allowEmptyServerName {
  110. return nil, errMissingServerName
  111. }
  112. var tlsConfig tls.Config
  113. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  114. tlsConfig.RootCAs = adapter.RootPoolFromContext(ctx)
  115. if options.Insecure {
  116. tlsConfig.InsecureSkipVerify = options.Insecure
  117. } else if options.DisableSNI {
  118. tlsConfig.InsecureSkipVerify = true
  119. }
  120. if len(options.CertificatePublicKeySHA256) > 0 {
  121. if len(options.Certificate) > 0 || options.CertificatePath != "" {
  122. return nil, E.New("certificate_public_key_sha256 is conflict with certificate or certificate_path")
  123. }
  124. tlsConfig.InsecureSkipVerify = true
  125. tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  126. return VerifyPublicKeySHA256(options.CertificatePublicKeySHA256, rawCerts)
  127. }
  128. }
  129. if len(options.ALPN) > 0 {
  130. tlsConfig.NextProtos = options.ALPN
  131. }
  132. if options.MinVersion != "" {
  133. minVersion, err := ParseTLSVersion(options.MinVersion)
  134. if err != nil {
  135. return nil, E.Cause(err, "parse min_version")
  136. }
  137. tlsConfig.MinVersion = minVersion
  138. }
  139. if options.MaxVersion != "" {
  140. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  141. if err != nil {
  142. return nil, E.Cause(err, "parse max_version")
  143. }
  144. tlsConfig.MaxVersion = maxVersion
  145. }
  146. if options.CipherSuites != nil {
  147. find:
  148. for _, cipherSuite := range options.CipherSuites {
  149. for _, tlsCipherSuite := range tls.CipherSuites() {
  150. if cipherSuite == tlsCipherSuite.Name {
  151. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  152. continue find
  153. }
  154. }
  155. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  156. }
  157. }
  158. for _, curve := range options.CurvePreferences {
  159. tlsConfig.CurvePreferences = append(tlsConfig.CurvePreferences, tls.CurveID(curve))
  160. }
  161. var certificate []byte
  162. if len(options.Certificate) > 0 {
  163. certificate = []byte(strings.Join(options.Certificate, "\n"))
  164. } else if options.CertificatePath != "" {
  165. content, err := os.ReadFile(options.CertificatePath)
  166. if err != nil {
  167. return nil, E.Cause(err, "read certificate")
  168. }
  169. certificate = content
  170. }
  171. if len(certificate) > 0 {
  172. certPool := x509.NewCertPool()
  173. if !certPool.AppendCertsFromPEM(certificate) {
  174. return nil, E.New("failed to parse certificate:\n\n", certificate)
  175. }
  176. tlsConfig.RootCAs = certPool
  177. }
  178. var clientCertificate []byte
  179. if len(options.ClientCertificate) > 0 {
  180. clientCertificate = []byte(strings.Join(options.ClientCertificate, "\n"))
  181. } else if options.ClientCertificatePath != "" {
  182. content, err := os.ReadFile(options.ClientCertificatePath)
  183. if err != nil {
  184. return nil, E.Cause(err, "read client certificate")
  185. }
  186. clientCertificate = content
  187. }
  188. var clientKey []byte
  189. if len(options.ClientKey) > 0 {
  190. clientKey = []byte(strings.Join(options.ClientKey, "\n"))
  191. } else if options.ClientKeyPath != "" {
  192. content, err := os.ReadFile(options.ClientKeyPath)
  193. if err != nil {
  194. return nil, E.Cause(err, "read client key")
  195. }
  196. clientKey = content
  197. }
  198. if len(clientCertificate) > 0 && len(clientKey) > 0 {
  199. keyPair, err := tls.X509KeyPair(clientCertificate, clientKey)
  200. if err != nil {
  201. return nil, E.Cause(err, "parse client x509 key pair")
  202. }
  203. tlsConfig.Certificates = []tls.Certificate{keyPair}
  204. } else if len(clientCertificate) > 0 || len(clientKey) > 0 {
  205. return nil, E.New("client certificate and client key must be provided together")
  206. }
  207. var handshakeTimeout time.Duration
  208. if options.HandshakeTimeout > 0 {
  209. handshakeTimeout = options.HandshakeTimeout.Build()
  210. } else {
  211. handshakeTimeout = C.TCPTimeout
  212. }
  213. spoof, spoofMethod, err := parseTLSSpoofOptions(serverName, options)
  214. if err != nil {
  215. return nil, err
  216. }
  217. var config Config = &STDClientConfig{
  218. ctx: ctx,
  219. config: &tlsConfig,
  220. serverName: serverName,
  221. disableSNI: options.DisableSNI,
  222. verifyServerName: options.DisableSNI && !options.Insecure,
  223. handshakeTimeout: handshakeTimeout,
  224. fragment: options.Fragment,
  225. fragmentFallbackDelay: time.Duration(options.FragmentFallbackDelay),
  226. recordFragment: options.RecordFragment,
  227. spoof: spoof,
  228. spoofMethod: spoofMethod,
  229. }
  230. config.SetServerName(serverName)
  231. if options.ECH != nil && options.ECH.Enabled {
  232. var err error
  233. config, err = parseECHClientConfig(ctx, config.(ECHCapableConfig), options)
  234. if err != nil {
  235. return nil, err
  236. }
  237. }
  238. if options.KernelRx || options.KernelTx {
  239. if !C.IsLinux {
  240. return nil, E.New("kTLS is only supported on Linux")
  241. }
  242. config = &KTLSClientConfig{
  243. Config: config,
  244. logger: logger,
  245. kernelTx: options.KernelTx,
  246. kernelRx: options.KernelRx,
  247. }
  248. }
  249. return config, nil
  250. }
  251. func verifyConnection(rootCAs *x509.CertPool, timeFunc func() time.Time, serverName string) func(state tls.ConnectionState) error {
  252. return func(state tls.ConnectionState) error {
  253. if serverName == "" {
  254. return errMissingServerName
  255. }
  256. verifyOptions := x509.VerifyOptions{
  257. Roots: rootCAs,
  258. DNSName: serverName,
  259. Intermediates: x509.NewCertPool(),
  260. }
  261. for _, cert := range state.PeerCertificates[1:] {
  262. verifyOptions.Intermediates.AddCert(cert)
  263. }
  264. if timeFunc != nil {
  265. verifyOptions.CurrentTime = timeFunc()
  266. }
  267. _, err := state.PeerCertificates[0].Verify(verifyOptions)
  268. return err
  269. }
  270. }
  271. func VerifyPublicKeySHA256(knownHashValues [][]byte, rawCerts [][]byte) error {
  272. leafCertificate, err := x509.ParseCertificate(rawCerts[0])
  273. if err != nil {
  274. return E.Cause(err, "failed to parse leaf certificate")
  275. }
  276. pubKeyBytes, err := x509.MarshalPKIXPublicKey(leafCertificate.PublicKey)
  277. if err != nil {
  278. return E.Cause(err, "failed to marshal public key")
  279. }
  280. hashValue := sha256.Sum256(pubKeyBytes)
  281. for _, value := range knownHashValues {
  282. if bytes.Equal(value, hashValue[:]) {
  283. return nil
  284. }
  285. }
  286. return E.New("unrecognized remote public key: ", base64.StdEncoding.EncodeToString(hashValue[:]))
  287. }