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

1340 linhas
38 KiB

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