conn.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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
  27. handshakeErr error // error resulting from handshake
  28. vers uint16 // TLS version
  29. haveVers bool // version has been negotiated
  30. config *Config // configuration passed to constructor
  31. // handshakeComplete is true if the connection is currently transferring
  32. // application data (i.e. is not currently processing a handshake).
  33. handshakeComplete bool
  34. // handshakes counts the number of handshakes performed on the
  35. // connection so far. If renegotiation is disabled then this is either
  36. // zero or one.
  37. handshakes int
  38. didResume bool // whether this connection was a session resumption
  39. cipherSuite uint16
  40. ocspResponse []byte // stapled OCSP response
  41. scts [][]byte // signed certificate timestamps from server
  42. peerCertificates []*x509.Certificate
  43. // verifiedChains contains the certificate chains that we built, as
  44. // opposed to the ones presented by the server.
  45. verifiedChains [][]*x509.Certificate
  46. // serverName contains the server name indicated by the client, if any.
  47. serverName string
  48. // secureRenegotiation is true if the server echoed the secure
  49. // renegotiation extension. (This is meaningless as a server because
  50. // renegotiation is not supported in that case.)
  51. secureRenegotiation bool
  52. // ekm is a closure for exporting keying material.
  53. ekm func(label string, context []byte, length int) ([]byte, bool)
  54. // clientFinishedIsFirst is true if the client sent the first Finished
  55. // message during the most recent handshake. This is recorded because
  56. // the first transmitted Finished message is the tls-unique
  57. // channel-binding value.
  58. clientFinishedIsFirst bool
  59. // closeNotifyErr is any error from sending the alertCloseNotify record.
  60. closeNotifyErr error
  61. // closeNotifySent is true if the Conn attempted to send an
  62. // alertCloseNotify record.
  63. closeNotifySent bool
  64. // clientFinished and serverFinished contain the Finished message sent
  65. // by the client or server in the most recent handshake. This is
  66. // retained to support the renegotiation extension and tls-unique
  67. // channel-binding.
  68. clientFinished [12]byte
  69. serverFinished [12]byte
  70. clientProtocol string
  71. clientProtocolFallback bool
  72. // input/output
  73. in, out halfConn
  74. rawInput *block // raw input, right off the wire
  75. input *block // application data waiting to be read
  76. hand bytes.Buffer // handshake data waiting to be read
  77. buffering bool // whether records are buffered in sendBuf
  78. sendBuf []byte // a buffer of records waiting to be sent
  79. // bytesSent counts the bytes of application data sent.
  80. // packetsSent counts packets.
  81. bytesSent int64
  82. packetsSent int64
  83. // warnCount counts the number of consecutive warning alerts received
  84. // by Conn.readRecord. Protected by in.Mutex.
  85. warnCount int
  86. // activeCall is an atomic int32; the low bit is whether Close has
  87. // been called. the rest of the bits are the number of goroutines
  88. // in Conn.Write.
  89. activeCall int32
  90. tmp [16]byte
  91. }
  92. // Access to net.Conn methods.
  93. // Cannot just embed net.Conn because that would
  94. // export the struct field too.
  95. // LocalAddr returns the local network address.
  96. func (c *Conn) LocalAddr() net.Addr {
  97. return c.conn.LocalAddr()
  98. }
  99. // RemoteAddr returns the remote network address.
  100. func (c *Conn) RemoteAddr() net.Addr {
  101. return c.conn.RemoteAddr()
  102. }
  103. // SetDeadline sets the read and write deadlines associated with the connection.
  104. // A zero value for t means Read and Write will not time out.
  105. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  106. func (c *Conn) SetDeadline(t time.Time) error {
  107. return c.conn.SetDeadline(t)
  108. }
  109. // SetReadDeadline sets the read deadline on the underlying connection.
  110. // A zero value for t means Read will not time out.
  111. func (c *Conn) SetReadDeadline(t time.Time) error {
  112. return c.conn.SetReadDeadline(t)
  113. }
  114. // SetWriteDeadline sets the write deadline on the underlying connection.
  115. // A zero value for t means Write will not time out.
  116. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  117. func (c *Conn) SetWriteDeadline(t time.Time) error {
  118. return c.conn.SetWriteDeadline(t)
  119. }
  120. // A halfConn represents one direction of the record layer
  121. // connection, either sending or receiving.
  122. type halfConn struct {
  123. sync.Mutex
  124. err error // first permanent error
  125. version uint16 // protocol version
  126. cipher interface{} // cipher algorithm
  127. mac macFunction
  128. seq [8]byte // 64-bit sequence number
  129. bfree *block // list of free blocks
  130. additionalData [13]byte // to avoid allocs; interface method args escape
  131. nextCipher interface{} // next encryption state
  132. nextMac macFunction // next MAC algorithm
  133. // used to save allocating a new buffer for each MAC.
  134. inDigestBuf, outDigestBuf []byte
  135. }
  136. func (hc *halfConn) setErrorLocked(err error) error {
  137. hc.err = err
  138. return err
  139. }
  140. // prepareCipherSpec sets the encryption and MAC states
  141. // that a subsequent changeCipherSpec will use.
  142. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  143. hc.version = version
  144. hc.nextCipher = cipher
  145. hc.nextMac = mac
  146. }
  147. // changeCipherSpec changes the encryption and MAC states
  148. // to the ones previously passed to prepareCipherSpec.
  149. func (hc *halfConn) changeCipherSpec() error {
  150. if hc.nextCipher == nil {
  151. return alertInternalError
  152. }
  153. hc.cipher = hc.nextCipher
  154. hc.mac = hc.nextMac
  155. hc.nextCipher = nil
  156. hc.nextMac = nil
  157. for i := range hc.seq {
  158. hc.seq[i] = 0
  159. }
  160. return nil
  161. }
  162. // incSeq increments the sequence number.
  163. func (hc *halfConn) incSeq() {
  164. for i := 7; i >= 0; i-- {
  165. hc.seq[i]++
  166. if hc.seq[i] != 0 {
  167. return
  168. }
  169. }
  170. // Not allowed to let sequence number wrap.
  171. // Instead, must renegotiate before it does.
  172. // Not likely enough to bother.
  173. panic("TLS: sequence number wraparound")
  174. }
  175. // extractPadding returns, in constant time, the length of the padding to remove
  176. // from the end of payload. It also returns a byte which is equal to 255 if the
  177. // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  178. func extractPadding(payload []byte) (toRemove int, good byte) {
  179. if len(payload) < 1 {
  180. return 0, 0
  181. }
  182. paddingLen := payload[len(payload)-1]
  183. t := uint(len(payload)-1) - uint(paddingLen)
  184. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  185. good = byte(int32(^t) >> 31)
  186. // The maximum possible padding length plus the actual length field
  187. toCheck := 256
  188. // The length of the padded data is public, so we can use an if here
  189. if toCheck > len(payload) {
  190. toCheck = len(payload)
  191. }
  192. for i := 0; i < toCheck; i++ {
  193. t := uint(paddingLen) - uint(i)
  194. // if i <= paddingLen then the MSB of t is zero
  195. mask := byte(int32(^t) >> 31)
  196. b := payload[len(payload)-1-i]
  197. good &^= mask&paddingLen ^ mask&b
  198. }
  199. // We AND together the bits of good and replicate the result across
  200. // all the bits.
  201. good &= good << 4
  202. good &= good << 2
  203. good &= good << 1
  204. good = uint8(int8(good) >> 7)
  205. toRemove = int(paddingLen) + 1
  206. return
  207. }
  208. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  209. // protocol version is SSLv3. In this version, the contents of the padding
  210. // are random and cannot be checked.
  211. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  212. if len(payload) < 1 {
  213. return 0, 0
  214. }
  215. paddingLen := int(payload[len(payload)-1]) + 1
  216. if paddingLen > len(payload) {
  217. return 0, 0
  218. }
  219. return paddingLen, 255
  220. }
  221. func roundUp(a, b int) int {
  222. return a + (b-a%b)%b
  223. }
  224. // cbcMode is an interface for block ciphers using cipher block chaining.
  225. type cbcMode interface {
  226. cipher.BlockMode
  227. SetIV([]byte)
  228. }
  229. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  230. // success boolean, the number of bytes to skip from the start of the record in
  231. // order to get the application payload, and an optional alert value.
  232. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  233. // pull out payload
  234. payload := b.data[recordHeaderLen:]
  235. macSize := 0
  236. if hc.mac != nil {
  237. macSize = hc.mac.Size()
  238. }
  239. paddingGood := byte(255)
  240. paddingLen := 0
  241. explicitIVLen := 0
  242. // decrypt
  243. if hc.cipher != nil {
  244. switch c := hc.cipher.(type) {
  245. case cipher.Stream:
  246. c.XORKeyStream(payload, payload)
  247. case aead:
  248. explicitIVLen = c.explicitNonceLen()
  249. if len(payload) < explicitIVLen {
  250. return false, 0, alertBadRecordMAC
  251. }
  252. nonce := payload[:explicitIVLen]
  253. payload = payload[explicitIVLen:]
  254. if len(nonce) == 0 {
  255. nonce = hc.seq[:]
  256. }
  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. var err error
  263. payload, err = c.Open(payload[:0], nonce, payload, hc.additionalData[:])
  264. if err != nil {
  265. return false, 0, alertBadRecordMAC
  266. }
  267. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  268. case cbcMode:
  269. blockSize := c.BlockSize()
  270. if hc.version >= VersionTLS11 {
  271. explicitIVLen = blockSize
  272. }
  273. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  274. return false, 0, alertBadRecordMAC
  275. }
  276. if explicitIVLen > 0 {
  277. c.SetIV(payload[:explicitIVLen])
  278. payload = payload[explicitIVLen:]
  279. }
  280. c.CryptBlocks(payload, payload)
  281. if hc.version == VersionSSL30 {
  282. paddingLen, paddingGood = extractPaddingSSL30(payload)
  283. } else {
  284. paddingLen, paddingGood = extractPadding(payload)
  285. // To protect against CBC padding oracles like Lucky13, the data
  286. // past paddingLen (which is secret) is passed to the MAC
  287. // function as extra data, to be fed into the HMAC after
  288. // computing the digest. This makes the MAC constant time as
  289. // long as the digest computation is constant time and does not
  290. // affect the subsequent write.
  291. }
  292. default:
  293. panic("unknown cipher type")
  294. }
  295. }
  296. // check, strip mac
  297. if hc.mac != nil {
  298. if len(payload) < macSize {
  299. return false, 0, alertBadRecordMAC
  300. }
  301. // strip mac off payload, b.data
  302. n := len(payload) - macSize - paddingLen
  303. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  304. b.data[3] = byte(n >> 8)
  305. b.data[4] = byte(n)
  306. remoteMAC := payload[n : n+macSize]
  307. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
  308. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  309. return false, 0, alertBadRecordMAC
  310. }
  311. hc.inDigestBuf = localMAC
  312. b.resize(recordHeaderLen + explicitIVLen + n)
  313. }
  314. hc.incSeq()
  315. return true, recordHeaderLen + explicitIVLen, 0
  316. }
  317. // padToBlockSize calculates the needed padding block, if any, for a payload.
  318. // On exit, prefix aliases payload and extends to the end of the last full
  319. // block of payload. finalBlock is a fresh slice which contains the contents of
  320. // any suffix of payload as well as the needed padding to make finalBlock a
  321. // full block.
  322. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  323. overrun := len(payload) % blockSize
  324. paddingLen := blockSize - overrun
  325. prefix = payload[:len(payload)-overrun]
  326. finalBlock = make([]byte, blockSize)
  327. copy(finalBlock, payload[len(payload)-overrun:])
  328. for i := overrun; i < blockSize; i++ {
  329. finalBlock[i] = byte(paddingLen - 1)
  330. }
  331. return
  332. }
  333. // encrypt encrypts and macs the data in b.
  334. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  335. // mac
  336. if hc.mac != nil {
  337. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
  338. n := len(b.data)
  339. b.resize(n + len(mac))
  340. copy(b.data[n:], mac)
  341. hc.outDigestBuf = mac
  342. }
  343. payload := b.data[recordHeaderLen:]
  344. // encrypt
  345. if hc.cipher != nil {
  346. switch c := hc.cipher.(type) {
  347. case cipher.Stream:
  348. c.XORKeyStream(payload, payload)
  349. case aead:
  350. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  351. b.resize(len(b.data) + c.Overhead())
  352. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  353. if len(nonce) == 0 {
  354. nonce = hc.seq[:]
  355. }
  356. payload := b.data[recordHeaderLen+explicitIVLen:]
  357. payload = payload[:payloadLen]
  358. copy(hc.additionalData[:], hc.seq[:])
  359. copy(hc.additionalData[8:], b.data[:3])
  360. hc.additionalData[11] = byte(payloadLen >> 8)
  361. hc.additionalData[12] = byte(payloadLen)
  362. c.Seal(payload[:0], nonce, payload, hc.additionalData[:])
  363. case cbcMode:
  364. blockSize := c.BlockSize()
  365. if explicitIVLen > 0 {
  366. c.SetIV(payload[:explicitIVLen])
  367. payload = payload[explicitIVLen:]
  368. }
  369. prefix, finalBlock := padToBlockSize(payload, blockSize)
  370. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  371. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  372. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  373. default:
  374. panic("unknown cipher type")
  375. }
  376. }
  377. // update length to include MAC and any block padding needed.
  378. n := len(b.data) - recordHeaderLen
  379. b.data[3] = byte(n >> 8)
  380. b.data[4] = byte(n)
  381. hc.incSeq()
  382. return true, 0
  383. }
  384. // A block is a simple data buffer.
  385. type block struct {
  386. data []byte
  387. off int // index for Read
  388. link *block
  389. }
  390. // resize resizes block to be n bytes, growing if necessary.
  391. func (b *block) resize(n int) {
  392. if n > cap(b.data) {
  393. b.reserve(n)
  394. }
  395. b.data = b.data[0:n]
  396. }
  397. // reserve makes sure that block contains a capacity of at least n bytes.
  398. func (b *block) reserve(n int) {
  399. if cap(b.data) >= n {
  400. return
  401. }
  402. m := cap(b.data)
  403. if m == 0 {
  404. m = 1024
  405. }
  406. for m < n {
  407. m *= 2
  408. }
  409. data := make([]byte, len(b.data), m)
  410. copy(data, b.data)
  411. b.data = data
  412. }
  413. // readFromUntil reads from r into b until b contains at least n bytes
  414. // or else returns an error.
  415. func (b *block) readFromUntil(r io.Reader, n int) error {
  416. // quick case
  417. if len(b.data) >= n {
  418. return nil
  419. }
  420. // read until have enough.
  421. b.reserve(n)
  422. for {
  423. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  424. b.data = b.data[0 : len(b.data)+m]
  425. if len(b.data) >= n {
  426. // TODO(bradfitz,agl): slightly suspicious
  427. // that we're throwing away r.Read's err here.
  428. break
  429. }
  430. if err != nil {
  431. return err
  432. }
  433. }
  434. return nil
  435. }
  436. func (b *block) Read(p []byte) (n int, err error) {
  437. n = copy(p, b.data[b.off:])
  438. b.off += n
  439. return
  440. }
  441. // newBlock allocates a new block, from hc's free list if possible.
  442. func (hc *halfConn) newBlock() *block {
  443. b := hc.bfree
  444. if b == nil {
  445. return new(block)
  446. }
  447. hc.bfree = b.link
  448. b.link = nil
  449. b.resize(0)
  450. return b
  451. }
  452. // freeBlock returns a block to hc's free list.
  453. // The protocol is such that each side only has a block or two on
  454. // its free list at a time, so there's no need to worry about
  455. // trimming the list, etc.
  456. func (hc *halfConn) freeBlock(b *block) {
  457. b.link = hc.bfree
  458. hc.bfree = b
  459. }
  460. // splitBlock splits a block after the first n bytes,
  461. // returning a block with those n bytes and a
  462. // block with the remainder. the latter may be nil.
  463. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  464. if len(b.data) <= n {
  465. return b, nil
  466. }
  467. bb := hc.newBlock()
  468. bb.resize(len(b.data) - n)
  469. copy(bb.data, b.data[n:])
  470. b.data = b.data[0:n]
  471. return b, bb
  472. }
  473. // RecordHeaderError results when a TLS record header is invalid.
  474. type RecordHeaderError struct {
  475. // Msg contains a human readable string that describes the error.
  476. Msg string
  477. // RecordHeader contains the five bytes of TLS record header that
  478. // triggered the error.
  479. RecordHeader [5]byte
  480. }
  481. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  482. func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
  483. err.Msg = msg
  484. copy(err.RecordHeader[:], c.rawInput.data)
  485. return err
  486. }
  487. // readRecord reads the next TLS record from the connection
  488. // and updates the record layer state.
  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. if typ != recordTypeAlert && len(data) > 0 {
  581. // this is a valid non-alert message: reset the count of alerts
  582. c.warnCount = 0
  583. }
  584. switch typ {
  585. default:
  586. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  587. case recordTypeAlert:
  588. if len(data) != 2 {
  589. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  590. break
  591. }
  592. if alert(data[1]) == alertCloseNotify {
  593. c.in.setErrorLocked(io.EOF)
  594. break
  595. }
  596. switch data[0] {
  597. case alertLevelWarning:
  598. // drop on the floor
  599. c.in.freeBlock(b)
  600. c.warnCount++
  601. if c.warnCount > maxWarnAlertCount {
  602. c.sendAlert(alertUnexpectedMessage)
  603. return c.in.setErrorLocked(errors.New("tls: too many warn alerts"))
  604. }
  605. goto Again
  606. case alertLevelError:
  607. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  608. default:
  609. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  610. }
  611. case recordTypeChangeCipherSpec:
  612. if typ != want || len(data) != 1 || data[0] != 1 {
  613. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  614. break
  615. }
  616. // Handshake messages are not allowed to fragment across the CCS
  617. if c.hand.Len() > 0 {
  618. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  619. break
  620. }
  621. err := c.in.changeCipherSpec()
  622. if err != nil {
  623. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  624. }
  625. case recordTypeApplicationData:
  626. if typ != want {
  627. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  628. break
  629. }
  630. c.input = b
  631. b = nil
  632. case recordTypeHandshake:
  633. // TODO(rsc): Should at least pick off connection close.
  634. if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) {
  635. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  636. }
  637. c.hand.Write(data)
  638. }
  639. if b != nil {
  640. c.in.freeBlock(b)
  641. }
  642. return c.in.err
  643. }
  644. // sendAlert sends a TLS alert message.
  645. func (c *Conn) sendAlertLocked(err alert) error {
  646. switch err {
  647. case alertNoRenegotiation, alertCloseNotify:
  648. c.tmp[0] = alertLevelWarning
  649. default:
  650. c.tmp[0] = alertLevelError
  651. }
  652. c.tmp[1] = byte(err)
  653. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  654. if err == alertCloseNotify {
  655. // closeNotify is a special case in that it isn't an error.
  656. return writeErr
  657. }
  658. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  659. }
  660. // sendAlert sends a TLS alert message.
  661. func (c *Conn) sendAlert(err alert) error {
  662. c.out.Lock()
  663. defer c.out.Unlock()
  664. return c.sendAlertLocked(err)
  665. }
  666. const (
  667. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  668. // size (MSS). A constant is used, rather than querying the kernel for
  669. // the actual MSS, to avoid complexity. The value here is the IPv6
  670. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  671. // bytes) and a TCP header with timestamps (32 bytes).
  672. tcpMSSEstimate = 1208
  673. // recordSizeBoostThreshold is the number of bytes of application data
  674. // sent after which the TLS record size will be increased to the
  675. // maximum.
  676. recordSizeBoostThreshold = 128 * 1024
  677. )
  678. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  679. // next application data record. There is the following trade-off:
  680. //
  681. // - For latency-sensitive applications, such as web browsing, each TLS
  682. // record should fit in one TCP segment.
  683. // - For throughput-sensitive applications, such as large file transfers,
  684. // larger TLS records better amortize framing and encryption overheads.
  685. //
  686. // A simple heuristic that works well in practice is to use small records for
  687. // the first 1MB of data, then use larger records for subsequent data, and
  688. // reset back to smaller records after the connection becomes idle. See "High
  689. // Performance Web Networking", Chapter 4, or:
  690. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  691. //
  692. // In the interests of simplicity and determinism, this code does not attempt
  693. // to reset the record size once the connection is idle, however.
  694. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  695. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  696. return maxPlaintext
  697. }
  698. if c.bytesSent >= recordSizeBoostThreshold {
  699. return maxPlaintext
  700. }
  701. // Subtract TLS overheads to get the maximum payload size.
  702. macSize := 0
  703. if c.out.mac != nil {
  704. macSize = c.out.mac.Size()
  705. }
  706. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  707. if c.out.cipher != nil {
  708. switch ciph := c.out.cipher.(type) {
  709. case cipher.Stream:
  710. payloadBytes -= macSize
  711. case cipher.AEAD:
  712. payloadBytes -= ciph.Overhead()
  713. case cbcMode:
  714. blockSize := ciph.BlockSize()
  715. // The payload must fit in a multiple of blockSize, with
  716. // room for at least one padding byte.
  717. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  718. // The MAC is appended before padding so affects the
  719. // payload size directly.
  720. payloadBytes -= macSize
  721. default:
  722. panic("unknown cipher type")
  723. }
  724. }
  725. // Allow packet growth in arithmetic progression up to max.
  726. pkt := c.packetsSent
  727. c.packetsSent++
  728. if pkt > 1000 {
  729. return maxPlaintext // avoid overflow in multiply below
  730. }
  731. n := payloadBytes * int(pkt+1)
  732. if n > maxPlaintext {
  733. n = maxPlaintext
  734. }
  735. return n
  736. }
  737. func (c *Conn) write(data []byte) (int, error) {
  738. if c.buffering {
  739. c.sendBuf = append(c.sendBuf, data...)
  740. return len(data), nil
  741. }
  742. n, err := c.conn.Write(data)
  743. c.bytesSent += int64(n)
  744. return n, err
  745. }
  746. func (c *Conn) flush() (int, error) {
  747. if len(c.sendBuf) == 0 {
  748. return 0, nil
  749. }
  750. n, err := c.conn.Write(c.sendBuf)
  751. c.bytesSent += int64(n)
  752. c.sendBuf = nil
  753. c.buffering = false
  754. return n, err
  755. }
  756. // writeRecordLocked writes a TLS record with the given type and payload to the
  757. // connection and updates the record layer state.
  758. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  759. b := c.out.newBlock()
  760. defer c.out.freeBlock(b)
  761. var n int
  762. for len(data) > 0 {
  763. explicitIVLen := 0
  764. explicitIVIsSeq := false
  765. var cbc cbcMode
  766. if c.out.version >= VersionTLS11 {
  767. var ok bool
  768. if cbc, ok = c.out.cipher.(cbcMode); ok {
  769. explicitIVLen = cbc.BlockSize()
  770. }
  771. }
  772. if explicitIVLen == 0 {
  773. if c, ok := c.out.cipher.(aead); ok {
  774. explicitIVLen = c.explicitNonceLen()
  775. // The AES-GCM construction in TLS has an
  776. // explicit nonce so that the nonce can be
  777. // random. However, the nonce is only 8 bytes
  778. // which is too small for a secure, random
  779. // nonce. Therefore we use the sequence number
  780. // as the nonce.
  781. explicitIVIsSeq = explicitIVLen > 0
  782. }
  783. }
  784. m := len(data)
  785. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  786. m = maxPayload
  787. }
  788. b.resize(recordHeaderLen + explicitIVLen + m)
  789. b.data[0] = byte(typ)
  790. vers := c.vers
  791. if vers == 0 {
  792. // Some TLS servers fail if the record version is
  793. // greater than TLS 1.0 for the initial ClientHello.
  794. vers = VersionTLS10
  795. }
  796. b.data[1] = byte(vers >> 8)
  797. b.data[2] = byte(vers)
  798. b.data[3] = byte(m >> 8)
  799. b.data[4] = byte(m)
  800. if explicitIVLen > 0 {
  801. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  802. if explicitIVIsSeq {
  803. copy(explicitIV, c.out.seq[:])
  804. } else {
  805. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  806. return n, err
  807. }
  808. }
  809. }
  810. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  811. c.out.encrypt(b, explicitIVLen)
  812. if _, err := c.write(b.data); err != nil {
  813. return n, err
  814. }
  815. n += m
  816. data = data[m:]
  817. }
  818. if typ == recordTypeChangeCipherSpec {
  819. if err := c.out.changeCipherSpec(); err != nil {
  820. return n, c.sendAlertLocked(err.(alert))
  821. }
  822. }
  823. return n, nil
  824. }
  825. // writeRecord writes a TLS record with the given type and payload to the
  826. // connection and updates the record layer state.
  827. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  828. c.out.Lock()
  829. defer c.out.Unlock()
  830. return c.writeRecordLocked(typ, data)
  831. }
  832. // readHandshake reads the next handshake message from
  833. // the record layer.
  834. func (c *Conn) readHandshake() (interface{}, error) {
  835. for c.hand.Len() < 4 {
  836. if err := c.in.err; err != nil {
  837. return nil, err
  838. }
  839. if err := c.readRecord(recordTypeHandshake); err != nil {
  840. return nil, err
  841. }
  842. }
  843. data := c.hand.Bytes()
  844. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  845. if n > maxHandshake {
  846. c.sendAlertLocked(alertInternalError)
  847. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  848. }
  849. for c.hand.Len() < 4+n {
  850. if err := c.in.err; err != nil {
  851. return nil, err
  852. }
  853. if err := c.readRecord(recordTypeHandshake); err != nil {
  854. return nil, err
  855. }
  856. }
  857. data = c.hand.Next(4 + n)
  858. var m handshakeMessage
  859. switch data[0] {
  860. case typeHelloRequest:
  861. m = new(helloRequestMsg)
  862. case typeClientHello:
  863. m = new(clientHelloMsg)
  864. case typeServerHello:
  865. m = new(serverHelloMsg)
  866. case typeNewSessionTicket:
  867. m = new(newSessionTicketMsg)
  868. case typeCertificate:
  869. m = new(certificateMsg)
  870. case typeCertificateRequest:
  871. m = &certificateRequestMsg{
  872. hasSignatureAndHash: c.vers >= VersionTLS12,
  873. }
  874. case typeCertificateStatus:
  875. m = new(certificateStatusMsg)
  876. case typeServerKeyExchange:
  877. m = new(serverKeyExchangeMsg)
  878. case typeServerHelloDone:
  879. m = new(serverHelloDoneMsg)
  880. case typeClientKeyExchange:
  881. m = new(clientKeyExchangeMsg)
  882. case typeCertificateVerify:
  883. m = &certificateVerifyMsg{
  884. hasSignatureAndHash: c.vers >= VersionTLS12,
  885. }
  886. case typeNextProtocol:
  887. m = new(nextProtoMsg)
  888. case typeFinished:
  889. m = new(finishedMsg)
  890. default:
  891. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  892. }
  893. // The handshake message unmarshalers
  894. // expect to be able to keep references to data,
  895. // so pass in a fresh copy that won't be overwritten.
  896. data = append([]byte(nil), data...)
  897. if !m.unmarshal(data) {
  898. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  899. }
  900. return m, nil
  901. }
  902. var (
  903. errClosed = errors.New("tls: use of closed connection")
  904. errShutdown = errors.New("tls: protocol is shutdown")
  905. )
  906. // Write writes data to the connection.
  907. func (c *Conn) Write(b []byte) (int, error) {
  908. // interlock with Close below
  909. for {
  910. x := atomic.LoadInt32(&c.activeCall)
  911. if x&1 != 0 {
  912. return 0, errClosed
  913. }
  914. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  915. defer atomic.AddInt32(&c.activeCall, -2)
  916. break
  917. }
  918. }
  919. if err := c.Handshake(); err != nil {
  920. return 0, err
  921. }
  922. c.out.Lock()
  923. defer c.out.Unlock()
  924. if err := c.out.err; err != nil {
  925. return 0, err
  926. }
  927. if !c.handshakeComplete {
  928. return 0, alertInternalError
  929. }
  930. if c.closeNotifySent {
  931. return 0, errShutdown
  932. }
  933. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  934. // attack when using block mode ciphers due to predictable IVs.
  935. // This can be prevented by splitting each Application Data
  936. // record into two records, effectively randomizing the IV.
  937. //
  938. // https://www.openssl.org/~bodo/tls-cbc.txt
  939. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  940. // https://www.imperialviolet.org/2012/01/15/beastfollowup.html
  941. var m int
  942. if len(b) > 1 && c.vers <= VersionTLS10 {
  943. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  944. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  945. if err != nil {
  946. return n, c.out.setErrorLocked(err)
  947. }
  948. m, b = 1, b[1:]
  949. }
  950. }
  951. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  952. return n + m, c.out.setErrorLocked(err)
  953. }
  954. // handleRenegotiation processes a HelloRequest handshake message.
  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.handshakeMutex.Lock()
  1111. defer c.handshakeMutex.Unlock()
  1112. if err := c.handshakeErr; err != nil {
  1113. return err
  1114. }
  1115. if c.handshakeComplete {
  1116. return nil
  1117. }
  1118. c.in.Lock()
  1119. defer c.in.Unlock()
  1120. if c.isClient {
  1121. c.handshakeErr = c.clientHandshake()
  1122. } else {
  1123. c.handshakeErr = c.serverHandshake()
  1124. }
  1125. if c.handshakeErr == nil {
  1126. c.handshakes++
  1127. } else {
  1128. // If an error occurred during the hadshake try to flush the
  1129. // alert that might be left in the buffer.
  1130. c.flush()
  1131. }
  1132. if c.handshakeErr == nil && !c.handshakeComplete {
  1133. panic("handshake should have had a result.")
  1134. }
  1135. return c.handshakeErr
  1136. }
  1137. // ConnectionState returns basic TLS details about the connection.
  1138. func (c *Conn) ConnectionState() ConnectionState {
  1139. c.handshakeMutex.Lock()
  1140. defer c.handshakeMutex.Unlock()
  1141. var state ConnectionState
  1142. state.HandshakeComplete = c.handshakeComplete
  1143. state.ServerName = c.serverName
  1144. if c.handshakeComplete {
  1145. state.Version = c.vers
  1146. state.NegotiatedProtocol = c.clientProtocol
  1147. state.DidResume = c.didResume
  1148. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1149. state.CipherSuite = c.cipherSuite
  1150. state.PeerCertificates = c.peerCertificates
  1151. state.VerifiedChains = c.verifiedChains
  1152. state.SignedCertificateTimestamps = c.scts
  1153. state.OCSPResponse = c.ocspResponse
  1154. if !c.didResume {
  1155. if c.clientFinishedIsFirst {
  1156. state.TLSUnique = c.clientFinished[:]
  1157. } else {
  1158. state.TLSUnique = c.serverFinished[:]
  1159. }
  1160. }
  1161. if c.config.Renegotiation != RenegotiateNever {
  1162. state.ExportKeyingMaterial = noExportedKeyingMaterial
  1163. } else {
  1164. state.ExportKeyingMaterial = c.ekm
  1165. }
  1166. }
  1167. return state
  1168. }
  1169. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1170. // any. (Only valid for client connections.)
  1171. func (c *Conn) OCSPResponse() []byte {
  1172. c.handshakeMutex.Lock()
  1173. defer c.handshakeMutex.Unlock()
  1174. return c.ocspResponse
  1175. }
  1176. // VerifyHostname checks that the peer certificate chain is valid for
  1177. // connecting to host. If so, it returns nil; if not, it returns an error
  1178. // describing the problem.
  1179. func (c *Conn) VerifyHostname(host string) error {
  1180. c.handshakeMutex.Lock()
  1181. defer c.handshakeMutex.Unlock()
  1182. if !c.isClient {
  1183. return errors.New("tls: VerifyHostname called on TLS server connection")
  1184. }
  1185. if !c.handshakeComplete {
  1186. return errors.New("tls: handshake has not yet been performed")
  1187. }
  1188. if len(c.verifiedChains) == 0 {
  1189. return errors.New("tls: handshake did not verify certificate chain")
  1190. }
  1191. return c.peerCertificates[0].VerifyHostname(host)
  1192. }