Alternative TLS implementation in Go
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

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