Alternative TLS implementation in Go
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

1732 lignes
49 KiB

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