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.
 
 
 
 
 
 

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