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.
 
 
 
 
 
 

829 lines
20 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. "io"
  12. "net"
  13. "os"
  14. "sync"
  15. )
  16. // A Conn represents a secured connection.
  17. // It implements the net.Conn interface.
  18. type Conn struct {
  19. // constant
  20. conn net.Conn
  21. isClient bool
  22. // constant after handshake; protected by handshakeMutex
  23. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  24. vers uint16 // TLS version
  25. haveVers bool // version has been negotiated
  26. config *Config // configuration passed to constructor
  27. handshakeComplete bool
  28. cipherSuite uint16
  29. ocspResponse []byte // stapled OCSP response
  30. peerCertificates []*x509.Certificate
  31. // verifiedChains contains the certificate chains that we built, as
  32. // opposed to the ones presented by the server.
  33. verifiedChains [][]*x509.Certificate
  34. clientProtocol string
  35. clientProtocolFallback bool
  36. // first permanent error
  37. errMutex sync.Mutex
  38. err os.Error
  39. // input/output
  40. in, out halfConn // in.Mutex < out.Mutex
  41. rawInput *block // raw input, right off the wire
  42. input *block // application data waiting to be read
  43. hand bytes.Buffer // handshake data waiting to be read
  44. tmp [16]byte
  45. }
  46. func (c *Conn) setError(err os.Error) os.Error {
  47. c.errMutex.Lock()
  48. defer c.errMutex.Unlock()
  49. if c.err == nil {
  50. c.err = err
  51. }
  52. return err
  53. }
  54. func (c *Conn) error() os.Error {
  55. c.errMutex.Lock()
  56. defer c.errMutex.Unlock()
  57. return c.err
  58. }
  59. // Access to net.Conn methods.
  60. // Cannot just embed net.Conn because that would
  61. // export the struct field too.
  62. // LocalAddr returns the local network address.
  63. func (c *Conn) LocalAddr() net.Addr {
  64. return c.conn.LocalAddr()
  65. }
  66. // RemoteAddr returns the remote network address.
  67. func (c *Conn) RemoteAddr() net.Addr {
  68. return c.conn.RemoteAddr()
  69. }
  70. // SetTimeout sets the read deadline associated with the connection.
  71. // There is no write deadline.
  72. func (c *Conn) SetTimeout(nsec int64) os.Error {
  73. return c.conn.SetTimeout(nsec)
  74. }
  75. // SetReadTimeout sets the time (in nanoseconds) that
  76. // Read will wait for data before returning os.EAGAIN.
  77. // Setting nsec == 0 (the default) disables the deadline.
  78. func (c *Conn) SetReadTimeout(nsec int64) os.Error {
  79. return c.conn.SetReadTimeout(nsec)
  80. }
  81. // SetWriteTimeout exists to satisfy the net.Conn interface
  82. // but is not implemented by TLS. It always returns an error.
  83. func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
  84. return os.NewError("TLS does not support SetWriteTimeout")
  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. version uint16 // protocol version
  91. cipher interface{} // cipher algorithm
  92. mac macFunction
  93. seq [8]byte // 64-bit sequence number
  94. bfree *block // list of free blocks
  95. nextCipher interface{} // next encryption state
  96. nextMac macFunction // next MAC algorithm
  97. }
  98. // prepareCipherSpec sets the encryption and MAC states
  99. // that a subsequent changeCipherSpec will use.
  100. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  101. hc.version = version
  102. hc.nextCipher = cipher
  103. hc.nextMac = mac
  104. }
  105. // changeCipherSpec changes the encryption and MAC states
  106. // to the ones previously passed to prepareCipherSpec.
  107. func (hc *halfConn) changeCipherSpec() os.Error {
  108. if hc.nextCipher == nil {
  109. return alertInternalError
  110. }
  111. hc.cipher = hc.nextCipher
  112. hc.mac = hc.nextMac
  113. hc.nextCipher = nil
  114. hc.nextMac = nil
  115. return nil
  116. }
  117. // incSeq increments the sequence number.
  118. func (hc *halfConn) incSeq() {
  119. for i := 7; i >= 0; i-- {
  120. hc.seq[i]++
  121. if hc.seq[i] != 0 {
  122. return
  123. }
  124. }
  125. // Not allowed to let sequence number wrap.
  126. // Instead, must renegotiate before it does.
  127. // Not likely enough to bother.
  128. panic("TLS: sequence number wraparound")
  129. }
  130. // resetSeq resets the sequence number to zero.
  131. func (hc *halfConn) resetSeq() {
  132. for i := range hc.seq {
  133. hc.seq[i] = 0
  134. }
  135. }
  136. // removePadding returns an unpadded slice, in constant time, which is a prefix
  137. // of the input. It also returns a byte which is equal to 255 if the padding
  138. // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  139. func removePadding(payload []byte) ([]byte, byte) {
  140. if len(payload) < 1 {
  141. return payload, 0
  142. }
  143. paddingLen := payload[len(payload)-1]
  144. t := uint(len(payload)-1) - uint(paddingLen)
  145. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  146. good := byte(int32(^t) >> 31)
  147. toCheck := 255 // the maximum possible padding length
  148. // The length of the padded data is public, so we can use an if here
  149. if toCheck+1 > len(payload) {
  150. toCheck = len(payload) - 1
  151. }
  152. for i := 0; i < toCheck; i++ {
  153. t := uint(paddingLen) - uint(i)
  154. // if i <= paddingLen then the MSB of t is zero
  155. mask := byte(int32(^t) >> 31)
  156. b := payload[len(payload)-1-i]
  157. good &^= mask&paddingLen ^ mask&b
  158. }
  159. // We AND together the bits of good and replicate the result across
  160. // all the bits.
  161. good &= good << 4
  162. good &= good << 2
  163. good &= good << 1
  164. good = uint8(int8(good) >> 7)
  165. toRemove := good&paddingLen + 1
  166. return payload[:len(payload)-int(toRemove)], good
  167. }
  168. // removePaddingSSL30 is a replacement for removePadding in the case that the
  169. // protocol version is SSLv3. In this version, the contents of the padding
  170. // are random and cannot be checked.
  171. func removePaddingSSL30(payload []byte) ([]byte, byte) {
  172. if len(payload) < 1 {
  173. return payload, 0
  174. }
  175. paddingLen := int(payload[len(payload)-1]) + 1
  176. if paddingLen > len(payload) {
  177. return payload, 0
  178. }
  179. return payload[:len(payload)-paddingLen], 255
  180. }
  181. func roundUp(a, b int) int {
  182. return a + (b-a%b)%b
  183. }
  184. // decrypt checks and strips the mac and decrypts the data in b.
  185. func (hc *halfConn) decrypt(b *block) (bool, alert) {
  186. // pull out payload
  187. payload := b.data[recordHeaderLen:]
  188. macSize := 0
  189. if hc.mac != nil {
  190. macSize = hc.mac.Size()
  191. }
  192. paddingGood := byte(255)
  193. // decrypt
  194. if hc.cipher != nil {
  195. switch c := hc.cipher.(type) {
  196. case cipher.Stream:
  197. c.XORKeyStream(payload, payload)
  198. case cipher.BlockMode:
  199. blockSize := c.BlockSize()
  200. if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
  201. return false, alertBadRecordMAC
  202. }
  203. c.CryptBlocks(payload, payload)
  204. if hc.version == versionSSL30 {
  205. payload, paddingGood = removePaddingSSL30(payload)
  206. } else {
  207. payload, paddingGood = removePadding(payload)
  208. }
  209. b.resize(recordHeaderLen + len(payload))
  210. // note that we still have a timing side-channel in the
  211. // MAC check, below. An attacker can align the record
  212. // so that a correct padding will cause one less hash
  213. // block to be calculated. Then they can iteratively
  214. // decrypt a record by breaking each byte. See
  215. // "Password Interception in a SSL/TLS Channel", Brice
  216. // Canvel et al.
  217. //
  218. // However, our behavior matches OpenSSL, so we leak
  219. // only as much as they do.
  220. default:
  221. panic("unknown cipher type")
  222. }
  223. }
  224. // check, strip mac
  225. if hc.mac != nil {
  226. if len(payload) < macSize {
  227. return false, alertBadRecordMAC
  228. }
  229. // strip mac off payload, b.data
  230. n := len(payload) - macSize
  231. b.data[3] = byte(n >> 8)
  232. b.data[4] = byte(n)
  233. b.resize(recordHeaderLen + n)
  234. remoteMAC := payload[n:]
  235. localMAC := hc.mac.MAC(hc.seq[0:], b.data)
  236. hc.incSeq()
  237. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  238. return false, alertBadRecordMAC
  239. }
  240. }
  241. return true, 0
  242. }
  243. // padToBlockSize calculates the needed padding block, if any, for a payload.
  244. // On exit, prefix aliases payload and extends to the end of the last full
  245. // block of payload. finalBlock is a fresh slice which contains the contents of
  246. // any suffix of payload as well as the needed padding to make finalBlock a
  247. // full block.
  248. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  249. overrun := len(payload) % blockSize
  250. paddingLen := blockSize - overrun
  251. prefix = payload[:len(payload)-overrun]
  252. finalBlock = make([]byte, blockSize)
  253. copy(finalBlock, payload[len(payload)-overrun:])
  254. for i := overrun; i < blockSize; i++ {
  255. finalBlock[i] = byte(paddingLen - 1)
  256. }
  257. return
  258. }
  259. // encrypt encrypts and macs the data in b.
  260. func (hc *halfConn) encrypt(b *block) (bool, alert) {
  261. // mac
  262. if hc.mac != nil {
  263. mac := hc.mac.MAC(hc.seq[0:], b.data)
  264. hc.incSeq()
  265. n := len(b.data)
  266. b.resize(n + len(mac))
  267. copy(b.data[n:], mac)
  268. }
  269. payload := b.data[recordHeaderLen:]
  270. // encrypt
  271. if hc.cipher != nil {
  272. switch c := hc.cipher.(type) {
  273. case cipher.Stream:
  274. c.XORKeyStream(payload, payload)
  275. case cipher.BlockMode:
  276. prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
  277. b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
  278. c.CryptBlocks(b.data[recordHeaderLen:], prefix)
  279. c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
  280. default:
  281. panic("unknown cipher type")
  282. }
  283. }
  284. // update length to include MAC and any block padding needed.
  285. n := len(b.data) - recordHeaderLen
  286. b.data[3] = byte(n >> 8)
  287. b.data[4] = byte(n)
  288. return true, 0
  289. }
  290. // A block is a simple data buffer.
  291. type block struct {
  292. data []byte
  293. off int // index for Read
  294. link *block
  295. }
  296. // resize resizes block to be n bytes, growing if necessary.
  297. func (b *block) resize(n int) {
  298. if n > cap(b.data) {
  299. b.reserve(n)
  300. }
  301. b.data = b.data[0:n]
  302. }
  303. // reserve makes sure that block contains a capacity of at least n bytes.
  304. func (b *block) reserve(n int) {
  305. if cap(b.data) >= n {
  306. return
  307. }
  308. m := cap(b.data)
  309. if m == 0 {
  310. m = 1024
  311. }
  312. for m < n {
  313. m *= 2
  314. }
  315. data := make([]byte, len(b.data), m)
  316. copy(data, b.data)
  317. b.data = data
  318. }
  319. // readFromUntil reads from r into b until b contains at least n bytes
  320. // or else returns an error.
  321. func (b *block) readFromUntil(r io.Reader, n int) os.Error {
  322. // quick case
  323. if len(b.data) >= n {
  324. return nil
  325. }
  326. // read until have enough.
  327. b.reserve(n)
  328. for {
  329. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  330. b.data = b.data[0 : len(b.data)+m]
  331. if len(b.data) >= n {
  332. break
  333. }
  334. if err != nil {
  335. return err
  336. }
  337. }
  338. return nil
  339. }
  340. func (b *block) Read(p []byte) (n int, err os.Error) {
  341. n = copy(p, b.data[b.off:])
  342. b.off += n
  343. return
  344. }
  345. // newBlock allocates a new block, from hc's free list if possible.
  346. func (hc *halfConn) newBlock() *block {
  347. b := hc.bfree
  348. if b == nil {
  349. return new(block)
  350. }
  351. hc.bfree = b.link
  352. b.link = nil
  353. b.resize(0)
  354. return b
  355. }
  356. // freeBlock returns a block to hc's free list.
  357. // The protocol is such that each side only has a block or two on
  358. // its free list at a time, so there's no need to worry about
  359. // trimming the list, etc.
  360. func (hc *halfConn) freeBlock(b *block) {
  361. b.link = hc.bfree
  362. hc.bfree = b
  363. }
  364. // splitBlock splits a block after the first n bytes,
  365. // returning a block with those n bytes and a
  366. // block with the remainder. the latter may be nil.
  367. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  368. if len(b.data) <= n {
  369. return b, nil
  370. }
  371. bb := hc.newBlock()
  372. bb.resize(len(b.data) - n)
  373. copy(bb.data, b.data[n:])
  374. b.data = b.data[0:n]
  375. return b, bb
  376. }
  377. // readRecord reads the next TLS record from the connection
  378. // and updates the record layer state.
  379. // c.in.Mutex <= L; c.input == nil.
  380. func (c *Conn) readRecord(want recordType) os.Error {
  381. // Caller must be in sync with connection:
  382. // handshake data if handshake not yet completed,
  383. // else application data. (We don't support renegotiation.)
  384. switch want {
  385. default:
  386. return c.sendAlert(alertInternalError)
  387. case recordTypeHandshake, recordTypeChangeCipherSpec:
  388. if c.handshakeComplete {
  389. return c.sendAlert(alertInternalError)
  390. }
  391. case recordTypeApplicationData:
  392. if !c.handshakeComplete {
  393. return c.sendAlert(alertInternalError)
  394. }
  395. }
  396. Again:
  397. if c.rawInput == nil {
  398. c.rawInput = c.in.newBlock()
  399. }
  400. b := c.rawInput
  401. // Read header, payload.
  402. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  403. // RFC suggests that EOF without an alertCloseNotify is
  404. // an error, but popular web sites seem to do this,
  405. // so we can't make it an error.
  406. // if err == os.EOF {
  407. // err = io.ErrUnexpectedEOF
  408. // }
  409. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  410. c.setError(err)
  411. }
  412. return err
  413. }
  414. typ := recordType(b.data[0])
  415. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  416. n := int(b.data[3])<<8 | int(b.data[4])
  417. if c.haveVers && vers != c.vers {
  418. return c.sendAlert(alertProtocolVersion)
  419. }
  420. if n > maxCiphertext {
  421. return c.sendAlert(alertRecordOverflow)
  422. }
  423. if !c.haveVers {
  424. // First message, be extra suspicious:
  425. // this might not be a TLS client.
  426. // Bail out before reading a full 'body', if possible.
  427. // The current max version is 3.1.
  428. // If the version is >= 16.0, it's probably not real.
  429. // Similarly, a clientHello message encodes in
  430. // well under a kilobyte. If the length is >= 12 kB,
  431. // it's probably not real.
  432. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
  433. return c.sendAlert(alertUnexpectedMessage)
  434. }
  435. }
  436. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  437. if err == os.EOF {
  438. err = io.ErrUnexpectedEOF
  439. }
  440. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  441. c.setError(err)
  442. }
  443. return err
  444. }
  445. // Process message.
  446. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  447. b.off = recordHeaderLen
  448. if ok, err := c.in.decrypt(b); !ok {
  449. return c.sendAlert(err)
  450. }
  451. data := b.data[b.off:]
  452. if len(data) > maxPlaintext {
  453. c.sendAlert(alertRecordOverflow)
  454. c.in.freeBlock(b)
  455. return c.error()
  456. }
  457. switch typ {
  458. default:
  459. c.sendAlert(alertUnexpectedMessage)
  460. case recordTypeAlert:
  461. if len(data) != 2 {
  462. c.sendAlert(alertUnexpectedMessage)
  463. break
  464. }
  465. if alert(data[1]) == alertCloseNotify {
  466. c.setError(os.EOF)
  467. break
  468. }
  469. switch data[0] {
  470. case alertLevelWarning:
  471. // drop on the floor
  472. c.in.freeBlock(b)
  473. goto Again
  474. case alertLevelError:
  475. c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
  476. default:
  477. c.sendAlert(alertUnexpectedMessage)
  478. }
  479. case recordTypeChangeCipherSpec:
  480. if typ != want || len(data) != 1 || data[0] != 1 {
  481. c.sendAlert(alertUnexpectedMessage)
  482. break
  483. }
  484. err := c.in.changeCipherSpec()
  485. if err != nil {
  486. c.sendAlert(err.(alert))
  487. }
  488. case recordTypeApplicationData:
  489. if typ != want {
  490. c.sendAlert(alertUnexpectedMessage)
  491. break
  492. }
  493. c.input = b
  494. b = nil
  495. case recordTypeHandshake:
  496. // TODO(rsc): Should at least pick off connection close.
  497. if typ != want {
  498. return c.sendAlert(alertNoRenegotiation)
  499. }
  500. c.hand.Write(data)
  501. }
  502. if b != nil {
  503. c.in.freeBlock(b)
  504. }
  505. return c.error()
  506. }
  507. // sendAlert sends a TLS alert message.
  508. // c.out.Mutex <= L.
  509. func (c *Conn) sendAlertLocked(err alert) os.Error {
  510. c.tmp[0] = alertLevelError
  511. if err == alertNoRenegotiation {
  512. c.tmp[0] = alertLevelWarning
  513. }
  514. c.tmp[1] = byte(err)
  515. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  516. // closeNotify is a special case in that it isn't an error:
  517. if err != alertCloseNotify {
  518. return c.setError(&net.OpError{Op: "local error", Error: err})
  519. }
  520. return nil
  521. }
  522. // sendAlert sends a TLS alert message.
  523. // L < c.out.Mutex.
  524. func (c *Conn) sendAlert(err alert) os.Error {
  525. c.out.Lock()
  526. defer c.out.Unlock()
  527. return c.sendAlertLocked(err)
  528. }
  529. // writeRecord writes a TLS record with the given type and payload
  530. // to the connection and updates the record layer state.
  531. // c.out.Mutex <= L.
  532. func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
  533. b := c.out.newBlock()
  534. for len(data) > 0 {
  535. m := len(data)
  536. if m > maxPlaintext {
  537. m = maxPlaintext
  538. }
  539. b.resize(recordHeaderLen + m)
  540. b.data[0] = byte(typ)
  541. vers := c.vers
  542. if vers == 0 {
  543. vers = maxVersion
  544. }
  545. b.data[1] = byte(vers >> 8)
  546. b.data[2] = byte(vers)
  547. b.data[3] = byte(m >> 8)
  548. b.data[4] = byte(m)
  549. copy(b.data[recordHeaderLen:], data)
  550. c.out.encrypt(b)
  551. _, err = c.conn.Write(b.data)
  552. if err != nil {
  553. break
  554. }
  555. n += m
  556. data = data[m:]
  557. }
  558. c.out.freeBlock(b)
  559. if typ == recordTypeChangeCipherSpec {
  560. err = c.out.changeCipherSpec()
  561. if err != nil {
  562. // Cannot call sendAlert directly,
  563. // because we already hold c.out.Mutex.
  564. c.tmp[0] = alertLevelError
  565. c.tmp[1] = byte(err.(alert))
  566. c.writeRecord(recordTypeAlert, c.tmp[0:2])
  567. c.err = &net.OpError{Op: "local error", Error: err}
  568. return n, c.err
  569. }
  570. }
  571. return
  572. }
  573. // readHandshake reads the next handshake message from
  574. // the record layer.
  575. // c.in.Mutex < L; c.out.Mutex < L.
  576. func (c *Conn) readHandshake() (interface{}, os.Error) {
  577. for c.hand.Len() < 4 {
  578. if c.err != nil {
  579. return nil, c.err
  580. }
  581. c.readRecord(recordTypeHandshake)
  582. }
  583. data := c.hand.Bytes()
  584. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  585. if n > maxHandshake {
  586. c.sendAlert(alertInternalError)
  587. return nil, c.err
  588. }
  589. for c.hand.Len() < 4+n {
  590. if c.err != nil {
  591. return nil, c.err
  592. }
  593. c.readRecord(recordTypeHandshake)
  594. }
  595. data = c.hand.Next(4 + n)
  596. var m handshakeMessage
  597. switch data[0] {
  598. case typeClientHello:
  599. m = new(clientHelloMsg)
  600. case typeServerHello:
  601. m = new(serverHelloMsg)
  602. case typeCertificate:
  603. m = new(certificateMsg)
  604. case typeCertificateRequest:
  605. m = new(certificateRequestMsg)
  606. case typeCertificateStatus:
  607. m = new(certificateStatusMsg)
  608. case typeServerKeyExchange:
  609. m = new(serverKeyExchangeMsg)
  610. case typeServerHelloDone:
  611. m = new(serverHelloDoneMsg)
  612. case typeClientKeyExchange:
  613. m = new(clientKeyExchangeMsg)
  614. case typeCertificateVerify:
  615. m = new(certificateVerifyMsg)
  616. case typeNextProtocol:
  617. m = new(nextProtoMsg)
  618. case typeFinished:
  619. m = new(finishedMsg)
  620. default:
  621. c.sendAlert(alertUnexpectedMessage)
  622. return nil, alertUnexpectedMessage
  623. }
  624. // The handshake message unmarshallers
  625. // expect to be able to keep references to data,
  626. // so pass in a fresh copy that won't be overwritten.
  627. data = append([]byte(nil), data...)
  628. if !m.unmarshal(data) {
  629. c.sendAlert(alertUnexpectedMessage)
  630. return nil, alertUnexpectedMessage
  631. }
  632. return m, nil
  633. }
  634. // Write writes data to the connection.
  635. func (c *Conn) Write(b []byte) (n int, err os.Error) {
  636. if err = c.Handshake(); err != nil {
  637. return
  638. }
  639. c.out.Lock()
  640. defer c.out.Unlock()
  641. if !c.handshakeComplete {
  642. return 0, alertInternalError
  643. }
  644. if c.err != nil {
  645. return 0, c.err
  646. }
  647. return c.writeRecord(recordTypeApplicationData, b)
  648. }
  649. // Read can be made to time out and return err == os.EAGAIN
  650. // after a fixed time limit; see SetTimeout and SetReadTimeout.
  651. func (c *Conn) Read(b []byte) (n int, err os.Error) {
  652. if err = c.Handshake(); err != nil {
  653. return
  654. }
  655. c.in.Lock()
  656. defer c.in.Unlock()
  657. for c.input == nil && c.err == nil {
  658. if err := c.readRecord(recordTypeApplicationData); err != nil {
  659. // Soft error, like EAGAIN
  660. return 0, err
  661. }
  662. }
  663. if c.err != nil {
  664. return 0, c.err
  665. }
  666. n, err = c.input.Read(b)
  667. if c.input.off >= len(c.input.data) {
  668. c.in.freeBlock(c.input)
  669. c.input = nil
  670. }
  671. return n, nil
  672. }
  673. // Close closes the connection.
  674. func (c *Conn) Close() os.Error {
  675. if err := c.Handshake(); err != nil {
  676. return err
  677. }
  678. return c.sendAlert(alertCloseNotify)
  679. }
  680. // Handshake runs the client or server handshake
  681. // protocol if it has not yet been run.
  682. // Most uses of this package need not call Handshake
  683. // explicitly: the first Read or Write will call it automatically.
  684. func (c *Conn) Handshake() os.Error {
  685. c.handshakeMutex.Lock()
  686. defer c.handshakeMutex.Unlock()
  687. if err := c.error(); err != nil {
  688. return err
  689. }
  690. if c.handshakeComplete {
  691. return nil
  692. }
  693. if c.isClient {
  694. return c.clientHandshake()
  695. }
  696. return c.serverHandshake()
  697. }
  698. // ConnectionState returns basic TLS details about the connection.
  699. func (c *Conn) ConnectionState() ConnectionState {
  700. c.handshakeMutex.Lock()
  701. defer c.handshakeMutex.Unlock()
  702. var state ConnectionState
  703. state.HandshakeComplete = c.handshakeComplete
  704. if c.handshakeComplete {
  705. state.NegotiatedProtocol = c.clientProtocol
  706. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  707. state.CipherSuite = c.cipherSuite
  708. state.PeerCertificates = c.peerCertificates
  709. state.VerifiedChains = c.verifiedChains
  710. }
  711. return state
  712. }
  713. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  714. // any. (Only valid for client connections.)
  715. func (c *Conn) OCSPResponse() []byte {
  716. c.handshakeMutex.Lock()
  717. defer c.handshakeMutex.Unlock()
  718. return c.ocspResponse
  719. }
  720. // VerifyHostname checks that the peer certificate chain is valid for
  721. // connecting to host. If so, it returns nil; if not, it returns an os.Error
  722. // describing the problem.
  723. func (c *Conn) VerifyHostname(host string) os.Error {
  724. c.handshakeMutex.Lock()
  725. defer c.handshakeMutex.Unlock()
  726. if !c.isClient {
  727. return os.NewError("VerifyHostname called on TLS server connection")
  728. }
  729. if !c.handshakeComplete {
  730. return os.NewError("TLS handshake has not yet been performed")
  731. }
  732. return c.peerCertificates[0].VerifyHostname(host)
  733. }