conn.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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. extendedMasterSecret bool // [Psiphon] whether this session used an extended master secret
  44. cipherSuite uint16
  45. ocspResponse []byte // stapled OCSP response
  46. scts [][]byte // signed certificate timestamps from server
  47. peerCertificates []*x509.Certificate
  48. // verifiedChains contains the certificate chains that we built, as
  49. // opposed to the ones presented by the server.
  50. verifiedChains [][]*x509.Certificate
  51. // serverName contains the server name indicated by the client, if any.
  52. serverName string
  53. // secureRenegotiation is true if the server echoed the secure
  54. // renegotiation extension. (This is meaningless as a server because
  55. // renegotiation is not supported in that case.)
  56. secureRenegotiation bool
  57. // clientFinishedIsFirst is true if the client sent the first Finished
  58. // message during the most recent handshake. This is recorded because
  59. // the first transmitted Finished message is the tls-unique
  60. // channel-binding value.
  61. clientFinishedIsFirst bool
  62. // closeNotifyErr is any error from sending the alertCloseNotify record.
  63. closeNotifyErr error
  64. // closeNotifySent is true if the Conn attempted to send an
  65. // alertCloseNotify record.
  66. closeNotifySent bool
  67. // clientFinished and serverFinished contain the Finished message sent
  68. // by the client or server in the most recent handshake. This is
  69. // retained to support the renegotiation extension and tls-unique
  70. // channel-binding.
  71. clientFinished [12]byte
  72. serverFinished [12]byte
  73. clientProtocol string
  74. clientProtocolFallback bool
  75. // input/output
  76. in, out halfConn // in.Mutex < out.Mutex
  77. rawInput *block // raw input, right off the wire
  78. input *block // application data waiting to be read
  79. hand bytes.Buffer // handshake data waiting to be read
  80. buffering bool // whether records are buffered in sendBuf
  81. sendBuf []byte // a buffer of records waiting to be sent
  82. // bytesSent counts the bytes of application data sent.
  83. // packetsSent counts packets.
  84. bytesSent int64
  85. packetsSent int64
  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. toCheck := 255 // the maximum possible padding length
  187. // The length of the padded data is public, so we can use an if here
  188. if toCheck+1 > len(payload) {
  189. toCheck = len(payload) - 1
  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. err := c.in.changeCipherSpec()
  608. if err != nil {
  609. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  610. }
  611. case recordTypeApplicationData:
  612. if typ != want {
  613. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  614. break
  615. }
  616. c.input = b
  617. b = nil
  618. case recordTypeHandshake:
  619. // TODO(rsc): Should at least pick off connection close.
  620. if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) {
  621. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  622. }
  623. c.hand.Write(data)
  624. }
  625. if b != nil {
  626. c.in.freeBlock(b)
  627. }
  628. return c.in.err
  629. }
  630. // sendAlert sends a TLS alert message.
  631. // c.out.Mutex <= L.
  632. func (c *Conn) sendAlertLocked(err alert) error {
  633. switch err {
  634. case alertNoRenegotiation, alertCloseNotify:
  635. c.tmp[0] = alertLevelWarning
  636. default:
  637. c.tmp[0] = alertLevelError
  638. }
  639. c.tmp[1] = byte(err)
  640. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  641. if err == alertCloseNotify {
  642. // closeNotify is a special case in that it isn't an error.
  643. return writeErr
  644. }
  645. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  646. }
  647. // sendAlert sends a TLS alert message.
  648. // L < c.out.Mutex.
  649. func (c *Conn) sendAlert(err alert) error {
  650. c.out.Lock()
  651. defer c.out.Unlock()
  652. return c.sendAlertLocked(err)
  653. }
  654. const (
  655. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  656. // size (MSS). A constant is used, rather than querying the kernel for
  657. // the actual MSS, to avoid complexity. The value here is the IPv6
  658. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  659. // bytes) and a TCP header with timestamps (32 bytes).
  660. tcpMSSEstimate = 1208
  661. // recordSizeBoostThreshold is the number of bytes of application data
  662. // sent after which the TLS record size will be increased to the
  663. // maximum.
  664. recordSizeBoostThreshold = 128 * 1024
  665. )
  666. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  667. // next application data record. There is the following trade-off:
  668. //
  669. // - For latency-sensitive applications, such as web browsing, each TLS
  670. // record should fit in one TCP segment.
  671. // - For throughput-sensitive applications, such as large file transfers,
  672. // larger TLS records better amortize framing and encryption overheads.
  673. //
  674. // A simple heuristic that works well in practice is to use small records for
  675. // the first 1MB of data, then use larger records for subsequent data, and
  676. // reset back to smaller records after the connection becomes idle. See "High
  677. // Performance Web Networking", Chapter 4, or:
  678. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  679. //
  680. // In the interests of simplicity and determinism, this code does not attempt
  681. // to reset the record size once the connection is idle, however.
  682. //
  683. // c.out.Mutex <= L.
  684. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  685. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  686. return maxPlaintext
  687. }
  688. if c.bytesSent >= recordSizeBoostThreshold {
  689. return maxPlaintext
  690. }
  691. // Subtract TLS overheads to get the maximum payload size.
  692. macSize := 0
  693. if c.out.mac != nil {
  694. macSize = c.out.mac.Size()
  695. }
  696. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  697. if c.out.cipher != nil {
  698. switch ciph := c.out.cipher.(type) {
  699. case cipher.Stream:
  700. payloadBytes -= macSize
  701. case cipher.AEAD:
  702. payloadBytes -= ciph.Overhead()
  703. case cbcMode:
  704. blockSize := ciph.BlockSize()
  705. // The payload must fit in a multiple of blockSize, with
  706. // room for at least one padding byte.
  707. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  708. // The MAC is appended before padding so affects the
  709. // payload size directly.
  710. payloadBytes -= macSize
  711. default:
  712. panic("unknown cipher type")
  713. }
  714. }
  715. // Allow packet growth in arithmetic progression up to max.
  716. pkt := c.packetsSent
  717. c.packetsSent++
  718. if pkt > 1000 {
  719. return maxPlaintext // avoid overflow in multiply below
  720. }
  721. n := payloadBytes * int(pkt+1)
  722. if n > maxPlaintext {
  723. n = maxPlaintext
  724. }
  725. return n
  726. }
  727. // c.out.Mutex <= L.
  728. func (c *Conn) write(data []byte) (int, error) {
  729. if c.buffering {
  730. c.sendBuf = append(c.sendBuf, data...)
  731. return len(data), nil
  732. }
  733. n, err := c.conn.Write(data)
  734. c.bytesSent += int64(n)
  735. return n, err
  736. }
  737. func (c *Conn) flush() (int, error) {
  738. if len(c.sendBuf) == 0 {
  739. return 0, nil
  740. }
  741. n, err := c.conn.Write(c.sendBuf)
  742. c.bytesSent += int64(n)
  743. c.sendBuf = nil
  744. c.buffering = false
  745. return n, err
  746. }
  747. // writeRecordLocked writes a TLS record with the given type and payload to the
  748. // connection and updates the record layer state.
  749. // c.out.Mutex <= L.
  750. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  751. b := c.out.newBlock()
  752. defer c.out.freeBlock(b)
  753. var n int
  754. for len(data) > 0 {
  755. explicitIVLen := 0
  756. explicitIVIsSeq := false
  757. var cbc cbcMode
  758. if c.out.version >= VersionTLS11 {
  759. var ok bool
  760. if cbc, ok = c.out.cipher.(cbcMode); ok {
  761. explicitIVLen = cbc.BlockSize()
  762. }
  763. }
  764. if explicitIVLen == 0 {
  765. if c, ok := c.out.cipher.(aead); ok {
  766. explicitIVLen = c.explicitNonceLen()
  767. // The AES-GCM construction in TLS has an
  768. // explicit nonce so that the nonce can be
  769. // random. However, the nonce is only 8 bytes
  770. // which is too small for a secure, random
  771. // nonce. Therefore we use the sequence number
  772. // as the nonce.
  773. explicitIVIsSeq = explicitIVLen > 0
  774. }
  775. }
  776. m := len(data)
  777. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  778. m = maxPayload
  779. }
  780. b.resize(recordHeaderLen + explicitIVLen + m)
  781. b.data[0] = byte(typ)
  782. vers := c.vers
  783. if vers == 0 {
  784. // Some TLS servers fail if the record version is
  785. // greater than TLS 1.0 for the initial ClientHello.
  786. vers = VersionTLS10
  787. }
  788. b.data[1] = byte(vers >> 8)
  789. b.data[2] = byte(vers)
  790. b.data[3] = byte(m >> 8)
  791. b.data[4] = byte(m)
  792. if explicitIVLen > 0 {
  793. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  794. if explicitIVIsSeq {
  795. copy(explicitIV, c.out.seq[:])
  796. } else {
  797. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  798. return n, err
  799. }
  800. }
  801. }
  802. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  803. c.out.encrypt(b, explicitIVLen)
  804. if _, err := c.write(b.data); err != nil {
  805. return n, err
  806. }
  807. n += m
  808. data = data[m:]
  809. }
  810. if typ == recordTypeChangeCipherSpec {
  811. if err := c.out.changeCipherSpec(); err != nil {
  812. return n, c.sendAlertLocked(err.(alert))
  813. }
  814. }
  815. return n, nil
  816. }
  817. // writeRecord writes a TLS record with the given type and payload to the
  818. // connection and updates the record layer state.
  819. // L < c.out.Mutex.
  820. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  821. c.out.Lock()
  822. defer c.out.Unlock()
  823. return c.writeRecordLocked(typ, data)
  824. }
  825. // readHandshake reads the next handshake message from
  826. // the record layer.
  827. // c.in.Mutex < L; c.out.Mutex < L.
  828. func (c *Conn) readHandshake() (interface{}, error) {
  829. for c.hand.Len() < 4 {
  830. if err := c.in.err; err != nil {
  831. return nil, err
  832. }
  833. if err := c.readRecord(recordTypeHandshake); err != nil {
  834. return nil, err
  835. }
  836. }
  837. data := c.hand.Bytes()
  838. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  839. if n > maxHandshake {
  840. c.sendAlertLocked(alertInternalError)
  841. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  842. }
  843. for c.hand.Len() < 4+n {
  844. if err := c.in.err; err != nil {
  845. return nil, err
  846. }
  847. if err := c.readRecord(recordTypeHandshake); err != nil {
  848. return nil, err
  849. }
  850. }
  851. data = c.hand.Next(4 + n)
  852. var m handshakeMessage
  853. switch data[0] {
  854. case typeHelloRequest:
  855. m = new(helloRequestMsg)
  856. case typeClientHello:
  857. m = new(clientHelloMsg)
  858. case typeServerHello:
  859. m = new(serverHelloMsg)
  860. case typeNewSessionTicket:
  861. m = new(newSessionTicketMsg)
  862. case typeCertificate:
  863. m = new(certificateMsg)
  864. case typeCertificateRequest:
  865. m = &certificateRequestMsg{
  866. hasSignatureAndHash: c.vers >= VersionTLS12,
  867. }
  868. case typeCertificateStatus:
  869. m = new(certificateStatusMsg)
  870. case typeServerKeyExchange:
  871. m = new(serverKeyExchangeMsg)
  872. case typeServerHelloDone:
  873. m = new(serverHelloDoneMsg)
  874. case typeClientKeyExchange:
  875. m = new(clientKeyExchangeMsg)
  876. case typeCertificateVerify:
  877. m = &certificateVerifyMsg{
  878. hasSignatureAndHash: c.vers >= VersionTLS12,
  879. }
  880. case typeNextProtocol:
  881. m = new(nextProtoMsg)
  882. case typeFinished:
  883. m = new(finishedMsg)
  884. default:
  885. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  886. }
  887. // The handshake message unmarshalers
  888. // expect to be able to keep references to data,
  889. // so pass in a fresh copy that won't be overwritten.
  890. data = append([]byte(nil), data...)
  891. if !m.unmarshal(data) {
  892. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  893. }
  894. return m, nil
  895. }
  896. var (
  897. errClosed = errors.New("tls: use of closed connection")
  898. errShutdown = errors.New("tls: protocol is shutdown")
  899. )
  900. // Write writes data to the connection.
  901. func (c *Conn) Write(b []byte) (int, error) {
  902. // interlock with Close below
  903. for {
  904. x := atomic.LoadInt32(&c.activeCall)
  905. if x&1 != 0 {
  906. return 0, errClosed
  907. }
  908. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  909. defer atomic.AddInt32(&c.activeCall, -2)
  910. break
  911. }
  912. }
  913. if err := c.Handshake(); err != nil {
  914. return 0, err
  915. }
  916. c.out.Lock()
  917. defer c.out.Unlock()
  918. if err := c.out.err; err != nil {
  919. return 0, err
  920. }
  921. if !c.handshakeComplete {
  922. return 0, alertInternalError
  923. }
  924. if c.closeNotifySent {
  925. return 0, errShutdown
  926. }
  927. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  928. // attack when using block mode ciphers due to predictable IVs.
  929. // This can be prevented by splitting each Application Data
  930. // record into two records, effectively randomizing the IV.
  931. //
  932. // http://www.openssl.org/~bodo/tls-cbc.txt
  933. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  934. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  935. var m int
  936. if len(b) > 1 && c.vers <= VersionTLS10 {
  937. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  938. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  939. if err != nil {
  940. return n, c.out.setErrorLocked(err)
  941. }
  942. m, b = 1, b[1:]
  943. }
  944. }
  945. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  946. return n + m, c.out.setErrorLocked(err)
  947. }
  948. // handleRenegotiation processes a HelloRequest handshake message.
  949. // c.in.Mutex <= L
  950. func (c *Conn) handleRenegotiation() error {
  951. msg, err := c.readHandshake()
  952. if err != nil {
  953. return err
  954. }
  955. _, ok := msg.(*helloRequestMsg)
  956. if !ok {
  957. c.sendAlert(alertUnexpectedMessage)
  958. return alertUnexpectedMessage
  959. }
  960. if !c.isClient {
  961. return c.sendAlert(alertNoRenegotiation)
  962. }
  963. switch c.config.Renegotiation {
  964. case RenegotiateNever:
  965. return c.sendAlert(alertNoRenegotiation)
  966. case RenegotiateOnceAsClient:
  967. if c.handshakes > 1 {
  968. return c.sendAlert(alertNoRenegotiation)
  969. }
  970. case RenegotiateFreelyAsClient:
  971. // Ok.
  972. default:
  973. c.sendAlert(alertInternalError)
  974. return errors.New("tls: unknown Renegotiation value")
  975. }
  976. c.handshakeMutex.Lock()
  977. defer c.handshakeMutex.Unlock()
  978. c.handshakeComplete = false
  979. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  980. c.handshakes++
  981. }
  982. return c.handshakeErr
  983. }
  984. // Read can be made to time out and return a net.Error with Timeout() == true
  985. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  986. func (c *Conn) Read(b []byte) (n int, err error) {
  987. if err = c.Handshake(); err != nil {
  988. return
  989. }
  990. if len(b) == 0 {
  991. // Put this after Handshake, in case people were calling
  992. // Read(nil) for the side effect of the Handshake.
  993. return
  994. }
  995. c.in.Lock()
  996. defer c.in.Unlock()
  997. // Some OpenSSL servers send empty records in order to randomize the
  998. // CBC IV. So this loop ignores a limited number of empty records.
  999. const maxConsecutiveEmptyRecords = 100
  1000. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1001. for c.input == nil && c.in.err == nil {
  1002. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1003. // Soft error, like EAGAIN
  1004. return 0, err
  1005. }
  1006. if c.hand.Len() > 0 {
  1007. // We received handshake bytes, indicating the
  1008. // start of a renegotiation.
  1009. if err := c.handleRenegotiation(); err != nil {
  1010. return 0, err
  1011. }
  1012. }
  1013. }
  1014. if err := c.in.err; err != nil {
  1015. return 0, err
  1016. }
  1017. n, err = c.input.Read(b)
  1018. if c.input.off >= len(c.input.data) {
  1019. c.in.freeBlock(c.input)
  1020. c.input = nil
  1021. }
  1022. // If a close-notify alert is waiting, read it so that
  1023. // we can return (n, EOF) instead of (n, nil), to signal
  1024. // to the HTTP response reading goroutine that the
  1025. // connection is now closed. This eliminates a race
  1026. // where the HTTP response reading goroutine would
  1027. // otherwise not observe the EOF until its next read,
  1028. // by which time a client goroutine might have already
  1029. // tried to reuse the HTTP connection for a new
  1030. // request.
  1031. // See https://codereview.appspot.com/76400046
  1032. // and https://golang.org/issue/3514
  1033. if ri := c.rawInput; ri != nil &&
  1034. n != 0 && err == nil &&
  1035. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1036. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1037. err = recErr // will be io.EOF on closeNotify
  1038. }
  1039. }
  1040. if n != 0 || err != nil {
  1041. return n, err
  1042. }
  1043. }
  1044. return 0, io.ErrNoProgress
  1045. }
  1046. // Close closes the connection.
  1047. func (c *Conn) Close() error {
  1048. // Interlock with Conn.Write above.
  1049. var x int32
  1050. for {
  1051. x = atomic.LoadInt32(&c.activeCall)
  1052. if x&1 != 0 {
  1053. return errClosed
  1054. }
  1055. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1056. break
  1057. }
  1058. }
  1059. if x != 0 {
  1060. // io.Writer and io.Closer should not be used concurrently.
  1061. // If Close is called while a Write is currently in-flight,
  1062. // interpret that as a sign that this Close is really just
  1063. // being used to break the Write and/or clean up resources and
  1064. // avoid sending the alertCloseNotify, which may block
  1065. // waiting on handshakeMutex or the c.out mutex.
  1066. return c.conn.Close()
  1067. }
  1068. var alertErr error
  1069. c.handshakeMutex.Lock()
  1070. defer c.handshakeMutex.Unlock()
  1071. if c.handshakeComplete {
  1072. alertErr = c.closeNotify()
  1073. }
  1074. if err := c.conn.Close(); err != nil {
  1075. return err
  1076. }
  1077. return alertErr
  1078. }
  1079. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1080. // CloseWrite shuts down the writing side of the connection. It should only be
  1081. // called once the handshake has completed and does not call CloseWrite on the
  1082. // underlying connection. Most callers should just use Close.
  1083. func (c *Conn) CloseWrite() error {
  1084. c.handshakeMutex.Lock()
  1085. defer c.handshakeMutex.Unlock()
  1086. if !c.handshakeComplete {
  1087. return errEarlyCloseWrite
  1088. }
  1089. return c.closeNotify()
  1090. }
  1091. func (c *Conn) closeNotify() error {
  1092. c.out.Lock()
  1093. defer c.out.Unlock()
  1094. if !c.closeNotifySent {
  1095. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1096. c.closeNotifySent = true
  1097. }
  1098. return c.closeNotifyErr
  1099. }
  1100. // Handshake runs the client or server handshake
  1101. // protocol if it has not yet been run.
  1102. // Most uses of this package need not call Handshake
  1103. // explicitly: the first Read or Write will call it automatically.
  1104. func (c *Conn) Handshake() error {
  1105. // c.handshakeErr and c.handshakeComplete are protected by
  1106. // c.handshakeMutex. In order to perform a handshake, we need to lock
  1107. // c.in also and c.handshakeMutex must be locked after c.in.
  1108. //
  1109. // However, if a Read() operation is hanging then it'll be holding the
  1110. // lock on c.in and so taking it here would cause all operations that
  1111. // need to check whether a handshake is pending (such as Write) to
  1112. // block.
  1113. //
  1114. // Thus we first take c.handshakeMutex to check whether a handshake is
  1115. // needed.
  1116. //
  1117. // If so then, previously, this code would unlock handshakeMutex and
  1118. // then lock c.in and handshakeMutex in the correct order to run the
  1119. // handshake. The problem was that it was possible for a Read to
  1120. // complete the handshake once handshakeMutex was unlocked and then
  1121. // keep c.in while waiting for network data. Thus a concurrent
  1122. // operation could be blocked on c.in.
  1123. //
  1124. // Thus handshakeCond is used to signal that a goroutine is committed
  1125. // to running the handshake and other goroutines can wait on it if they
  1126. // need. handshakeCond is protected by handshakeMutex.
  1127. c.handshakeMutex.Lock()
  1128. defer c.handshakeMutex.Unlock()
  1129. for {
  1130. if err := c.handshakeErr; err != nil {
  1131. return err
  1132. }
  1133. if c.handshakeComplete {
  1134. return nil
  1135. }
  1136. if c.handshakeCond == nil {
  1137. break
  1138. }
  1139. c.handshakeCond.Wait()
  1140. }
  1141. // Set handshakeCond to indicate that this goroutine is committing to
  1142. // running the handshake.
  1143. c.handshakeCond = sync.NewCond(&c.handshakeMutex)
  1144. c.handshakeMutex.Unlock()
  1145. c.in.Lock()
  1146. defer c.in.Unlock()
  1147. c.handshakeMutex.Lock()
  1148. // The handshake cannot have completed when handshakeMutex was unlocked
  1149. // because this goroutine set handshakeCond.
  1150. if c.handshakeErr != nil || c.handshakeComplete {
  1151. panic("handshake should not have been able to complete after handshakeCond was set")
  1152. }
  1153. if c.isClient {
  1154. c.handshakeErr = c.clientHandshake()
  1155. } else {
  1156. c.handshakeErr = c.serverHandshake()
  1157. }
  1158. if c.handshakeErr == nil {
  1159. c.handshakes++
  1160. } else {
  1161. // If an error occurred during the hadshake try to flush the
  1162. // alert that might be left in the buffer.
  1163. c.flush()
  1164. }
  1165. if c.handshakeErr == nil && !c.handshakeComplete {
  1166. panic("handshake should have had a result.")
  1167. }
  1168. // Wake any other goroutines that are waiting for this handshake to
  1169. // complete.
  1170. c.handshakeCond.Broadcast()
  1171. c.handshakeCond = nil
  1172. return c.handshakeErr
  1173. }
  1174. // ConnectionState returns basic TLS details about the connection.
  1175. func (c *Conn) ConnectionState() ConnectionState {
  1176. c.handshakeMutex.Lock()
  1177. defer c.handshakeMutex.Unlock()
  1178. var state ConnectionState
  1179. state.HandshakeComplete = c.handshakeComplete
  1180. state.ServerName = c.serverName
  1181. if c.handshakeComplete {
  1182. state.Version = c.vers
  1183. state.NegotiatedProtocol = c.clientProtocol
  1184. state.DidResume = c.didResume
  1185. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1186. state.CipherSuite = c.cipherSuite
  1187. state.PeerCertificates = c.peerCertificates
  1188. state.VerifiedChains = c.verifiedChains
  1189. state.SignedCertificateTimestamps = c.scts
  1190. state.OCSPResponse = c.ocspResponse
  1191. if !c.didResume {
  1192. if c.clientFinishedIsFirst {
  1193. state.TLSUnique = c.clientFinished[:]
  1194. } else {
  1195. state.TLSUnique = c.serverFinished[:]
  1196. }
  1197. }
  1198. }
  1199. return state
  1200. }
  1201. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1202. // any. (Only valid for client connections.)
  1203. func (c *Conn) OCSPResponse() []byte {
  1204. c.handshakeMutex.Lock()
  1205. defer c.handshakeMutex.Unlock()
  1206. return c.ocspResponse
  1207. }
  1208. // VerifyHostname checks that the peer certificate chain is valid for
  1209. // connecting to host. If so, it returns nil; if not, it returns an error
  1210. // describing the problem.
  1211. func (c *Conn) VerifyHostname(host string) error {
  1212. c.handshakeMutex.Lock()
  1213. defer c.handshakeMutex.Unlock()
  1214. if !c.isClient {
  1215. return errors.New("tls: VerifyHostname called on TLS server connection")
  1216. }
  1217. if !c.handshakeComplete {
  1218. return errors.New("tls: handshake has not yet been performed")
  1219. }
  1220. if len(c.verifiedChains) == 0 {
  1221. return errors.New("tls: handshake did not verify certificate chain")
  1222. }
  1223. return c.peerCertificates[0].VerifyHostname(host)
  1224. }