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