25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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