Alternative TLS implementation in Go
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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