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.
 
 
 
 
 
 

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