ticket.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright 2012 The Go Authors. 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/aes"
  7. "crypto/cipher"
  8. "crypto/hmac"
  9. "crypto/rand"
  10. "crypto/sha256"
  11. "crypto/subtle"
  12. "crypto/x509"
  13. "errors"
  14. "io"
  15. "math/big"
  16. math_rand "math/rand"
  17. "golang.org/x/crypto/cryptobyte"
  18. )
  19. // [Psiphon]
  20. var obfuscateSessionTickets = true
  21. // A SessionState is a resumable session.
  22. type SessionState struct {
  23. // Encoded as a SessionState (in the language of RFC 8446, Section 3).
  24. //
  25. // enum { server(1), client(2) } SessionStateType;
  26. //
  27. // opaque Certificate<1..2^24-1>;
  28. //
  29. // Certificate CertificateChain<0..2^24-1>;
  30. //
  31. // opaque Extra<0..2^24-1>;
  32. //
  33. // struct {
  34. // uint16 version;
  35. // SessionStateType type;
  36. // uint16 cipher_suite;
  37. // uint64 created_at;
  38. // opaque secret<1..2^8-1>;
  39. // Extra extra<0..2^24-1>;
  40. // uint8 ext_master_secret = { 0, 1 };
  41. // uint8 early_data = { 0, 1 };
  42. // CertificateEntry certificate_list<0..2^24-1>;
  43. // CertificateChain verified_chains<0..2^24-1>; /* excluding leaf */
  44. // select (SessionState.early_data) {
  45. // case 0: Empty;
  46. // case 1: opaque alpn<1..2^8-1>;
  47. // };
  48. // select (SessionState.type) {
  49. // case server: Empty;
  50. // case client: struct {
  51. // select (SessionState.version) {
  52. // case VersionTLS10..VersionTLS12: Empty;
  53. // case VersionTLS13: struct {
  54. // uint64 use_by;
  55. // uint32 age_add;
  56. // };
  57. // };
  58. // };
  59. // };
  60. // } SessionState;
  61. //
  62. // Extra is ignored by crypto/tls, but is encoded by [SessionState.Bytes]
  63. // and parsed by [ParseSessionState].
  64. //
  65. // This allows [Config.UnwrapSession]/[Config.WrapSession] and
  66. // [ClientSessionCache] implementations to store and retrieve additional
  67. // data alongside this session.
  68. //
  69. // To allow different layers in a protocol stack to share this field,
  70. // applications must only append to it, not replace it, and must use entries
  71. // that can be recognized even if out of order (for example, by starting
  72. // with a id and version prefix).
  73. Extra [][]byte
  74. // EarlyData indicates whether the ticket can be used for 0-RTT in a QUIC
  75. // connection. The application may set this to false if it is true to
  76. // decline to offer 0-RTT even if supported.
  77. EarlyData bool
  78. version uint16
  79. isClient bool
  80. cipherSuite uint16
  81. // createdAt is the generation time of the secret on the sever (which for
  82. // TLS 1.0–1.2 might be earlier than the current session) and the time at
  83. // which the ticket was received on the client.
  84. createdAt uint64 // seconds since UNIX epoch
  85. secret []byte // master secret for TLS 1.2, or the PSK for TLS 1.3
  86. extMasterSecret bool
  87. peerCertificates []*x509.Certificate
  88. activeCertHandles []*activeCert
  89. ocspResponse []byte
  90. scts [][]byte
  91. verifiedChains [][]*x509.Certificate
  92. alpnProtocol string // only set if EarlyData is true
  93. // Client-side TLS 1.3-only fields.
  94. useBy uint64 // seconds since UNIX epoch
  95. ageAdd uint32
  96. }
  97. // Bytes encodes the session, including any private fields, so that it can be
  98. // parsed by [ParseSessionState]. The encoding contains secret values critical
  99. // to the security of future and possibly past sessions.
  100. //
  101. // The specific encoding should be considered opaque and may change incompatibly
  102. // between Go versions.
  103. func (s *SessionState) Bytes() ([]byte, error) {
  104. var b cryptobyte.Builder
  105. b.AddUint16(s.version)
  106. if s.isClient {
  107. b.AddUint8(2) // client
  108. } else {
  109. b.AddUint8(1) // server
  110. }
  111. b.AddUint16(s.cipherSuite)
  112. addUint64(&b, s.createdAt)
  113. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  114. b.AddBytes(s.secret)
  115. })
  116. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  117. for _, extra := range s.Extra {
  118. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  119. b.AddBytes(extra)
  120. })
  121. }
  122. })
  123. if s.extMasterSecret {
  124. b.AddUint8(1)
  125. } else {
  126. b.AddUint8(0)
  127. }
  128. if s.EarlyData {
  129. b.AddUint8(1)
  130. } else {
  131. b.AddUint8(0)
  132. }
  133. marshalCertificate(&b, Certificate{
  134. Certificate: certificatesToBytesSlice(s.peerCertificates),
  135. OCSPStaple: s.ocspResponse,
  136. SignedCertificateTimestamps: s.scts,
  137. })
  138. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  139. for _, chain := range s.verifiedChains {
  140. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  141. // We elide the first certificate because it's always the leaf.
  142. if len(chain) == 0 {
  143. b.SetError(errors.New("tls: internal error: empty verified chain"))
  144. return
  145. }
  146. for _, cert := range chain[1:] {
  147. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  148. b.AddBytes(cert.Raw)
  149. })
  150. }
  151. })
  152. }
  153. })
  154. if s.EarlyData {
  155. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  156. b.AddBytes([]byte(s.alpnProtocol))
  157. })
  158. }
  159. if s.isClient {
  160. if s.version >= VersionTLS13 {
  161. addUint64(&b, s.useBy)
  162. b.AddUint32(s.ageAdd)
  163. }
  164. }
  165. // [Psiphon]
  166. bytes, err := b.Bytes()
  167. if err != nil {
  168. return nil, err
  169. }
  170. // [Psiphon]
  171. // Pad golang TLS session ticket to a more typical size.
  172. if obfuscateSessionTickets {
  173. paddedSizes := []int{160, 176, 192, 208, 218, 224, 240, 255}
  174. initialSize := 120
  175. randomInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(paddedSizes))))
  176. index := 0
  177. if err == nil {
  178. index = int(randomInt.Int64())
  179. } else {
  180. index = math_rand.Intn(len(paddedSizes))
  181. }
  182. paddingSize := paddedSizes[index] - initialSize
  183. ret := make([]byte, len(bytes)+paddingSize)
  184. copy(ret, bytes)
  185. return ret, nil
  186. }
  187. return bytes, nil
  188. }
  189. func certificatesToBytesSlice(certs []*x509.Certificate) [][]byte {
  190. s := make([][]byte, 0, len(certs))
  191. for _, c := range certs {
  192. s = append(s, c.Raw)
  193. }
  194. return s
  195. }
  196. // ParseSessionState parses a [SessionState] encoded by [SessionState.Bytes].
  197. func ParseSessionState(data []byte) (*SessionState, error) {
  198. ss := &SessionState{}
  199. s := cryptobyte.String(data)
  200. var typ, extMasterSecret, earlyData uint8
  201. var cert Certificate
  202. var extra cryptobyte.String
  203. if !s.ReadUint16(&ss.version) ||
  204. !s.ReadUint8(&typ) ||
  205. (typ != 1 && typ != 2) ||
  206. !s.ReadUint16(&ss.cipherSuite) ||
  207. !readUint64(&s, &ss.createdAt) ||
  208. !readUint8LengthPrefixed(&s, &ss.secret) ||
  209. !s.ReadUint24LengthPrefixed(&extra) ||
  210. !s.ReadUint8(&extMasterSecret) ||
  211. !s.ReadUint8(&earlyData) ||
  212. len(ss.secret) == 0 ||
  213. !unmarshalCertificate(&s, &cert) {
  214. return nil, errors.New("tls: invalid session encoding")
  215. }
  216. for !extra.Empty() {
  217. var e []byte
  218. if !readUint24LengthPrefixed(&extra, &e) {
  219. return nil, errors.New("tls: invalid session encoding")
  220. }
  221. ss.Extra = append(ss.Extra, e)
  222. }
  223. switch extMasterSecret {
  224. case 0:
  225. ss.extMasterSecret = false
  226. case 1:
  227. ss.extMasterSecret = true
  228. default:
  229. return nil, errors.New("tls: invalid session encoding")
  230. }
  231. switch earlyData {
  232. case 0:
  233. ss.EarlyData = false
  234. case 1:
  235. ss.EarlyData = true
  236. default:
  237. return nil, errors.New("tls: invalid session encoding")
  238. }
  239. for _, cert := range cert.Certificate {
  240. c, err := globalCertCache.newCert(cert)
  241. if err != nil {
  242. return nil, err
  243. }
  244. ss.activeCertHandles = append(ss.activeCertHandles, c)
  245. ss.peerCertificates = append(ss.peerCertificates, c.cert)
  246. }
  247. ss.ocspResponse = cert.OCSPStaple
  248. ss.scts = cert.SignedCertificateTimestamps
  249. var chainList cryptobyte.String
  250. if !s.ReadUint24LengthPrefixed(&chainList) {
  251. return nil, errors.New("tls: invalid session encoding")
  252. }
  253. for !chainList.Empty() {
  254. var certList cryptobyte.String
  255. if !chainList.ReadUint24LengthPrefixed(&certList) {
  256. return nil, errors.New("tls: invalid session encoding")
  257. }
  258. var chain []*x509.Certificate
  259. if len(ss.peerCertificates) == 0 {
  260. return nil, errors.New("tls: invalid session encoding")
  261. }
  262. chain = append(chain, ss.peerCertificates[0])
  263. for !certList.Empty() {
  264. var cert []byte
  265. if !readUint24LengthPrefixed(&certList, &cert) {
  266. return nil, errors.New("tls: invalid session encoding")
  267. }
  268. c, err := globalCertCache.newCert(cert)
  269. if err != nil {
  270. return nil, err
  271. }
  272. ss.activeCertHandles = append(ss.activeCertHandles, c)
  273. chain = append(chain, c.cert)
  274. }
  275. ss.verifiedChains = append(ss.verifiedChains, chain)
  276. }
  277. if ss.EarlyData {
  278. var alpn []byte
  279. if !readUint8LengthPrefixed(&s, &alpn) {
  280. return nil, errors.New("tls: invalid session encoding")
  281. }
  282. ss.alpnProtocol = string(alpn)
  283. }
  284. if isClient := typ == 2; !isClient {
  285. // [Psiphon]
  286. // Ignore padding for obfuscated session tickets.
  287. if !s.Empty() && !allZeros(s) {
  288. return nil, errors.New("tls: invalid session encoding")
  289. }
  290. return ss, nil
  291. }
  292. ss.isClient = true
  293. if len(ss.peerCertificates) == 0 {
  294. return nil, errors.New("tls: no server certificates in client session")
  295. }
  296. if ss.version < VersionTLS13 {
  297. if !s.Empty() {
  298. return nil, errors.New("tls: invalid session encoding")
  299. }
  300. return ss, nil
  301. }
  302. if !s.ReadUint64(&ss.useBy) || !s.ReadUint32(&ss.ageAdd) || !s.Empty() {
  303. return nil, errors.New("tls: invalid session encoding")
  304. }
  305. return ss, nil
  306. }
  307. // sessionState returns a partially filled-out [SessionState] with information
  308. // from the current connection.
  309. func (c *Conn) sessionState() (*SessionState, error) {
  310. return &SessionState{
  311. version: c.vers,
  312. cipherSuite: c.cipherSuite,
  313. createdAt: uint64(c.config.time().Unix()),
  314. alpnProtocol: c.clientProtocol,
  315. peerCertificates: c.peerCertificates,
  316. activeCertHandles: c.activeCertHandles,
  317. ocspResponse: c.ocspResponse,
  318. scts: c.scts,
  319. isClient: c.isClient,
  320. extMasterSecret: c.extMasterSecret,
  321. verifiedChains: c.verifiedChains,
  322. }, nil
  323. }
  324. // EncryptTicket encrypts a ticket with the Config's configured (or default)
  325. // session ticket keys. It can be used as a [Config.WrapSession] implementation.
  326. func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error) {
  327. ticketKeys := c.ticketKeys(nil)
  328. stateBytes, err := ss.Bytes()
  329. if err != nil {
  330. return nil, err
  331. }
  332. return c.encryptTicket(stateBytes, ticketKeys)
  333. }
  334. func (c *Config) encryptTicket(state []byte, ticketKeys []ticketKey) ([]byte, error) {
  335. if len(ticketKeys) == 0 {
  336. return nil, errors.New("tls: internal error: session ticket keys unavailable")
  337. }
  338. encrypted := make([]byte, aes.BlockSize+len(state)+sha256.Size)
  339. iv := encrypted[:aes.BlockSize]
  340. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  341. authenticated := encrypted[:len(encrypted)-sha256.Size]
  342. macBytes := encrypted[len(encrypted)-sha256.Size:]
  343. if _, err := io.ReadFull(c.rand(), iv); err != nil {
  344. return nil, err
  345. }
  346. key := ticketKeys[0]
  347. block, err := aes.NewCipher(key.aesKey[:])
  348. if err != nil {
  349. return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error())
  350. }
  351. cipher.NewCTR(block, iv).XORKeyStream(ciphertext, state)
  352. mac := hmac.New(sha256.New, key.hmacKey[:])
  353. mac.Write(authenticated)
  354. mac.Sum(macBytes[:0])
  355. return encrypted, nil
  356. }
  357. // DecryptTicket decrypts a ticket encrypted by [Config.EncryptTicket]. It can
  358. // be used as a [Config.UnwrapSession] implementation.
  359. //
  360. // If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).
  361. func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error) {
  362. ticketKeys := c.ticketKeys(nil)
  363. stateBytes := c.decryptTicket(identity, ticketKeys)
  364. if stateBytes == nil {
  365. return nil, nil
  366. }
  367. s, err := ParseSessionState(stateBytes)
  368. if err != nil {
  369. return nil, nil // drop unparsable tickets on the floor
  370. }
  371. return s, nil
  372. }
  373. func (c *Config) decryptTicket(encrypted []byte, ticketKeys []ticketKey) []byte {
  374. if len(encrypted) < aes.BlockSize+sha256.Size {
  375. return nil
  376. }
  377. iv := encrypted[:aes.BlockSize]
  378. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  379. authenticated := encrypted[:len(encrypted)-sha256.Size]
  380. macBytes := encrypted[len(encrypted)-sha256.Size:]
  381. for _, key := range ticketKeys {
  382. mac := hmac.New(sha256.New, key.hmacKey[:])
  383. mac.Write(authenticated)
  384. expected := mac.Sum(nil)
  385. if subtle.ConstantTimeCompare(macBytes, expected) != 1 {
  386. continue
  387. }
  388. block, err := aes.NewCipher(key.aesKey[:])
  389. if err != nil {
  390. return nil
  391. }
  392. plaintext := make([]byte, len(ciphertext))
  393. cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext)
  394. return plaintext
  395. }
  396. return nil
  397. }
  398. // ClientSessionState contains the state needed by a client to
  399. // resume a previous TLS session.
  400. type ClientSessionState struct {
  401. ticket []byte
  402. session *SessionState
  403. }
  404. // ResumptionState returns the session ticket sent by the server (also known as
  405. // the session's identity) and the state necessary to resume this session.
  406. //
  407. // It can be called by [ClientSessionCache.Put] to serialize (with
  408. // [SessionState.Bytes]) and store the session.
  409. func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error) {
  410. return cs.ticket, cs.session, nil
  411. }
  412. // NewResumptionState returns a state value that can be returned by
  413. // [ClientSessionCache.Get] to resume a previous session.
  414. //
  415. // state needs to be returned by [ParseSessionState], and the ticket and session
  416. // state must have been returned by [ClientSessionState.ResumptionState].
  417. func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error) {
  418. return &ClientSessionState{
  419. ticket: ticket, session: state,
  420. }, nil
  421. }
  422. // [Psiphon]
  423. type ObfuscatedClientSessionState struct {
  424. SessionTicket []uint8
  425. Vers uint16
  426. CipherSuite uint16
  427. MasterSecret []byte
  428. ServerCertificates []*x509.Certificate
  429. VerifiedChains [][]*x509.Certificate
  430. UseEMS bool
  431. }
  432. var obfuscatedSessionTicketCipherSuite = TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  433. // [Psiphon]
  434. // NewObfuscatedClientSessionState produces obfuscated session tickets.
  435. //
  436. // # Obfuscated Session Tickets
  437. //
  438. // Obfuscated session tickets is a network traffic obfuscation protocol that appears
  439. // to be valid TLS using session tickets. The client actually generates the session
  440. // ticket and encrypts it with a shared secret, enabling a TLS session that entirely
  441. // skips the most fingerprintable aspects of TLS.
  442. // The scheme is described here:
  443. // https://lists.torproject.org/pipermail/tor-dev/2016-September/011354.html
  444. //
  445. // Circumvention notes:
  446. // - TLS session ticket implementations are widespread:
  447. // https://istlsfastyet.com/#cdn-paas.
  448. // - An adversary cannot easily block session ticket capability, as this requires
  449. // a downgrade attack against TLS.
  450. // - Anti-probing defence is provided, as the adversary must use the correct obfuscation
  451. // shared secret to form valid obfuscation session ticket; otherwise server offers
  452. // standard session tickets.
  453. // - Limitation: an adversary with the obfuscation shared secret can decrypt the session
  454. // ticket and observe the plaintext traffic. It's assumed that the adversary will not
  455. // learn the obfuscated shared secret without also learning the address of the TLS
  456. // server and blocking it anyway; it's also assumed that the TLS payload is not
  457. // plaintext but is protected with some other security layer (e.g., SSH).
  458. //
  459. // Implementation notes:
  460. // - The TLS ClientHello includes an SNI field, even when using session tickets, so
  461. // the client should populate the ServerName.
  462. // - Server should set its SetSessionTicketKeys with first a standard key, followed by
  463. // the obfuscation shared secret.
  464. // - Since the client creates the session ticket, it selects parameters that were not
  465. // negotiated with the server, such as the cipher suite. It's implicitly assumed that
  466. // the server can support the selected parameters.
  467. // - Obfuscated session tickets are not supported for TLS 1.3 _clients_, which use a
  468. // distinct scheme. Obfuscated session ticket support in this package is intended to
  469. // support TLS 1.2 clients.
  470. func NewObfuscatedClientSessionState(sharedSecret [32]byte) (*ObfuscatedClientSessionState, error) {
  471. // Create a session ticket that wasn't actually issued by the server.
  472. vers := uint16(VersionTLS12)
  473. cipherSuite := obfuscatedSessionTicketCipherSuite
  474. masterSecret := make([]byte, masterSecretLength)
  475. _, err := rand.Read(masterSecret)
  476. if err != nil {
  477. return nil, err
  478. }
  479. serverState := &SessionState{
  480. version: vers,
  481. cipherSuite: cipherSuite,
  482. secret: masterSecret,
  483. peerCertificates: nil,
  484. }
  485. config := &Config{}
  486. sessionTicketKeys := []ticketKey{config.ticketKeyFromBytes(sharedSecret)}
  487. ssBytes, err := serverState.Bytes()
  488. if err != nil {
  489. return nil, err
  490. }
  491. sessionTicket, err := config.encryptTicket(ssBytes, sessionTicketKeys)
  492. if err != nil {
  493. return nil, err
  494. }
  495. // ObfuscatedClientSessionState fields are used to construct
  496. // ClientSessionState objects for use in ClientSessionCaches. The client will
  497. // use this cache to pretend it got that session ticket from the server.
  498. clientState := &ObfuscatedClientSessionState{
  499. SessionTicket: sessionTicket,
  500. Vers: vers,
  501. CipherSuite: cipherSuite,
  502. MasterSecret: masterSecret,
  503. }
  504. return clientState, nil
  505. }
  506. func ContainsObfuscatedSessionTicketCipherSuite(cipherSuites []uint16) bool {
  507. for _, cipherSuite := range cipherSuites {
  508. if cipherSuite == obfuscatedSessionTicketCipherSuite {
  509. return true
  510. }
  511. }
  512. return false
  513. }
  514. // allZeros returns true if remaining bytes are all zero.
  515. func allZeros(s cryptobyte.String) bool {
  516. b := []byte(s)
  517. for _, v := range b {
  518. if v != 0x0 {
  519. return false
  520. }
  521. }
  522. return true
  523. }