ticket.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. ticket []byte
  92. }
  93. // Bytes encodes the session, including any private fields, so that it can be
  94. // parsed by [ParseSessionState]. The encoding contains secret values critical
  95. // to the security of future and possibly past sessions.
  96. //
  97. // The specific encoding should be considered opaque and may change incompatibly
  98. // between Go versions.
  99. func (s *SessionState) Bytes() ([]byte, error) {
  100. var b cryptobyte.Builder
  101. b.AddUint16(s.version)
  102. if s.isClient {
  103. b.AddUint8(2) // client
  104. } else {
  105. b.AddUint8(1) // server
  106. }
  107. b.AddUint16(s.cipherSuite)
  108. addUint64(&b, s.createdAt)
  109. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  110. b.AddBytes(s.secret)
  111. })
  112. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  113. for _, extra := range s.Extra {
  114. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  115. b.AddBytes(extra)
  116. })
  117. }
  118. })
  119. if s.extMasterSecret {
  120. b.AddUint8(1)
  121. } else {
  122. b.AddUint8(0)
  123. }
  124. if s.EarlyData {
  125. b.AddUint8(1)
  126. } else {
  127. b.AddUint8(0)
  128. }
  129. marshalCertificate(&b, Certificate{
  130. Certificate: certificatesToBytesSlice(s.peerCertificates),
  131. OCSPStaple: s.ocspResponse,
  132. SignedCertificateTimestamps: s.scts,
  133. })
  134. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  135. for _, chain := range s.verifiedChains {
  136. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  137. // We elide the first certificate because it's always the leaf.
  138. if len(chain) == 0 {
  139. b.SetError(errors.New("tls: internal error: empty verified chain"))
  140. return
  141. }
  142. for _, cert := range chain[1:] {
  143. b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  144. b.AddBytes(cert.Raw)
  145. })
  146. }
  147. })
  148. }
  149. })
  150. if s.EarlyData {
  151. b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  152. b.AddBytes([]byte(s.alpnProtocol))
  153. })
  154. }
  155. if s.isClient {
  156. if s.version >= VersionTLS13 {
  157. addUint64(&b, s.useBy)
  158. b.AddUint32(s.ageAdd)
  159. }
  160. }
  161. return b.Bytes()
  162. }
  163. func certificatesToBytesSlice(certs []*x509.Certificate) [][]byte {
  164. s := make([][]byte, 0, len(certs))
  165. for _, c := range certs {
  166. s = append(s, c.Raw)
  167. }
  168. return s
  169. }
  170. // ParseSessionState parses a [SessionState] encoded by [SessionState.Bytes].
  171. func ParseSessionState(data []byte) (*SessionState, error) {
  172. ss := &SessionState{}
  173. s := cryptobyte.String(data)
  174. var typ, extMasterSecret, earlyData uint8
  175. var cert Certificate
  176. var extra cryptobyte.String
  177. if !s.ReadUint16(&ss.version) ||
  178. !s.ReadUint8(&typ) ||
  179. (typ != 1 && typ != 2) ||
  180. !s.ReadUint16(&ss.cipherSuite) ||
  181. !readUint64(&s, &ss.createdAt) ||
  182. !readUint8LengthPrefixed(&s, &ss.secret) ||
  183. !s.ReadUint24LengthPrefixed(&extra) ||
  184. !s.ReadUint8(&extMasterSecret) ||
  185. !s.ReadUint8(&earlyData) ||
  186. len(ss.secret) == 0 ||
  187. !unmarshalCertificate(&s, &cert) {
  188. return nil, errors.New("tls: invalid session encoding")
  189. }
  190. for !extra.Empty() {
  191. var e []byte
  192. if !readUint24LengthPrefixed(&extra, &e) {
  193. return nil, errors.New("tls: invalid session encoding")
  194. }
  195. ss.Extra = append(ss.Extra, e)
  196. }
  197. switch extMasterSecret {
  198. case 0:
  199. ss.extMasterSecret = false
  200. case 1:
  201. ss.extMasterSecret = true
  202. default:
  203. return nil, errors.New("tls: invalid session encoding")
  204. }
  205. switch earlyData {
  206. case 0:
  207. ss.EarlyData = false
  208. case 1:
  209. ss.EarlyData = true
  210. default:
  211. return nil, errors.New("tls: invalid session encoding")
  212. }
  213. for _, cert := range cert.Certificate {
  214. c, err := globalCertCache.newCert(cert)
  215. if err != nil {
  216. return nil, err
  217. }
  218. ss.activeCertHandles = append(ss.activeCertHandles, c)
  219. ss.peerCertificates = append(ss.peerCertificates, c.cert)
  220. }
  221. ss.ocspResponse = cert.OCSPStaple
  222. ss.scts = cert.SignedCertificateTimestamps
  223. var chainList cryptobyte.String
  224. if !s.ReadUint24LengthPrefixed(&chainList) {
  225. return nil, errors.New("tls: invalid session encoding")
  226. }
  227. for !chainList.Empty() {
  228. var certList cryptobyte.String
  229. if !chainList.ReadUint24LengthPrefixed(&certList) {
  230. return nil, errors.New("tls: invalid session encoding")
  231. }
  232. var chain []*x509.Certificate
  233. if len(ss.peerCertificates) == 0 {
  234. return nil, errors.New("tls: invalid session encoding")
  235. }
  236. chain = append(chain, ss.peerCertificates[0])
  237. for !certList.Empty() {
  238. var cert []byte
  239. if !readUint24LengthPrefixed(&certList, &cert) {
  240. return nil, errors.New("tls: invalid session encoding")
  241. }
  242. c, err := globalCertCache.newCert(cert)
  243. if err != nil {
  244. return nil, err
  245. }
  246. ss.activeCertHandles = append(ss.activeCertHandles, c)
  247. chain = append(chain, c.cert)
  248. }
  249. ss.verifiedChains = append(ss.verifiedChains, chain)
  250. }
  251. if ss.EarlyData {
  252. var alpn []byte
  253. if !readUint8LengthPrefixed(&s, &alpn) {
  254. return nil, errors.New("tls: invalid session encoding")
  255. }
  256. ss.alpnProtocol = string(alpn)
  257. }
  258. if isClient := typ == 2; !isClient {
  259. if !s.Empty() {
  260. return nil, errors.New("tls: invalid session encoding")
  261. }
  262. return ss, nil
  263. }
  264. ss.isClient = true
  265. if len(ss.peerCertificates) == 0 {
  266. return nil, errors.New("tls: no server certificates in client session")
  267. }
  268. if ss.version < VersionTLS13 {
  269. if !s.Empty() {
  270. return nil, errors.New("tls: invalid session encoding")
  271. }
  272. return ss, nil
  273. }
  274. if !s.ReadUint64(&ss.useBy) || !s.ReadUint32(&ss.ageAdd) || !s.Empty() {
  275. return nil, errors.New("tls: invalid session encoding")
  276. }
  277. return ss, nil
  278. }
  279. // sessionState returns a partially filled-out [SessionState] with information
  280. // from the current connection.
  281. func (c *Conn) sessionState() *SessionState {
  282. return &SessionState{
  283. version: c.vers,
  284. cipherSuite: c.cipherSuite,
  285. createdAt: uint64(c.config.time().Unix()),
  286. alpnProtocol: c.clientProtocol,
  287. peerCertificates: c.peerCertificates,
  288. activeCertHandles: c.activeCertHandles,
  289. ocspResponse: c.ocspResponse,
  290. scts: c.scts,
  291. isClient: c.isClient,
  292. extMasterSecret: c.extMasterSecret,
  293. verifiedChains: c.verifiedChains,
  294. }
  295. }
  296. // EncryptTicket encrypts a ticket with the [Config]'s configured (or default)
  297. // session ticket keys. It can be used as a [Config.WrapSession] implementation.
  298. func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error) {
  299. ticketKeys := c.ticketKeys(nil)
  300. stateBytes, err := ss.Bytes()
  301. if err != nil {
  302. return nil, err
  303. }
  304. return c.encryptTicket(stateBytes, ticketKeys)
  305. }
  306. func (c *Config) encryptTicket(state []byte, ticketKeys []ticketKey) ([]byte, error) {
  307. if len(ticketKeys) == 0 {
  308. return nil, errors.New("tls: internal error: session ticket keys unavailable")
  309. }
  310. encrypted := make([]byte, aes.BlockSize+len(state)+sha256.Size)
  311. iv := encrypted[:aes.BlockSize]
  312. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  313. authenticated := encrypted[:len(encrypted)-sha256.Size]
  314. macBytes := encrypted[len(encrypted)-sha256.Size:]
  315. if _, err := io.ReadFull(c.rand(), iv); err != nil {
  316. return nil, err
  317. }
  318. key := ticketKeys[0]
  319. block, err := aes.NewCipher(key.aesKey[:])
  320. if err != nil {
  321. return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error())
  322. }
  323. cipher.NewCTR(block, iv).XORKeyStream(ciphertext, state)
  324. mac := hmac.New(sha256.New, key.hmacKey[:])
  325. mac.Write(authenticated)
  326. mac.Sum(macBytes[:0])
  327. return encrypted, nil
  328. }
  329. // DecryptTicket decrypts a ticket encrypted by [Config.EncryptTicket]. It can
  330. // be used as a [Config.UnwrapSession] implementation.
  331. //
  332. // If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).
  333. func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error) {
  334. ticketKeys := c.ticketKeys(nil)
  335. stateBytes := c.decryptTicket(identity, ticketKeys)
  336. if stateBytes == nil {
  337. return nil, nil
  338. }
  339. s, err := ParseSessionState(stateBytes)
  340. if err != nil {
  341. return nil, nil // drop unparsable tickets on the floor
  342. }
  343. return s, nil
  344. }
  345. func (c *Config) decryptTicket(encrypted []byte, ticketKeys []ticketKey) []byte {
  346. if len(encrypted) < aes.BlockSize+sha256.Size {
  347. return nil
  348. }
  349. iv := encrypted[:aes.BlockSize]
  350. ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size]
  351. authenticated := encrypted[:len(encrypted)-sha256.Size]
  352. macBytes := encrypted[len(encrypted)-sha256.Size:]
  353. for _, key := range ticketKeys {
  354. mac := hmac.New(sha256.New, key.hmacKey[:])
  355. mac.Write(authenticated)
  356. expected := mac.Sum(nil)
  357. if subtle.ConstantTimeCompare(macBytes, expected) != 1 {
  358. continue
  359. }
  360. block, err := aes.NewCipher(key.aesKey[:])
  361. if err != nil {
  362. return nil
  363. }
  364. plaintext := make([]byte, len(ciphertext))
  365. cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext)
  366. return plaintext
  367. }
  368. return nil
  369. }
  370. // ClientSessionState contains the state needed by a client to
  371. // resume a previous TLS session.
  372. type ClientSessionState struct {
  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. if cs == nil || cs.session == nil {
  382. return nil, nil, nil
  383. }
  384. return cs.session.ticket, cs.session, nil
  385. }
  386. // NewResumptionState returns a state value that can be returned by
  387. // [ClientSessionCache.Get] to resume a previous session.
  388. //
  389. // state needs to be returned by [ParseSessionState], and the ticket and session
  390. // state must have been returned by [ClientSessionState.ResumptionState].
  391. func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error) {
  392. state.ticket = ticket
  393. return &ClientSessionState{
  394. session: state,
  395. }, nil
  396. }