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