tlsDialer_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 := 2
  108. if protocol.TLSProfileIsRandomized(tlsProfile) {
  109. repeats = 20
  110. }
  111. success := 0
  112. tlsVersions := []string{}
  113. for i := 0; i < repeats; i++ {
  114. transformHostname := i%2 == 0
  115. tlsConfig := &CustomTLSConfig{
  116. ClientParameters: clientParameters,
  117. Dial: dialer,
  118. SkipVerify: true,
  119. TLSProfile: tlsProfile,
  120. }
  121. if transformHostname {
  122. tlsConfig.SNIServerName = values.GetHostName()
  123. } else {
  124. tlsConfig.UseDialAddrSNI = true
  125. }
  126. ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
  127. conn, err := CustomTLSDial(ctx, "tcp", address, tlsConfig)
  128. if err != nil {
  129. t.Logf("%s (transformHostname: %v): %s\n",
  130. tlsProfile, transformHostname, err)
  131. } else {
  132. tlsVersion := ""
  133. version := conn.(*utls.UConn).ConnectionState().Version
  134. if version == utls.VersionTLS12 {
  135. tlsVersion = "TLS 1.2"
  136. } else if version == utls.VersionTLS13 {
  137. tlsVersion = "TLS 1.3"
  138. } else {
  139. t.Fatalf("Unexpected TLS version: %v", version)
  140. }
  141. if !common.Contains(tlsVersions, tlsVersion) {
  142. tlsVersions = append(tlsVersions, tlsVersion)
  143. }
  144. conn.Close()
  145. success += 1
  146. }
  147. cancelFunc()
  148. time.Sleep(100 * time.Millisecond)
  149. }
  150. result := fmt.Sprintf(
  151. "%s: %d/%d successful; negotiated TLS versions: %v\n",
  152. tlsProfile, success, repeats, tlsVersions)
  153. if success == repeats {
  154. t.Logf(result)
  155. } else {
  156. t.Errorf(result)
  157. }
  158. }
  159. }
  160. func TestSelectTLSProfile(t *testing.T) {
  161. clientParameters := makeCustomTLSProfilesClientParameters(t, false, "")
  162. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  163. profiles = append(profiles, clientParameters.Get().CustomTLSProfileNames()...)
  164. selected := make(map[string]int)
  165. numSelections := 10000
  166. for i := 0; i < numSelections; i++ {
  167. profile := SelectTLSProfile(false, false, "", clientParameters.Get())
  168. selected[profile] += 1
  169. }
  170. // All TLS profiles should be selected at least once.
  171. for _, profile := range profiles {
  172. if selected[profile] < 1 {
  173. t.Errorf("TLS profile %s not selected", profile)
  174. }
  175. }
  176. // Only expected profiles should be selected
  177. if len(selected) != len(profiles) {
  178. t.Errorf("unexpected TLS profile selected")
  179. }
  180. // Randomized TLS profiles should be selected with expected probability.
  181. numRandomized := 0
  182. for profile, n := range selected {
  183. if protocol.TLSProfileIsRandomized(profile) {
  184. numRandomized += n
  185. }
  186. }
  187. t.Logf("ratio of randomized selected: %d/%d",
  188. numRandomized, numSelections)
  189. randomizedProbability := clientParameters.Get().Float(
  190. parameters.SelectRandomizedTLSProfileProbability)
  191. if numRandomized < int(0.9*float64(numSelections)*randomizedProbability) ||
  192. numRandomized > int(1.1*float64(numSelections)*randomizedProbability) {
  193. t.Error("Unexpected ratio")
  194. }
  195. // getUTLSClientHelloID should map each TLS profile to a utls ClientHelloID.
  196. for i, profile := range profiles {
  197. utlsClientHelloID, utlsClientHelloSpec, err :=
  198. getUTLSClientHelloID(clientParameters.Get(), profile)
  199. if err != nil {
  200. t.Fatalf("getUTLSClientHelloID failed: %s\n", err)
  201. }
  202. var unexpectedClientHelloID, unexpectedClientHelloSpec bool
  203. if i < len(protocol.SupportedTLSProfiles) {
  204. if utlsClientHelloID == utls.HelloCustom {
  205. unexpectedClientHelloID = true
  206. }
  207. if utlsClientHelloSpec != nil {
  208. unexpectedClientHelloSpec = true
  209. }
  210. } else {
  211. if utlsClientHelloID != utls.HelloCustom {
  212. unexpectedClientHelloID = true
  213. }
  214. if utlsClientHelloSpec == nil {
  215. unexpectedClientHelloSpec = true
  216. }
  217. }
  218. if unexpectedClientHelloID {
  219. t.Errorf("Unexpected ClientHelloID for TLS profile %s", profile)
  220. }
  221. if unexpectedClientHelloSpec {
  222. t.Errorf("Unexpected ClientHelloSpec for TLS profile %s", profile)
  223. }
  224. }
  225. // Only custom TLS profiles should be selected
  226. clientParameters = makeCustomTLSProfilesClientParameters(t, true, "")
  227. customTLSProfileNames := clientParameters.Get().CustomTLSProfileNames()
  228. for i := 0; i < numSelections; i++ {
  229. profile := SelectTLSProfile(false, false, "", clientParameters.Get())
  230. if !common.Contains(customTLSProfileNames, profile) {
  231. t.Errorf("unexpected non-custom TLS profile selected")
  232. }
  233. }
  234. // Disabled TLS profiles should not be selected
  235. frontingProviderID := "frontingProviderID"
  236. clientParameters = makeCustomTLSProfilesClientParameters(t, false, frontingProviderID)
  237. disableTLSProfiles := clientParameters.Get().LabeledTLSProfiles(
  238. parameters.DisableFrontingProviderTLSProfiles, frontingProviderID)
  239. if len(disableTLSProfiles) < 1 {
  240. t.Errorf("unexpected disabled TLS profiles count")
  241. }
  242. for i := 0; i < numSelections; i++ {
  243. profile := SelectTLSProfile(false, true, frontingProviderID, clientParameters.Get())
  244. if common.Contains(disableTLSProfiles, profile) {
  245. t.Errorf("unexpected disabled TLS profile selected")
  246. }
  247. }
  248. // Session ticket incapable TLS 1.2 profiles should not be selected
  249. for i := 0; i < numSelections; i++ {
  250. profile := SelectTLSProfile(true, false, "", clientParameters.Get())
  251. if protocol.TLS12ProfileOmitsSessionTickets(profile) {
  252. t.Errorf("unexpected session ticket incapable TLS profile selected")
  253. }
  254. }
  255. }
  256. func BenchmarkRandomizedGetClientHelloVersion(b *testing.B) {
  257. for n := 0; n < b.N; n++ {
  258. utlsClientHelloID := utls.HelloRandomized
  259. utlsClientHelloID.Seed, _ = utls.NewPRNGSeed()
  260. getClientHelloVersion(utlsClientHelloID, nil)
  261. }
  262. }
  263. func makeCustomTLSProfilesClientParameters(
  264. t *testing.T, useOnlyCustomTLSProfiles bool, frontingProviderID string) *parameters.ClientParameters {
  265. clientParameters, err := parameters.NewClientParameters(nil)
  266. if err != nil {
  267. t.Fatalf("NewClientParameters failed: %s\n", err)
  268. }
  269. // Equivilent to utls.HelloChrome_62
  270. customTLSProfilesJSON := []byte(`
  271. [
  272. {
  273. "Name": "CustomProfile",
  274. "UTLSSpec": {
  275. "TLSVersMax": 771,
  276. "TLSVersMin": 769,
  277. "CipherSuites": [2570, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157, 47, 53, 10],
  278. "CompressionMethods": [0],
  279. "Extensions" : [
  280. {"Name": "GREASE"},
  281. {"Name": "SNI"},
  282. {"Name": "ExtendedMasterSecret"},
  283. {"Name": "SessionTicket"},
  284. {"Name": "SignatureAlgorithms", "Data": {"SupportedSignatureAlgorithms": [1027, 2052, 1025, 1283, 2053, 1281, 2054, 1537, 513]}},
  285. {"Name": "StatusRequest"},
  286. {"Name": "SCT"},
  287. {"Name": "ALPN", "Data": {"AlpnProtocols": ["h2", "http/1.1"]}},
  288. {"Name": "ChannelID"},
  289. {"Name": "SupportedPoints", "Data": {"SupportedPoints": [0]}},
  290. {"Name": "SupportedCurves", "Data": {"Curves": [2570, 29, 23, 24]}},
  291. {"Name": "BoringPadding"},
  292. {"Name": "GREASE"}],
  293. "GetSessionID": "SHA-256"
  294. }
  295. }
  296. ]`)
  297. var customTLSProfiles protocol.CustomTLSProfiles
  298. err = json.Unmarshal(customTLSProfilesJSON, &customTLSProfiles)
  299. if err != nil {
  300. t.Fatalf("Unmarshal failed: %s", err)
  301. }
  302. applyParameters := make(map[string]interface{})
  303. applyParameters[parameters.UseOnlyCustomTLSProfiles] = useOnlyCustomTLSProfiles
  304. applyParameters[parameters.CustomTLSProfiles] = customTLSProfiles
  305. if frontingProviderID != "" {
  306. tlsProfiles := make(protocol.TLSProfiles, 0)
  307. tlsProfiles = append(tlsProfiles, "CustomProfile")
  308. for i, tlsProfile := range protocol.SupportedTLSProfiles {
  309. if i%2 == 0 {
  310. tlsProfiles = append(tlsProfiles, tlsProfile)
  311. }
  312. }
  313. disabledTLSProfiles := make(protocol.LabeledTLSProfiles)
  314. disabledTLSProfiles[frontingProviderID] = tlsProfiles
  315. applyParameters[parameters.DisableFrontingProviderTLSProfiles] = disabledTLSProfiles
  316. }
  317. _, err = clientParameters.Set("", false, applyParameters)
  318. if err != nil {
  319. t.Fatalf("Set failed: %s", err)
  320. }
  321. customTLSProfileNames := clientParameters.Get().CustomTLSProfileNames()
  322. if len(customTLSProfileNames) != 1 {
  323. t.Fatalf("Unexpected CustomTLSProfileNames count")
  324. }
  325. return clientParameters
  326. }