Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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