ticket.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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/sha256"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "errors"
  13. "io"
  14. "golang.org/x/crypto/cryptobyte"
  15. )
  16. // A SessionState is a resumable session.
  17. type SessionState struct {
  18. // Encoded as a SessionState (in the language of RFC 8446, Section 3).
  19. //
  20. // enum { server(1), client(2) } SessionStateType;
  21. //
  22. // opaque Certificate<1..2^24-1>;
  23. //
  24. // Certificate CertificateChain<0..2^24-1>;
  25. //
  26. // opaque Extra<0..2^24-1>;
  27. //
  28. // struct {
  29. // uint16 version;
  30. // SessionStateType type;
  31. // uint16 cipher_suite;
  32. // uint64 created_at;
  33. // opaque secret<1..2^8-1>;
  34. // Extra extra<0..2^24-1>;
  35. // uint8 ext_master_secret = { 0, 1 };
  36. // uint8 early_data = { 0, 1 };
  37. // CertificateEntry certificate_list<0..2^24-1>;
  38. // CertificateChain verified_chains<0..2^24-1>; /* excluding leaf */
  39. // select (SessionState.early_data) {
  40. // case 0: Empty;
  41. // case 1: opaque alpn<1..2^8-1>;
  42. // };
  43. // select (SessionState.type) {
  44. // case server: Empty;
  45. // case client: struct {
  46. // select (SessionState.version) {
  47. // case VersionTLS10..VersionTLS12: Empty;
  48. // case VersionTLS13: struct {
  49. // uint64 use_by;
  50. // uint32 age_add;
  51. // };
  52. // };
  53. // };
  54. // };
  55. // } SessionState;
  56. //
  57. // Extra is ignored by crypto/tls, but is encoded by [SessionState.Bytes]
  58. // and parsed by [ParseSessionState].
  59. //
  60. // This allows [Config.UnwrapSession]/[Config.WrapSession] and
  61. // [ClientSessionCache] implementations to store and retrieve additional
  62. // data alongside this session.
  63. //
  64. // To allow different layers in a protocol stack to share this field,
  65. // applications must only append to it, not replace it, and must use entries
  66. // that can be recognized even if out of order (for example, by starting
  67. // with an id and version prefix).
  68. Extra [][]byte
  69. // EarlyData indicates whether the ticket can be used for 0-RTT in a QUIC
  70. // connection. The application may set this to false if it is true to
  71. // decline to offer 0-RTT even if supported.
  72. EarlyData bool
  73. version uint16
  74. isClient bool
  75. cipherSuite uint16
  76. // createdAt is the generation time of the secret on the sever (which for
  77. // TLS 1.0–1.2 might be earlier than the current session) and the time at
  78. // which the ticket was received on the client.
  79. createdAt uint64 // seconds since UNIX epoch
  80. secret []byte // master secret for TLS 1.2, or the PSK for TLS 1.3
  81. extMasterSecret bool
  82. peerCertificates []*x509.Certificate
  83. activeCertHandles []*activeCert
  84. ocspResponse []byte
  85. scts [][]byte
  86. verifiedChains [][]*x509.Certificate
  87. alpnProtocol string // only set if EarlyData is true
  88. // Client-side TLS 1.3-only fields.
  89. useBy uint64 // seconds since UNIX epoch
  90. ageAdd uint32
  91. }
  92. // Bytes encodes the session, including any private fields, so that it can be
  93. // parsed by [ParseSessionState]. The encoding contains secret values critical
  94. // to the security of future and possibly past sessions.
  95. //
  96. // The specific encoding should be considered opaque and may change incompatibly
  97. // between Go versions.
  98. func (s *SessionState) Bytes() ([]byte, error) {
  99. var b cryptobyte.Builder
  100. b.AddUint16(s.version)
  101. if s.isClient {
  102. b.AddUint8(2) // client
  103. } else {
  104. b.AddUint8(1) // server
  105. }
  106. b.AddUint16(s.cipherSuite)
  107. addUint64(&b, s.createdAt)
  108. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  109. b.AddBytes(s.secret)
  110. })
  111. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  112. for _, extra := range s.Extra {
  113. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  114. b.AddBytes(extra)
  115. })
  116. }
  117. })
  118. if s.extMasterSecret {
  119. b.AddUint8(1)
  120. } else {
  121. b.AddUint8(0)
  122. }
  123. if s.EarlyData {
  124. b.AddUint8(1)
  125. } else {
  126. b.AddUint8(0)
  127. }
  128. marshalCertificate(&b, Certificate{
  129. Certificate: certificatesToBytesSlice(s.peerCertificates),
  130. OCSPStaple: s.ocspResponse,
  131. SignedCertificateTimestamps: s.scts,
  132. })
  133. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  134. for _, chain := range s.verifiedChains {
  135. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  136. // We elide the first certificate because it's always the leaf.
  137. if len(chain) == 0 {
  138. b.SetError(errors.New("tls: internal error: empty verified chain"))
  139. return
  140. }
  141. for _, cert := range chain[1:] {
  142. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  143. b.AddBytes(cert.Raw)
  144. })
  145. }
  146. })
  147. }
  148. })
  149. if s.EarlyData {
  150. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  151. b.AddBytes([]byte(s.alpnProtocol))
  152. })
  153. }
  154. if s.isClient {
  155. if s.version >= VersionTLS13 {
  156. addUint64(&b, s.useBy)
  157. b.AddUint32(s.ageAdd)
  158. }
  159. }
  160. return b.Bytes()
  161. }
  162. func certificatesToBytesSlice(certs []*x509.Certificate) [][]byte {
  163. s := make([][]byte, 0, len(certs))
  164. for _, c := range certs {
  165. s = append(s, c.Raw)
  166. }
  167. return s
  168. }
  169. // ParseSessionState parses a [SessionState] encoded by [SessionState.Bytes].
  170. func ParseSessionState(data []byte) (*SessionState, error) {
  171. ss := &SessionState{}
  172. s := cryptobyte.String(data)
  173. var typ, extMasterSecret, earlyData uint8
  174. var cert Certificate
  175. var extra cryptobyte.String
  176. if !s.ReadUint16(&ss.version) ||
  177. !s.ReadUint8(&typ) ||
  178. (typ != 1 && typ != 2) ||
  179. !s.ReadUint16(&ss.cipherSuite) ||
  180. !readUint64(&s, &ss.createdAt) ||
  181. !readUint8LengthPrefixed(&s, &ss.secret) ||
  182. !s.ReadUint24LengthPrefixed(&extra) ||
  183. !s.ReadUint8(&extMasterSecret) ||
  184. !s.ReadUint8(&earlyData) ||
  185. len(ss.secret) == 0 ||
  186. !unmarshalCertificate(&s, &cert) {
  187. return nil, errors.New("tls: invalid session encoding")
  188. }
  189. for !extra.Empty() {
  190. var e []byte
  191. if !readUint24LengthPrefixed(&extra, &e) {
  192. return nil, errors.New("tls: invalid session encoding")
  193. }
  194. ss.Extra = append(ss.Extra, e)
  195. }
  196. switch extMasterSecret {
  197. case 0:
  198. ss.extMasterSecret = false
  199. case 1:
  200. ss.extMasterSecret = true
  201. default:
  202. return nil, errors.New("tls: invalid session encoding")
  203. }
  204. switch earlyData {
  205. case 0:
  206. ss.EarlyData = false
  207. case 1:
  208. ss.EarlyData = true
  209. default:
  210. return nil, errors.New("tls: invalid session encoding")
  211. }
  212. for _, cert := range cert.Certificate {
  213. c, err := globalCertCache.newCert(cert)
  214. if err != nil {
  215. return nil, err
  216. }
  217. ss.activeCertHandles = append(ss.activeCertHandles, c)
  218. ss.peerCertificates = append(ss.peerCertificates, c.cert)
  219. }
  220. ss.ocspResponse = cert.OCSPStaple
  221. ss.scts = cert.SignedCertificateTimestamps
  222. var chainList cryptobyte.String
  223. if !s.ReadUint24LengthPrefixed(&chainList) {
  224. return nil, errors.New("tls: invalid session encoding")
  225. }
  226. for !chainList.Empty() {
  227. var certList cryptobyte.String
  228. if !chainList.ReadUint24LengthPrefixed(&certList) {
  229. return nil, errors.New("tls: invalid session encoding")
  230. }
  231. var chain []*x509.Certificate
  232. if len(ss.peerCertificates) == 0 {
  233. return nil, errors.New("tls: invalid session encoding")
  234. }
  235. chain = append(chain, ss.peerCertificates[0])
  236. for !certList.Empty() {
  237. var cert []byte
  238. if !readUint24LengthPrefixed(&certList, &cert) {
  239. return nil, errors.New("tls: invalid session encoding")
  240. }
  241. c, err := globalCertCache.newCert(cert)
  242. if err != nil {
  243. return nil, err
  244. }
  245. ss.activeCertHandles = append(ss.activeCertHandles, c)
  246. chain = append(chain, c.cert)
  247. }
  248. ss.verifiedChains = append(ss.verifiedChains, chain)
  249. }
  250. if ss.EarlyData {
  251. var alpn []byte
  252. if !readUint8LengthPrefixed(&s, &alpn) {
  253. return nil, errors.New("tls: invalid session encoding")
  254. }
  255. ss.alpnProtocol = string(alpn)
  256. }
  257. if isClient := typ == 2; !isClient {
  258. if !s.Empty() {
  259. return nil, errors.New("tls: invalid session encoding")
  260. }
  261. return ss, nil
  262. }
  263. ss.isClient = true
  264. if len(ss.peerCertificates) == 0 {
  265. return nil, errors.New("tls: no server certificates in client session")
  266. }
  267. if ss.version < VersionTLS13 {
  268. if !s.Empty() {
  269. return nil, errors.New("tls: invalid session encoding")
  270. }
  271. return ss, nil
  272. }
  273. if !s.ReadUint64(&ss.useBy) || !s.ReadUint32(&ss.ageAdd) || !s.Empty() {
  274. return nil, errors.New("tls: invalid session encoding")
  275. }
  276. return ss, nil
  277. }
  278. // sessionState returns a partially filled-out [SessionState] with information
  279. // from the current connection.
  280. func (c *Conn) sessionState() (*SessionState, error) {
  281. return &SessionState{
  282. version: c.vers,
  283. cipherSuite: c.cipherSuite,
  284. createdAt: uint64(c.config.time().Unix()),
  285. alpnProtocol: c.clientProtocol,
  286. peerCertificates: c.peerCertificates,
  287. activeCertHandles: c.activeCertHandles,
  288. ocspResponse: c.ocspResponse,
  289. scts: c.scts,
  290. isClient: c.isClient,
  291. extMasterSecret: c.extMasterSecret,
  292. verifiedChains: c.verifiedChains,
  293. }, nil
  294. }
  295. // EncryptTicket encrypts a ticket with the [Config]'s configured (or default)
  296. // session ticket keys. It can be used as a [Config.WrapSession] implementation.
  297. func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error) {
  298. ticketKeys := c.ticketKeys(nil)
  299. stateBytes, err := ss.Bytes()
  300. if err != nil {
  301. return nil, err
  302. }
  303. return c.encryptTicket(stateBytes, ticketKeys)
  304. }
  305. func (c *Config) encryptTicket(state []byte, ticketKeys []ticketKey) ([]byte, error) {
  306. if len(ticketKeys) == 0 {
  307. return nil, errors.New("tls: internal error: session ticket keys unavailable")
  308. }
  309. encrypted := make([]byte, aes.BlockSize+len(state)+sha256.Size)
  310. iv := encrypted[:aes.BlockSize]
  311. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  312. authenticated := encrypted[:len(encrypted)-sha256.Size]
  313. macBytes := encrypted[len(encrypted)-sha256.Size:]
  314. if _, err := io.ReadFull(c.rand(), iv); err != nil {
  315. return nil, err
  316. }
  317. key := ticketKeys[0]
  318. block, err := aes.NewCipher(key.aesKey[:])
  319. if err != nil {
  320. return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error())
  321. }
  322. cipher.NewCTR(block, iv).XORKeyStream(ciphertext, state)
  323. mac := hmac.New(sha256.New, key.hmacKey[:])
  324. mac.Write(authenticated)
  325. mac.Sum(macBytes[:0])
  326. return encrypted, nil
  327. }
  328. // DecryptTicket decrypts a ticket encrypted by [Config.EncryptTicket]. It can
  329. // be used as a [Config.UnwrapSession] implementation.
  330. //
  331. // If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).
  332. func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error) {
  333. ticketKeys := c.ticketKeys(nil)
  334. stateBytes := c.decryptTicket(identity, ticketKeys)
  335. if stateBytes == nil {
  336. return nil, nil
  337. }
  338. s, err := ParseSessionState(stateBytes)
  339. if err != nil {
  340. return nil, nil // drop unparsable tickets on the floor
  341. }
  342. return s, nil
  343. }
  344. func (c *Config) decryptTicket(encrypted []byte, ticketKeys []ticketKey) []byte {
  345. if len(encrypted) < aes.BlockSize+sha256.Size {
  346. return nil
  347. }
  348. iv := encrypted[:aes.BlockSize]
  349. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  350. authenticated := encrypted[:len(encrypted)-sha256.Size]
  351. macBytes := encrypted[len(encrypted)-sha256.Size:]
  352. for _, key := range ticketKeys {
  353. mac := hmac.New(sha256.New, key.hmacKey[:])
  354. mac.Write(authenticated)
  355. expected := mac.Sum(nil)
  356. if subtle.ConstantTimeCompare(macBytes, expected) != 1 {
  357. continue
  358. }
  359. block, err := aes.NewCipher(key.aesKey[:])
  360. if err != nil {
  361. return nil
  362. }
  363. plaintext := make([]byte, len(ciphertext))
  364. cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext)
  365. return plaintext
  366. }
  367. return nil
  368. }
  369. // ClientSessionState contains the state needed by a client to
  370. // resume a previous TLS session.
  371. type ClientSessionState struct {
  372. ticket []byte
  373. session *SessionState
  374. }
  375. // ResumptionState returns the session ticket sent by the server (also known as
  376. // the session's identity) and the state necessary to resume this session.
  377. //
  378. // It can be called by [ClientSessionCache.Put] to serialize (with
  379. // [SessionState.Bytes]) and store the session.
  380. func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error) {
  381. return cs.ticket, cs.session, nil
  382. }
  383. // NewResumptionState returns a state value that can be returned by
  384. // [ClientSessionCache.Get] to resume a previous session.
  385. //
  386. // state needs to be returned by [ParseSessionState], and the ticket and session
  387. // state must have been returned by [ClientSessionState.ResumptionState].
  388. func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error) {
  389. return &ClientSessionState{
  390. ticket: ticket, session: state,
  391. }, nil
  392. }
  393. // // DecryptTicketWith decrypts an encrypted session ticket
  394. // // using a TicketKeys (ie []TicketKey) struct
  395. // //
  396. // // usedOldKey will be true if the key used for decryption is
  397. // // not the first in the []TicketKey slice
  398. // //
  399. // // [uTLS] changed to be made public and take a TicketKeys and use a fake conn receiver
  400. // func DecryptTicketWith(encrypted []byte, tks TicketKeys) (plaintext []byte, usedOldKey bool) {
  401. // // create fake conn
  402. // c := &Conn{
  403. // ticketKeys: tks.ToPrivate(),
  404. // }
  405. // return c.decryptTicket(encrypted)
  406. // }