tlsTunnel.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "crypto/rand"
  22. "encoding/hex"
  23. std_errors "errors"
  24. "net"
  25. tls "github.com/Psiphon-Labs/psiphon-tls"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  32. )
  33. // TLSTunnelServer tunnels TCP traffic (in the case of Psiphon, Obfuscated SSH
  34. // traffic) over TLS.
  35. type TLSTunnelServer struct {
  36. support *SupportServices
  37. listener net.Listener
  38. listenerTunnelProtocol string
  39. listenerPort int
  40. passthroughAddress string
  41. tlsConfig *tls.Config
  42. obfuscatorSeedHistory *obfuscator.SeedHistory
  43. }
  44. // ListenTLSTunnel returns the listener of a new TLSTunnelServer.
  45. // Note: the first Read or Write call on a connection returned by the listener
  46. // will trigger the underlying TLS handshake.
  47. func ListenTLSTunnel(
  48. support *SupportServices,
  49. listener net.Listener,
  50. listenerTunnelProtocol string,
  51. listenerPort int,
  52. ) (net.Listener, error) {
  53. server, err := NewTLSTunnelServer(support, listener, listenerTunnelProtocol, listenerPort)
  54. if err != nil {
  55. return nil, errors.Trace(err)
  56. }
  57. listener = tls.NewListener(server.listener, server.tlsConfig)
  58. return NewTLSTunnelListener(listener, server), nil
  59. }
  60. // NewTLSTunnelServer initializes a new TLSTunnelServer.
  61. func NewTLSTunnelServer(
  62. support *SupportServices,
  63. listener net.Listener,
  64. listenerTunnelProtocol string,
  65. listenerPort int) (*TLSTunnelServer, error) {
  66. passthroughAddress := support.Config.TunnelProtocolPassthroughAddresses[listenerTunnelProtocol]
  67. tlsServer := &TLSTunnelServer{
  68. support: support,
  69. listener: listener,
  70. listenerTunnelProtocol: listenerTunnelProtocol,
  71. listenerPort: listenerPort,
  72. passthroughAddress: passthroughAddress,
  73. obfuscatorSeedHistory: obfuscator.NewSeedHistory(nil),
  74. }
  75. tlsConfig, err := tlsServer.makeTLSTunnelConfig(support.Config.MeekObfuscatedKey)
  76. if err != nil {
  77. return nil, errors.Trace(err)
  78. }
  79. tlsServer.tlsConfig = tlsConfig
  80. return tlsServer, nil
  81. }
  82. // makeTLSTunnelConfig creates a TLS config for a TLSTunnelServer listener.
  83. func (server *TLSTunnelServer) makeTLSTunnelConfig(sessionTicketKey string) (*tls.Config, error) {
  84. // Limitation: certificate value changes on restart.
  85. certificate, privateKey, _, err := common.GenerateWebServerCertificate(values.GetHostName())
  86. if err != nil {
  87. return nil, errors.Trace(err)
  88. }
  89. tlsCertificate, err := tls.X509KeyPair(
  90. []byte(certificate), []byte(privateKey))
  91. if err != nil {
  92. return nil, errors.Trace(err)
  93. }
  94. var minVersion uint16
  95. if protocol.TunnelProtocolUsesTLSOSSH(server.listenerTunnelProtocol) {
  96. // Use min TLS 1.3 so cert is not plaintext on the wire.
  97. minVersion = tls.VersionTLS13
  98. } else {
  99. // Need to support older TLS versions for backwards compatibility.
  100. // Vary the minimum version to frustrate scanning/fingerprinting of unfronted servers.
  101. // Limitation: like the certificate, this value changes on restart.
  102. minVersionCandidates := []uint16{tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12}
  103. minVersion = minVersionCandidates[prng.Intn(len(minVersionCandidates))]
  104. }
  105. config := &tls.Config{
  106. Certificates: []tls.Certificate{tlsCertificate},
  107. NextProtos: []string{"http/1.1"},
  108. MinVersion: minVersion,
  109. }
  110. if sessionTicketKey != "" {
  111. // See obfuscated session ticket overview
  112. // in NewObfuscatedClientSessionState.
  113. config.UseObfuscatedSessionTickets = true
  114. var obfuscatedSessionTicketKey [32]byte
  115. key, err := hex.DecodeString(server.support.Config.MeekObfuscatedKey)
  116. if err == nil && len(key) != 32 {
  117. err = std_errors.New("invalid obfuscated session key length")
  118. }
  119. if err != nil {
  120. return nil, errors.Trace(err)
  121. }
  122. copy(obfuscatedSessionTicketKey[:], key)
  123. var standardSessionTicketKey [32]byte
  124. _, err = rand.Read(standardSessionTicketKey[:])
  125. if err != nil {
  126. return nil, errors.Trace(err)
  127. }
  128. config.SessionTicketKey = obfuscatedSessionTicketKey
  129. config.SetSessionTicketKeys([][32]byte{
  130. standardSessionTicketKey,
  131. obfuscatedSessionTicketKey})
  132. }
  133. // When configured, initialize passthrough mode, an anti-probing defense.
  134. // Clients must prove knowledge of the obfuscated key via a message sent in
  135. // the TLS ClientHello random field.
  136. //
  137. // When clients fail to provide a valid message, the client connection is
  138. // relayed to the designated passthrough address, typically another web site.
  139. // The entire flow is relayed, including the original ClientHello, so the
  140. // client will perform a TLS handshake with the passthrough target.
  141. //
  142. // Irregular events are logged for invalid client activity.
  143. if server.passthroughAddress != "" {
  144. config.PassthroughAddress = server.passthroughAddress
  145. config.PassthroughVerifyMessage = func(
  146. message []byte) bool {
  147. return obfuscator.VerifyTLSPassthroughMessage(
  148. true,
  149. // Meek obfuscated key used for legacy reasons. See comment for
  150. // MeekObfuscatedKey.
  151. server.support.Config.MeekObfuscatedKey,
  152. message)
  153. }
  154. config.PassthroughLogInvalidMessage = func(
  155. clientIP string) {
  156. logIrregularTunnel(
  157. server.support,
  158. server.listenerTunnelProtocol,
  159. server.listenerPort,
  160. clientIP,
  161. errors.TraceNew("invalid passthrough message"),
  162. nil)
  163. }
  164. config.PassthroughHistoryAddNew = func(
  165. clientIP string,
  166. clientRandom []byte) bool {
  167. // Use a custom, shorter TTL based on the validity period of the
  168. // passthrough message.
  169. TTL := obfuscator.TLS_PASSTHROUGH_TIME_PERIOD
  170. // strictMode is true as legitimate clients never retry TLS
  171. // connections using a previous random value.
  172. strictMode := true
  173. ok, logFields := server.obfuscatorSeedHistory.AddNewWithTTL(
  174. strictMode,
  175. clientIP,
  176. "client-random",
  177. clientRandom,
  178. TTL)
  179. if logFields != nil {
  180. logIrregularTunnel(
  181. server.support,
  182. server.listenerTunnelProtocol,
  183. server.listenerPort,
  184. clientIP,
  185. errors.TraceNew("duplicate passthrough message"),
  186. LogFields(*logFields))
  187. }
  188. return ok
  189. }
  190. }
  191. return config, nil
  192. }
  193. // TLSTunnelListener implements the net.Listener interface. Accept returns a
  194. // net.Conn which implements the common.MetricsSource interface.
  195. type TLSTunnelListener struct {
  196. net.Listener
  197. server *TLSTunnelServer
  198. }
  199. // NewTLSTunnelListener initializes a new TLSTunnelListener.
  200. func NewTLSTunnelListener(listener net.Listener, server *TLSTunnelServer) *TLSTunnelListener {
  201. return &TLSTunnelListener{
  202. Listener: listener,
  203. server: server,
  204. }
  205. }
  206. func (l *TLSTunnelListener) Accept() (net.Conn, error) {
  207. conn, err := l.Listener.Accept()
  208. if err != nil {
  209. return nil, errors.Trace(err)
  210. }
  211. return NewTLSTunnelConn(conn, l.server), nil
  212. }
  213. // TLSTunnelConn implements the net.Conn and common.MetricsSource interfaces.
  214. type TLSTunnelConn struct {
  215. net.Conn
  216. server *TLSTunnelServer
  217. }
  218. // NewTLSTunnelConn initializes a new TLSTunnelConn.
  219. func NewTLSTunnelConn(conn net.Conn, server *TLSTunnelServer) *TLSTunnelConn {
  220. return &TLSTunnelConn{
  221. Conn: conn,
  222. server: server,
  223. }
  224. }
  225. // GetMetrics implements the common.MetricsSource interface.
  226. func (conn *TLSTunnelConn) GetMetrics() common.LogFields {
  227. var logFields common.LogFields
  228. // Relay any metrics from the underlying conn.
  229. if m, ok := conn.Conn.(common.MetricsSource); ok {
  230. logFields = m.GetMetrics()
  231. } else {
  232. logFields = make(common.LogFields)
  233. }
  234. if conn.server.passthroughAddress != "" {
  235. logFields["passthrough_address"] = conn.server.passthroughAddress
  236. }
  237. return logFields
  238. }