tls.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package tls
  2. import (
  3. "crypto/tls"
  4. utls "github.com/refraction-networking/utls"
  5. "github.com/xtls/xray-core/common/buf"
  6. "github.com/xtls/xray-core/common/net"
  7. )
  8. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  9. var _ buf.Writer = (*Conn)(nil)
  10. type Conn struct {
  11. *tls.Conn
  12. }
  13. func (c *Conn) WriteMultiBuffer(mb buf.MultiBuffer) error {
  14. mb = buf.Compact(mb)
  15. mb, err := buf.WriteMultiBuffer(c, mb)
  16. buf.ReleaseMulti(mb)
  17. return err
  18. }
  19. func (c *Conn) HandshakeAddress() net.Address {
  20. if err := c.Handshake(); err != nil {
  21. return nil
  22. }
  23. state := c.ConnectionState()
  24. if state.ServerName == "" {
  25. return nil
  26. }
  27. return net.ParseAddress(state.ServerName)
  28. }
  29. func (c *Conn) NegotiatedProtocol() (name string, mutual bool) {
  30. state := c.ConnectionState()
  31. return state.NegotiatedProtocol, state.NegotiatedProtocolIsMutual
  32. }
  33. // Client initiates a TLS client handshake on the given connection.
  34. func Client(c net.Conn, config *tls.Config) net.Conn {
  35. tlsConn := tls.Client(c, config)
  36. return &Conn{Conn: tlsConn}
  37. }
  38. // Server initiates a TLS server handshake on the given connection.
  39. func Server(c net.Conn, config *tls.Config) net.Conn {
  40. tlsConn := tls.Server(c, config)
  41. return &Conn{Conn: tlsConn}
  42. }
  43. type UConn struct {
  44. *utls.UConn
  45. }
  46. func (c *UConn) HandshakeAddress() net.Address {
  47. if err := c.Handshake(); err != nil {
  48. return nil
  49. }
  50. state := c.ConnectionState()
  51. if state.ServerName == "" {
  52. return nil
  53. }
  54. return net.ParseAddress(state.ServerName)
  55. }
  56. func (c *UConn) NegotiatedProtocol() (name string, mutual bool) {
  57. state := c.ConnectionState()
  58. return state.NegotiatedProtocol, state.NegotiatedProtocolIsMutual
  59. }
  60. func UClient(c net.Conn, config *tls.Config, fingerprint *utls.ClientHelloID) net.Conn {
  61. utlsConn := utls.UClient(c, copyConfig(config), *fingerprint)
  62. return &UConn{UConn: utlsConn}
  63. }
  64. func copyConfig(c *tls.Config) *utls.Config {
  65. return &utls.Config{
  66. RootCAs: c.RootCAs,
  67. ServerName: c.ServerName,
  68. InsecureSkipVerify: c.InsecureSkipVerify,
  69. }
  70. }
  71. var Fingerprints = map[string]*utls.ClientHelloID{
  72. "chrome": &utls.HelloChrome_Auto,
  73. "firefox": &utls.HelloFirefox_Auto,
  74. "safari": &utls.HelloIOS_Auto,
  75. "randomized": &utls.HelloRandomized,
  76. }
  77. type Interface interface {
  78. net.Conn
  79. Handshake() error
  80. VerifyHostname(host string) error
  81. NegotiatedProtocol() (name string, mutual bool)
  82. }