You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1027 lines
28 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. "time"
  17. )
  18. // A Conn represents a secured connection.
  19. // It implements the net.Conn interface.
  20. type Conn struct {
  21. // constant
  22. conn net.Conn
  23. isClient bool
  24. // constant after handshake; protected by handshakeMutex
  25. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  26. handshakeErr error // error resulting from handshake
  27. vers uint16 // TLS version
  28. haveVers bool // version has been negotiated
  29. config *Config // configuration passed to constructor
  30. handshakeComplete bool
  31. didResume bool // whether this connection was a session resumption
  32. cipherSuite uint16
  33. ocspResponse []byte // stapled OCSP response
  34. peerCertificates []*x509.Certificate
  35. // verifiedChains contains the certificate chains that we built, as
  36. // opposed to the ones presented by the server.
  37. verifiedChains [][]*x509.Certificate
  38. // serverName contains the server name indicated by the client, if any.
  39. serverName string
  40. // firstFinished contains the first Finished hash sent during the
  41. // handshake. This is the "tls-unique" channel binding value.
  42. firstFinished [12]byte
  43. clientProtocol string
  44. clientProtocolFallback bool
  45. // input/output
  46. in, out halfConn // in.Mutex < out.Mutex
  47. rawInput *block // raw input, right off the wire
  48. input *block // application data waiting to be read
  49. hand bytes.Buffer // handshake data waiting to be read
  50. tmp [16]byte
  51. }
  52. // Access to net.Conn methods.
  53. // Cannot just embed net.Conn because that would
  54. // export the struct field too.
  55. // LocalAddr returns the local network address.
  56. func (c *Conn) LocalAddr() net.Addr {
  57. return c.conn.LocalAddr()
  58. }
  59. // RemoteAddr returns the remote network address.
  60. func (c *Conn) RemoteAddr() net.Addr {
  61. return c.conn.RemoteAddr()
  62. }
  63. // SetDeadline sets the read and write deadlines associated with the connection.
  64. // A zero value for t means Read and Write will not time out.
  65. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  66. func (c *Conn) SetDeadline(t time.Time) error {
  67. return c.conn.SetDeadline(t)
  68. }
  69. // SetReadDeadline sets the read deadline on the underlying connection.
  70. // A zero value for t means Read will not time out.
  71. func (c *Conn) SetReadDeadline(t time.Time) error {
  72. return c.conn.SetReadDeadline(t)
  73. }
  74. // SetWriteDeadline sets the write deadline on the underlying connection.
  75. // A zero value for t means Write will not time out.
  76. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  77. func (c *Conn) SetWriteDeadline(t time.Time) error {
  78. return c.conn.SetWriteDeadline(t)
  79. }
  80. // A halfConn represents one direction of the record layer
  81. // connection, either sending or receiving.
  82. type halfConn struct {
  83. sync.Mutex
  84. err error // first permanent error
  85. version uint16 // protocol version
  86. cipher interface{} // cipher algorithm
  87. mac macFunction
  88. seq [8]byte // 64-bit sequence number
  89. bfree *block // list of free blocks
  90. nextCipher interface{} // next encryption state
  91. nextMac macFunction // next MAC algorithm
  92. // used to save allocating a new buffer for each MAC.
  93. inDigestBuf, outDigestBuf []byte
  94. }
  95. func (hc *halfConn) setErrorLocked(err error) error {
  96. hc.err = err
  97. return err
  98. }
  99. func (hc *halfConn) error() error {
  100. hc.Lock()
  101. err := hc.err
  102. hc.Unlock()
  103. return err
  104. }
  105. // prepareCipherSpec sets the encryption and MAC states
  106. // that a subsequent changeCipherSpec will use.
  107. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  108. hc.version = version
  109. hc.nextCipher = cipher
  110. hc.nextMac = mac
  111. }
  112. // changeCipherSpec changes the encryption and MAC states
  113. // to the ones previously passed to prepareCipherSpec.
  114. func (hc *halfConn) changeCipherSpec() error {
  115. if hc.nextCipher == nil {
  116. return alertInternalError
  117. }
  118. hc.cipher = hc.nextCipher
  119. hc.mac = hc.nextMac
  120. hc.nextCipher = nil
  121. hc.nextMac = nil
  122. for i := range hc.seq {
  123. hc.seq[i] = 0
  124. }
  125. return nil
  126. }
  127. // incSeq increments the sequence number.
  128. func (hc *halfConn) incSeq() {
  129. for i := 7; i >= 0; i-- {
  130. hc.seq[i]++
  131. if hc.seq[i] != 0 {
  132. return
  133. }
  134. }
  135. // Not allowed to let sequence number wrap.
  136. // Instead, must renegotiate before it does.
  137. // Not likely enough to bother.
  138. panic("TLS: sequence number wraparound")
  139. }
  140. // resetSeq resets the sequence number to zero.
  141. func (hc *halfConn) resetSeq() {
  142. for i := range hc.seq {
  143. hc.seq[i] = 0
  144. }
  145. }
  146. // removePadding returns an unpadded slice, in constant time, which is a prefix
  147. // of the input. It also returns a byte which is equal to 255 if the padding
  148. // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  149. func removePadding(payload []byte) ([]byte, byte) {
  150. if len(payload) < 1 {
  151. return payload, 0
  152. }
  153. paddingLen := payload[len(payload)-1]
  154. t := uint(len(payload)-1) - uint(paddingLen)
  155. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  156. good := byte(int32(^t) >> 31)
  157. toCheck := 255 // the maximum possible padding length
  158. // The length of the padded data is public, so we can use an if here
  159. if toCheck+1 > len(payload) {
  160. toCheck = len(payload) - 1
  161. }
  162. for i := 0; i < toCheck; i++ {
  163. t := uint(paddingLen) - uint(i)
  164. // if i <= paddingLen then the MSB of t is zero
  165. mask := byte(int32(^t) >> 31)
  166. b := payload[len(payload)-1-i]
  167. good &^= mask&paddingLen ^ mask&b
  168. }
  169. // We AND together the bits of good and replicate the result across
  170. // all the bits.
  171. good &= good << 4
  172. good &= good << 2
  173. good &= good << 1
  174. good = uint8(int8(good) >> 7)
  175. toRemove := good&paddingLen + 1
  176. return payload[:len(payload)-int(toRemove)], good
  177. }
  178. // removePaddingSSL30 is a replacement for removePadding in the case that the
  179. // protocol version is SSLv3. In this version, the contents of the padding
  180. // are random and cannot be checked.
  181. func removePaddingSSL30(payload []byte) ([]byte, byte) {
  182. if len(payload) < 1 {
  183. return payload, 0
  184. }
  185. paddingLen := int(payload[len(payload)-1]) + 1
  186. if paddingLen > len(payload) {
  187. return payload, 0
  188. }
  189. return payload[:len(payload)-paddingLen], 255
  190. }
  191. func roundUp(a, b int) int {
  192. return a + (b-a%b)%b
  193. }
  194. // cbcMode is an interface for block ciphers using cipher block chaining.
  195. type cbcMode interface {
  196. cipher.BlockMode
  197. SetIV([]byte)
  198. }
  199. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  200. // success boolean, the number of bytes to skip from the start of the record in
  201. // order to get the application payload, and an optional alert value.
  202. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  203. // pull out payload
  204. payload := b.data[recordHeaderLen:]
  205. macSize := 0
  206. if hc.mac != nil {
  207. macSize = hc.mac.Size()
  208. }
  209. paddingGood := byte(255)
  210. explicitIVLen := 0
  211. // decrypt
  212. if hc.cipher != nil {
  213. switch c := hc.cipher.(type) {
  214. case cipher.Stream:
  215. c.XORKeyStream(payload, payload)
  216. case cipher.AEAD:
  217. explicitIVLen = 8
  218. if len(payload) < explicitIVLen {
  219. return false, 0, alertBadRecordMAC
  220. }
  221. nonce := payload[:8]
  222. payload = payload[8:]
  223. var additionalData [13]byte
  224. copy(additionalData[:], hc.seq[:])
  225. copy(additionalData[8:], b.data[:3])
  226. n := len(payload) - c.Overhead()
  227. additionalData[11] = byte(n >> 8)
  228. additionalData[12] = byte(n)
  229. var err error
  230. payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
  231. if err != nil {
  232. return false, 0, alertBadRecordMAC
  233. }
  234. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  235. case cbcMode:
  236. blockSize := c.BlockSize()
  237. if hc.version >= VersionTLS11 {
  238. explicitIVLen = blockSize
  239. }
  240. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  241. return false, 0, alertBadRecordMAC
  242. }
  243. if explicitIVLen > 0 {
  244. c.SetIV(payload[:explicitIVLen])
  245. payload = payload[explicitIVLen:]
  246. }
  247. c.CryptBlocks(payload, payload)
  248. if hc.version == VersionSSL30 {
  249. payload, paddingGood = removePaddingSSL30(payload)
  250. } else {
  251. payload, paddingGood = removePadding(payload)
  252. }
  253. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  254. // note that we still have a timing side-channel in the
  255. // MAC check, below. An attacker can align the record
  256. // so that a correct padding will cause one less hash
  257. // block to be calculated. Then they can iteratively
  258. // decrypt a record by breaking each byte. See
  259. // "Password Interception in a SSL/TLS Channel", Brice
  260. // Canvel et al.
  261. //
  262. // However, our behavior matches OpenSSL, so we leak
  263. // only as much as they do.
  264. default:
  265. panic("unknown cipher type")
  266. }
  267. }
  268. // check, strip mac
  269. if hc.mac != nil {
  270. if len(payload) < macSize {
  271. return false, 0, alertBadRecordMAC
  272. }
  273. // strip mac off payload, b.data
  274. n := len(payload) - macSize
  275. b.data[3] = byte(n >> 8)
  276. b.data[4] = byte(n)
  277. b.resize(recordHeaderLen + explicitIVLen + n)
  278. remoteMAC := payload[n:]
  279. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n])
  280. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  281. return false, 0, alertBadRecordMAC
  282. }
  283. hc.inDigestBuf = localMAC
  284. }
  285. hc.incSeq()
  286. return true, recordHeaderLen + explicitIVLen, 0
  287. }
  288. // padToBlockSize calculates the needed padding block, if any, for a payload.
  289. // On exit, prefix aliases payload and extends to the end of the last full
  290. // block of payload. finalBlock is a fresh slice which contains the contents of
  291. // any suffix of payload as well as the needed padding to make finalBlock a
  292. // full block.
  293. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  294. overrun := len(payload) % blockSize
  295. paddingLen := blockSize - overrun
  296. prefix = payload[:len(payload)-overrun]
  297. finalBlock = make([]byte, blockSize)
  298. copy(finalBlock, payload[len(payload)-overrun:])
  299. for i := overrun; i < blockSize; i++ {
  300. finalBlock[i] = byte(paddingLen - 1)
  301. }
  302. return
  303. }
  304. // encrypt encrypts and macs the data in b.
  305. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  306. // mac
  307. if hc.mac != nil {
  308. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
  309. n := len(b.data)
  310. b.resize(n + len(mac))
  311. copy(b.data[n:], mac)
  312. hc.outDigestBuf = mac
  313. }
  314. payload := b.data[recordHeaderLen:]
  315. // encrypt
  316. if hc.cipher != nil {
  317. switch c := hc.cipher.(type) {
  318. case cipher.Stream:
  319. c.XORKeyStream(payload, payload)
  320. case cipher.AEAD:
  321. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  322. b.resize(len(b.data) + c.Overhead())
  323. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  324. payload := b.data[recordHeaderLen+explicitIVLen:]
  325. payload = payload[:payloadLen]
  326. var additionalData [13]byte
  327. copy(additionalData[:], hc.seq[:])
  328. copy(additionalData[8:], b.data[:3])
  329. additionalData[11] = byte(payloadLen >> 8)
  330. additionalData[12] = byte(payloadLen)
  331. c.Seal(payload[:0], nonce, payload, additionalData[:])
  332. case cbcMode:
  333. blockSize := c.BlockSize()
  334. if explicitIVLen > 0 {
  335. c.SetIV(payload[:explicitIVLen])
  336. payload = payload[explicitIVLen:]
  337. }
  338. prefix, finalBlock := padToBlockSize(payload, blockSize)
  339. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  340. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  341. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  342. default:
  343. panic("unknown cipher type")
  344. }
  345. }
  346. // update length to include MAC and any block padding needed.
  347. n := len(b.data) - recordHeaderLen
  348. b.data[3] = byte(n >> 8)
  349. b.data[4] = byte(n)
  350. hc.incSeq()
  351. return true, 0
  352. }
  353. // A block is a simple data buffer.
  354. type block struct {
  355. data []byte
  356. off int // index for Read
  357. link *block
  358. }
  359. // resize resizes block to be n bytes, growing if necessary.
  360. func (b *block) resize(n int) {
  361. if n > cap(b.data) {
  362. b.reserve(n)
  363. }
  364. b.data = b.data[0:n]
  365. }
  366. // reserve makes sure that block contains a capacity of at least n bytes.
  367. func (b *block) reserve(n int) {
  368. if cap(b.data) >= n {
  369. return
  370. }
  371. m := cap(b.data)
  372. if m == 0 {
  373. m = 1024
  374. }
  375. for m < n {
  376. m *= 2
  377. }
  378. data := make([]byte, len(b.data), m)
  379. copy(data, b.data)
  380. b.data = data
  381. }
  382. // readFromUntil reads from r into b until b contains at least n bytes
  383. // or else returns an error.
  384. func (b *block) readFromUntil(r io.Reader, n int) error {
  385. // quick case
  386. if len(b.data) >= n {
  387. return nil
  388. }
  389. // read until have enough.
  390. b.reserve(n)
  391. for {
  392. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  393. b.data = b.data[0 : len(b.data)+m]
  394. if len(b.data) >= n {
  395. // TODO(bradfitz,agl): slightly suspicious
  396. // that we're throwing away r.Read's err here.
  397. break
  398. }
  399. if err != nil {
  400. return err
  401. }
  402. }
  403. return nil
  404. }
  405. func (b *block) Read(p []byte) (n int, err error) {
  406. n = copy(p, b.data[b.off:])
  407. b.off += n
  408. return
  409. }
  410. // newBlock allocates a new block, from hc's free list if possible.
  411. func (hc *halfConn) newBlock() *block {
  412. b := hc.bfree
  413. if b == nil {
  414. return new(block)
  415. }
  416. hc.bfree = b.link
  417. b.link = nil
  418. b.resize(0)
  419. return b
  420. }
  421. // freeBlock returns a block to hc's free list.
  422. // The protocol is such that each side only has a block or two on
  423. // its free list at a time, so there's no need to worry about
  424. // trimming the list, etc.
  425. func (hc *halfConn) freeBlock(b *block) {
  426. b.link = hc.bfree
  427. hc.bfree = b
  428. }
  429. // splitBlock splits a block after the first n bytes,
  430. // returning a block with those n bytes and a
  431. // block with the remainder. the latter may be nil.
  432. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  433. if len(b.data) <= n {
  434. return b, nil
  435. }
  436. bb := hc.newBlock()
  437. bb.resize(len(b.data) - n)
  438. copy(bb.data, b.data[n:])
  439. b.data = b.data[0:n]
  440. return b, bb
  441. }
  442. // readRecord reads the next TLS record from the connection
  443. // and updates the record layer state.
  444. // c.in.Mutex <= L; c.input == nil.
  445. func (c *Conn) readRecord(want recordType) error {
  446. // Caller must be in sync with connection:
  447. // handshake data if handshake not yet completed,
  448. // else application data. (We don't support renegotiation.)
  449. switch want {
  450. default:
  451. c.sendAlert(alertInternalError)
  452. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  453. case recordTypeHandshake, recordTypeChangeCipherSpec:
  454. if c.handshakeComplete {
  455. c.sendAlert(alertInternalError)
  456. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
  457. }
  458. case recordTypeApplicationData:
  459. if !c.handshakeComplete {
  460. c.sendAlert(alertInternalError)
  461. return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete"))
  462. }
  463. }
  464. Again:
  465. if c.rawInput == nil {
  466. c.rawInput = c.in.newBlock()
  467. }
  468. b := c.rawInput
  469. // Read header, payload.
  470. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  471. // RFC suggests that EOF without an alertCloseNotify is
  472. // an error, but popular web sites seem to do this,
  473. // so we can't make it an error.
  474. // if err == io.EOF {
  475. // err = io.ErrUnexpectedEOF
  476. // }
  477. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  478. c.in.setErrorLocked(err)
  479. }
  480. return err
  481. }
  482. typ := recordType(b.data[0])
  483. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  484. // start with a uint16 length where the MSB is set and the first record
  485. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  486. // an SSLv2 client.
  487. if want == recordTypeHandshake && typ == 0x80 {
  488. c.sendAlert(alertProtocolVersion)
  489. return c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
  490. }
  491. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  492. n := int(b.data[3])<<8 | int(b.data[4])
  493. if c.haveVers && vers != c.vers {
  494. c.sendAlert(alertProtocolVersion)
  495. return c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers))
  496. }
  497. if n > maxCiphertext {
  498. c.sendAlert(alertRecordOverflow)
  499. return c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n))
  500. }
  501. if !c.haveVers {
  502. // First message, be extra suspicious: this might not be a TLS
  503. // client. Bail out before reading a full 'body', if possible.
  504. // The current max version is 3.3 so if the version is >= 16.0,
  505. // it's probably not real.
  506. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  507. c.sendAlert(alertUnexpectedMessage)
  508. return c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake"))
  509. }
  510. }
  511. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  512. if err == io.EOF {
  513. err = io.ErrUnexpectedEOF
  514. }
  515. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  516. c.in.setErrorLocked(err)
  517. }
  518. return err
  519. }
  520. // Process message.
  521. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  522. ok, off, err := c.in.decrypt(b)
  523. if !ok {
  524. c.in.setErrorLocked(c.sendAlert(err))
  525. }
  526. b.off = off
  527. data := b.data[b.off:]
  528. if len(data) > maxPlaintext {
  529. err := c.sendAlert(alertRecordOverflow)
  530. c.in.freeBlock(b)
  531. return c.in.setErrorLocked(err)
  532. }
  533. switch typ {
  534. default:
  535. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  536. case recordTypeAlert:
  537. if len(data) != 2 {
  538. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  539. break
  540. }
  541. if alert(data[1]) == alertCloseNotify {
  542. c.in.setErrorLocked(io.EOF)
  543. break
  544. }
  545. switch data[0] {
  546. case alertLevelWarning:
  547. // drop on the floor
  548. c.in.freeBlock(b)
  549. goto Again
  550. case alertLevelError:
  551. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  552. default:
  553. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  554. }
  555. case recordTypeChangeCipherSpec:
  556. if typ != want || len(data) != 1 || data[0] != 1 {
  557. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  558. break
  559. }
  560. err := c.in.changeCipherSpec()
  561. if err != nil {
  562. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  563. }
  564. case recordTypeApplicationData:
  565. if typ != want {
  566. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  567. break
  568. }
  569. c.input = b
  570. b = nil
  571. case recordTypeHandshake:
  572. // TODO(rsc): Should at least pick off connection close.
  573. if typ != want {
  574. return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
  575. }
  576. c.hand.Write(data)
  577. }
  578. if b != nil {
  579. c.in.freeBlock(b)
  580. }
  581. return c.in.err
  582. }
  583. // sendAlert sends a TLS alert message.
  584. // c.out.Mutex <= L.
  585. func (c *Conn) sendAlertLocked(err alert) error {
  586. switch err {
  587. case alertNoRenegotiation, alertCloseNotify:
  588. c.tmp[0] = alertLevelWarning
  589. default:
  590. c.tmp[0] = alertLevelError
  591. }
  592. c.tmp[1] = byte(err)
  593. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  594. // closeNotify is a special case in that it isn't an error:
  595. if err != alertCloseNotify {
  596. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  597. }
  598. return nil
  599. }
  600. // sendAlert sends a TLS alert message.
  601. // L < c.out.Mutex.
  602. func (c *Conn) sendAlert(err alert) error {
  603. c.out.Lock()
  604. defer c.out.Unlock()
  605. return c.sendAlertLocked(err)
  606. }
  607. // writeRecord writes a TLS record with the given type and payload
  608. // to the connection and updates the record layer state.
  609. // c.out.Mutex <= L.
  610. func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
  611. b := c.out.newBlock()
  612. for len(data) > 0 {
  613. m := len(data)
  614. if m > maxPlaintext {
  615. m = maxPlaintext
  616. }
  617. explicitIVLen := 0
  618. explicitIVIsSeq := false
  619. var cbc cbcMode
  620. if c.out.version >= VersionTLS11 {
  621. var ok bool
  622. if cbc, ok = c.out.cipher.(cbcMode); ok {
  623. explicitIVLen = cbc.BlockSize()
  624. }
  625. }
  626. if explicitIVLen == 0 {
  627. if _, ok := c.out.cipher.(cipher.AEAD); ok {
  628. explicitIVLen = 8
  629. // The AES-GCM construction in TLS has an
  630. // explicit nonce so that the nonce can be
  631. // random. However, the nonce is only 8 bytes
  632. // which is too small for a secure, random
  633. // nonce. Therefore we use the sequence number
  634. // as the nonce.
  635. explicitIVIsSeq = true
  636. }
  637. }
  638. b.resize(recordHeaderLen + explicitIVLen + m)
  639. b.data[0] = byte(typ)
  640. vers := c.vers
  641. if vers == 0 {
  642. // Some TLS servers fail if the record version is
  643. // greater than TLS 1.0 for the initial ClientHello.
  644. vers = VersionTLS10
  645. }
  646. b.data[1] = byte(vers >> 8)
  647. b.data[2] = byte(vers)
  648. b.data[3] = byte(m >> 8)
  649. b.data[4] = byte(m)
  650. if explicitIVLen > 0 {
  651. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  652. if explicitIVIsSeq {
  653. copy(explicitIV, c.out.seq[:])
  654. } else {
  655. if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
  656. break
  657. }
  658. }
  659. }
  660. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  661. c.out.encrypt(b, explicitIVLen)
  662. _, err = c.conn.Write(b.data)
  663. if err != nil {
  664. break
  665. }
  666. n += m
  667. data = data[m:]
  668. }
  669. c.out.freeBlock(b)
  670. if typ == recordTypeChangeCipherSpec {
  671. err = c.out.changeCipherSpec()
  672. if err != nil {
  673. // Cannot call sendAlert directly,
  674. // because we already hold c.out.Mutex.
  675. c.tmp[0] = alertLevelError
  676. c.tmp[1] = byte(err.(alert))
  677. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  678. return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  679. }
  680. }
  681. return
  682. }
  683. // readHandshake reads the next handshake message from
  684. // the record layer.
  685. // c.in.Mutex < L; c.out.Mutex < L.
  686. func (c *Conn) readHandshake() (interface{}, error) {
  687. for c.hand.Len() < 4 {
  688. if err := c.in.err; err != nil {
  689. return nil, err
  690. }
  691. if err := c.readRecord(recordTypeHandshake); err != nil {
  692. return nil, err
  693. }
  694. }
  695. data := c.hand.Bytes()
  696. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  697. if n > maxHandshake {
  698. return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError))
  699. }
  700. for c.hand.Len() < 4+n {
  701. if err := c.in.err; err != nil {
  702. return nil, err
  703. }
  704. if err := c.readRecord(recordTypeHandshake); err != nil {
  705. return nil, err
  706. }
  707. }
  708. data = c.hand.Next(4 + n)
  709. var m handshakeMessage
  710. switch data[0] {
  711. case typeClientHello:
  712. m = new(clientHelloMsg)
  713. case typeServerHello:
  714. m = new(serverHelloMsg)
  715. case typeNewSessionTicket:
  716. m = new(newSessionTicketMsg)
  717. case typeCertificate:
  718. m = new(certificateMsg)
  719. case typeCertificateRequest:
  720. m = &certificateRequestMsg{
  721. hasSignatureAndHash: c.vers >= VersionTLS12,
  722. }
  723. case typeCertificateStatus:
  724. m = new(certificateStatusMsg)
  725. case typeServerKeyExchange:
  726. m = new(serverKeyExchangeMsg)
  727. case typeServerHelloDone:
  728. m = new(serverHelloDoneMsg)
  729. case typeClientKeyExchange:
  730. m = new(clientKeyExchangeMsg)
  731. case typeCertificateVerify:
  732. m = &certificateVerifyMsg{
  733. hasSignatureAndHash: c.vers >= VersionTLS12,
  734. }
  735. case typeNextProtocol:
  736. m = new(nextProtoMsg)
  737. case typeFinished:
  738. m = new(finishedMsg)
  739. default:
  740. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  741. }
  742. // The handshake message unmarshallers
  743. // expect to be able to keep references to data,
  744. // so pass in a fresh copy that won't be overwritten.
  745. data = append([]byte(nil), data...)
  746. if !m.unmarshal(data) {
  747. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  748. }
  749. return m, nil
  750. }
  751. // Write writes data to the connection.
  752. func (c *Conn) Write(b []byte) (int, error) {
  753. if err := c.Handshake(); err != nil {
  754. return 0, err
  755. }
  756. c.out.Lock()
  757. defer c.out.Unlock()
  758. if err := c.out.err; err != nil {
  759. return 0, err
  760. }
  761. if !c.handshakeComplete {
  762. return 0, alertInternalError
  763. }
  764. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  765. // attack when using block mode ciphers due to predictable IVs.
  766. // This can be prevented by splitting each Application Data
  767. // record into two records, effectively randomizing the IV.
  768. //
  769. // http://www.openssl.org/~bodo/tls-cbc.txt
  770. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  771. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  772. var m int
  773. if len(b) > 1 && c.vers <= VersionTLS10 {
  774. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  775. n, err := c.writeRecord(recordTypeApplicationData, b[:1])
  776. if err != nil {
  777. return n, c.out.setErrorLocked(err)
  778. }
  779. m, b = 1, b[1:]
  780. }
  781. }
  782. n, err := c.writeRecord(recordTypeApplicationData, b)
  783. return n + m, c.out.setErrorLocked(err)
  784. }
  785. // Read can be made to time out and return a net.Error with Timeout() == true
  786. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  787. func (c *Conn) Read(b []byte) (n int, err error) {
  788. if err = c.Handshake(); err != nil {
  789. return
  790. }
  791. if len(b) == 0 {
  792. // Put this after Handshake, in case people were calling
  793. // Read(nil) for the side effect of the Handshake.
  794. return
  795. }
  796. c.in.Lock()
  797. defer c.in.Unlock()
  798. // Some OpenSSL servers send empty records in order to randomize the
  799. // CBC IV. So this loop ignores a limited number of empty records.
  800. const maxConsecutiveEmptyRecords = 100
  801. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  802. for c.input == nil && c.in.err == nil {
  803. if err := c.readRecord(recordTypeApplicationData); err != nil {
  804. // Soft error, like EAGAIN
  805. return 0, err
  806. }
  807. }
  808. if err := c.in.err; err != nil {
  809. return 0, err
  810. }
  811. n, err = c.input.Read(b)
  812. if c.input.off >= len(c.input.data) {
  813. c.in.freeBlock(c.input)
  814. c.input = nil
  815. }
  816. // If a close-notify alert is waiting, read it so that
  817. // we can return (n, EOF) instead of (n, nil), to signal
  818. // to the HTTP response reading goroutine that the
  819. // connection is now closed. This eliminates a race
  820. // where the HTTP response reading goroutine would
  821. // otherwise not observe the EOF until its next read,
  822. // by which time a client goroutine might have already
  823. // tried to reuse the HTTP connection for a new
  824. // request.
  825. // See https://codereview.appspot.com/76400046
  826. // and http://golang.org/issue/3514
  827. if ri := c.rawInput; ri != nil &&
  828. n != 0 && err == nil &&
  829. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  830. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  831. err = recErr // will be io.EOF on closeNotify
  832. }
  833. }
  834. if n != 0 || err != nil {
  835. return n, err
  836. }
  837. }
  838. return 0, io.ErrNoProgress
  839. }
  840. // Close closes the connection.
  841. func (c *Conn) Close() error {
  842. var alertErr error
  843. c.handshakeMutex.Lock()
  844. defer c.handshakeMutex.Unlock()
  845. if c.handshakeComplete {
  846. alertErr = c.sendAlert(alertCloseNotify)
  847. }
  848. if err := c.conn.Close(); err != nil {
  849. return err
  850. }
  851. return alertErr
  852. }
  853. // Handshake runs the client or server handshake
  854. // protocol if it has not yet been run.
  855. // Most uses of this package need not call Handshake
  856. // explicitly: the first Read or Write will call it automatically.
  857. func (c *Conn) Handshake() error {
  858. c.handshakeMutex.Lock()
  859. defer c.handshakeMutex.Unlock()
  860. if err := c.handshakeErr; err != nil {
  861. return err
  862. }
  863. if c.handshakeComplete {
  864. return nil
  865. }
  866. if c.isClient {
  867. c.handshakeErr = c.clientHandshake()
  868. } else {
  869. c.handshakeErr = c.serverHandshake()
  870. }
  871. return c.handshakeErr
  872. }
  873. // ConnectionState returns basic TLS details about the connection.
  874. func (c *Conn) ConnectionState() ConnectionState {
  875. c.handshakeMutex.Lock()
  876. defer c.handshakeMutex.Unlock()
  877. var state ConnectionState
  878. state.HandshakeComplete = c.handshakeComplete
  879. if c.handshakeComplete {
  880. state.Version = c.vers
  881. state.NegotiatedProtocol = c.clientProtocol
  882. state.DidResume = c.didResume
  883. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  884. state.CipherSuite = c.cipherSuite
  885. state.PeerCertificates = c.peerCertificates
  886. state.VerifiedChains = c.verifiedChains
  887. state.ServerName = c.serverName
  888. if !c.didResume {
  889. state.TLSUnique = c.firstFinished[:]
  890. }
  891. }
  892. return state
  893. }
  894. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  895. // any. (Only valid for client connections.)
  896. func (c *Conn) OCSPResponse() []byte {
  897. c.handshakeMutex.Lock()
  898. defer c.handshakeMutex.Unlock()
  899. return c.ocspResponse
  900. }
  901. // VerifyHostname checks that the peer certificate chain is valid for
  902. // connecting to host. If so, it returns nil; if not, it returns an error
  903. // describing the problem.
  904. func (c *Conn) VerifyHostname(host string) error {
  905. c.handshakeMutex.Lock()
  906. defer c.handshakeMutex.Unlock()
  907. if !c.isClient {
  908. return errors.New("tls: VerifyHostname called on TLS server connection")
  909. }
  910. if !c.handshakeComplete {
  911. return errors.New("tls: handshake has not yet been performed")
  912. }
  913. return c.peerCertificates[0].VerifyHostname(host)
  914. }