tlsDialer_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. "crypto/rand"
  23. "crypto/rsa"
  24. "crypto/sha256"
  25. "crypto/tls"
  26. "crypto/x509"
  27. "crypto/x509/pkix"
  28. "encoding/base64"
  29. "encoding/json"
  30. "encoding/pem"
  31. "fmt"
  32. "io/ioutil"
  33. "math/big"
  34. "net"
  35. "net/http"
  36. "os"
  37. "path/filepath"
  38. "strings"
  39. "sync"
  40. "testing"
  41. "time"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  46. tris "github.com/Psiphon-Labs/tls-tris"
  47. utls "github.com/Psiphon-Labs/utls"
  48. )
  49. func TestTLSCertificateVerification(t *testing.T) {
  50. testDataDirName, err := ioutil.TempDir("", "psiphon-tls-certificate-verification-test")
  51. if err != nil {
  52. t.Fatalf("TempDir failed: %v", err)
  53. }
  54. defer os.RemoveAll(testDataDirName)
  55. serverName := "example.org"
  56. rootCAsFileName,
  57. rootCACertificatePin,
  58. serverCertificatePin,
  59. shutdown,
  60. serverAddr,
  61. dialer := initTestCertificatesAndWebServer(
  62. t, testDataDirName, serverName)
  63. defer shutdown()
  64. // Test: without custom RootCAs, the TLS dial fails.
  65. params, err := parameters.NewParameters(nil)
  66. if err != nil {
  67. t.Fatalf("parameters.NewParameters failed: %v", err)
  68. }
  69. conn, err := CustomTLSDial(
  70. context.Background(), "tcp", serverAddr,
  71. &CustomTLSConfig{
  72. Parameters: params,
  73. Dial: dialer,
  74. })
  75. if err == nil {
  76. conn.Close()
  77. t.Errorf("unexpected success without custom RootCAs")
  78. }
  79. // Test: without custom RootCAs and with SkipVerify, the TLS dial succeeds.
  80. conn, err = CustomTLSDial(
  81. context.Background(), "tcp", serverAddr,
  82. &CustomTLSConfig{
  83. Parameters: params,
  84. Dial: dialer,
  85. SkipVerify: true,
  86. })
  87. if err != nil {
  88. t.Errorf("CustomTLSDial failed: %v", err)
  89. } else {
  90. conn.Close()
  91. }
  92. // Test: with custom RootCAs, the TLS dial succeeds.
  93. conn, err = CustomTLSDial(
  94. context.Background(), "tcp", serverAddr,
  95. &CustomTLSConfig{
  96. Parameters: params,
  97. Dial: dialer,
  98. TrustedCACertificatesFilename: rootCAsFileName,
  99. })
  100. if err != nil {
  101. t.Errorf("CustomTLSDial failed: %v", err)
  102. } else {
  103. conn.Close()
  104. }
  105. // Test: with SNI changed and VerifyServerName set, the TLS dial succeeds.
  106. conn, err = CustomTLSDial(
  107. context.Background(), "tcp", serverAddr,
  108. &CustomTLSConfig{
  109. Parameters: params,
  110. Dial: dialer,
  111. SNIServerName: "not-" + serverName,
  112. VerifyServerName: serverName,
  113. TrustedCACertificatesFilename: rootCAsFileName,
  114. })
  115. if err != nil {
  116. t.Errorf("CustomTLSDial failed: %v", err)
  117. } else {
  118. conn.Close()
  119. }
  120. // Test: with an invalid pin, the TLS dial fails.
  121. invalidPin := base64.StdEncoding.EncodeToString(make([]byte, 32))
  122. conn, err = CustomTLSDial(
  123. context.Background(), "tcp", serverAddr,
  124. &CustomTLSConfig{
  125. Parameters: params,
  126. Dial: dialer,
  127. VerifyPins: []string{invalidPin},
  128. TrustedCACertificatesFilename: rootCAsFileName,
  129. })
  130. if err == nil {
  131. conn.Close()
  132. t.Errorf("unexpected success without invalid pin")
  133. }
  134. // Test: with the root CA certirficate pinned, the TLS dial succeeds.
  135. conn, err = CustomTLSDial(
  136. context.Background(), "tcp", serverAddr,
  137. &CustomTLSConfig{
  138. Parameters: params,
  139. Dial: dialer,
  140. VerifyPins: []string{rootCACertificatePin},
  141. TrustedCACertificatesFilename: rootCAsFileName,
  142. })
  143. if err != nil {
  144. t.Errorf("CustomTLSDial failed: %v", err)
  145. } else {
  146. conn.Close()
  147. }
  148. // Test: with the server certificate pinned, the TLS dial succeeds.
  149. conn, err = CustomTLSDial(
  150. context.Background(), "tcp", serverAddr,
  151. &CustomTLSConfig{
  152. Parameters: params,
  153. Dial: dialer,
  154. VerifyPins: []string{serverCertificatePin},
  155. TrustedCACertificatesFilename: rootCAsFileName,
  156. })
  157. if err != nil {
  158. t.Errorf("CustomTLSDial failed: %v", err)
  159. } else {
  160. conn.Close()
  161. }
  162. // Test: with SNI changed, VerifyServerName set, and pinning the TLS dial
  163. // succeeds.
  164. conn, err = CustomTLSDial(
  165. context.Background(), "tcp", serverAddr,
  166. &CustomTLSConfig{
  167. Parameters: params,
  168. Dial: dialer,
  169. SNIServerName: "not-" + serverName,
  170. VerifyServerName: serverName,
  171. VerifyPins: []string{rootCACertificatePin},
  172. TrustedCACertificatesFilename: rootCAsFileName,
  173. })
  174. if err != nil {
  175. t.Errorf("CustomTLSDial failed: %v", err)
  176. } else {
  177. conn.Close()
  178. }
  179. }
  180. // initTestCertificatesAndWebServer creates a Root CA, a web server
  181. // certificate, for serverName, signed by that Root CA, and runs a web server
  182. // that uses that server certificate. initRootCAandWebServer returns:
  183. //
  184. // - the file name containing the Root CA, to be used with
  185. // CustomTLSConfig.TrustedCACertificatesFilename
  186. //
  187. // - pin values for the Root CA and server certificare, to be used with
  188. // CustomTLSConfig.VerifyPins
  189. //
  190. // - a shutdown function which the caller must invoked to terminate the web
  191. // server
  192. //
  193. // - the web server dial address: serverName and port
  194. //
  195. // - and a dialer function, which bypasses DNS resolution of serverName, to be
  196. // used with CustomTLSConfig.Dial
  197. func initTestCertificatesAndWebServer(
  198. t *testing.T,
  199. testDataDirName string,
  200. serverName string) (string, string, string, func(), string, common.Dialer) {
  201. // Generate a root CA certificate.
  202. rootCACertificate := &x509.Certificate{
  203. SerialNumber: big.NewInt(1),
  204. Subject: pkix.Name{
  205. Organization: []string{"test"},
  206. },
  207. NotBefore: time.Now(),
  208. NotAfter: time.Now().AddDate(1, 0, 0),
  209. IsCA: true,
  210. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  211. KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
  212. BasicConstraintsValid: true,
  213. }
  214. rootCAPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
  215. if err != nil {
  216. t.Fatalf("rsa.GenerateKey failed: %v", err)
  217. }
  218. rootCACertificateBytes, err := x509.CreateCertificate(
  219. rand.Reader,
  220. rootCACertificate,
  221. rootCACertificate,
  222. &rootCAPrivateKey.PublicKey,
  223. rootCAPrivateKey)
  224. if err != nil {
  225. t.Fatalf("x509.CreateCertificate failed: %v", err)
  226. }
  227. pemRootCACertificate := pem.EncodeToMemory(
  228. &pem.Block{
  229. Type: "CERTIFICATE",
  230. Bytes: rootCACertificateBytes,
  231. })
  232. // Generate a server certificate.
  233. serverCertificate := &x509.Certificate{
  234. SerialNumber: big.NewInt(2),
  235. Subject: pkix.Name{
  236. Organization: []string{"test"},
  237. },
  238. DNSNames: []string{serverName},
  239. NotBefore: time.Now(),
  240. NotAfter: time.Now().AddDate(1, 0, 0),
  241. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  242. KeyUsage: x509.KeyUsageDigitalSignature,
  243. }
  244. serverPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
  245. if err != nil {
  246. t.Fatalf("rsa.GenerateKey failed: %v", err)
  247. }
  248. serverCertificateBytes, err := x509.CreateCertificate(
  249. rand.Reader,
  250. serverCertificate,
  251. rootCACertificate,
  252. &serverPrivateKey.PublicKey,
  253. rootCAPrivateKey)
  254. if err != nil {
  255. t.Fatalf("x509.CreateCertificate failed: %v", err)
  256. }
  257. pemServerCertificate := pem.EncodeToMemory(
  258. &pem.Block{
  259. Type: "CERTIFICATE",
  260. Bytes: serverCertificateBytes,
  261. })
  262. pemServerPrivateKey := pem.EncodeToMemory(
  263. &pem.Block{
  264. Type: "RSA PRIVATE KEY",
  265. Bytes: x509.MarshalPKCS1PrivateKey(serverPrivateKey),
  266. })
  267. // Pave Root CA file.
  268. rootCAsFileName := filepath.Join(testDataDirName, "RootCAs.pem")
  269. err = ioutil.WriteFile(rootCAsFileName, pemRootCACertificate, 0600)
  270. if err != nil {
  271. t.Fatalf("WriteFile failed: %v", err)
  272. }
  273. // Calculate certificate pins.
  274. parsedCertificate, err := x509.ParseCertificate(rootCACertificateBytes)
  275. if err != nil {
  276. t.Fatalf("x509.ParseCertificate failed: %v", err)
  277. }
  278. publicKeyDigest := sha256.Sum256(parsedCertificate.RawSubjectPublicKeyInfo)
  279. rootCACertificatePin := base64.StdEncoding.EncodeToString(publicKeyDigest[:])
  280. parsedCertificate, err = x509.ParseCertificate(serverCertificateBytes)
  281. if err != nil {
  282. t.Fatalf("x509.ParseCertificate failed: %v", err)
  283. }
  284. publicKeyDigest = sha256.Sum256(parsedCertificate.RawSubjectPublicKeyInfo)
  285. serverCertificatePin := base64.StdEncoding.EncodeToString(publicKeyDigest[:])
  286. // Run an HTTPS server with the server certificate.
  287. serverKeyPair, err := tls.X509KeyPair(
  288. pemServerCertificate, pemServerPrivateKey)
  289. if err != nil {
  290. t.Fatalf("tls.X509KeyPair failed: %v", err)
  291. }
  292. mux := http.NewServeMux()
  293. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  294. w.Write([]byte("test"))
  295. })
  296. server := &http.Server{
  297. Handler: mux,
  298. }
  299. listener, err := net.Listen("tcp", "127.0.0.1:0")
  300. if err != nil {
  301. t.Fatalf("net.Listen failed: %v", err)
  302. }
  303. dialAddr := listener.Addr().String()
  304. _, port, _ := net.SplitHostPort(dialAddr)
  305. serverAddr := fmt.Sprintf("%s:%s", serverName, port)
  306. listener = tls.NewListener(
  307. listener,
  308. &tls.Config{
  309. Certificates: []tls.Certificate{serverKeyPair},
  310. })
  311. var wg sync.WaitGroup
  312. wg.Add(1)
  313. go func() {
  314. wg.Done()
  315. server.Serve(listener)
  316. }()
  317. shutdown := func() {
  318. listener.Close()
  319. server.Shutdown(context.Background())
  320. wg.Wait()
  321. }
  322. // Initialize a custom dialer for the client which bypasses DNS resolution.
  323. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  324. d := &net.Dialer{}
  325. // Ignore the address input, which will be serverAddr, and dial dialAddr, as
  326. // if the serverName in serverAddr had been resolved to "127.0.0.1".
  327. return d.DialContext(ctx, network, dialAddr)
  328. }
  329. return rootCAsFileName,
  330. rootCACertificatePin,
  331. serverCertificatePin,
  332. shutdown,
  333. serverAddr,
  334. dialer
  335. }
  336. func TestTLSDialerCompatibility(t *testing.T) {
  337. // This test checks that each TLS profile can successfully complete a TLS
  338. // handshake with various servers. By default, only the "psiphon" case is
  339. // run, which runs the same TLS listener used by a Psiphon server.
  340. //
  341. // An optional config file, when supplied, enables testing against remote
  342. // servers. Config should be newline delimited list of domain/IP:port TLS
  343. // host addresses to connect to.
  344. var configAddresses []string
  345. config, err := ioutil.ReadFile("tlsDialerCompatibility_test.config")
  346. if err == nil {
  347. configAddresses = strings.Split(string(config), "\n")
  348. }
  349. runner := func(address string) func(t *testing.T) {
  350. return func(t *testing.T) {
  351. testTLSDialerCompatibility(t, address)
  352. }
  353. }
  354. for _, address := range configAddresses {
  355. if len(address) > 0 {
  356. t.Run(address, runner(address))
  357. }
  358. }
  359. t.Run("psiphon", runner(""))
  360. }
  361. func testTLSDialerCompatibility(t *testing.T, address string) {
  362. if address == "" {
  363. // Same tls-tris config as psiphon/server/meek.go
  364. certificate, privateKey, err := common.GenerateWebServerCertificate(values.GetHostName())
  365. if err != nil {
  366. t.Fatalf("common.GenerateWebServerCertificate failed: %v", err)
  367. }
  368. tlsCertificate, err := tris.X509KeyPair([]byte(certificate), []byte(privateKey))
  369. if err != nil {
  370. t.Fatalf("tris.X509KeyPair failed: %v", err)
  371. }
  372. config := &tris.Config{
  373. Certificates: []tris.Certificate{tlsCertificate},
  374. NextProtos: []string{"http/1.1"},
  375. MinVersion: tris.VersionTLS10,
  376. UseExtendedMasterSecret: true,
  377. }
  378. tcpListener, err := net.Listen("tcp", "127.0.0.1:0")
  379. if err != nil {
  380. t.Fatalf("net.Listen failed: %v", err)
  381. }
  382. tlsListener := tris.NewListener(tcpListener, config)
  383. defer tlsListener.Close()
  384. address = tlsListener.Addr().String()
  385. go func() {
  386. for {
  387. conn, err := tlsListener.Accept()
  388. if err != nil {
  389. return
  390. }
  391. err = conn.(*tris.Conn).Handshake()
  392. if err != nil {
  393. t.Logf("tris.Conn.Handshake failed: %v", err)
  394. }
  395. conn.Close()
  396. }
  397. }()
  398. }
  399. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  400. d := &net.Dialer{}
  401. return d.DialContext(ctx, network, address)
  402. }
  403. params := makeCustomTLSProfilesParameters(t, false, "")
  404. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  405. profiles = append(profiles, params.Get().CustomTLSProfileNames()...)
  406. for _, tlsProfile := range profiles {
  407. repeats := 2
  408. if protocol.TLSProfileIsRandomized(tlsProfile) {
  409. repeats = 20
  410. }
  411. success := 0
  412. tlsVersions := []string{}
  413. for i := 0; i < repeats; i++ {
  414. transformHostname := i%2 == 0
  415. tlsConfig := &CustomTLSConfig{
  416. Parameters: params,
  417. Dial: dialer,
  418. SkipVerify: true,
  419. TLSProfile: tlsProfile,
  420. }
  421. if transformHostname {
  422. tlsConfig.SNIServerName = values.GetHostName()
  423. } else {
  424. tlsConfig.UseDialAddrSNI = true
  425. }
  426. ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
  427. conn, err := CustomTLSDial(ctx, "tcp", address, tlsConfig)
  428. if err != nil {
  429. t.Logf("CustomTLSDial failed: %s (transformHostname: %v): %v",
  430. tlsProfile, transformHostname, err)
  431. } else {
  432. tlsVersion := ""
  433. version := conn.(*utls.UConn).ConnectionState().Version
  434. if version == utls.VersionTLS12 {
  435. tlsVersion = "TLS 1.2"
  436. } else if version == utls.VersionTLS13 {
  437. tlsVersion = "TLS 1.3"
  438. } else {
  439. t.Fatalf("Unexpected TLS version: %v", version)
  440. }
  441. if !common.Contains(tlsVersions, tlsVersion) {
  442. tlsVersions = append(tlsVersions, tlsVersion)
  443. }
  444. conn.Close()
  445. success += 1
  446. }
  447. cancelFunc()
  448. time.Sleep(100 * time.Millisecond)
  449. }
  450. result := fmt.Sprintf(
  451. "%s: %d/%d successful; negotiated TLS versions: %v",
  452. tlsProfile, success, repeats, tlsVersions)
  453. if success == repeats {
  454. t.Logf(result)
  455. } else {
  456. t.Errorf(result)
  457. }
  458. }
  459. }
  460. func TestSelectTLSProfile(t *testing.T) {
  461. params := makeCustomTLSProfilesParameters(t, false, "")
  462. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  463. profiles = append(profiles, params.Get().CustomTLSProfileNames()...)
  464. selected := make(map[string]int)
  465. numSelections := 10000
  466. for i := 0; i < numSelections; i++ {
  467. profile := SelectTLSProfile(false, false, "", params.Get())
  468. selected[profile] += 1
  469. }
  470. // All TLS profiles should be selected at least once.
  471. for _, profile := range profiles {
  472. if selected[profile] < 1 {
  473. t.Errorf("TLS profile %s not selected", profile)
  474. }
  475. }
  476. // Only expected profiles should be selected
  477. if len(selected) != len(profiles) {
  478. t.Errorf("unexpected TLS profile selected")
  479. }
  480. // Randomized TLS profiles should be selected with expected probability.
  481. numRandomized := 0
  482. for profile, n := range selected {
  483. if protocol.TLSProfileIsRandomized(profile) {
  484. numRandomized += n
  485. }
  486. }
  487. t.Logf("ratio of randomized selected: %d/%d",
  488. numRandomized, numSelections)
  489. randomizedProbability := params.Get().Float(
  490. parameters.SelectRandomizedTLSProfileProbability)
  491. if numRandomized < int(0.9*float64(numSelections)*randomizedProbability) ||
  492. numRandomized > int(1.1*float64(numSelections)*randomizedProbability) {
  493. t.Error("Unexpected ratio")
  494. }
  495. // getUTLSClientHelloID should map each TLS profile to a utls ClientHelloID.
  496. for i, profile := range profiles {
  497. utlsClientHelloID, utlsClientHelloSpec, err :=
  498. getUTLSClientHelloID(params.Get(), profile)
  499. if err != nil {
  500. t.Fatalf("getUTLSClientHelloID failed: %v", err)
  501. }
  502. var unexpectedClientHelloID, unexpectedClientHelloSpec bool
  503. if i < len(protocol.SupportedTLSProfiles) {
  504. if utlsClientHelloID == utls.HelloCustom {
  505. unexpectedClientHelloID = true
  506. }
  507. if utlsClientHelloSpec != nil {
  508. unexpectedClientHelloSpec = true
  509. }
  510. } else {
  511. if utlsClientHelloID != utls.HelloCustom {
  512. unexpectedClientHelloID = true
  513. }
  514. if utlsClientHelloSpec == nil {
  515. unexpectedClientHelloSpec = true
  516. }
  517. }
  518. if unexpectedClientHelloID {
  519. t.Errorf("Unexpected ClientHelloID for TLS profile %s", profile)
  520. }
  521. if unexpectedClientHelloSpec {
  522. t.Errorf("Unexpected ClientHelloSpec for TLS profile %s", profile)
  523. }
  524. }
  525. // Only custom TLS profiles should be selected
  526. params = makeCustomTLSProfilesParameters(t, true, "")
  527. customTLSProfileNames := params.Get().CustomTLSProfileNames()
  528. for i := 0; i < numSelections; i++ {
  529. profile := SelectTLSProfile(false, false, "", params.Get())
  530. if !common.Contains(customTLSProfileNames, profile) {
  531. t.Errorf("unexpected non-custom TLS profile selected")
  532. }
  533. }
  534. // Disabled TLS profiles should not be selected
  535. frontingProviderID := "frontingProviderID"
  536. params = makeCustomTLSProfilesParameters(t, false, frontingProviderID)
  537. disableTLSProfiles := params.Get().LabeledTLSProfiles(
  538. parameters.DisableFrontingProviderTLSProfiles, frontingProviderID)
  539. if len(disableTLSProfiles) < 1 {
  540. t.Errorf("unexpected disabled TLS profiles count")
  541. }
  542. for i := 0; i < numSelections; i++ {
  543. profile := SelectTLSProfile(false, true, frontingProviderID, params.Get())
  544. if common.Contains(disableTLSProfiles, profile) {
  545. t.Errorf("unexpected disabled TLS profile selected")
  546. }
  547. }
  548. // Session ticket incapable TLS 1.2 profiles should not be selected
  549. for i := 0; i < numSelections; i++ {
  550. profile := SelectTLSProfile(true, false, "", params.Get())
  551. if protocol.TLS12ProfileOmitsSessionTickets(profile) {
  552. t.Errorf("unexpected session ticket incapable TLS profile selected")
  553. }
  554. }
  555. }
  556. func BenchmarkRandomizedGetClientHelloVersion(b *testing.B) {
  557. for n := 0; n < b.N; n++ {
  558. utlsClientHelloID := utls.HelloRandomized
  559. utlsClientHelloID.Seed, _ = utls.NewPRNGSeed()
  560. getClientHelloVersion(utlsClientHelloID, nil)
  561. }
  562. }
  563. func makeCustomTLSProfilesParameters(
  564. t *testing.T, useOnlyCustomTLSProfiles bool, frontingProviderID string) *parameters.Parameters {
  565. params, err := parameters.NewParameters(nil)
  566. if err != nil {
  567. t.Fatalf("NewParameters failed: %v", err)
  568. }
  569. // Equivilent to utls.HelloChrome_62
  570. customTLSProfilesJSON := []byte(`
  571. [
  572. {
  573. "Name": "CustomProfile",
  574. "UTLSSpec": {
  575. "TLSVersMax": 771,
  576. "TLSVersMin": 769,
  577. "CipherSuites": [2570, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157, 47, 53, 10],
  578. "CompressionMethods": [0],
  579. "Extensions" : [
  580. {"Name": "GREASE"},
  581. {"Name": "SNI"},
  582. {"Name": "ExtendedMasterSecret"},
  583. {"Name": "SessionTicket"},
  584. {"Name": "SignatureAlgorithms", "Data": {"SupportedSignatureAlgorithms": [1027, 2052, 1025, 1283, 2053, 1281, 2054, 1537, 513]}},
  585. {"Name": "StatusRequest"},
  586. {"Name": "SCT"},
  587. {"Name": "ALPN", "Data": {"AlpnProtocols": ["h2", "http/1.1"]}},
  588. {"Name": "ChannelID"},
  589. {"Name": "SupportedPoints", "Data": {"SupportedPoints": [0]}},
  590. {"Name": "SupportedCurves", "Data": {"Curves": [2570, 29, 23, 24]}},
  591. {"Name": "BoringPadding"},
  592. {"Name": "GREASE"}],
  593. "GetSessionID": "SHA-256"
  594. }
  595. }
  596. ]`)
  597. var customTLSProfiles protocol.CustomTLSProfiles
  598. err = json.Unmarshal(customTLSProfilesJSON, &customTLSProfiles)
  599. if err != nil {
  600. t.Fatalf("Unmarshal failed: %v", err)
  601. }
  602. applyParameters := make(map[string]interface{})
  603. applyParameters[parameters.UseOnlyCustomTLSProfiles] = useOnlyCustomTLSProfiles
  604. applyParameters[parameters.CustomTLSProfiles] = customTLSProfiles
  605. if frontingProviderID != "" {
  606. tlsProfiles := make(protocol.TLSProfiles, 0)
  607. tlsProfiles = append(tlsProfiles, "CustomProfile")
  608. for i, tlsProfile := range protocol.SupportedTLSProfiles {
  609. if i%2 == 0 {
  610. tlsProfiles = append(tlsProfiles, tlsProfile)
  611. }
  612. }
  613. disabledTLSProfiles := make(protocol.LabeledTLSProfiles)
  614. disabledTLSProfiles[frontingProviderID] = tlsProfiles
  615. applyParameters[parameters.DisableFrontingProviderTLSProfiles] = disabledTLSProfiles
  616. }
  617. _, err = params.Set("", false, applyParameters)
  618. if err != nil {
  619. t.Fatalf("Set failed: %v", err)
  620. }
  621. customTLSProfileNames := params.Get().CustomTLSProfileNames()
  622. if len(customTLSProfileNames) != 1 {
  623. t.Fatalf("Unexpected CustomTLSProfileNames count")
  624. }
  625. return params
  626. }