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

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