Alternative TLS implementation in Go
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.

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