tlsDialer_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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/refraction-networking/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 certificate 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. // Test: with DisableSystemRootCAs set and without VerifyServerName or
  180. // VerifyPins set, the TLS dial succeeds.
  181. conn, err = CustomTLSDial(
  182. context.Background(), "tcp", serverAddr,
  183. &CustomTLSConfig{
  184. Parameters: params,
  185. Dial: dialer,
  186. SNIServerName: "not-" + serverName,
  187. DisableSystemRootCAs: true,
  188. })
  189. if err != nil {
  190. t.Errorf("CustomTLSDial failed: %v", err)
  191. } else {
  192. conn.Close()
  193. }
  194. // Test: with DisableSystemRootCAs set along with VerifyServerName and
  195. // VerifyPins, the TLS dial fails.
  196. conn, err = CustomTLSDial(
  197. context.Background(), "tcp", serverAddr,
  198. &CustomTLSConfig{
  199. Parameters: params,
  200. Dial: dialer,
  201. SNIServerName: serverName,
  202. DisableSystemRootCAs: true,
  203. VerifyServerName: serverName,
  204. VerifyPins: []string{rootCACertificatePin},
  205. })
  206. if err == nil {
  207. conn.Close()
  208. t.Errorf("unexpected success with DisableSystemRootCAs set along with VerifyServerName and VerifyPins")
  209. }
  210. // Test: with DisableSystemRootCAs set, SNI changed, and without
  211. // VerifyServerName or VerifyPins set, the TLS dial succeeds.
  212. conn, err = CustomTLSDial(
  213. context.Background(), "tcp", serverAddr,
  214. &CustomTLSConfig{
  215. Parameters: params,
  216. Dial: dialer,
  217. SNIServerName: "not-" + serverName,
  218. DisableSystemRootCAs: true,
  219. })
  220. if err != nil {
  221. t.Errorf("CustomTLSDial failed: %v", err)
  222. } else {
  223. conn.Close()
  224. }
  225. }
  226. // initTestCertificatesAndWebServer creates a Root CA, a web server
  227. // certificate, for serverName, signed by that Root CA, and runs a web server
  228. // that uses that server certificate. initRootCAandWebServer returns:
  229. //
  230. // - the file name containing the Root CA, to be used with
  231. // CustomTLSConfig.TrustedCACertificatesFilename
  232. //
  233. // - pin values for the Root CA and server certificare, to be used with
  234. // CustomTLSConfig.VerifyPins
  235. //
  236. // - a shutdown function which the caller must invoked to terminate the web
  237. // server
  238. //
  239. // - the web server dial address: serverName and port
  240. //
  241. // - and a dialer function, which bypasses DNS resolution of serverName, to be
  242. // used with CustomTLSConfig.Dial
  243. func initTestCertificatesAndWebServer(
  244. t *testing.T,
  245. testDataDirName string,
  246. serverName string) (string, string, string, func(), string, common.Dialer) {
  247. // Generate a root CA certificate.
  248. rootCACertificate := &x509.Certificate{
  249. SerialNumber: big.NewInt(1),
  250. Subject: pkix.Name{
  251. Organization: []string{"test"},
  252. },
  253. NotBefore: time.Now(),
  254. NotAfter: time.Now().AddDate(1, 0, 0),
  255. IsCA: true,
  256. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  257. KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
  258. BasicConstraintsValid: true,
  259. }
  260. rootCAPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
  261. if err != nil {
  262. t.Fatalf("rsa.GenerateKey failed: %v", err)
  263. }
  264. rootCACertificateBytes, err := x509.CreateCertificate(
  265. rand.Reader,
  266. rootCACertificate,
  267. rootCACertificate,
  268. &rootCAPrivateKey.PublicKey,
  269. rootCAPrivateKey)
  270. if err != nil {
  271. t.Fatalf("x509.CreateCertificate failed: %v", err)
  272. }
  273. pemRootCACertificate := pem.EncodeToMemory(
  274. &pem.Block{
  275. Type: "CERTIFICATE",
  276. Bytes: rootCACertificateBytes,
  277. })
  278. // Generate a server certificate.
  279. serverCertificate := &x509.Certificate{
  280. SerialNumber: big.NewInt(2),
  281. Subject: pkix.Name{
  282. Organization: []string{"test"},
  283. },
  284. DNSNames: []string{serverName},
  285. NotBefore: time.Now(),
  286. NotAfter: time.Now().AddDate(1, 0, 0),
  287. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  288. KeyUsage: x509.KeyUsageDigitalSignature,
  289. }
  290. serverPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
  291. if err != nil {
  292. t.Fatalf("rsa.GenerateKey failed: %v", err)
  293. }
  294. serverCertificateBytes, err := x509.CreateCertificate(
  295. rand.Reader,
  296. serverCertificate,
  297. rootCACertificate,
  298. &serverPrivateKey.PublicKey,
  299. rootCAPrivateKey)
  300. if err != nil {
  301. t.Fatalf("x509.CreateCertificate failed: %v", err)
  302. }
  303. pemServerCertificate := pem.EncodeToMemory(
  304. &pem.Block{
  305. Type: "CERTIFICATE",
  306. Bytes: serverCertificateBytes,
  307. })
  308. pemServerPrivateKey := pem.EncodeToMemory(
  309. &pem.Block{
  310. Type: "RSA PRIVATE KEY",
  311. Bytes: x509.MarshalPKCS1PrivateKey(serverPrivateKey),
  312. })
  313. // Pave Root CA file.
  314. rootCAsFileName := filepath.Join(testDataDirName, "RootCAs.pem")
  315. err = ioutil.WriteFile(rootCAsFileName, pemRootCACertificate, 0600)
  316. if err != nil {
  317. t.Fatalf("WriteFile failed: %v", err)
  318. }
  319. // Calculate certificate pins.
  320. parsedCertificate, err := x509.ParseCertificate(rootCACertificateBytes)
  321. if err != nil {
  322. t.Fatalf("x509.ParseCertificate failed: %v", err)
  323. }
  324. publicKeyDigest := sha256.Sum256(parsedCertificate.RawSubjectPublicKeyInfo)
  325. rootCACertificatePin := base64.StdEncoding.EncodeToString(publicKeyDigest[:])
  326. parsedCertificate, err = x509.ParseCertificate(serverCertificateBytes)
  327. if err != nil {
  328. t.Fatalf("x509.ParseCertificate failed: %v", err)
  329. }
  330. publicKeyDigest = sha256.Sum256(parsedCertificate.RawSubjectPublicKeyInfo)
  331. serverCertificatePin := base64.StdEncoding.EncodeToString(publicKeyDigest[:])
  332. // Run an HTTPS server with the server certificate.
  333. // Do not include the Root CA certificate in the certificate chain returned
  334. // by the server to the client in the TLS handshake by excluding it from
  335. // the key pair, which matches the behavior observed in the wild.
  336. serverKeyPair, err := tls.X509KeyPair(
  337. pemServerCertificate, pemServerPrivateKey)
  338. if err != nil {
  339. t.Fatalf("tls.X509KeyPair failed: %v", err)
  340. }
  341. mux := http.NewServeMux()
  342. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  343. w.Write([]byte("test"))
  344. })
  345. server := &http.Server{
  346. Handler: mux,
  347. }
  348. listener, err := net.Listen("tcp", "127.0.0.1:0")
  349. if err != nil {
  350. t.Fatalf("net.Listen failed: %v", err)
  351. }
  352. dialAddr := listener.Addr().String()
  353. _, port, _ := net.SplitHostPort(dialAddr)
  354. serverAddr := fmt.Sprintf("%s:%s", serverName, port)
  355. listener = tls.NewListener(
  356. listener,
  357. &tls.Config{
  358. Certificates: []tls.Certificate{serverKeyPair},
  359. })
  360. var wg sync.WaitGroup
  361. wg.Add(1)
  362. go func() {
  363. wg.Done()
  364. server.Serve(listener)
  365. }()
  366. shutdown := func() {
  367. listener.Close()
  368. server.Shutdown(context.Background())
  369. wg.Wait()
  370. }
  371. // Initialize a custom dialer for the client which bypasses DNS resolution.
  372. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  373. d := &net.Dialer{}
  374. // Ignore the address input, which will be serverAddr, and dial dialAddr, as
  375. // if the serverName in serverAddr had been resolved to "127.0.0.1".
  376. return d.DialContext(ctx, network, dialAddr)
  377. }
  378. return rootCAsFileName,
  379. rootCACertificatePin,
  380. serverCertificatePin,
  381. shutdown,
  382. serverAddr,
  383. dialer
  384. }
  385. func TestTLSDialerCompatibility(t *testing.T) {
  386. // This test checks that each TLS profile in combination with TLS ClientHello
  387. // fragmentation can successfully complete a TLS
  388. // handshake with various servers. By default, only the "psiphon" case is
  389. // run, which runs the same TLS listener used by a Psiphon server.
  390. //
  391. // An optional config file, when supplied, enables testing against remote
  392. // servers. Config should be newline delimited list of domain/IP:port TLS
  393. // host addresses to connect to.
  394. var configAddresses []string
  395. config, err := ioutil.ReadFile("tlsDialerCompatibility_test.config")
  396. if err == nil {
  397. configAddresses = strings.Split(string(config), "\n")
  398. }
  399. runner := func(address string, fragmentClientHello bool) func(t *testing.T) {
  400. return func(t *testing.T) {
  401. testTLSDialerCompatibility(t, address, fragmentClientHello)
  402. }
  403. }
  404. for _, address := range configAddresses {
  405. for _, fragmentClientHello := range []bool{false, true} {
  406. if len(address) > 0 {
  407. t.Run(fmt.Sprintf("%s (fragmentClientHello: %v)", address, fragmentClientHello),
  408. runner(address, fragmentClientHello))
  409. }
  410. }
  411. }
  412. t.Run("psiphon", runner("", false))
  413. }
  414. func testTLSDialerCompatibility(t *testing.T, address string, fragmentClientHello bool) {
  415. if address == "" {
  416. // Same tls-tris config as psiphon/server/meek.go
  417. certificate, privateKey, err := common.GenerateWebServerCertificate(values.GetHostName())
  418. if err != nil {
  419. t.Fatalf("common.GenerateWebServerCertificate failed: %v", err)
  420. }
  421. tlsCertificate, err := tris.X509KeyPair([]byte(certificate), []byte(privateKey))
  422. if err != nil {
  423. t.Fatalf("tris.X509KeyPair failed: %v", err)
  424. }
  425. config := &tris.Config{
  426. Certificates: []tris.Certificate{tlsCertificate},
  427. NextProtos: []string{"http/1.1"},
  428. MinVersion: tris.VersionTLS10,
  429. UseExtendedMasterSecret: true,
  430. }
  431. tcpListener, err := net.Listen("tcp", "127.0.0.1:0")
  432. if err != nil {
  433. t.Fatalf("net.Listen failed: %v", err)
  434. }
  435. tlsListener := tris.NewListener(tcpListener, config)
  436. defer tlsListener.Close()
  437. address = tlsListener.Addr().String()
  438. go func() {
  439. for {
  440. conn, err := tlsListener.Accept()
  441. if err != nil {
  442. return
  443. }
  444. err = conn.(*tris.Conn).Handshake()
  445. if err != nil {
  446. t.Logf("tris.Conn.Handshake failed: %v", err)
  447. }
  448. conn.Close()
  449. }
  450. }()
  451. }
  452. dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
  453. d := &net.Dialer{}
  454. return d.DialContext(ctx, network, address)
  455. }
  456. params := makeCustomTLSProfilesParameters(t, false, "")
  457. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  458. profiles = append(profiles, params.Get().CustomTLSProfileNames()...)
  459. for _, tlsProfile := range profiles {
  460. repeats := 2
  461. if protocol.TLSProfileIsRandomized(tlsProfile) {
  462. repeats = 20
  463. }
  464. success := 0
  465. tlsVersions := []string{}
  466. for i := 0; i < repeats; i++ {
  467. transformHostname := i%2 == 0
  468. tlsConfig := &CustomTLSConfig{
  469. Parameters: params,
  470. Dial: dialer,
  471. SkipVerify: true,
  472. TLSProfile: tlsProfile,
  473. FragmentClientHello: fragmentClientHello,
  474. }
  475. if transformHostname {
  476. tlsConfig.SNIServerName = values.GetHostName()
  477. } else {
  478. tlsConfig.UseDialAddrSNI = true
  479. }
  480. ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
  481. conn, err := CustomTLSDial(ctx, "tcp", address, tlsConfig)
  482. if err != nil {
  483. t.Logf("CustomTLSDial failed: %s (transformHostname: %v): %v",
  484. tlsProfile, transformHostname, err)
  485. } else {
  486. tlsVersion := ""
  487. version := conn.(*utls.UConn).ConnectionState().Version
  488. if version == utls.VersionTLS12 {
  489. tlsVersion = "TLS 1.2"
  490. } else if version == utls.VersionTLS13 {
  491. tlsVersion = "TLS 1.3"
  492. } else {
  493. t.Fatalf("Unexpected TLS version: %v", version)
  494. }
  495. if !common.Contains(tlsVersions, tlsVersion) {
  496. tlsVersions = append(tlsVersions, tlsVersion)
  497. }
  498. conn.Close()
  499. success += 1
  500. }
  501. cancelFunc()
  502. time.Sleep(100 * time.Millisecond)
  503. }
  504. result := fmt.Sprintf(
  505. "%s: %d/%d successful; negotiated TLS versions: %v",
  506. tlsProfile, success, repeats, tlsVersions)
  507. if success == repeats {
  508. t.Logf(result)
  509. } else {
  510. t.Errorf(result)
  511. }
  512. }
  513. }
  514. func TestSelectTLSProfile(t *testing.T) {
  515. params := makeCustomTLSProfilesParameters(t, false, "")
  516. profiles := append([]string(nil), protocol.SupportedTLSProfiles...)
  517. profiles = append(profiles, params.Get().CustomTLSProfileNames()...)
  518. selected := make(map[string]int)
  519. numSelections := 10000
  520. for i := 0; i < numSelections; i++ {
  521. profile, _, seed, err := SelectTLSProfile(false, false, false, "", params.Get())
  522. if err != nil {
  523. t.Fatalf("SelectTLSProfile failed: %v", err)
  524. }
  525. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  526. t.Errorf("expected non-nil seed for randomized TLS profile")
  527. }
  528. selected[profile] += 1
  529. }
  530. // All TLS profiles should be selected at least once.
  531. for _, profile := range profiles {
  532. if selected[profile] < 1 {
  533. t.Errorf("TLS profile %s not selected", profile)
  534. }
  535. }
  536. // Only expected profiles should be selected
  537. if len(selected) != len(profiles) {
  538. t.Errorf("unexpected TLS profile selected")
  539. }
  540. // Randomized TLS profiles should be selected with expected probability.
  541. numRandomized := 0
  542. for profile, n := range selected {
  543. if protocol.TLSProfileIsRandomized(profile) {
  544. numRandomized += n
  545. }
  546. }
  547. t.Logf("ratio of randomized selected: %d/%d",
  548. numRandomized, numSelections)
  549. randomizedProbability := params.Get().Float(
  550. parameters.SelectRandomizedTLSProfileProbability)
  551. if numRandomized < int(0.9*float64(numSelections)*randomizedProbability) ||
  552. numRandomized > int(1.1*float64(numSelections)*randomizedProbability) {
  553. t.Error("Unexpected ratio")
  554. }
  555. // getUTLSClientHelloID should map each TLS profile to a utls ClientHelloID.
  556. for i, profile := range profiles {
  557. utlsClientHelloID, utlsClientHelloSpec, err :=
  558. getUTLSClientHelloID(params.Get(), profile)
  559. if err != nil {
  560. t.Fatalf("getUTLSClientHelloID failed: %v", err)
  561. }
  562. var unexpectedClientHelloID, unexpectedClientHelloSpec bool
  563. // TLS_PROFILE_CHROME_112_PSK profile is a special case. Check getUTLSClientHelloID for details.
  564. if i < len(protocol.SupportedTLSProfiles) && profile != protocol.TLS_PROFILE_CHROME_112_PSK {
  565. if utlsClientHelloID == utls.HelloCustom {
  566. unexpectedClientHelloID = true
  567. }
  568. if utlsClientHelloSpec != nil {
  569. unexpectedClientHelloSpec = true
  570. }
  571. } else {
  572. if utlsClientHelloID != utls.HelloCustom {
  573. unexpectedClientHelloID = true
  574. }
  575. if utlsClientHelloSpec == nil {
  576. unexpectedClientHelloSpec = true
  577. }
  578. }
  579. if unexpectedClientHelloID {
  580. t.Errorf("Unexpected ClientHelloID for TLS profile %s", profile)
  581. }
  582. if unexpectedClientHelloSpec {
  583. t.Errorf("Unexpected ClientHelloSpec for TLS profile %s", profile)
  584. }
  585. }
  586. // Only custom TLS profiles should be selected
  587. params = makeCustomTLSProfilesParameters(t, true, "")
  588. customTLSProfileNames := params.Get().CustomTLSProfileNames()
  589. for i := 0; i < numSelections; i++ {
  590. profile, _, seed, err := SelectTLSProfile(false, false, false, "", params.Get())
  591. if err != nil {
  592. t.Fatalf("SelectTLSProfile failed: %v", err)
  593. }
  594. if !common.Contains(customTLSProfileNames, profile) {
  595. t.Errorf("unexpected non-custom TLS profile selected")
  596. }
  597. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  598. t.Errorf("expected non-nil seed for randomized TLS profile")
  599. }
  600. }
  601. // Disabled TLS profiles should not be selected
  602. frontingProviderID := "frontingProviderID"
  603. params = makeCustomTLSProfilesParameters(t, false, frontingProviderID)
  604. disableTLSProfiles := params.Get().LabeledTLSProfiles(
  605. parameters.DisableFrontingProviderTLSProfiles, frontingProviderID)
  606. if len(disableTLSProfiles) < 1 {
  607. t.Errorf("unexpected disabled TLS profiles count")
  608. }
  609. for i := 0; i < numSelections; i++ {
  610. profile, _, seed, err := SelectTLSProfile(false, false, true, frontingProviderID, params.Get())
  611. if err != nil {
  612. t.Fatalf("SelectTLSProfile failed: %v", err)
  613. }
  614. if common.Contains(disableTLSProfiles, profile) {
  615. t.Errorf("unexpected disabled TLS profile selected")
  616. }
  617. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  618. t.Errorf("expected non-nil seed for randomized TLS profile")
  619. }
  620. }
  621. // Session ticket incapable TLS 1.2 profiles should not be selected
  622. for i := 0; i < numSelections; i++ {
  623. profile, _, seed, err := SelectTLSProfile(true, false, false, "", params.Get())
  624. if err != nil {
  625. t.Fatalf("SelectTLSProfile failed: %v", err)
  626. }
  627. if protocol.TLS12ProfileOmitsSessionTickets(profile) {
  628. t.Errorf("unexpected session ticket incapable TLS profile selected")
  629. }
  630. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  631. t.Errorf("expected non-nil seed for randomized TLS profile")
  632. }
  633. }
  634. // Only TLS 1.3 profiles should be selected
  635. for i := 0; i < numSelections; i++ {
  636. profile, tlsVersion, seed, err := SelectTLSProfile(false, true, false, "", params.Get())
  637. if err != nil {
  638. t.Fatalf("SelectTLSProfile failed: %v", err)
  639. }
  640. if tlsVersion != protocol.TLS_VERSION_13 {
  641. t.Errorf("expected TLS 1.3 profile to be selected")
  642. }
  643. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  644. t.Errorf("expected non-nil seed for randomized TLS profile")
  645. }
  646. }
  647. // Only TLS 1.3 profiles should be selected. All TLS 1.3 profiles should be
  648. // session ticket capable.
  649. for i := 0; i < numSelections; i++ {
  650. profile, tlsVersion, seed, err := SelectTLSProfile(true, true, false, "", params.Get())
  651. if err != nil {
  652. t.Fatalf("SelectTLSProfile failed: %v", err)
  653. }
  654. if protocol.TLS12ProfileOmitsSessionTickets(profile) {
  655. t.Errorf("unexpected session ticket incapable TLS profile selected")
  656. }
  657. if tlsVersion != protocol.TLS_VERSION_13 {
  658. t.Errorf("expected TLS 1.3 profile to be selected")
  659. }
  660. if protocol.TLSProfileIsRandomized(profile) && seed == nil {
  661. t.Errorf("expected non-nil seed for randomized TLS profile")
  662. }
  663. }
  664. }
  665. func TestTLSFragmentorWithoutSNI(t *testing.T) {
  666. testDataDirName, err := ioutil.TempDir("", "psiphon-tls-certificate-verification-test")
  667. if err != nil {
  668. t.Fatalf("TempDir failed: %v", err)
  669. }
  670. defer os.RemoveAll(testDataDirName)
  671. serverName := "example.org"
  672. rootCAsFileName,
  673. _,
  674. serverCertificatePin,
  675. shutdown,
  676. serverAddr,
  677. dialer := initTestCertificatesAndWebServer(
  678. t, testDataDirName, serverName)
  679. defer shutdown()
  680. params, err := parameters.NewParameters(nil)
  681. if err != nil {
  682. t.Fatalf("parameters.NewParameters failed: %v", err)
  683. }
  684. // Test: missing SNI, the TLS dial fails
  685. conn, err := CustomTLSDial(
  686. context.Background(), "tcp", serverAddr,
  687. &CustomTLSConfig{
  688. Parameters: params,
  689. Dial: dialer,
  690. SNIServerName: "",
  691. VerifyServerName: serverName,
  692. VerifyPins: []string{serverCertificatePin},
  693. TrustedCACertificatesFilename: rootCAsFileName,
  694. FragmentClientHello: true,
  695. })
  696. if err == nil {
  697. t.Errorf("unexpected success without SNI")
  698. conn.Close()
  699. }
  700. // Test: with SNI, the TLS dial succeeds
  701. conn, err = CustomTLSDial(
  702. context.Background(), "tcp", serverAddr,
  703. &CustomTLSConfig{
  704. Parameters: params,
  705. Dial: dialer,
  706. SNIServerName: serverName,
  707. VerifyServerName: serverName,
  708. VerifyPins: []string{serverCertificatePin},
  709. TrustedCACertificatesFilename: rootCAsFileName,
  710. FragmentClientHello: true,
  711. })
  712. if err != nil {
  713. t.Errorf("CustomTLSDial failed: %v", err)
  714. } else {
  715. conn.Close()
  716. }
  717. }
  718. func BenchmarkRandomizedGetClientHelloVersion(b *testing.B) {
  719. for n := 0; n < b.N; n++ {
  720. utlsClientHelloID := utls.HelloRandomized
  721. utlsClientHelloID.Seed, _ = utls.NewPRNGSeed()
  722. getClientHelloVersion(utlsClientHelloID, nil)
  723. }
  724. }
  725. func makeCustomTLSProfilesParameters(
  726. t *testing.T, useOnlyCustomTLSProfiles bool, frontingProviderID string) *parameters.Parameters {
  727. params, err := parameters.NewParameters(nil)
  728. if err != nil {
  729. t.Fatalf("NewParameters failed: %v", err)
  730. }
  731. // Equivilent to utls.HelloChrome_62
  732. customTLSProfilesJSON := []byte(`
  733. [
  734. {
  735. "Name": "CustomProfile",
  736. "UTLSSpec": {
  737. "TLSVersMax": 771,
  738. "TLSVersMin": 769,
  739. "CipherSuites": [2570, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157, 47, 53, 10],
  740. "CompressionMethods": [0],
  741. "Extensions" : [
  742. {"Name": "GREASE"},
  743. {"Name": "SNI"},
  744. {"Name": "ExtendedMasterSecret"},
  745. {"Name": "SessionTicket"},
  746. {"Name": "SignatureAlgorithms", "Data": {"SupportedSignatureAlgorithms": [1027, 2052, 1025, 1283, 2053, 1281, 2054, 1537, 513]}},
  747. {"Name": "StatusRequest"},
  748. {"Name": "SCT"},
  749. {"Name": "ALPN", "Data": {"AlpnProtocols": ["h2", "http/1.1"]}},
  750. {"Name": "ChannelID"},
  751. {"Name": "SupportedPoints", "Data": {"SupportedPoints": [0]}},
  752. {"Name": "SupportedCurves", "Data": {"Curves": [2570, 29, 23, 24]}},
  753. {"Name": "BoringPadding"},
  754. {"Name": "GREASE"}],
  755. "GetSessionID": "SHA-256"
  756. }
  757. }
  758. ]`)
  759. var customTLSProfiles protocol.CustomTLSProfiles
  760. err = json.Unmarshal(customTLSProfilesJSON, &customTLSProfiles)
  761. if err != nil {
  762. t.Fatalf("Unmarshal failed: %v", err)
  763. }
  764. applyParameters := make(map[string]interface{})
  765. applyParameters[parameters.UseOnlyCustomTLSProfiles] = useOnlyCustomTLSProfiles
  766. applyParameters[parameters.CustomTLSProfiles] = customTLSProfiles
  767. if frontingProviderID != "" {
  768. tlsProfiles := make(protocol.TLSProfiles, 0)
  769. tlsProfiles = append(tlsProfiles, "CustomProfile")
  770. for i, tlsProfile := range protocol.SupportedTLSProfiles {
  771. if i%2 == 0 {
  772. tlsProfiles = append(tlsProfiles, tlsProfile)
  773. }
  774. }
  775. disabledTLSProfiles := make(protocol.LabeledTLSProfiles)
  776. disabledTLSProfiles[frontingProviderID] = tlsProfiles
  777. applyParameters[parameters.DisableFrontingProviderTLSProfiles] = disabledTLSProfiles
  778. }
  779. _, err = params.Set("", false, applyParameters)
  780. if err != nil {
  781. t.Fatalf("Set failed: %v", err)
  782. }
  783. customTLSProfileNames := params.Get().CustomTLSProfileNames()
  784. if len(customTLSProfileNames) != 1 {
  785. t.Fatalf("Unexpected CustomTLSProfileNames count")
  786. }
  787. return params
  788. }