tlsDialer_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright (c) 2019, 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 psiphon
  20. import (
  21. "context"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. "net"
  26. "strings"
  27. "testing"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  33. tris "github.com/Psiphon-Labs/tls-tris"
  34. utls "github.com/refraction-networking/utls"
  35. )
  36. func TestTLSDialerCompatibility(t *testing.T) {
  37. // This test checks that each TLS profile can successfully complete a TLS
  38. // handshake with various servers. By default, only the "psiphon" case is
  39. // run, which runs the same TLS listener used by a Psiphon server.
  40. //
  41. // An optional config file, when supplied, enables testing against remote
  42. // servers. Config should be newline delimited list of domain/IP:port TLS
  43. // host addresses to connect to.
  44. var configAddresses []string
  45. config, err := ioutil.ReadFile("tlsDialerCompatibility_test.config")
  46. if err == nil {
  47. configAddresses = strings.Split(string(config), "\n")
  48. }
  49. runner := func(address string) func(t *testing.T) {
  50. return func(t *testing.T) {
  51. testTLSDialerCompatibility(t, address)
  52. }
  53. }
  54. for _, address := range configAddresses {
  55. if len(address) > 0 {
  56. t.Run(address, runner(address))
  57. }
  58. }
  59. t.Run("psiphon", runner(""))
  60. }
  61. func testTLSDialerCompatibility(t *testing.T, address string) {
  62. if address == "" {
  63. // Same tls-tris config as psiphon/server/meek.go
  64. certificate, privateKey, err := common.GenerateWebServerCertificate(values.GetHostName())
  65. if err != nil {
  66. t.Fatalf("%s\n", err)
  67. }
  68. tlsCertificate, err := tris.X509KeyPair([]byte(certificate), []byte(privateKey))
  69. if err != nil {
  70. t.Fatalf("%s\n", err)
  71. }
  72. config := &tris.Config{
  73. Certificates: []tris.Certificate{tlsCertificate},
  74. NextProtos: []string{"http/1.1"},
  75. MinVersion: tris.VersionTLS10,
  76. UseExtendedMasterSecret: true,
  77. }
  78. tcpListener, err := net.Listen("tcp", "127.0.0.1:0")
  79. if err != nil {
  80. t.Fatalf("%s\n", err)
  81. }
  82. tlsListener := tris.NewListener(tcpListener, config)
  83. defer tlsListener.Close()
  84. address = tlsListener.Addr().String()
  85. go func() {
  86. for {
  87. conn, err := tlsListener.Accept()
  88. if err != nil {
  89. return
  90. }
  91. err = conn.(*tris.Conn).Handshake()
  92. if err != nil {
  93. t.Logf("server handshake: %s", err)
  94. }
  95. conn.Close()
  96. }
  97. }()
  98. }
  99. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  100. d := &net.Dialer{}
  101. return d.DialContext(ctx, network, address)
  102. }
  103. clientParameters := makeCustomTLSProfilesClientParameters(t, false)
  104. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  105. profiles = append(profiles, clientParameters.Get().CustomTLSProfileNames()...)
  106. for _, tlsProfile := range profiles {
  107. repeats := 1
  108. if protocol.TLSProfileIsRandomized(tlsProfile) {
  109. repeats = 20
  110. }
  111. success := 0
  112. for i := 0; i < repeats; i++ {
  113. tlsConfig := &CustomTLSConfig{
  114. ClientParameters: clientParameters,
  115. Dial: dialer,
  116. UseDialAddrSNI: true,
  117. SkipVerify: true,
  118. TLSProfile: tlsProfile,
  119. }
  120. ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
  121. conn, err := CustomTLSDial(ctx, "tcp", address, tlsConfig)
  122. if err != nil {
  123. t.Logf("%s: %s\n", tlsProfile, err)
  124. } else {
  125. conn.Close()
  126. success += 1
  127. }
  128. cancelFunc()
  129. time.Sleep(100 * time.Millisecond)
  130. }
  131. result := fmt.Sprintf("%s: %d/%d successful\n", tlsProfile, success, repeats)
  132. if success == repeats {
  133. t.Logf(result)
  134. } else {
  135. t.Errorf(result)
  136. }
  137. }
  138. }
  139. func TestSelectTLSProfile(t *testing.T) {
  140. clientParameters := makeCustomTLSProfilesClientParameters(t, false)
  141. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  142. profiles = append(profiles, clientParameters.Get().CustomTLSProfileNames()...)
  143. selected := make(map[string]int)
  144. numSelections := 10000
  145. for i := 0; i < numSelections; i++ {
  146. profile := SelectTLSProfile(clientParameters.Get())
  147. selected[profile] += 1
  148. }
  149. // All TLS profiles should be selected at least once.
  150. for _, profile := range profiles {
  151. if selected[profile] < 1 {
  152. t.Errorf("TLS profile %s not selected", profile)
  153. }
  154. }
  155. // Only expected profiles should be selected
  156. if len(selected) != len(profiles) {
  157. t.Errorf("unexpected TLS profile selected")
  158. }
  159. // Randomized TLS profiles should be selected with expected probability.
  160. numRandomized := 0
  161. for profile, n := range selected {
  162. if protocol.TLSProfileIsRandomized(profile) {
  163. numRandomized += n
  164. }
  165. }
  166. t.Logf("ratio of randomized selected: %d/%d",
  167. numRandomized, numSelections)
  168. randomizedProbability := clientParameters.Get().Float(
  169. parameters.SelectRandomizedTLSProfileProbability)
  170. if numRandomized < int(0.9*float64(numSelections)*randomizedProbability) ||
  171. numRandomized > int(1.1*float64(numSelections)*randomizedProbability) {
  172. t.Error("Unexpected ratio")
  173. }
  174. // getUTLSClientHelloID should map each TLS profile to a utls ClientHelloID.
  175. for i, profile := range profiles {
  176. utlsClientHelloID, utlsClientHelloSpec, err :=
  177. getUTLSClientHelloID(clientParameters.Get(), profile)
  178. if err != nil {
  179. t.Fatalf("getUTLSClientHelloID failed: %s\n", err)
  180. }
  181. var unexpectedClientHelloID, unexpectedClientHelloSpec bool
  182. if i < len(protocol.SupportedTLSProfiles) {
  183. if utlsClientHelloID == utls.HelloCustom {
  184. unexpectedClientHelloID = true
  185. }
  186. if utlsClientHelloSpec != nil {
  187. unexpectedClientHelloSpec = true
  188. }
  189. } else {
  190. if utlsClientHelloID != utls.HelloCustom {
  191. unexpectedClientHelloID = true
  192. }
  193. if utlsClientHelloSpec == nil {
  194. unexpectedClientHelloSpec = true
  195. }
  196. }
  197. if unexpectedClientHelloID {
  198. t.Errorf("Unexpected ClientHelloID for TLS profile %s", profile)
  199. }
  200. if unexpectedClientHelloSpec {
  201. t.Errorf("Unexpected ClientHelloSpec for TLS profile %s", profile)
  202. }
  203. }
  204. // Only custom TLS profiles should be selected
  205. clientParameters = makeCustomTLSProfilesClientParameters(t, true)
  206. customTLSProfileNames := clientParameters.Get().CustomTLSProfileNames()
  207. for i := 0; i < numSelections; i++ {
  208. profile := SelectTLSProfile(clientParameters.Get())
  209. if !common.Contains(customTLSProfileNames, profile) {
  210. t.Errorf("unexpected non-custom TLS profile selected")
  211. }
  212. }
  213. }
  214. func BenchmarkRandomizedGetClientHelloVersion(b *testing.B) {
  215. for n := 0; n < b.N; n++ {
  216. utlsClientHelloID := utls.HelloRandomized
  217. utlsClientHelloID.Seed, _ = utls.NewPRNGSeed()
  218. getClientHelloVersion(utlsClientHelloID, nil)
  219. }
  220. }
  221. func makeCustomTLSProfilesClientParameters(
  222. t *testing.T, useOnlyCustomTLSProfiles bool) *parameters.ClientParameters {
  223. clientParameters, err := parameters.NewClientParameters(nil)
  224. if err != nil {
  225. t.Fatalf("NewClientParameters failed: %s\n", err)
  226. }
  227. // Equivilent to utls.HelloChrome_62
  228. customTLSProfilesJSON := []byte(`
  229. [
  230. {
  231. "Name": "CustomProfile",
  232. "UTLSSpec": {
  233. "TLSVersMax": 771,
  234. "TLSVersMin": 769,
  235. "CipherSuites": [2570, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157, 47, 53, 10],
  236. "CompressionMethods": [0],
  237. "Extensions" : [
  238. {"Name": "GREASE"},
  239. {"Name": "SNI"},
  240. {"Name": "ExtendedMasterSecret"},
  241. {"Name": "SessionTicket"},
  242. {"Name": "SignatureAlgorithms", "Data": {"SupportedSignatureAlgorithms": [1027, 2052, 1025, 1283, 2053, 1281, 2054, 1537, 513]}},
  243. {"Name": "StatusRequest"},
  244. {"Name": "SCT"},
  245. {"Name": "ALPN", "Data": {"AlpnProtocols": ["h2", "http/1.1"]}},
  246. {"Name": "ChannelID"},
  247. {"Name": "SupportedPoints", "Data": {"SupportedPoints": [0]}},
  248. {"Name": "SupportedCurves", "Data": {"Curves": [2570, 29, 23, 24]}},
  249. {"Name": "BoringPadding"},
  250. {"Name": "GREASE"}],
  251. "GetSessionID": "SHA-256"
  252. }
  253. }
  254. ]`)
  255. var customTLSProfiles protocol.CustomTLSProfiles
  256. err = json.Unmarshal(customTLSProfilesJSON, &customTLSProfiles)
  257. if err != nil {
  258. t.Fatalf("Unmarshal failed: %s", err)
  259. }
  260. applyParameters := make(map[string]interface{})
  261. applyParameters[parameters.UseOnlyCustomTLSProfiles] = useOnlyCustomTLSProfiles
  262. applyParameters[parameters.CustomTLSProfiles] = customTLSProfiles
  263. _, err = clientParameters.Set("", false, applyParameters)
  264. if err != nil {
  265. t.Fatalf("Set failed: %s", err)
  266. }
  267. customTLSProfileNames := clientParameters.Get().CustomTLSProfileNames()
  268. if len(customTLSProfileNames) != 1 {
  269. t.Fatalf("Unexpected CustomTLSProfileNames count")
  270. }
  271. return clientParameters
  272. }