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