Debian Codegraph @

external/boringssl/ssl/test/runner/conn.go

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