conn.go 38 KB

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