u_parrots.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. // Copyright 2017 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "math/big"
  13. "sort"
  14. "strconv"
  15. "time"
  16. )
  17. func utlsIdToSpec(id ClientHelloID) (ClientHelloSpec, error) {
  18. switch id {
  19. case HelloChrome_58, HelloChrome_62:
  20. return ClientHelloSpec{
  21. TLSVersMax: VersionTLS12,
  22. TLSVersMin: VersionTLS10,
  23. CipherSuites: []uint16{
  24. GREASE_PLACEHOLDER,
  25. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  26. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  27. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  28. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  29. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  30. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  31. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  32. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  33. TLS_RSA_WITH_AES_128_GCM_SHA256,
  34. TLS_RSA_WITH_AES_256_GCM_SHA384,
  35. TLS_RSA_WITH_AES_128_CBC_SHA,
  36. TLS_RSA_WITH_AES_256_CBC_SHA,
  37. TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  38. },
  39. CompressionMethods: []byte{compressionNone},
  40. Extensions: []TLSExtension{
  41. &UtlsGREASEExtension{},
  42. &RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient},
  43. &SNIExtension{},
  44. &UtlsExtendedMasterSecretExtension{},
  45. &SessionTicketExtension{},
  46. &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{
  47. ECDSAWithP256AndSHA256,
  48. PSSWithSHA256,
  49. PKCS1WithSHA256,
  50. ECDSAWithP384AndSHA384,
  51. PSSWithSHA384,
  52. PKCS1WithSHA384,
  53. PSSWithSHA512,
  54. PKCS1WithSHA512,
  55. PKCS1WithSHA1},
  56. },
  57. &StatusRequestExtension{},
  58. &SCTExtension{},
  59. &ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}},
  60. &FakeChannelIDExtension{},
  61. &SupportedPointsExtension{SupportedPoints: []byte{pointFormatUncompressed}},
  62. &SupportedCurvesExtension{[]CurveID{CurveID(GREASE_PLACEHOLDER),
  63. X25519, CurveP256, CurveP384}},
  64. &UtlsGREASEExtension{},
  65. &UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle},
  66. },
  67. GetSessionID: sha256.Sum256,
  68. }, nil
  69. case HelloChrome_70:
  70. return ClientHelloSpec{
  71. TLSVersMin: VersionTLS10,
  72. TLSVersMax: VersionTLS13,
  73. CipherSuites: []uint16{
  74. GREASE_PLACEHOLDER,
  75. TLS_AES_128_GCM_SHA256,
  76. TLS_AES_256_GCM_SHA384,
  77. TLS_CHACHA20_POLY1305_SHA256,
  78. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  79. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  80. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  81. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  82. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  83. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  84. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  85. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  86. TLS_RSA_WITH_AES_128_GCM_SHA256,
  87. TLS_RSA_WITH_AES_256_GCM_SHA384,
  88. TLS_RSA_WITH_AES_128_CBC_SHA,
  89. TLS_RSA_WITH_AES_256_CBC_SHA,
  90. TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  91. },
  92. CompressionMethods: []byte{
  93. compressionNone,
  94. },
  95. Extensions: []TLSExtension{
  96. &UtlsGREASEExtension{},
  97. &RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient},
  98. &SNIExtension{},
  99. &UtlsExtendedMasterSecretExtension{},
  100. &SessionTicketExtension{},
  101. &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{
  102. ECDSAWithP256AndSHA256,
  103. PSSWithSHA256,
  104. PKCS1WithSHA256,
  105. ECDSAWithP384AndSHA384,
  106. PSSWithSHA384,
  107. PKCS1WithSHA384,
  108. PSSWithSHA512,
  109. PKCS1WithSHA512,
  110. PKCS1WithSHA1,
  111. }},
  112. &StatusRequestExtension{},
  113. &SCTExtension{},
  114. &ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}},
  115. &FakeChannelIDExtension{},
  116. &SupportedPointsExtension{SupportedPoints: []byte{
  117. pointFormatUncompressed,
  118. }},
  119. &KeyShareExtension{[]KeyShare{
  120. {Group: CurveID(GREASE_PLACEHOLDER), Data: []byte{0}},
  121. {Group: X25519},
  122. }},
  123. &PSKKeyExchangeModesExtension{[]uint8{pskModeDHE}},
  124. &SupportedVersionsExtension{[]uint16{
  125. GREASE_PLACEHOLDER,
  126. VersionTLS13,
  127. VersionTLS12,
  128. VersionTLS11,
  129. VersionTLS10}},
  130. &SupportedCurvesExtension{[]CurveID{
  131. CurveID(GREASE_PLACEHOLDER),
  132. X25519,
  133. CurveP256,
  134. CurveP384,
  135. }},
  136. &GenericExtension{id: fakeCertCompressionAlgs, data: []byte{02, 00, 02}},
  137. &UtlsGREASEExtension{},
  138. &UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle},
  139. },
  140. }, nil
  141. case HelloFirefox_55, HelloFirefox_56:
  142. return ClientHelloSpec{
  143. TLSVersMax: VersionTLS12,
  144. TLSVersMin: VersionTLS10,
  145. CipherSuites: []uint16{
  146. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  147. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  148. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  149. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  150. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  151. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  152. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  153. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  154. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  155. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  156. FAKE_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
  157. FAKE_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
  158. TLS_RSA_WITH_AES_128_CBC_SHA,
  159. TLS_RSA_WITH_AES_256_CBC_SHA,
  160. TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  161. },
  162. CompressionMethods: []byte{compressionNone},
  163. Extensions: []TLSExtension{
  164. &SNIExtension{},
  165. &UtlsExtendedMasterSecretExtension{},
  166. &RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient},
  167. &SupportedCurvesExtension{[]CurveID{X25519, CurveP256, CurveP384, CurveP521}},
  168. &SupportedPointsExtension{SupportedPoints: []byte{pointFormatUncompressed}},
  169. &SessionTicketExtension{},
  170. &ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}},
  171. &StatusRequestExtension{},
  172. &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{
  173. ECDSAWithP256AndSHA256,
  174. ECDSAWithP384AndSHA384,
  175. ECDSAWithP521AndSHA512,
  176. PSSWithSHA256,
  177. PSSWithSHA384,
  178. PSSWithSHA512,
  179. PKCS1WithSHA256,
  180. PKCS1WithSHA384,
  181. PKCS1WithSHA512,
  182. ECDSAWithSHA1,
  183. PKCS1WithSHA1},
  184. },
  185. &UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle},
  186. },
  187. GetSessionID: nil,
  188. }, nil
  189. case HelloFirefox_63:
  190. return ClientHelloSpec{
  191. TLSVersMin: VersionTLS10,
  192. TLSVersMax: VersionTLS13,
  193. CipherSuites: []uint16{
  194. TLS_AES_128_GCM_SHA256,
  195. TLS_CHACHA20_POLY1305_SHA256,
  196. TLS_AES_256_GCM_SHA384,
  197. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  198. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  199. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  200. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  201. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  202. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  203. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  204. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  205. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  206. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  207. FAKE_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
  208. FAKE_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
  209. TLS_RSA_WITH_AES_128_CBC_SHA,
  210. TLS_RSA_WITH_AES_256_CBC_SHA,
  211. TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  212. },
  213. CompressionMethods: []byte{
  214. compressionNone,
  215. },
  216. Extensions: []TLSExtension{
  217. &SNIExtension{},
  218. &UtlsExtendedMasterSecretExtension{},
  219. &RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient},
  220. &SupportedCurvesExtension{[]CurveID{
  221. X25519,
  222. CurveP256,
  223. CurveP384,
  224. CurveP521,
  225. CurveID(FakeFFDHE2048),
  226. CurveID(FakeFFDHE3072),
  227. }},
  228. &SupportedPointsExtension{SupportedPoints: []byte{
  229. pointFormatUncompressed,
  230. }},
  231. &SessionTicketExtension{},
  232. &ALPNExtension{AlpnProtocols: []string{"h2", "http/1.1"}},
  233. &StatusRequestExtension{},
  234. &KeyShareExtension{[]KeyShare{
  235. {Group: X25519},
  236. {Group: CurveP256},
  237. }},
  238. &SupportedVersionsExtension{[]uint16{
  239. VersionTLS13,
  240. VersionTLS12,
  241. VersionTLS11,
  242. VersionTLS10}},
  243. &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{
  244. ECDSAWithP256AndSHA256,
  245. ECDSAWithP384AndSHA384,
  246. ECDSAWithP521AndSHA512,
  247. PSSWithSHA256,
  248. PSSWithSHA384,
  249. PSSWithSHA512,
  250. PKCS1WithSHA256,
  251. PKCS1WithSHA384,
  252. PKCS1WithSHA512,
  253. ECDSAWithSHA1,
  254. PKCS1WithSHA1,
  255. }},
  256. &PSKKeyExchangeModesExtension{[]uint8{pskModeDHE}},
  257. &GenericExtension{id: fakeRecordSizeLimit, data: []byte{0x40, 0x01}},
  258. &UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle},
  259. }}, nil
  260. case HelloIOS_11_1:
  261. return ClientHelloSpec{
  262. TLSVersMax: VersionTLS12,
  263. TLSVersMin: VersionTLS10,
  264. CipherSuites: []uint16{
  265. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  266. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  267. DISABLED_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
  268. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  269. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  270. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  271. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  272. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  273. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  274. DISABLED_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
  275. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  276. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  277. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  278. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  279. TLS_RSA_WITH_AES_256_GCM_SHA384,
  280. TLS_RSA_WITH_AES_128_GCM_SHA256,
  281. DISABLED_TLS_RSA_WITH_AES_256_CBC_SHA256,
  282. TLS_RSA_WITH_AES_128_CBC_SHA256,
  283. TLS_RSA_WITH_AES_256_CBC_SHA,
  284. TLS_RSA_WITH_AES_128_CBC_SHA,
  285. },
  286. CompressionMethods: []byte{
  287. compressionNone,
  288. },
  289. Extensions: []TLSExtension{
  290. &RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient},
  291. &SNIExtension{},
  292. &UtlsExtendedMasterSecretExtension{},
  293. &SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []SignatureScheme{
  294. ECDSAWithP256AndSHA256,
  295. PSSWithSHA256,
  296. PKCS1WithSHA256,
  297. ECDSAWithP384AndSHA384,
  298. PSSWithSHA384,
  299. PKCS1WithSHA384,
  300. PSSWithSHA512,
  301. PKCS1WithSHA512,
  302. PKCS1WithSHA1,
  303. }},
  304. &StatusRequestExtension{},
  305. &NPNExtension{},
  306. &SCTExtension{},
  307. &ALPNExtension{AlpnProtocols: []string{"h2", "h2-16", "h2-15", "h2-14", "spdy/3.1", "spdy/3", "http/1.1"}},
  308. &SupportedPointsExtension{SupportedPoints: []byte{
  309. pointFormatUncompressed,
  310. }},
  311. &SupportedCurvesExtension{Curves: []CurveID{
  312. X25519,
  313. CurveP256,
  314. CurveP384,
  315. CurveP521,
  316. }},
  317. },
  318. }, nil
  319. default:
  320. return ClientHelloSpec{}, errors.New("ClientHello ID " + id.Str() + " is unknown")
  321. }
  322. }
  323. func (uconn *UConn) applyPresetByID(id ClientHelloID) (err error) {
  324. var spec ClientHelloSpec
  325. // choose/generate the spec
  326. switch id {
  327. case HelloRandomized:
  328. if tossBiasedCoin(0.5) {
  329. return uconn.applyPresetByID(HelloRandomizedALPN)
  330. } else {
  331. return uconn.applyPresetByID(HelloRandomizedNoALPN)
  332. }
  333. case HelloRandomizedALPN:
  334. spec, err = uconn.generateRandomizedSpec(true)
  335. if err != nil {
  336. return err
  337. }
  338. case HelloRandomizedNoALPN:
  339. spec, err = uconn.generateRandomizedSpec(false)
  340. if err != nil {
  341. return err
  342. }
  343. case HelloCustom:
  344. return nil
  345. default:
  346. spec, err = utlsIdToSpec(id)
  347. if err != nil {
  348. return err
  349. }
  350. }
  351. uconn.clientHelloID = id
  352. return uconn.ApplyPreset(&spec)
  353. }
  354. // ApplyPreset should only be used in conjunction with HelloCustom to apply custom specs.
  355. // Fields of TLSExtensions that are slices/pointers are shared across different connections with
  356. // same ClientHelloSpec. It is advised to use different specs and avoid any shared state.
  357. func (uconn *UConn) ApplyPreset(p *ClientHelloSpec) error {
  358. var err error
  359. err = uconn.SetTLSVers(p.TLSVersMin, p.TLSVersMax)
  360. if err != nil {
  361. return err
  362. }
  363. privateHello, ecdheParams, err := uconn.makeClientHello()
  364. if err != nil {
  365. return err
  366. }
  367. uconn.HandshakeState.Hello = privateHello.getPublicPtr()
  368. uconn.HandshakeState.State13.EcdheParams = ecdheParams
  369. hello := uconn.HandshakeState.Hello
  370. session := uconn.HandshakeState.Session
  371. switch len(hello.Random) {
  372. case 0:
  373. hello.Random = make([]byte, 32)
  374. _, err := io.ReadFull(uconn.config.rand(), hello.Random)
  375. if err != nil {
  376. return errors.New("tls: short read from Rand: " + err.Error())
  377. }
  378. case 32:
  379. // carry on
  380. default:
  381. return errors.New("ClientHello expected length: 32 bytes. Got: " +
  382. strconv.Itoa(len(hello.Random)) + " bytes")
  383. }
  384. if len(hello.CipherSuites) == 0 {
  385. hello.CipherSuites = defaultCipherSuites()
  386. }
  387. if len(hello.CompressionMethods) == 0 {
  388. hello.CompressionMethods = []uint8{compressionNone}
  389. }
  390. // Currently, GREASE is assumed to come from BoringSSL
  391. grease_bytes := make([]byte, 2*ssl_grease_last_index)
  392. grease_extensions_seen := 0
  393. _, err = io.ReadFull(uconn.config.rand(), grease_bytes)
  394. if err != nil {
  395. return errors.New("tls: short read from Rand: " + err.Error())
  396. }
  397. for i := range uconn.greaseSeed {
  398. uconn.greaseSeed[i] = binary.LittleEndian.Uint16(grease_bytes[2*i : 2*i+2])
  399. }
  400. if uconn.greaseSeed[ssl_grease_extension1] == uconn.greaseSeed[ssl_grease_extension2] {
  401. uconn.greaseSeed[ssl_grease_extension2] ^= 0x1010
  402. }
  403. hello.CipherSuites = make([]uint16, len(p.CipherSuites))
  404. copy(hello.CipherSuites, p.CipherSuites)
  405. for i := range hello.CipherSuites {
  406. if hello.CipherSuites[i] == GREASE_PLACEHOLDER {
  407. hello.CipherSuites[i] = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_cipher)
  408. }
  409. }
  410. uconn.GetSessionID = p.GetSessionID
  411. uconn.Extensions = make([]TLSExtension, len(p.Extensions))
  412. copy(uconn.Extensions, p.Extensions)
  413. // reGrease, and point things to each other
  414. for _, e := range uconn.Extensions {
  415. switch ext := e.(type) {
  416. case *SNIExtension:
  417. if ext.ServerName == "" {
  418. ext.ServerName = uconn.config.ServerName
  419. }
  420. case *UtlsGREASEExtension:
  421. switch grease_extensions_seen {
  422. case 0:
  423. ext.Value = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension1)
  424. case 1:
  425. ext.Value = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_extension2)
  426. ext.Body = []byte{0}
  427. default:
  428. return errors.New("at most 2 grease extensions are supported")
  429. }
  430. grease_extensions_seen += 1
  431. case *SessionTicketExtension:
  432. err := uconn.SetSessionState(session)
  433. if err != nil {
  434. return err
  435. }
  436. case *SupportedCurvesExtension:
  437. for i := range ext.Curves {
  438. if ext.Curves[i] == GREASE_PLACEHOLDER {
  439. ext.Curves[i] = CurveID(GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_group))
  440. }
  441. }
  442. case *KeyShareExtension:
  443. preferredCurveIsSet := false
  444. for i := range ext.KeyShares {
  445. curveID := ext.KeyShares[i].Group
  446. if curveID == GREASE_PLACEHOLDER {
  447. ext.KeyShares[i].Group = CurveID(GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_group))
  448. continue
  449. }
  450. if len(ext.KeyShares[i].Data) > 1 {
  451. continue
  452. }
  453. ecdheParams, err := generateECDHEParameters(uconn.config.rand(), curveID)
  454. if err != nil {
  455. return fmt.Errorf("unsupported Curve in KeyShareExtension: %v."+
  456. "To mimic it, fill the Data(key) field manually.", curveID)
  457. }
  458. ext.KeyShares[i].Data = ecdheParams.PublicKey()
  459. if !preferredCurveIsSet {
  460. // only do this once for the first non-grease curve
  461. uconn.HandshakeState.State13.EcdheParams = ecdheParams
  462. preferredCurveIsSet = true
  463. }
  464. }
  465. case *SupportedVersionsExtension:
  466. for i := range ext.Versions {
  467. if ext.Versions[i] == GREASE_PLACEHOLDER {
  468. ext.Versions[i] = GetBoringGREASEValue(uconn.greaseSeed, ssl_grease_version)
  469. }
  470. }
  471. }
  472. }
  473. return nil
  474. }
  475. func (uconn *UConn) generateRandomizedSpec(WithALPN bool) (ClientHelloSpec, error) {
  476. p := ClientHelloSpec{}
  477. p.CipherSuites = make([]uint16, len(defaultCipherSuites()))
  478. copy(p.CipherSuites, defaultCipherSuites())
  479. shuffledSuites, err := shuffledCiphers()
  480. if err != nil {
  481. return p, err
  482. }
  483. if tossBiasedCoin(0.4) {
  484. p.TLSVersMin = VersionTLS10
  485. p.TLSVersMax = VersionTLS13
  486. tls13ciphers := defaultCipherSuitesTLS13()
  487. err = shuffleUInts16(tls13ciphers)
  488. if err != nil {
  489. return p, err
  490. }
  491. // appending TLS 1.3 ciphers before TLS 1.2, since that's what popular implementations do
  492. shuffledSuites = append(tls13ciphers, shuffledSuites...)
  493. // TLS 1.3 forbids RC4 in any configurations
  494. shuffledSuites = removeRC4Ciphers(shuffledSuites)
  495. } else {
  496. p.TLSVersMin = VersionTLS10
  497. p.TLSVersMax = VersionTLS12
  498. }
  499. p.CipherSuites = removeRandomCiphers(shuffledSuites, 0.4)
  500. sni := SNIExtension{uconn.config.ServerName}
  501. sessionTicket := SessionTicketExtension{Session: uconn.HandshakeState.Session}
  502. sigAndHashAlgos := []SignatureScheme{
  503. ECDSAWithP256AndSHA256,
  504. PKCS1WithSHA256,
  505. ECDSAWithP384AndSHA384,
  506. PKCS1WithSHA384,
  507. PKCS1WithSHA1,
  508. PKCS1WithSHA512,
  509. }
  510. if tossBiasedCoin(0.63) {
  511. sigAndHashAlgos = append(sigAndHashAlgos, ECDSAWithSHA1)
  512. }
  513. if tossBiasedCoin(0.59) {
  514. sigAndHashAlgos = append(sigAndHashAlgos, ECDSAWithP521AndSHA512)
  515. }
  516. if tossBiasedCoin(0.51) || p.TLSVersMax == VersionTLS13 {
  517. // https://tools.ietf.org/html/rfc8446 says "...RSASSA-PSS (which is mandatory in TLS 1.3)..."
  518. sigAndHashAlgos = append(sigAndHashAlgos, PSSWithSHA256)
  519. if tossBiasedCoin(0.9) {
  520. // these usually go together
  521. sigAndHashAlgos = append(sigAndHashAlgos, PSSWithSHA384)
  522. sigAndHashAlgos = append(sigAndHashAlgos, PSSWithSHA512)
  523. }
  524. }
  525. err = shuffleSignatures(sigAndHashAlgos)
  526. if err != nil {
  527. return p, err
  528. }
  529. sigAndHash := SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: sigAndHashAlgos}
  530. status := StatusRequestExtension{}
  531. sct := SCTExtension{}
  532. ems := UtlsExtendedMasterSecretExtension{}
  533. points := SupportedPointsExtension{SupportedPoints: []byte{pointFormatUncompressed}}
  534. curveIDs := []CurveID{}
  535. if tossBiasedCoin(0.71) || p.TLSVersMax == VersionTLS13 {
  536. curveIDs = append(curveIDs, X25519)
  537. }
  538. curveIDs = append(curveIDs, CurveP256, CurveP384)
  539. if tossBiasedCoin(0.46) {
  540. curveIDs = append(curveIDs, CurveP521)
  541. }
  542. curves := SupportedCurvesExtension{curveIDs}
  543. padding := UtlsPaddingExtension{GetPaddingLen: BoringPaddingStyle}
  544. reneg := RenegotiationInfoExtension{renegotiation: RenegotiateOnceAsClient}
  545. p.Extensions = []TLSExtension{
  546. &sni,
  547. &sessionTicket,
  548. &sigAndHash,
  549. &points,
  550. &curves,
  551. }
  552. if WithALPN {
  553. if len(uconn.config.NextProtos) == 0 {
  554. // if user didn't specify alpn yet, choose something popular
  555. uconn.config.NextProtos = []string{"h2", "http/1.1"}
  556. }
  557. alpn := ALPNExtension{AlpnProtocols: uconn.config.NextProtos}
  558. p.Extensions = append(p.Extensions, &alpn)
  559. }
  560. if tossBiasedCoin(0.62) || p.TLSVersMax == VersionTLS13 {
  561. // always include for TLS 1.3, since TLS 1.3 ClientHellos are often over 256 bytes
  562. // and that's when padding is required to work around buggy middleboxes
  563. p.Extensions = append(p.Extensions, &padding)
  564. }
  565. if tossBiasedCoin(0.74) {
  566. p.Extensions = append(p.Extensions, &status)
  567. }
  568. if tossBiasedCoin(0.46) {
  569. p.Extensions = append(p.Extensions, &sct)
  570. }
  571. if tossBiasedCoin(0.75) {
  572. p.Extensions = append(p.Extensions, &reneg)
  573. }
  574. if tossBiasedCoin(0.77) {
  575. p.Extensions = append(p.Extensions, &ems)
  576. }
  577. if p.TLSVersMax == VersionTLS13 {
  578. ks := KeyShareExtension{[]KeyShare{
  579. {Group: X25519}, // the key for the group will be generated later
  580. }}
  581. if tossBiasedCoin(0.25) {
  582. // do not ADD second keyShare because crypto/tls does not support multiple ecdheParams
  583. // TODO: add it back when they implement multiple keyShares, or implement it oursevles
  584. // ks.KeyShares = append(ks.KeyShares, KeyShare{Group: CurveP256})
  585. ks.KeyShares[0].Group = CurveP256
  586. }
  587. pskExchangeModes := PSKKeyExchangeModesExtension{[]uint8{pskModeDHE}}
  588. supportedVersionsExt := SupportedVersionsExtension{
  589. Versions: makeSupportedVersions(p.TLSVersMin, p.TLSVersMax),
  590. }
  591. p.Extensions = append(p.Extensions, &ks, &pskExchangeModes, &supportedVersionsExt)
  592. }
  593. err = shuffleTLSExtensions(p.Extensions)
  594. if err != nil {
  595. return p, err
  596. }
  597. err = uconn.SetTLSVers(p.TLSVersMin, p.TLSVersMax)
  598. if err != nil {
  599. return p, err
  600. }
  601. return p, nil
  602. }
  603. func tossBiasedCoin(probability float32) bool {
  604. // probability is expected to be in [0,1]
  605. // this function never returns errors for ease of use
  606. const precision = 0xffff
  607. threshold := float32(precision) * probability
  608. value, err := getRandInt(precision)
  609. if err != nil {
  610. // I doubt that this code will ever actually be used, as other functions are expected to complain
  611. // about used source of entropy. Nonetheless, this is more than enough for given purpose
  612. return ((time.Now().Unix() & 1) == 0)
  613. }
  614. if float32(value) <= threshold {
  615. return true
  616. } else {
  617. return false
  618. }
  619. }
  620. func removeRandomCiphers(s []uint16, maxRemovalProbability float32) []uint16 {
  621. // removes elements in place
  622. // probability to remove increases for further elements
  623. // never remove first cipher
  624. if len(s) <= 1 {
  625. return s
  626. }
  627. // remove random elements
  628. floatLen := float32(len(s))
  629. sliceLen := len(s)
  630. for i := 1; i < sliceLen; i++ {
  631. if tossBiasedCoin(maxRemovalProbability * float32(i) / floatLen) {
  632. s = append(s[:i], s[i+1:]...)
  633. sliceLen--
  634. i--
  635. }
  636. }
  637. return s[:sliceLen]
  638. }
  639. func removeRC4Ciphers(s []uint16) []uint16 {
  640. // removes elements in place
  641. sliceLen := len(s)
  642. for i := 0; i < sliceLen; i++ {
  643. cipher := s[i]
  644. if cipher == TLS_ECDHE_ECDSA_WITH_RC4_128_SHA ||
  645. cipher == TLS_ECDHE_RSA_WITH_RC4_128_SHA ||
  646. cipher == TLS_RSA_WITH_RC4_128_SHA {
  647. s = append(s[:i], s[i+1:]...)
  648. sliceLen--
  649. i--
  650. }
  651. }
  652. return s[:sliceLen]
  653. }
  654. func getRandInt(max int) (int, error) {
  655. bigInt, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
  656. return int(bigInt.Int64()), err
  657. }
  658. func getRandPerm(n int) ([]int, error) {
  659. permArray := make([]int, n)
  660. for i := 1; i < n; i++ {
  661. j, err := getRandInt(i + 1)
  662. if err != nil {
  663. return permArray, err
  664. }
  665. permArray[i] = permArray[j]
  666. permArray[j] = i
  667. }
  668. return permArray, nil
  669. }
  670. func shuffledCiphers() ([]uint16, error) {
  671. ciphers := make(sortableCiphers, len(cipherSuites))
  672. perm, err := getRandPerm(len(cipherSuites))
  673. if err != nil {
  674. return nil, err
  675. }
  676. for i, suite := range cipherSuites {
  677. ciphers[i] = sortableCipher{suite: suite.id,
  678. isObsolete: ((suite.flags & suiteTLS12) == 0),
  679. randomTag: perm[i]}
  680. }
  681. sort.Sort(ciphers)
  682. return ciphers.GetCiphers(), nil
  683. }
  684. type sortableCipher struct {
  685. isObsolete bool
  686. randomTag int
  687. suite uint16
  688. }
  689. type sortableCiphers []sortableCipher
  690. func (ciphers sortableCiphers) Len() int {
  691. return len(ciphers)
  692. }
  693. func (ciphers sortableCiphers) Less(i, j int) bool {
  694. if ciphers[i].isObsolete && !ciphers[j].isObsolete {
  695. return false
  696. }
  697. if ciphers[j].isObsolete && !ciphers[i].isObsolete {
  698. return true
  699. }
  700. return ciphers[i].randomTag < ciphers[j].randomTag
  701. }
  702. func (ciphers sortableCiphers) Swap(i, j int) {
  703. ciphers[i], ciphers[j] = ciphers[j], ciphers[i]
  704. }
  705. func (ciphers sortableCiphers) GetCiphers() []uint16 {
  706. cipherIDs := make([]uint16, len(ciphers))
  707. for i := range ciphers {
  708. cipherIDs[i] = ciphers[i].suite
  709. }
  710. return cipherIDs
  711. }
  712. // so much for generics
  713. func shuffleTLSExtensions(s []TLSExtension) error {
  714. // shuffles array in place
  715. perm, err := getRandPerm(len(s))
  716. if err != nil {
  717. return err
  718. }
  719. for i := range s {
  720. s[i], s[perm[i]] = s[perm[i]], s[i]
  721. }
  722. return nil
  723. }
  724. // so much for generics
  725. func shuffleSignatures(s []SignatureScheme) error {
  726. // shuffles array in place
  727. perm, err := getRandPerm(len(s))
  728. if err != nil {
  729. return err
  730. }
  731. for i := range s {
  732. s[i], s[perm[i]] = s[perm[i]], s[i]
  733. }
  734. return nil
  735. }
  736. // so much for generics
  737. func shuffleUInts16(s []uint16) error {
  738. // shuffles array in place
  739. perm, err := getRandPerm(len(s))
  740. if err != nil {
  741. return err
  742. }
  743. for i := range s {
  744. s[i], s[perm[i]] = s[perm[i]], s[i]
  745. }
  746. return nil
  747. }