Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

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