Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

1726 Zeilen
48 KiB

  1. // Copyright 2010 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. // TLS low level connection and record layer
  5. package tls
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "encoding/binary"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "sync"
  17. "sync/atomic"
  18. "time"
  19. )
  20. // A Conn represents a secured connection.
  21. // It implements the net.Conn interface.
  22. type Conn struct {
  23. // constant
  24. conn net.Conn
  25. isClient bool
  26. phase handshakeStatus // protected by in.Mutex
  27. // handshakeConfirmed is an atomic bool for phase == handshakeConfirmed
  28. handshakeConfirmed int32
  29. // confirmMutex is held by any read operation before handshakeConfirmed
  30. confirmMutex sync.Mutex
  31. // constant after handshake; protected by handshakeMutex
  32. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  33. handshakeErr error // error resulting from handshake
  34. connID []byte // Random connection id
  35. clientHello []byte // ClientHello packet contents
  36. vers uint16 // TLS version
  37. haveVers bool // version has been negotiated
  38. config *Config // configuration passed to constructor
  39. // handshakeComplete is true if the connection reached application data
  40. // and it's equivalent to phase > handshakeRunning
  41. handshakeComplete bool
  42. // handshakes counts the number of handshakes performed on the
  43. // connection so far. If renegotiation is disabled then this is either
  44. // zero or one.
  45. handshakes int
  46. didResume bool // whether this connection was a session resumption
  47. cipherSuite uint16
  48. ocspResponse []byte // stapled OCSP response
  49. scts [][]byte // Signed certificate timestamps from server
  50. peerCertificates []*x509.Certificate
  51. // verifiedChains contains the certificate chains that we built, as
  52. // opposed to the ones presented by the server.
  53. verifiedChains [][]*x509.Certificate
  54. // verifiedDc is set by a client who negotiates the use of a valid delegated
  55. // credential.
  56. verifiedDc *delegatedCredential
  57. // serverName contains the server name indicated by the client, if any.
  58. serverName string
  59. // secureRenegotiation is true if the server echoed the secure
  60. // renegotiation extension. (This is meaningless as a server because
  61. // renegotiation is not supported in that case.)
  62. secureRenegotiation bool
  63. // clientFinishedIsFirst is true if the client sent the first Finished
  64. // message during the most recent handshake. This is recorded because
  65. // the first transmitted Finished message is the tls-unique
  66. // channel-binding value.
  67. clientFinishedIsFirst bool
  68. // closeNotifyErr is any error from sending the alertCloseNotify record.
  69. closeNotifyErr error
  70. // closeNotifySent is true if the Conn attempted to send an
  71. // alertCloseNotify record.
  72. closeNotifySent bool
  73. // clientFinished and serverFinished contain the Finished message sent
  74. // by the client or server in the most recent handshake. This is
  75. // retained to support the renegotiation extension and tls-unique
  76. // channel-binding.
  77. clientFinished [12]byte
  78. serverFinished [12]byte
  79. clientProtocol string
  80. clientProtocolFallback bool
  81. // ticketMaxEarlyData is the maximum bytes of 0-RTT application data
  82. // that the client is allowed to send on the ticket it used.
  83. ticketMaxEarlyData int64
  84. // input/output
  85. in, out halfConn // in.Mutex < out.Mutex
  86. rawInput *block // raw input, right off the wire
  87. input *block // application data waiting to be read
  88. hand bytes.Buffer // handshake data waiting to be read
  89. buffering bool // whether records are buffered in sendBuf
  90. sendBuf []byte // a buffer of records waiting to be sent
  91. // bytesSent counts the bytes of application data sent.
  92. // packetsSent counts packets.
  93. bytesSent int64
  94. packetsSent int64
  95. // warnCount counts the number of consecutive warning alerts received
  96. // by Conn.readRecord. Protected by in.Mutex.
  97. warnCount int
  98. // activeCall is an atomic int32; the low bit is whether Close has
  99. // been called. the rest of the bits are the number of goroutines
  100. // in Conn.Write.
  101. activeCall int32
  102. // TLS 1.3 needs the server state until it reaches the Client Finished
  103. hs *serverHandshakeState
  104. // earlyDataBytes is the number of bytes of early data received so
  105. // far. Tracked to enforce max_early_data_size.
  106. // We don't keep track of rejected 0-RTT data since there's no need
  107. // to ever buffer it. in.Mutex.
  108. earlyDataBytes int64
  109. // binder is the value of the PSK binder that was validated to
  110. // accept the 0-RTT data. Exposed as ConnectionState.Unique0RTTToken.
  111. binder []byte
  112. tmp [16]byte
  113. }
  114. type handshakeStatus int
  115. const (
  116. handshakeRunning handshakeStatus = iota
  117. discardingEarlyData
  118. readingEarlyData
  119. waitingClientFinished
  120. readingClientFinished
  121. handshakeConfirmed
  122. )
  123. // Access to net.Conn methods.
  124. // Cannot just embed net.Conn because that would
  125. // export the struct field too.
  126. // LocalAddr returns the local network address.
  127. func (c *Conn) LocalAddr() net.Addr {
  128. return c.conn.LocalAddr()
  129. }
  130. // RemoteAddr returns the remote network address.
  131. func (c *Conn) RemoteAddr() net.Addr {
  132. return c.conn.RemoteAddr()
  133. }
  134. // SetDeadline sets the read and write deadlines associated with the connection.
  135. // A zero value for t means Read and Write will not time out.
  136. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  137. func (c *Conn) SetDeadline(t time.Time) error {
  138. return c.conn.SetDeadline(t)
  139. }
  140. // SetReadDeadline sets the read deadline on the underlying connection.
  141. // A zero value for t means Read will not time out.
  142. func (c *Conn) SetReadDeadline(t time.Time) error {
  143. return c.conn.SetReadDeadline(t)
  144. }
  145. // SetWriteDeadline sets the write deadline on the underlying connection.
  146. // A zero value for t means Write will not time out.
  147. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  148. func (c *Conn) SetWriteDeadline(t time.Time) error {
  149. return c.conn.SetWriteDeadline(t)
  150. }
  151. // A halfConn represents one direction of the record layer
  152. // connection, either sending or receiving.
  153. type halfConn struct {
  154. sync.Mutex
  155. err error // first permanent error
  156. version uint16 // protocol version
  157. cipher interface{} // cipher algorithm
  158. mac macFunction
  159. seq [8]byte // 64-bit sequence number
  160. bfree *block // list of free blocks
  161. additionalData [13]byte // to avoid allocs; interface method args escape
  162. nextCipher interface{} // next encryption state
  163. nextMac macFunction // next MAC algorithm
  164. // used to save allocating a new buffer for each MAC.
  165. inDigestBuf, outDigestBuf []byte
  166. traceErr func(error)
  167. }
  168. func (hc *halfConn) setErrorLocked(err error) error {
  169. hc.err = err
  170. if hc.traceErr != nil {
  171. hc.traceErr(err)
  172. }
  173. return err
  174. }
  175. // prepareCipherSpec sets the encryption and MAC states
  176. // that a subsequent changeCipherSpec will use.
  177. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  178. hc.version = version
  179. hc.nextCipher = cipher
  180. hc.nextMac = mac
  181. }
  182. // changeCipherSpec changes the encryption and MAC states
  183. // to the ones previously passed to prepareCipherSpec.
  184. func (hc *halfConn) changeCipherSpec() error {
  185. if hc.nextCipher == nil {
  186. return alertInternalError
  187. }
  188. hc.cipher = hc.nextCipher
  189. hc.mac = hc.nextMac
  190. hc.nextCipher = nil
  191. hc.nextMac = nil
  192. for i := range hc.seq {
  193. hc.seq[i] = 0
  194. }
  195. return nil
  196. }
  197. func (hc *halfConn) setCipher(version uint16, cipher interface{}) {
  198. hc.version = version
  199. hc.cipher = cipher
  200. for i := range hc.seq {
  201. hc.seq[i] = 0
  202. }
  203. }
  204. // incSeq increments the sequence number.
  205. func (hc *halfConn) incSeq() {
  206. for i := 7; i >= 0; i-- {
  207. hc.seq[i]++
  208. if hc.seq[i] != 0 {
  209. return
  210. }
  211. }
  212. // Not allowed to let sequence number wrap.
  213. // Instead, must renegotiate before it does.
  214. // Not likely enough to bother.
  215. panic("TLS: sequence number wraparound")
  216. }
  217. // extractPadding returns, in constant time, the length of the padding to remove
  218. // from the end of payload. It also returns a byte which is equal to 255 if the
  219. // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  220. func extractPadding(payload []byte) (toRemove int, good byte) {
  221. if len(payload) < 1 {
  222. return 0, 0
  223. }
  224. paddingLen := payload[len(payload)-1]
  225. t := uint(len(payload)-1) - uint(paddingLen)
  226. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  227. good = byte(int32(^t) >> 31)
  228. // The maximum possible padding length plus the actual length field
  229. toCheck := 256
  230. // The length of the padded data is public, so we can use an if here
  231. if toCheck > len(payload) {
  232. toCheck = len(payload)
  233. }
  234. for i := 0; i < toCheck; i++ {
  235. t := uint(paddingLen) - uint(i)
  236. // if i <= paddingLen then the MSB of t is zero
  237. mask := byte(int32(^t) >> 31)
  238. b := payload[len(payload)-1-i]
  239. good &^= mask&paddingLen ^ mask&b
  240. }
  241. // We AND together the bits of good and replicate the result across
  242. // all the bits.
  243. good &= good << 4
  244. good &= good << 2
  245. good &= good << 1
  246. good = uint8(int8(good) >> 7)
  247. toRemove = int(paddingLen) + 1
  248. return
  249. }
  250. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  251. // protocol version is SSLv3. In this version, the contents of the padding
  252. // are random and cannot be checked.
  253. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  254. if len(payload) < 1 {
  255. return 0, 0
  256. }
  257. paddingLen := int(payload[len(payload)-1]) + 1
  258. if paddingLen > len(payload) {
  259. return 0, 0
  260. }
  261. return paddingLen, 255
  262. }
  263. func roundUp(a, b int) int {
  264. return a + (b-a%b)%b
  265. }
  266. // cbcMode is an interface for block ciphers using cipher block chaining.
  267. type cbcMode interface {
  268. cipher.BlockMode
  269. SetIV([]byte)
  270. }
  271. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  272. // success boolean, the number of bytes to skip from the start of the record in
  273. // order to get the application payload, and an optional alert value.
  274. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  275. // pull out payload
  276. payload := b.data[recordHeaderLen:]
  277. macSize := 0
  278. if hc.mac != nil {
  279. macSize = hc.mac.Size()
  280. }
  281. paddingGood := byte(255)
  282. paddingLen := 0
  283. explicitIVLen := 0
  284. // decrypt
  285. if hc.cipher != nil {
  286. switch c := hc.cipher.(type) {
  287. case cipher.Stream:
  288. c.XORKeyStream(payload, payload)
  289. case aead:
  290. explicitIVLen = c.explicitNonceLen()
  291. if len(payload) < explicitIVLen {
  292. return false, 0, alertBadRecordMAC
  293. }
  294. nonce := payload[:explicitIVLen]
  295. payload = payload[explicitIVLen:]
  296. if len(nonce) == 0 {
  297. nonce = hc.seq[:]
  298. }
  299. var additionalData []byte
  300. if hc.version < VersionTLS13 {
  301. copy(hc.additionalData[:], hc.seq[:])
  302. copy(hc.additionalData[8:], b.data[:3])
  303. n := len(payload) - c.Overhead()
  304. hc.additionalData[11] = byte(n >> 8)
  305. hc.additionalData[12] = byte(n)
  306. additionalData = hc.additionalData[:]
  307. } else {
  308. if len(payload) > int((1<<14)+256) {
  309. return false, 0, alertRecordOverflow
  310. }
  311. // Check AD header, see 5.2 of RFC8446
  312. additionalData = make([]byte, 5)
  313. additionalData[0] = byte(recordTypeApplicationData)
  314. binary.BigEndian.PutUint16(additionalData[1:], VersionTLS12)
  315. binary.BigEndian.PutUint16(additionalData[3:], uint16(len(payload)))
  316. }
  317. var err error
  318. payload, err = c.Open(payload[:0], nonce, payload, additionalData)
  319. if err != nil {
  320. return false, 0, alertBadRecordMAC
  321. }
  322. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  323. case cbcMode:
  324. blockSize := c.BlockSize()
  325. if hc.version >= VersionTLS11 {
  326. explicitIVLen = blockSize
  327. }
  328. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  329. return false, 0, alertBadRecordMAC
  330. }
  331. if explicitIVLen > 0 {
  332. c.SetIV(payload[:explicitIVLen])
  333. payload = payload[explicitIVLen:]
  334. }
  335. c.CryptBlocks(payload, payload)
  336. if hc.version == VersionSSL30 {
  337. paddingLen, paddingGood = extractPaddingSSL30(payload)
  338. } else {
  339. paddingLen, paddingGood = extractPadding(payload)
  340. // To protect against CBC padding oracles like Lucky13, the data
  341. // past paddingLen (which is secret) is passed to the MAC
  342. // function as extra data, to be fed into the HMAC after
  343. // computing the digest. This makes the MAC constant time as
  344. // long as the digest computation is constant time and does not
  345. // affect the subsequent write.
  346. }
  347. default:
  348. panic("unknown cipher type")
  349. }
  350. }
  351. // check, strip mac
  352. if hc.mac != nil {
  353. if len(payload) < macSize {
  354. return false, 0, alertBadRecordMAC
  355. }
  356. // strip mac off payload, b.data
  357. n := len(payload) - macSize - paddingLen
  358. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  359. b.data[3] = byte(n >> 8)
  360. b.data[4] = byte(n)
  361. remoteMAC := payload[n : n+macSize]
  362. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
  363. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  364. return false, 0, alertBadRecordMAC
  365. }
  366. hc.inDigestBuf = localMAC
  367. b.resize(recordHeaderLen + explicitIVLen + n)
  368. }
  369. hc.incSeq()
  370. return true, recordHeaderLen + explicitIVLen, 0
  371. }
  372. // padToBlockSize calculates the needed padding block, if any, for a payload.
  373. // On exit, prefix aliases payload and extends to the end of the last full
  374. // block of payload. finalBlock is a fresh slice which contains the contents of
  375. // any suffix of payload as well as the needed padding to make finalBlock a
  376. // full block.
  377. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  378. overrun := len(payload) % blockSize
  379. paddingLen := blockSize - overrun
  380. prefix = payload[:len(payload)-overrun]
  381. finalBlock = make([]byte, blockSize)
  382. copy(finalBlock, payload[len(payload)-overrun:])
  383. for i := overrun; i < blockSize; i++ {
  384. finalBlock[i] = byte(paddingLen - 1)
  385. }
  386. return
  387. }
  388. // encrypt encrypts and macs the data in b.
  389. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  390. // mac
  391. if hc.mac != nil {
  392. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
  393. n := len(b.data)
  394. b.resize(n + len(mac))
  395. copy(b.data[n:], mac)
  396. hc.outDigestBuf = mac
  397. }
  398. payload := b.data[recordHeaderLen:]
  399. // encrypt
  400. if hc.cipher != nil {
  401. switch c := hc.cipher.(type) {
  402. case cipher.Stream:
  403. c.XORKeyStream(payload, payload)
  404. case aead:
  405. // explicitIVLen is always 0 for TLS1.3
  406. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  407. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  408. if len(nonce) == 0 {
  409. nonce = hc.seq[:]
  410. }
  411. payload = b.data[recordHeaderLen+explicitIVLen:]
  412. payload = payload[:payloadLen]
  413. var additionalData []byte
  414. if hc.version < VersionTLS13 {
  415. copy(hc.additionalData[:], hc.seq[:])
  416. copy(hc.additionalData[8:], b.data[:3])
  417. binary.BigEndian.PutUint16(hc.additionalData[11:], uint16(payloadLen))
  418. additionalData = hc.additionalData[:]
  419. b.resize(len(b.data) + c.Overhead())
  420. } else {
  421. // 1 byte of content type is appended to payload and encrypted
  422. payload = append(payload, b.data[0])
  423. // opaque_type
  424. b.data[0] = byte(recordTypeApplicationData)
  425. // Add AD header, see 5.2 of RFC8446
  426. additionalData = make([]byte, 5)
  427. additionalData[0] = b.data[0]
  428. binary.BigEndian.PutUint16(additionalData[1:], VersionTLS12)
  429. binary.BigEndian.PutUint16(additionalData[3:], uint16(len(payload)+c.Overhead()))
  430. // make room for TLSCiphertext.encrypted_record
  431. b.resize(len(payload) + recordHeaderLen + c.Overhead())
  432. }
  433. c.Seal(payload[:0], nonce, payload, additionalData)
  434. case cbcMode:
  435. blockSize := c.BlockSize()
  436. if explicitIVLen > 0 {
  437. c.SetIV(payload[:explicitIVLen])
  438. payload = payload[explicitIVLen:]
  439. }
  440. prefix, finalBlock := padToBlockSize(payload, blockSize)
  441. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  442. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  443. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  444. default:
  445. panic("unknown cipher type")
  446. }
  447. }
  448. // update length to include MAC and any block padding needed.
  449. n := len(b.data) - recordHeaderLen
  450. b.data[3] = byte(n >> 8)
  451. b.data[4] = byte(n)
  452. hc.incSeq()
  453. return true, 0
  454. }
  455. // A block is a simple data buffer.
  456. type block struct {
  457. data []byte
  458. off int // index for Read
  459. link *block
  460. }
  461. // resize resizes block to be n bytes, growing if necessary.
  462. func (b *block) resize(n int) {
  463. if n > cap(b.data) {
  464. b.reserve(n)
  465. }
  466. b.data = b.data[0:n]
  467. }
  468. // reserve makes sure that block contains a capacity of at least n bytes.
  469. func (b *block) reserve(n int) {
  470. if cap(b.data) >= n {
  471. return
  472. }
  473. m := cap(b.data)
  474. if m == 0 {
  475. m = 1024
  476. }
  477. for m < n {
  478. m *= 2
  479. }
  480. data := make([]byte, len(b.data), m)
  481. copy(data, b.data)
  482. b.data = data
  483. }
  484. // readFromUntil reads from r into b until b contains at least n bytes
  485. // or else returns an error.
  486. func (b *block) readFromUntil(r io.Reader, n int) error {
  487. // quick case
  488. if len(b.data) >= n {
  489. return nil
  490. }
  491. // read until have enough.
  492. b.reserve(n)
  493. for {
  494. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  495. b.data = b.data[0 : len(b.data)+m]
  496. if len(b.data) >= n {
  497. // TODO(bradfitz,agl): slightly suspicious
  498. // that we're throwing away r.Read's err here.
  499. break
  500. }
  501. if err != nil {
  502. return err
  503. }
  504. }
  505. return nil
  506. }
  507. func (b *block) Read(p []byte) (n int, err error) {
  508. n = copy(p, b.data[b.off:])
  509. b.off += n
  510. if b.off >= len(b.data) {
  511. err = io.EOF
  512. }
  513. return
  514. }
  515. // newBlock allocates a new block, from hc's free list if possible.
  516. func (hc *halfConn) newBlock() *block {
  517. b := hc.bfree
  518. if b == nil {
  519. return new(block)
  520. }
  521. hc.bfree = b.link
  522. b.link = nil
  523. b.resize(0)
  524. return b
  525. }
  526. // freeBlock returns a block to hc's free list.
  527. // The protocol is such that each side only has a block or two on
  528. // its free list at a time, so there's no need to worry about
  529. // trimming the list, etc.
  530. func (hc *halfConn) freeBlock(b *block) {
  531. b.link = hc.bfree
  532. hc.bfree = b
  533. }
  534. // splitBlock splits a block after the first n bytes,
  535. // returning a block with those n bytes and a
  536. // block with the remainder. the latter may be nil.
  537. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  538. if len(b.data) <= n {
  539. return b, nil
  540. }
  541. bb := hc.newBlock()
  542. bb.resize(len(b.data) - n)
  543. copy(bb.data, b.data[n:])
  544. b.data = b.data[0:n]
  545. return b, bb
  546. }
  547. // RecordHeaderError results when a TLS record header is invalid.
  548. type RecordHeaderError struct {
  549. // Msg contains a human readable string that describes the error.
  550. Msg string
  551. // RecordHeader contains the five bytes of TLS record header that
  552. // triggered the error.
  553. RecordHeader [5]byte
  554. }
  555. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  556. func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
  557. err.Msg = msg
  558. copy(err.RecordHeader[:], c.rawInput.data)
  559. return err
  560. }
  561. // readRecord reads the next TLS record from the connection
  562. // and updates the record layer state.
  563. // c.in.Mutex <= L; c.input == nil.
  564. // c.input can still be nil after a call, retry if so.
  565. func (c *Conn) readRecord(want recordType) error {
  566. // Caller must be in sync with connection:
  567. // handshake data if handshake not yet completed,
  568. // else application data.
  569. switch want {
  570. default:
  571. c.sendAlert(alertInternalError)
  572. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  573. case recordTypeHandshake, recordTypeChangeCipherSpec:
  574. if c.phase != handshakeRunning && c.phase != readingClientFinished {
  575. c.sendAlert(alertInternalError)
  576. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
  577. }
  578. case recordTypeApplicationData:
  579. if c.phase == handshakeRunning || c.phase == readingClientFinished {
  580. c.sendAlert(alertInternalError)
  581. return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
  582. }
  583. }
  584. Again:
  585. if c.rawInput == nil {
  586. c.rawInput = c.in.newBlock()
  587. }
  588. b := c.rawInput
  589. // Read header, payload.
  590. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  591. // RFC suggests that EOF without an alertCloseNotify is
  592. // an error, but popular web sites seem to do this,
  593. // so we can't make it an error.
  594. // if err == io.EOF {
  595. // err = io.ErrUnexpectedEOF
  596. // }
  597. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  598. c.in.setErrorLocked(err)
  599. }
  600. return err
  601. }
  602. typ := recordType(b.data[0])
  603. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  604. // start with a uint16 length where the MSB is set and the first record
  605. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  606. // an SSLv2 client.
  607. if want == recordTypeHandshake && typ == 0x80 {
  608. c.sendAlert(alertProtocolVersion)
  609. return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
  610. }
  611. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  612. n := int(b.data[3])<<8 | int(b.data[4])
  613. if n > maxCiphertext {
  614. c.sendAlert(alertRecordOverflow)
  615. msg := fmt.Sprintf("oversized record received with length %d", n)
  616. return c.in.setErrorLocked(c.newRecordHeaderError(msg))
  617. }
  618. if !c.haveVers {
  619. // First message, be extra suspicious: this might not be a TLS
  620. // client. Bail out before reading a full 'body', if possible.
  621. // The current max version is 3.3 so if the version is >= 16.0,
  622. // it's probably not real.
  623. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  624. c.sendAlert(alertUnexpectedMessage)
  625. return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
  626. }
  627. }
  628. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  629. if err == io.EOF {
  630. err = io.ErrUnexpectedEOF
  631. }
  632. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  633. c.in.setErrorLocked(err)
  634. }
  635. return err
  636. }
  637. // Process message.
  638. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  639. // TLS 1.3 middlebox compatibility: skip over unencrypted CCS.
  640. if c.vers >= VersionTLS13 && typ == recordTypeChangeCipherSpec && c.phase != handshakeConfirmed {
  641. if len(b.data) != 6 || b.data[5] != 1 {
  642. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  643. }
  644. c.in.freeBlock(b)
  645. return c.in.err
  646. }
  647. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  648. ok, off, alertValue := c.in.decrypt(b)
  649. switch {
  650. case !ok && c.phase == discardingEarlyData:
  651. // If the client said that it's sending early data and we did not
  652. // accept it, we are expected to fail decryption.
  653. c.in.freeBlock(b)
  654. return nil
  655. case ok && c.phase == discardingEarlyData:
  656. c.phase = waitingClientFinished
  657. case !ok:
  658. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  659. c.in.freeBlock(b)
  660. err := c.sendAlert(alertValue)
  661. // If decryption failed because the message is an unencrypted
  662. // alert, return a more meaningful error message
  663. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  664. err = peekedAlert
  665. }
  666. return c.in.setErrorLocked(err)
  667. }
  668. b.off = off
  669. data := b.data[b.off:]
  670. if (c.vers < VersionTLS13 && len(data) > maxPlaintext) || len(data) > maxPlaintext+1 {
  671. c.in.freeBlock(b)
  672. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  673. }
  674. // After checking the plaintext length, remove 1.3 padding and
  675. // extract the real content type.
  676. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  677. if c.vers >= VersionTLS13 {
  678. i := len(data) - 1
  679. for i >= 0 {
  680. if data[i] != 0 {
  681. break
  682. }
  683. i--
  684. }
  685. if i < 0 {
  686. c.in.freeBlock(b)
  687. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  688. }
  689. typ = recordType(data[i])
  690. data = data[:i]
  691. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  692. }
  693. if typ != recordTypeAlert && len(data) > 0 {
  694. // this is a valid non-alert message: reset the count of alerts
  695. c.warnCount = 0
  696. }
  697. switch typ {
  698. default:
  699. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  700. case recordTypeAlert:
  701. if len(data) != 2 {
  702. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  703. break
  704. }
  705. if alert(data[1]) == alertCloseNotify {
  706. c.in.setErrorLocked(io.EOF)
  707. break
  708. }
  709. switch data[0] {
  710. case alertLevelWarning:
  711. // drop on the floor
  712. c.in.freeBlock(b)
  713. c.warnCount++
  714. if c.warnCount > maxWarnAlertCount {
  715. c.sendAlert(alertUnexpectedMessage)
  716. return c.in.setErrorLocked(errors.New("tls: too many warn alerts"))
  717. }
  718. goto Again
  719. case alertLevelError:
  720. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  721. default:
  722. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  723. }
  724. case recordTypeChangeCipherSpec:
  725. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  726. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  727. break
  728. }
  729. // Handshake messages are not allowed to fragment across the CCS
  730. if c.hand.Len() > 0 {
  731. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  732. break
  733. }
  734. // Handshake messages are not allowed to fragment across the CCS
  735. if c.hand.Len() > 0 {
  736. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  737. break
  738. }
  739. err := c.in.changeCipherSpec()
  740. if err != nil {
  741. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  742. }
  743. case recordTypeApplicationData:
  744. if typ != want || c.phase == waitingClientFinished {
  745. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  746. break
  747. }
  748. if c.phase == readingEarlyData {
  749. c.earlyDataBytes += int64(len(b.data) - b.off)
  750. if c.earlyDataBytes > c.ticketMaxEarlyData {
  751. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  752. }
  753. }
  754. c.input = b
  755. b = nil
  756. case recordTypeHandshake:
  757. // TODO(rsc): Should at least pick off connection close.
  758. // If early data was being read, a Finished message is expected
  759. // instead of (early) application data. Other post-handshake
  760. // messages include HelloRequest and NewSessionTicket.
  761. if typ != want && want != recordTypeApplicationData {
  762. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  763. }
  764. c.hand.Write(data)
  765. }
  766. if b != nil {
  767. c.in.freeBlock(b)
  768. }
  769. return c.in.err
  770. }
  771. // peekAlert looks at a message to spot an unencrypted alert. It must be
  772. // called before decryption to avoid a side channel, and its result must
  773. // only be used if decryption fails, to avoid false positives.
  774. func peekAlert(b *block) error {
  775. if len(b.data) < 7 {
  776. return nil
  777. }
  778. if recordType(b.data[0]) != recordTypeAlert {
  779. return nil
  780. }
  781. return &net.OpError{Op: "remote error", Err: alert(b.data[6])}
  782. }
  783. // sendAlert sends a TLS alert message.
  784. // c.out.Mutex <= L.
  785. func (c *Conn) sendAlertLocked(err alert) error {
  786. switch err {
  787. case alertNoRenegotiation, alertCloseNotify:
  788. c.tmp[0] = alertLevelWarning
  789. default:
  790. c.tmp[0] = alertLevelError
  791. }
  792. c.tmp[1] = byte(err)
  793. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  794. if err == alertCloseNotify {
  795. // closeNotify is a special case in that it isn't an error.
  796. return writeErr
  797. }
  798. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  799. }
  800. // sendAlert sends a TLS alert message.
  801. // L < c.out.Mutex.
  802. func (c *Conn) sendAlert(err alert) error {
  803. c.out.Lock()
  804. defer c.out.Unlock()
  805. return c.sendAlertLocked(err)
  806. }
  807. const (
  808. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  809. // size (MSS). A constant is used, rather than querying the kernel for
  810. // the actual MSS, to avoid complexity. The value here is the IPv6
  811. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  812. // bytes) and a TCP header with timestamps (32 bytes).
  813. tcpMSSEstimate = 1208
  814. // recordSizeBoostThreshold is the number of bytes of application data
  815. // sent after which the TLS record size will be increased to the
  816. // maximum.
  817. recordSizeBoostThreshold = 128 * 1024
  818. )
  819. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  820. // next application data record. There is the following trade-off:
  821. //
  822. // - For latency-sensitive applications, such as web browsing, each TLS
  823. // record should fit in one TCP segment.
  824. // - For throughput-sensitive applications, such as large file transfers,
  825. // larger TLS records better amortize framing and encryption overheads.
  826. //
  827. // A simple heuristic that works well in practice is to use small records for
  828. // the first 1MB of data, then use larger records for subsequent data, and
  829. // reset back to smaller records after the connection becomes idle. See "High
  830. // Performance Web Networking", Chapter 4, or:
  831. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  832. //
  833. // In the interests of simplicity and determinism, this code does not attempt
  834. // to reset the record size once the connection is idle, however.
  835. //
  836. // c.out.Mutex <= L.
  837. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  838. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  839. return maxPlaintext
  840. }
  841. if c.bytesSent >= recordSizeBoostThreshold {
  842. return maxPlaintext
  843. }
  844. // Subtract TLS overheads to get the maximum payload size.
  845. macSize := 0
  846. if c.out.mac != nil {
  847. macSize = c.out.mac.Size()
  848. }
  849. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  850. if c.out.cipher != nil {
  851. switch ciph := c.out.cipher.(type) {
  852. case cipher.Stream:
  853. payloadBytes -= macSize
  854. case cipher.AEAD:
  855. payloadBytes -= ciph.Overhead()
  856. if c.vers >= VersionTLS13 {
  857. payloadBytes -= 1 // ContentType
  858. }
  859. case cbcMode:
  860. blockSize := ciph.BlockSize()
  861. // The payload must fit in a multiple of blockSize, with
  862. // room for at least one padding byte.
  863. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  864. // The MAC is appended before padding so affects the
  865. // payload size directly.
  866. payloadBytes -= macSize
  867. default:
  868. panic("unknown cipher type")
  869. }
  870. }
  871. // Allow packet growth in arithmetic progression up to max.
  872. pkt := c.packetsSent
  873. c.packetsSent++
  874. if pkt > 1000 {
  875. return maxPlaintext // avoid overflow in multiply below
  876. }
  877. n := payloadBytes * int(pkt+1)
  878. if n > maxPlaintext {
  879. n = maxPlaintext
  880. }
  881. return n
  882. }
  883. // c.out.Mutex <= L.
  884. func (c *Conn) write(data []byte) (int, error) {
  885. if c.buffering {
  886. c.sendBuf = append(c.sendBuf, data...)
  887. return len(data), nil
  888. }
  889. n, err := c.conn.Write(data)
  890. c.bytesSent += int64(n)
  891. return n, err
  892. }
  893. func (c *Conn) flush() (int, error) {
  894. if len(c.sendBuf) == 0 {
  895. return 0, nil
  896. }
  897. n, err := c.conn.Write(c.sendBuf)
  898. c.bytesSent += int64(n)
  899. c.sendBuf = nil
  900. c.buffering = false
  901. return n, err
  902. }
  903. // writeRecordLocked writes a TLS record with the given type and payload to the
  904. // connection and updates the record layer state.
  905. // c.out.Mutex <= L.
  906. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  907. b := c.out.newBlock()
  908. defer c.out.freeBlock(b)
  909. var n int
  910. for len(data) > 0 {
  911. explicitIVLen := 0
  912. explicitIVIsSeq := false
  913. var cbc cbcMode
  914. if c.out.version >= VersionTLS11 {
  915. var ok bool
  916. if cbc, ok = c.out.cipher.(cbcMode); ok {
  917. explicitIVLen = cbc.BlockSize()
  918. }
  919. }
  920. if explicitIVLen == 0 {
  921. if c, ok := c.out.cipher.(aead); ok {
  922. explicitIVLen = c.explicitNonceLen()
  923. // The AES-GCM construction in TLS has an
  924. // explicit nonce so that the nonce can be
  925. // random. However, the nonce is only 8 bytes
  926. // which is too small for a secure, random
  927. // nonce. Therefore we use the sequence number
  928. // as the nonce.
  929. explicitIVIsSeq = explicitIVLen > 0
  930. }
  931. }
  932. m := len(data)
  933. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  934. m = maxPayload
  935. }
  936. b.resize(recordHeaderLen + explicitIVLen + m)
  937. b.data[0] = byte(typ)
  938. vers := c.vers
  939. if vers == 0 {
  940. // Some TLS servers fail if the record version is
  941. // greater than TLS 1.0 for the initial ClientHello.
  942. vers = VersionTLS10
  943. }
  944. if c.vers >= VersionTLS13 {
  945. // TLS 1.3 froze the record layer version at { 3, 1 }.
  946. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.1.
  947. // But for draft 22, this was changed to { 3, 3 }.
  948. vers = VersionTLS12
  949. }
  950. b.data[1] = byte(vers >> 8)
  951. b.data[2] = byte(vers)
  952. b.data[3] = byte(m >> 8)
  953. b.data[4] = byte(m)
  954. if explicitIVLen > 0 {
  955. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  956. if explicitIVIsSeq {
  957. copy(explicitIV, c.out.seq[:])
  958. } else {
  959. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  960. return n, err
  961. }
  962. }
  963. }
  964. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  965. c.out.encrypt(b, explicitIVLen)
  966. if _, err := c.write(b.data); err != nil {
  967. return n, err
  968. }
  969. n += m
  970. data = data[m:]
  971. }
  972. if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
  973. if err := c.out.changeCipherSpec(); err != nil {
  974. return n, c.sendAlertLocked(err.(alert))
  975. }
  976. }
  977. return n, nil
  978. }
  979. // writeRecord writes a TLS record with the given type and payload to the
  980. // connection and updates the record layer state.
  981. // L < c.out.Mutex.
  982. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  983. c.out.Lock()
  984. defer c.out.Unlock()
  985. return c.writeRecordLocked(typ, data)
  986. }
  987. // readHandshake reads the next handshake message from
  988. // the record layer.
  989. // c.in.Mutex < L; c.out.Mutex < L.
  990. func (c *Conn) readHandshake() (interface{}, error) {
  991. for c.hand.Len() < 4 {
  992. if err := c.in.err; err != nil {
  993. return nil, err
  994. }
  995. if err := c.readRecord(recordTypeHandshake); err != nil {
  996. return nil, err
  997. }
  998. }
  999. data := c.hand.Bytes()
  1000. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1001. if n > maxHandshake {
  1002. c.sendAlertLocked(alertInternalError)
  1003. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  1004. }
  1005. for c.hand.Len() < 4+n {
  1006. if err := c.in.err; err != nil {
  1007. return nil, err
  1008. }
  1009. if err := c.readRecord(recordTypeHandshake); err != nil {
  1010. return nil, err
  1011. }
  1012. }
  1013. data = c.hand.Next(4 + n)
  1014. var m handshakeMessage
  1015. switch data[0] {
  1016. case typeHelloRequest:
  1017. m = new(helloRequestMsg)
  1018. case typeClientHello:
  1019. m = new(clientHelloMsg)
  1020. case typeServerHello:
  1021. m = new(serverHelloMsg)
  1022. case typeEncryptedExtensions:
  1023. m = new(encryptedExtensionsMsg)
  1024. case typeNewSessionTicket:
  1025. if c.vers >= VersionTLS13 {
  1026. m = new(newSessionTicketMsg13)
  1027. } else {
  1028. m = new(newSessionTicketMsg)
  1029. }
  1030. case typeEndOfEarlyData:
  1031. m = new(endOfEarlyDataMsg)
  1032. case typeCertificate:
  1033. if c.vers >= VersionTLS13 {
  1034. m = new(certificateMsg13)
  1035. } else {
  1036. m = new(certificateMsg)
  1037. }
  1038. case typeCertificateRequest:
  1039. if c.vers >= VersionTLS13 {
  1040. m = new(certificateRequestMsg13)
  1041. } else {
  1042. m = &certificateRequestMsg{
  1043. hasSignatureAndHash: c.vers >= VersionTLS12,
  1044. }
  1045. }
  1046. case typeCertificateStatus:
  1047. m = new(certificateStatusMsg)
  1048. case typeServerKeyExchange:
  1049. m = new(serverKeyExchangeMsg)
  1050. case typeServerHelloDone:
  1051. m = new(serverHelloDoneMsg)
  1052. case typeClientKeyExchange:
  1053. m = new(clientKeyExchangeMsg)
  1054. case typeCertificateVerify:
  1055. m = &certificateVerifyMsg{
  1056. hasSignatureAndHash: c.vers >= VersionTLS12,
  1057. }
  1058. case typeNextProtocol:
  1059. m = new(nextProtoMsg)
  1060. case typeFinished:
  1061. m = new(finishedMsg)
  1062. default:
  1063. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1064. }
  1065. // The handshake message unmarshalers
  1066. // expect to be able to keep references to data,
  1067. // so pass in a fresh copy that won't be overwritten.
  1068. data = append([]byte(nil), data...)
  1069. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1070. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1071. }
  1072. return m, nil
  1073. }
  1074. var (
  1075. errClosed = errors.New("tls: use of closed connection")
  1076. errShutdown = errors.New("tls: protocol is shutdown")
  1077. )
  1078. // Write writes data to the connection.
  1079. func (c *Conn) Write(b []byte) (int, error) {
  1080. // interlock with Close below
  1081. for {
  1082. x := atomic.LoadInt32(&c.activeCall)
  1083. if x&1 != 0 {
  1084. return 0, errClosed
  1085. }
  1086. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1087. defer atomic.AddInt32(&c.activeCall, -2)
  1088. break
  1089. }
  1090. }
  1091. if err := c.Handshake(); err != nil {
  1092. return 0, err
  1093. }
  1094. c.out.Lock()
  1095. defer c.out.Unlock()
  1096. if err := c.out.err; err != nil {
  1097. return 0, err
  1098. }
  1099. if !c.handshakeComplete {
  1100. return 0, alertInternalError
  1101. }
  1102. if c.closeNotifySent {
  1103. return 0, errShutdown
  1104. }
  1105. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1106. // attack when using block mode ciphers due to predictable IVs.
  1107. // This can be prevented by splitting each Application Data
  1108. // record into two records, effectively randomizing the IV.
  1109. //
  1110. // http://www.openssl.org/~bodo/tls-cbc.txt
  1111. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1112. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1113. var m int
  1114. if len(b) > 1 && c.vers <= VersionTLS10 {
  1115. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1116. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1117. if err != nil {
  1118. return n, c.out.setErrorLocked(err)
  1119. }
  1120. m, b = 1, b[1:]
  1121. }
  1122. }
  1123. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1124. return n + m, c.out.setErrorLocked(err)
  1125. }
  1126. // Process Handshake messages after the handshake has completed.
  1127. // c.in.Mutex <= L
  1128. func (c *Conn) handlePostHandshake() error {
  1129. msg, err := c.readHandshake()
  1130. if err != nil {
  1131. return err
  1132. }
  1133. switch hm := msg.(type) {
  1134. case *helloRequestMsg:
  1135. return c.handleRenegotiation(hm)
  1136. case *newSessionTicketMsg13:
  1137. if !c.isClient {
  1138. c.sendAlert(alertUnexpectedMessage)
  1139. return alertUnexpectedMessage
  1140. }
  1141. return nil // TODO implement session tickets
  1142. default:
  1143. c.sendAlert(alertUnexpectedMessage)
  1144. return alertUnexpectedMessage
  1145. }
  1146. }
  1147. // handleRenegotiation processes a HelloRequest handshake message.
  1148. // c.in.Mutex <= L
  1149. func (c *Conn) handleRenegotiation(*helloRequestMsg) error {
  1150. if !c.isClient {
  1151. return c.sendAlert(alertNoRenegotiation)
  1152. }
  1153. if c.vers >= VersionTLS13 {
  1154. return c.sendAlert(alertNoRenegotiation)
  1155. }
  1156. switch c.config.Renegotiation {
  1157. case RenegotiateNever:
  1158. return c.sendAlert(alertNoRenegotiation)
  1159. case RenegotiateOnceAsClient:
  1160. if c.handshakes > 1 {
  1161. return c.sendAlert(alertNoRenegotiation)
  1162. }
  1163. case RenegotiateFreelyAsClient:
  1164. // Ok.
  1165. default:
  1166. c.sendAlert(alertInternalError)
  1167. return errors.New("tls: unknown Renegotiation value")
  1168. }
  1169. c.handshakeMutex.Lock()
  1170. defer c.handshakeMutex.Unlock()
  1171. c.phase = handshakeRunning
  1172. c.handshakeComplete = false
  1173. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1174. c.handshakes++
  1175. }
  1176. return c.handshakeErr
  1177. }
  1178. // ConfirmHandshake waits for the handshake to reach a point at which
  1179. // the connection is certainly not replayed. That is, after receiving
  1180. // the Client Finished.
  1181. //
  1182. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1183. // returns, the 0-RTT data should not be trusted not to be replayed.
  1184. //
  1185. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1186. // client sent valid 0-RTT data. In any other case it's equivalent to
  1187. // calling Handshake.
  1188. func (c *Conn) ConfirmHandshake() error {
  1189. if c.isClient {
  1190. panic("ConfirmHandshake should only be called for servers")
  1191. }
  1192. if err := c.Handshake(); err != nil {
  1193. return err
  1194. }
  1195. if c.vers < VersionTLS13 {
  1196. return nil
  1197. }
  1198. c.confirmMutex.Lock()
  1199. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1200. c.confirmMutex.Unlock()
  1201. return nil
  1202. } else {
  1203. defer func() {
  1204. // If we transitioned to handshakeConfirmed we already released the lock,
  1205. // otherwise do it here.
  1206. if c.phase != handshakeConfirmed {
  1207. c.confirmMutex.Unlock()
  1208. }
  1209. }()
  1210. }
  1211. c.in.Lock()
  1212. defer c.in.Unlock()
  1213. var input *block
  1214. // Try to read all data (if phase==readingEarlyData) or extract the
  1215. // remaining data from the previous read that could not fit in the read
  1216. // buffer (if c.input != nil).
  1217. if c.phase == readingEarlyData || c.input != nil {
  1218. buf := &bytes.Buffer{}
  1219. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1220. c.in.setErrorLocked(err)
  1221. return err
  1222. }
  1223. input = &block{data: buf.Bytes()}
  1224. }
  1225. // At this point, earlyDataReader has read all early data and received
  1226. // the end_of_early_data signal. Expect a Finished message.
  1227. // Locks held so far: c.confirmMutex, c.in
  1228. // not confirmed implies c.phase == discardingEarlyData || c.phase == waitingClientFinished
  1229. for c.phase != handshakeConfirmed {
  1230. if err := c.hs.readClientFinished13(true); err != nil {
  1231. c.in.setErrorLocked(err)
  1232. return err
  1233. }
  1234. }
  1235. if c.phase != handshakeConfirmed {
  1236. panic("should have reached handshakeConfirmed state")
  1237. }
  1238. if c.input != nil {
  1239. panic("should not have read past the Client Finished")
  1240. }
  1241. c.input = input
  1242. return nil
  1243. }
  1244. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1245. // and still on the wire.
  1246. type earlyDataReader struct {
  1247. c *Conn
  1248. }
  1249. // c.in.Mutex <= L
  1250. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1251. c := r.c
  1252. if c.phase == handshakeConfirmed {
  1253. // c.input might not be early data
  1254. panic("earlyDataReader called at handshakeConfirmed")
  1255. }
  1256. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1257. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1258. return 0, err
  1259. }
  1260. if c.hand.Len() > 0 {
  1261. if err := c.handleEndOfEarlyData(); err != nil {
  1262. return 0, err
  1263. }
  1264. }
  1265. }
  1266. if err := c.in.err; err != nil {
  1267. return 0, err
  1268. }
  1269. if c.input != nil {
  1270. n, err = c.input.Read(b)
  1271. if err == io.EOF {
  1272. err = nil
  1273. c.in.freeBlock(c.input)
  1274. c.input = nil
  1275. }
  1276. }
  1277. // Following early application data, an end_of_early_data is expected.
  1278. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1279. err = io.EOF
  1280. }
  1281. return
  1282. }
  1283. // Read can be made to time out and return a net.Error with Timeout() == true
  1284. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1285. func (c *Conn) Read(b []byte) (n int, err error) {
  1286. if err = c.Handshake(); err != nil {
  1287. return
  1288. }
  1289. if len(b) == 0 {
  1290. // Put this after Handshake, in case people were calling
  1291. // Read(nil) for the side effect of the Handshake.
  1292. return
  1293. }
  1294. c.confirmMutex.Lock()
  1295. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1296. c.confirmMutex.Unlock()
  1297. } else {
  1298. defer func() {
  1299. // If we transitioned to handshakeConfirmed we already released the lock,
  1300. // otherwise do it here.
  1301. if c.phase != handshakeConfirmed {
  1302. c.confirmMutex.Unlock()
  1303. }
  1304. }()
  1305. }
  1306. c.in.Lock()
  1307. defer c.in.Unlock()
  1308. // Some OpenSSL servers send empty records in order to randomize the
  1309. // CBC IV. So this loop ignores a limited number of empty records.
  1310. const maxConsecutiveEmptyRecords = 100
  1311. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1312. for c.input == nil && c.in.err == nil {
  1313. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1314. // Soft error, like EAGAIN
  1315. return 0, err
  1316. }
  1317. if c.hand.Len() > 0 {
  1318. if c.phase == readingEarlyData || c.phase == waitingClientFinished {
  1319. if c.phase == readingEarlyData {
  1320. if err := c.handleEndOfEarlyData(); err != nil {
  1321. return 0, err
  1322. }
  1323. }
  1324. // Server has received all early data, confirm
  1325. // by reading the Client Finished message.
  1326. if err := c.hs.readClientFinished13(true); err != nil {
  1327. c.in.setErrorLocked(err)
  1328. return 0, err
  1329. }
  1330. continue
  1331. }
  1332. if err := c.handlePostHandshake(); err != nil {
  1333. return 0, err
  1334. }
  1335. }
  1336. }
  1337. if err := c.in.err; err != nil {
  1338. return 0, err
  1339. }
  1340. n, err = c.input.Read(b)
  1341. if err == io.EOF {
  1342. err = nil
  1343. c.in.freeBlock(c.input)
  1344. c.input = nil
  1345. }
  1346. // If a close-notify alert is waiting, read it so that
  1347. // we can return (n, EOF) instead of (n, nil), to signal
  1348. // to the HTTP response reading goroutine that the
  1349. // connection is now closed. This eliminates a race
  1350. // where the HTTP response reading goroutine would
  1351. // otherwise not observe the EOF until its next read,
  1352. // by which time a client goroutine might have already
  1353. // tried to reuse the HTTP connection for a new
  1354. // request.
  1355. // See https://codereview.appspot.com/76400046
  1356. // and https://golang.org/issue/3514
  1357. if ri := c.rawInput; ri != nil &&
  1358. n != 0 && err == nil &&
  1359. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1360. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1361. err = recErr // will be io.EOF on closeNotify
  1362. }
  1363. }
  1364. if n != 0 || err != nil {
  1365. return n, err
  1366. }
  1367. }
  1368. return 0, io.ErrNoProgress
  1369. }
  1370. // Close closes the connection.
  1371. func (c *Conn) Close() error {
  1372. // Interlock with Conn.Write above.
  1373. var x int32
  1374. for {
  1375. x = atomic.LoadInt32(&c.activeCall)
  1376. if x&1 != 0 {
  1377. return errClosed
  1378. }
  1379. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1380. break
  1381. }
  1382. }
  1383. if x != 0 {
  1384. // io.Writer and io.Closer should not be used concurrently.
  1385. // If Close is called while a Write is currently in-flight,
  1386. // interpret that as a sign that this Close is really just
  1387. // being used to break the Write and/or clean up resources and
  1388. // avoid sending the alertCloseNotify, which may block
  1389. // waiting on handshakeMutex or the c.out mutex.
  1390. return c.conn.Close()
  1391. }
  1392. var alertErr error
  1393. c.handshakeMutex.Lock()
  1394. if c.handshakeComplete {
  1395. alertErr = c.closeNotify()
  1396. }
  1397. c.handshakeMutex.Unlock()
  1398. if err := c.conn.Close(); err != nil {
  1399. return err
  1400. }
  1401. return alertErr
  1402. }
  1403. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1404. // CloseWrite shuts down the writing side of the connection. It should only be
  1405. // called once the handshake has completed and does not call CloseWrite on the
  1406. // underlying connection. Most callers should just use Close.
  1407. func (c *Conn) CloseWrite() error {
  1408. c.handshakeMutex.Lock()
  1409. defer c.handshakeMutex.Unlock()
  1410. if !c.handshakeComplete {
  1411. return errEarlyCloseWrite
  1412. }
  1413. return c.closeNotify()
  1414. }
  1415. func (c *Conn) closeNotify() error {
  1416. c.out.Lock()
  1417. defer c.out.Unlock()
  1418. if !c.closeNotifySent {
  1419. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1420. c.closeNotifySent = true
  1421. }
  1422. return c.closeNotifyErr
  1423. }
  1424. // Handshake runs the client or server handshake
  1425. // protocol if it has not yet been run.
  1426. // Most uses of this package need not call Handshake
  1427. // explicitly: the first Read or Write will call it automatically.
  1428. //
  1429. // In TLS 1.3 Handshake returns after the client and server first flights,
  1430. // without waiting for the Client Finished.
  1431. func (c *Conn) Handshake() error {
  1432. c.handshakeMutex.Lock()
  1433. defer c.handshakeMutex.Unlock()
  1434. if err := c.handshakeErr; err != nil {
  1435. return err
  1436. }
  1437. if c.handshakeComplete {
  1438. return nil
  1439. }
  1440. c.in.Lock()
  1441. defer c.in.Unlock()
  1442. // The handshake cannot have completed when handshakeMutex was unlocked
  1443. // because this goroutine set handshakeCond.
  1444. if c.handshakeErr != nil || c.handshakeComplete {
  1445. panic("handshake should not have been able to complete after handshakeCond was set")
  1446. }
  1447. c.connID = make([]byte, 8)
  1448. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1449. return err
  1450. }
  1451. if c.isClient {
  1452. c.handshakeErr = c.clientHandshake()
  1453. } else {
  1454. c.handshakeErr = c.serverHandshake()
  1455. }
  1456. if c.handshakeErr == nil {
  1457. c.handshakes++
  1458. } else {
  1459. // If an error occurred during the hadshake try to flush the
  1460. // alert that might be left in the buffer.
  1461. c.flush()
  1462. }
  1463. if c.handshakeErr == nil && !c.handshakeComplete {
  1464. panic("handshake should have had a result.")
  1465. }
  1466. return c.handshakeErr
  1467. }
  1468. // ConnectionState returns basic TLS details about the connection.
  1469. func (c *Conn) ConnectionState() ConnectionState {
  1470. c.handshakeMutex.Lock()
  1471. defer c.handshakeMutex.Unlock()
  1472. var state ConnectionState
  1473. state.HandshakeComplete = c.handshakeComplete
  1474. state.ServerName = c.serverName
  1475. if c.handshakeComplete {
  1476. state.ConnectionID = c.connID
  1477. state.ClientHello = c.clientHello
  1478. state.Version = c.vers
  1479. state.NegotiatedProtocol = c.clientProtocol
  1480. state.DidResume = c.didResume
  1481. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1482. state.CipherSuite = c.cipherSuite
  1483. state.PeerCertificates = c.peerCertificates
  1484. state.VerifiedChains = c.verifiedChains
  1485. state.SignedCertificateTimestamps = c.scts
  1486. state.OCSPResponse = c.ocspResponse
  1487. if c.verifiedDc != nil {
  1488. state.DelegatedCredential = c.verifiedDc.raw
  1489. }
  1490. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1491. if !state.HandshakeConfirmed {
  1492. state.Unique0RTTToken = c.binder
  1493. }
  1494. if !c.didResume {
  1495. if c.clientFinishedIsFirst {
  1496. state.TLSUnique = c.clientFinished[:]
  1497. } else {
  1498. state.TLSUnique = c.serverFinished[:]
  1499. }
  1500. }
  1501. }
  1502. return state
  1503. }
  1504. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1505. // any. (Only valid for client connections.)
  1506. func (c *Conn) OCSPResponse() []byte {
  1507. c.handshakeMutex.Lock()
  1508. defer c.handshakeMutex.Unlock()
  1509. return c.ocspResponse
  1510. }
  1511. // VerifyHostname checks that the peer certificate chain is valid for
  1512. // connecting to host. If so, it returns nil; if not, it returns an error
  1513. // describing the problem.
  1514. func (c *Conn) VerifyHostname(host string) error {
  1515. c.handshakeMutex.Lock()
  1516. defer c.handshakeMutex.Unlock()
  1517. if !c.isClient {
  1518. return errors.New("tls: VerifyHostname called on TLS server connection")
  1519. }
  1520. if !c.handshakeComplete {
  1521. return errors.New("tls: handshake has not yet been performed")
  1522. }
  1523. if len(c.verifiedChains) == 0 {
  1524. return errors.New("tls: handshake did not verify certificate chain")
  1525. }
  1526. return c.peerCertificates[0].VerifyHostname(host)
  1527. }