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.
5 // TLS low level connection and record layer
22 // A Conn represents a secured connection.
23 // It implements the net.Conn interface.
29 // constant after handshake; protected by handshakeMutex
30 handshakeMutex sync
.Mutex
// handshakeMutex < in.Mutex, out.Mutex, errMutex
31 handshakeErr error
// error resulting from handshake
32 vers
uint16 // TLS version
33 haveVers
bool // version has been negotiated
34 config
*Config
// configuration passed to constructor
35 handshakeComplete
bool
36 didResume
bool // whether this connection was a session resumption
38 ocspResponse
[]byte // stapled OCSP response
39 peerCertificates
[]*x509
.Certificate
40 // verifiedChains contains the certificate chains that we built, as
41 // opposed to the ones presented by the server.
42 verifiedChains
[][]*x509
.Certificate
43 // serverName contains the server name indicated by the client, if any.
47 clientProtocolFallback
bool
50 in
, out halfConn
// in.Mutex < out.Mutex
51 rawInput
*block
// raw input, right off the wire
52 input
*block
// application data waiting to be read
53 hand bytes
.Buffer
// handshake data waiting to be read
58 // Access to net.Conn methods.
59 // Cannot just embed net.Conn because that would
60 // export the struct field too.
62 // LocalAddr returns the local network address.
63 func (c
*Conn
) LocalAddr() net
.Addr
{
64 return c
.conn
.LocalAddr()
67 // RemoteAddr returns the remote network address.
68 func (c
*Conn
) RemoteAddr() net
.Addr
{
69 return c
.conn
.RemoteAddr()
72 // SetDeadline sets the read and write deadlines associated with the connection.
73 // A zero value for t means Read and Write will not time out.
74 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
75 func (c
*Conn
) SetDeadline(t time
.Time
) error
{
76 return c
.conn
.SetDeadline(t
)
79 // SetReadDeadline sets the read deadline on the underlying connection.
80 // A zero value for t means Read will not time out.
81 func (c
*Conn
) SetReadDeadline(t time
.Time
) error
{
82 return c
.conn
.SetReadDeadline(t
)
85 // SetWriteDeadline sets the write deadline on the underlying connection.
86 // A zero value for t means Write will not time out.
87 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
88 func (c
*Conn
) SetWriteDeadline(t time
.Time
) error
{
89 return c
.conn
.SetWriteDeadline(t
)
92 // A halfConn represents one direction of the record layer
93 // connection, either sending or receiving.
94 type halfConn
struct {
97 err error
// first permanent error
98 version
uint16 // protocol version
99 cipher
interface{} // cipher algorithm
101 seq
[8]byte // 64-bit sequence number
102 bfree
*block
// list of free blocks
104 nextCipher
interface{} // next encryption state
105 nextMac macFunction
// next MAC algorithm
107 // used to save allocating a new buffer for each MAC.
108 inDigestBuf
, outDigestBuf
[]byte
111 func (hc
*halfConn
) setErrorLocked(err error
) error
{
116 func (hc
*halfConn
) error() error
{
123 // prepareCipherSpec sets the encryption and MAC states
124 // that a subsequent changeCipherSpec will use.
125 func (hc
*halfConn
) prepareCipherSpec(version
uint16, cipher
interface{}, mac macFunction
) {
127 hc
.nextCipher
= cipher
131 // changeCipherSpec changes the encryption and MAC states
132 // to the ones previously passed to prepareCipherSpec.
133 func (hc
*halfConn
) changeCipherSpec() error
{
134 if hc
.nextCipher
== nil {
135 return alertInternalError
137 hc
.cipher
= hc
.nextCipher
141 for i
:= range hc
.seq
{
147 // incSeq increments the sequence number.
148 func (hc
*halfConn
) incSeq() {
149 for i
:= 7; i
>= 0; i
-- {
156 // Not allowed to let sequence number wrap.
157 // Instead, must renegotiate before it does.
158 // Not likely enough to bother.
159 panic("TLS: sequence number wraparound")
162 // resetSeq resets the sequence number to zero.
163 func (hc
*halfConn
) resetSeq() {
164 for i
:= range hc
.seq
{
169 // removePadding returns an unpadded slice, in constant time, which is a prefix
170 // of the input. It also returns a byte which is equal to 255 if the padding
171 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
172 func removePadding(payload
[]byte) ([]byte, byte) {
173 if len(payload
) < 1 {
177 paddingLen
:= payload
[len(payload
)-1]
178 t
:= uint(len(payload
)-1) - uint(paddingLen
)
179 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
180 good
:= byte(int32(^t
) >> 31)
182 toCheck
:= 255 // the maximum possible padding length
183 // The length of the padded data is public, so we can use an if here
184 if toCheck
+1 > len(payload
) {
185 toCheck
= len(payload
) - 1
188 for i
:= 0; i
< toCheck
; i
++ {
189 t
:= uint(paddingLen
) - uint(i
)
190 // if i <= paddingLen then the MSB of t is zero
191 mask
:= byte(int32(^t
) >> 31)
192 b
:= payload
[len(payload
)-1-i
]
193 good
&^= mask
&paddingLen
^ mask
&b
196 // We AND together the bits of good and replicate the result across
201 good
= uint8(int8(good
) >> 7)
203 toRemove
:= good
&paddingLen
+ 1
204 return payload
[:len(payload
)-int(toRemove
)], good
207 // removePaddingSSL30 is a replacement for removePadding in the case that the
208 // protocol version is SSLv3. In this version, the contents of the padding
209 // are random and cannot be checked.
210 func removePaddingSSL30(payload
[]byte) ([]byte, byte) {
211 if len(payload
) < 1 {
215 paddingLen
:= int(payload
[len(payload
)-1]) + 1
216 if paddingLen
> len(payload
) {
220 return payload
[:len(payload
)-paddingLen
], 255
223 func roundUp(a
, b
int) int {
227 // cbcMode is an interface for block ciphers using cipher block chaining.
228 type cbcMode
interface {
233 // decrypt checks and strips the mac and decrypts the data in b. Returns a
234 // success boolean, the number of bytes to skip from the start of the record in
235 // order to get the application payload, and an optional alert value.
236 func (hc
*halfConn
) decrypt(b
*block
) (ok
bool, prefixLen
int, alertValue alert
) {
238 payload
:= b
.data
[recordHeaderLen
:]
242 macSize
= hc
.mac
.Size()
245 paddingGood
:= byte(255)
249 if hc
.cipher
!= nil {
250 switch c
:= hc
.cipher
.(type) {
252 c
.XORKeyStream(payload
, payload
)
255 if len(payload
) < explicitIVLen
{
256 return false, 0, alertBadRecordMAC
259 payload
= payload
[8:]
261 var additionalData
[13]byte
262 copy(additionalData
[:], hc
.seq
[:])
263 copy(additionalData
[8:], b
.data
[:3])
264 n
:= len(payload
) - c
.Overhead()
265 additionalData
[11] = byte(n
>> 8)
266 additionalData
[12] = byte(n
)
268 payload
, err
= c
.Open(payload
[:0], nonce
, payload
, additionalData
[:])
270 return false, 0, alertBadRecordMAC
272 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(payload
))
274 blockSize
:= c
.BlockSize()
275 if hc
.version
>= VersionTLS11
{
276 explicitIVLen
= blockSize
279 if len(payload
)%blockSize
!= 0 ||
len(payload
) < roundUp(explicitIVLen
+macSize
+1, blockSize
) {
280 return false, 0, alertBadRecordMAC
283 if explicitIVLen
> 0 {
284 c
.SetIV(payload
[:explicitIVLen
])
285 payload
= payload
[explicitIVLen
:]
287 c
.CryptBlocks(payload
, payload
)
288 if hc
.version
== VersionSSL30
{
289 payload
, paddingGood
= removePaddingSSL30(payload
)
291 payload
, paddingGood
= removePadding(payload
)
293 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(payload
))
295 // note that we still have a timing side-channel in the
296 // MAC check, below. An attacker can align the record
297 // so that a correct padding will cause one less hash
298 // block to be calculated. Then they can iteratively
299 // decrypt a record by breaking each byte. See
300 // "Password Interception in a SSL/TLS Channel", Brice
303 // However, our behavior matches OpenSSL, so we leak
304 // only as much as they do.
306 panic("unknown cipher type")
312 if len(payload
) < macSize
{
313 return false, 0, alertBadRecordMAC
316 // strip mac off payload, b.data
317 n
:= len(payload
) - macSize
318 b
.data
[3] = byte(n
>> 8)
320 b
.resize(recordHeaderLen
+ explicitIVLen
+ n
)
321 remoteMAC
:= payload
[n
:]
322 localMAC
:= hc
.mac
.MAC(hc
.inDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], payload
[:n
])
324 if subtle
.ConstantTimeCompare(localMAC
, remoteMAC
) != 1 || paddingGood
!= 255 {
325 return false, 0, alertBadRecordMAC
327 hc
.inDigestBuf
= localMAC
331 return true, recordHeaderLen
+ explicitIVLen
, 0
334 // padToBlockSize calculates the needed padding block, if any, for a payload.
335 // On exit, prefix aliases payload and extends to the end of the last full
336 // block of payload. finalBlock is a fresh slice which contains the contents of
337 // any suffix of payload as well as the needed padding to make finalBlock a
339 func padToBlockSize(payload
[]byte, blockSize
int) (prefix
, finalBlock
[]byte) {
340 overrun
:= len(payload
) % blockSize
341 paddingLen
:= blockSize
- overrun
342 prefix
= payload
[:len(payload
)-overrun
]
343 finalBlock
= make([]byte, blockSize
)
344 copy(finalBlock
, payload
[len(payload
)-overrun
:])
345 for i
:= overrun
; i
< blockSize
; i
++ {
346 finalBlock
[i
] = byte(paddingLen
- 1)
351 // encrypt encrypts and macs the data in b.
352 func (hc
*halfConn
) encrypt(b
*block
, explicitIVLen
int) (bool, alert
) {
355 mac
:= hc
.mac
.MAC(hc
.outDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], b
.data
[recordHeaderLen
+explicitIVLen
:])
358 b
.resize(n
+ len(mac
))
359 copy(b
.data
[n
:], mac
)
360 hc
.outDigestBuf
= mac
363 payload
:= b
.data
[recordHeaderLen
:]
366 if hc
.cipher
!= nil {
367 switch c
:= hc
.cipher
.(type) {
369 c
.XORKeyStream(payload
, payload
)
371 payloadLen
:= len(b
.data
) - recordHeaderLen
- explicitIVLen
372 b
.resize(len(b
.data
) + c
.Overhead())
373 nonce
:= b
.data
[recordHeaderLen
: recordHeaderLen
+explicitIVLen
]
374 payload
:= b
.data
[recordHeaderLen
+explicitIVLen
:]
375 payload
= payload
[:payloadLen
]
377 var additionalData
[13]byte
378 copy(additionalData
[:], hc
.seq
[:])
379 copy(additionalData
[8:], b
.data
[:3])
380 additionalData
[11] = byte(payloadLen
>> 8)
381 additionalData
[12] = byte(payloadLen
)
383 c
.Seal(payload
[:0], nonce
, payload
, additionalData
[:])
385 blockSize
:= c
.BlockSize()
386 if explicitIVLen
> 0 {
387 c
.SetIV(payload
[:explicitIVLen
])
388 payload
= payload
[explicitIVLen
:]
390 prefix
, finalBlock
:= padToBlockSize(payload
, blockSize
)
391 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(prefix
) + len(finalBlock
))
392 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
:], prefix
)
393 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
+len(prefix
):], finalBlock
)
395 panic("unknown cipher type")
399 // update length to include MAC and any block padding needed.
400 n
:= len(b
.data
) - recordHeaderLen
401 b
.data
[3] = byte(n
>> 8)
408 // A block is a simple data buffer.
411 off
int // index for Read
415 // resize resizes block to be n bytes, growing if necessary.
416 func (b
*block
) resize(n
int) {
423 // reserve makes sure that block contains a capacity of at least n bytes.
424 func (b
*block
) reserve(n
int) {
425 if cap(b
.data
) >= n
{
435 data
:= make([]byte, len(b
.data
), m
)
440 // readFromUntil reads from r into b until b contains at least n bytes
441 // or else returns an error.
442 func (b
*block
) readFromUntil(r io
.Reader
, n
int) error
{
444 if len(b
.data
) >= n
{
448 // read until have enough.
451 m
, err
:= r
.Read(b
.data
[len(b
.data
):cap(b
.data
)])
452 b
.data
= b
.data
[0 : len(b
.data
)+m
]
453 if len(b
.data
) >= n
{
454 // TODO(bradfitz,agl): slightly suspicious
455 // that we're throwing away r.Read's err here.
465 func (b
*block
) Read(p
[]byte) (n
int, err error
) {
466 n
= copy(p
, b
.data
[b
.off
:])
471 // newBlock allocates a new block, from hc's free list if possible.
472 func (hc
*halfConn
) newBlock() *block
{
483 // freeBlock returns a block to hc's free list.
484 // The protocol is such that each side only has a block or two on
485 // its free list at a time, so there's no need to worry about
486 // trimming the list, etc.
487 func (hc
*halfConn
) freeBlock(b
*block
) {
492 // splitBlock splits a block after the first n bytes,
493 // returning a block with those n bytes and a
494 // block with the remainder. the latter may be nil.
495 func (hc
*halfConn
) splitBlock(b
*block
, n
int) (*block
, *block
) {
496 if len(b
.data
) <= n
{
500 bb
.resize(len(b
.data
) - n
)
501 copy(bb
.data
, b
.data
[n
:])
506 // readRecord reads the next TLS record from the connection
507 // and updates the record layer state.
508 // c.in.Mutex <= L; c.input == nil.
509 func (c
*Conn
) readRecord(want recordType
) error
{
510 // Caller must be in sync with connection:
511 // handshake data if handshake not yet completed,
512 // else application data. (We don't support renegotiation.)
515 c
.sendAlert(alertInternalError
)
516 return c
.in
.setErrorLocked(errors
.New("tls: unknown record type requested"))
517 case recordTypeHandshake
, recordTypeChangeCipherSpec
:
518 if c
.handshakeComplete
{
519 c
.sendAlert(alertInternalError
)
520 return c
.in
.setErrorLocked(errors
.New("tls: handshake or ChangeCipherSpec requested after handshake complete"))
522 case recordTypeApplicationData
:
523 if !c
.handshakeComplete
{
524 c
.sendAlert(alertInternalError
)
525 return c
.in
.setErrorLocked(errors
.New("tls: application data record requested before handshake complete"))
530 if c
.rawInput
== nil {
531 c
.rawInput
= c
.in
.newBlock()
535 // Read header, payload.
536 if err
:= b
.readFromUntil(c
.conn
, recordHeaderLen
); err
!= nil {
537 // RFC suggests that EOF without an alertCloseNotify is
538 // an error, but popular web sites seem to do this,
539 // so we can't make it an error.
540 // if err == io.EOF {
541 // err = io.ErrUnexpectedEOF
543 if e
, ok
:= err
.(net
.Error
); !ok ||
!e
.Temporary() {
544 c
.in
.setErrorLocked(err
)
548 typ
:= recordType(b
.data
[0])
550 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
551 // start with a uint16 length where the MSB is set and the first record
552 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
554 if want
== recordTypeHandshake
&& typ
== 0x80 {
555 c
.sendAlert(alertProtocolVersion
)
556 return c
.in
.setErrorLocked(errors
.New("tls: unsupported SSLv2 handshake received"))
559 vers
:= uint16(b
.data
[1])<<8 |
uint16(b
.data
[2])
560 n
:= int(b
.data
[3])<<8 |
int(b
.data
[4])
561 if c
.haveVers
&& vers
!= c
.vers
{
562 c
.sendAlert(alertProtocolVersion
)
563 return c
.in
.setErrorLocked(fmt
.Errorf("tls: received record with version %x when expecting version %x", vers
, c
.vers
))
565 if n
> maxCiphertext
{
566 c
.sendAlert(alertRecordOverflow
)
567 return c
.in
.setErrorLocked(fmt
.Errorf("tls: oversized record received with length %d", n
))
570 // First message, be extra suspicious:
571 // this might not be a TLS client.
572 // Bail out before reading a full 'body', if possible.
573 // The current max version is 3.1.
574 // If the version is >= 16.0, it's probably not real.
575 // Similarly, a clientHello message encodes in
576 // well under a kilobyte. If the length is >= 12 kB,
577 // it's probably not real.
578 if (typ
!= recordTypeAlert
&& typ
!= want
) || vers
>= 0x1000 || n
>= 0x3000 {
579 c
.sendAlert(alertUnexpectedMessage
)
580 return c
.in
.setErrorLocked(fmt
.Errorf("tls: first record does not look like a TLS handshake"))
583 if err
:= b
.readFromUntil(c
.conn
, recordHeaderLen
+n
); err
!= nil {
585 err
= io
.ErrUnexpectedEOF
587 if e
, ok
:= err
.(net
.Error
); !ok ||
!e
.Temporary() {
588 c
.in
.setErrorLocked(err
)
594 b
, c
.rawInput
= c
.in
.splitBlock(b
, recordHeaderLen
+n
)
595 ok
, off
, err
:= c
.in
.decrypt(b
)
597 c
.in
.setErrorLocked(c
.sendAlert(err
))
600 data
:= b
.data
[b
.off
:]
601 if len(data
) > maxPlaintext
{
602 err
:= c
.sendAlert(alertRecordOverflow
)
604 return c
.in
.setErrorLocked(err
)
609 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
611 case recordTypeAlert
:
613 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
616 if alert(data
[1]) == alertCloseNotify
{
617 c
.in
.setErrorLocked(io
.EOF
)
621 case alertLevelWarning
:
625 case alertLevelError
:
626 c
.in
.setErrorLocked(&net
.OpError
{Op
: "remote error", Err
: alert(data
[1])})
628 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
631 case recordTypeChangeCipherSpec
:
632 if typ
!= want ||
len(data
) != 1 || data
[0] != 1 {
633 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
636 err
:= c
.in
.changeCipherSpec()
638 c
.in
.setErrorLocked(c
.sendAlert(err
.(alert
)))
641 case recordTypeApplicationData
:
643 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
649 case recordTypeHandshake
:
650 // TODO(rsc): Should at least pick off connection close.
652 return c
.in
.setErrorLocked(c
.sendAlert(alertNoRenegotiation
))
663 // sendAlert sends a TLS alert message.
665 func (c
*Conn
) sendAlertLocked(err alert
) error
{
667 case alertNoRenegotiation
, alertCloseNotify
:
668 c
.tmp
[0] = alertLevelWarning
670 c
.tmp
[0] = alertLevelError
673 c
.writeRecord(recordTypeAlert
, c
.tmp
[0:2])
674 // closeNotify is a special case in that it isn't an error:
675 if err
!= alertCloseNotify
{
676 return c
.out
.setErrorLocked(&net
.OpError
{Op
: "local error", Err
: err
})
681 // sendAlert sends a TLS alert message.
683 func (c
*Conn
) sendAlert(err alert
) error
{
686 return c
.sendAlertLocked(err
)
689 // writeRecord writes a TLS record with the given type and payload
690 // to the connection and updates the record layer state.
692 func (c
*Conn
) writeRecord(typ recordType
, data
[]byte) (n
int, err error
) {
693 b
:= c
.out
.newBlock()
696 if m
> maxPlaintext
{
700 explicitIVIsSeq
:= false
703 if c
.out
.version
>= VersionTLS11
{
705 if cbc
, ok
= c
.out
.cipher
.(cbcMode
); ok
{
706 explicitIVLen
= cbc
.BlockSize()
709 if explicitIVLen
== 0 {
710 if _
, ok
:= c
.out
.cipher
.(cipher
.AEAD
); ok
{
712 // The AES-GCM construction in TLS has an
713 // explicit nonce so that the nonce can be
714 // random. However, the nonce is only 8 bytes
715 // which is too small for a secure, random
716 // nonce. Therefore we use the sequence number
718 explicitIVIsSeq
= true
721 b
.resize(recordHeaderLen
+ explicitIVLen
+ m
)
722 b
.data
[0] = byte(typ
)
725 // Some TLS servers fail if the record version is
726 // greater than TLS 1.0 for the initial ClientHello.
729 b
.data
[1] = byte(vers
>> 8)
730 b
.data
[2] = byte(vers
)
731 b
.data
[3] = byte(m
>> 8)
733 if explicitIVLen
> 0 {
734 explicitIV
:= b
.data
[recordHeaderLen
: recordHeaderLen
+explicitIVLen
]
736 copy(explicitIV
, c
.out
.seq
[:])
738 if _
, err
= io
.ReadFull(c
.config
.rand(), explicitIV
); err
!= nil {
743 copy(b
.data
[recordHeaderLen
+explicitIVLen
:], data
)
744 c
.out
.encrypt(b
, explicitIVLen
)
745 _
, err
= c
.conn
.Write(b
.data
)
754 if typ
== recordTypeChangeCipherSpec
{
755 err
= c
.out
.changeCipherSpec()
757 // Cannot call sendAlert directly,
758 // because we already hold c.out.Mutex.
759 c
.tmp
[0] = alertLevelError
760 c
.tmp
[1] = byte(err
.(alert
))
761 c
.writeRecord(recordTypeAlert
, c
.tmp
[0:2])
762 return n
, c
.out
.setErrorLocked(&net
.OpError
{Op
: "local error", Err
: err
})
768 // readHandshake reads the next handshake message from
770 // c.in.Mutex < L; c.out.Mutex < L.
771 func (c
*Conn
) readHandshake() (interface{}, error
) {
772 for c
.hand
.Len() < 4 {
773 if err
:= c
.in
.err
; err
!= nil {
776 if err
:= c
.readRecord(recordTypeHandshake
); err
!= nil {
781 data
:= c
.hand
.Bytes()
782 n
:= int(data
[1])<<16 |
int(data
[2])<<8 |
int(data
[3])
783 if n
> maxHandshake
{
784 return nil, c
.in
.setErrorLocked(c
.sendAlert(alertInternalError
))
786 for c
.hand
.Len() < 4+n
{
787 if err
:= c
.in
.err
; err
!= nil {
790 if err
:= c
.readRecord(recordTypeHandshake
); err
!= nil {
794 data
= c
.hand
.Next(4 + n
)
795 var m handshakeMessage
797 case typeClientHello
:
798 m
= new(clientHelloMsg
)
799 case typeServerHello
:
800 m
= new(serverHelloMsg
)
801 case typeNewSessionTicket
:
802 m
= new(newSessionTicketMsg
)
803 case typeCertificate
:
804 m
= new(certificateMsg
)
805 case typeCertificateRequest
:
806 m
= &certificateRequestMsg
{
807 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
809 case typeCertificateStatus
:
810 m
= new(certificateStatusMsg
)
811 case typeServerKeyExchange
:
812 m
= new(serverKeyExchangeMsg
)
813 case typeServerHelloDone
:
814 m
= new(serverHelloDoneMsg
)
815 case typeClientKeyExchange
:
816 m
= new(clientKeyExchangeMsg
)
817 case typeCertificateVerify
:
818 m
= &certificateVerifyMsg
{
819 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
821 case typeNextProtocol
:
822 m
= new(nextProtoMsg
)
826 return nil, c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
829 // The handshake message unmarshallers
830 // expect to be able to keep references to data,
831 // so pass in a fresh copy that won't be overwritten.
832 data
= append([]byte(nil), data
...)
834 if !m
.unmarshal(data
) {
835 return nil, c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
840 // Write writes data to the connection.
841 func (c
*Conn
) Write(b
[]byte) (int, error
) {
842 if err
:= c
.Handshake(); err
!= nil {
849 if err
:= c
.out
.err
; err
!= nil {
853 if !c
.handshakeComplete
{
854 return 0, alertInternalError
857 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
858 // attack when using block mode ciphers due to predictable IVs.
859 // This can be prevented by splitting each Application Data
860 // record into two records, effectively randomizing the IV.
862 // http://www.openssl.org/~bodo/tls-cbc.txt
863 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
864 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
867 if len(b
) > 1 && c
.vers
<= VersionTLS10
{
868 if _
, ok
:= c
.out
.cipher
.(cipher
.BlockMode
); ok
{
869 n
, err
:= c
.writeRecord(recordTypeApplicationData
, b
[:1])
871 return n
, c
.out
.setErrorLocked(err
)
877 n
, err
:= c
.writeRecord(recordTypeApplicationData
, b
)
878 return n
+ m
, c
.out
.setErrorLocked(err
)
881 // Read can be made to time out and return a net.Error with Timeout() == true
882 // after a fixed time limit; see SetDeadline and SetReadDeadline.
883 func (c
*Conn
) Read(b
[]byte) (n
int, err error
) {
884 if err
= c
.Handshake(); err
!= nil {
888 // Put this after Handshake, in case people were calling
889 // Read(nil) for the side effect of the Handshake.
896 // Some OpenSSL servers send empty records in order to randomize the
897 // CBC IV. So this loop ignores a limited number of empty records.
898 const maxConsecutiveEmptyRecords
= 100
899 for emptyRecordCount
:= 0; emptyRecordCount
<= maxConsecutiveEmptyRecords
; emptyRecordCount
++ {
900 for c
.input
== nil && c
.in
.err
== nil {
901 if err
:= c
.readRecord(recordTypeApplicationData
); err
!= nil {
902 // Soft error, like EAGAIN
906 if err
:= c
.in
.err
; err
!= nil {
910 n
, err
= c
.input
.Read(b
)
911 if c
.input
.off
>= len(c
.input
.data
) {
912 c
.in
.freeBlock(c
.input
)
916 // If a close-notify alert is waiting, read it so that
917 // we can return (n, EOF) instead of (n, nil), to signal
918 // to the HTTP response reading goroutine that the
919 // connection is now closed. This eliminates a race
920 // where the HTTP response reading goroutine would
921 // otherwise not observe the EOF until its next read,
922 // by which time a client goroutine might have already
923 // tried to reuse the HTTP connection for a new
925 // See https://codereview.appspot.com/76400046
926 // and http://golang.org/issue/3514
927 if ri
:= c
.rawInput
; ri
!= nil &&
928 n
!= 0 && err
== nil &&
929 c
.input
== nil && len(ri
.data
) > 0 && recordType(ri
.data
[0]) == recordTypeAlert
{
930 if recErr
:= c
.readRecord(recordTypeApplicationData
); recErr
!= nil {
931 err
= recErr
// will be io.EOF on closeNotify
935 if n
!= 0 || err
!= nil {
940 return 0, io
.ErrNoProgress
943 // Close closes the connection.
944 func (c
*Conn
) Close() error
{
947 c
.handshakeMutex
.Lock()
948 defer c
.handshakeMutex
.Unlock()
949 if c
.handshakeComplete
{
950 alertErr
= c
.sendAlert(alertCloseNotify
)
953 if err
:= c
.conn
.Close(); err
!= nil {
959 // Handshake runs the client or server handshake
960 // protocol if it has not yet been run.
961 // Most uses of this package need not call Handshake
962 // explicitly: the first Read or Write will call it automatically.
963 func (c
*Conn
) Handshake() error
{
964 c
.handshakeMutex
.Lock()
965 defer c
.handshakeMutex
.Unlock()
966 if err
:= c
.handshakeErr
; err
!= nil {
969 if c
.handshakeComplete
{
974 c
.handshakeErr
= c
.clientHandshake()
976 c
.handshakeErr
= c
.serverHandshake()
978 return c
.handshakeErr
981 // ConnectionState returns basic TLS details about the connection.
982 func (c
*Conn
) ConnectionState() ConnectionState
{
983 c
.handshakeMutex
.Lock()
984 defer c
.handshakeMutex
.Unlock()
986 var state ConnectionState
987 state
.HandshakeComplete
= c
.handshakeComplete
988 if c
.handshakeComplete
{
989 state
.Version
= c
.vers
990 state
.NegotiatedProtocol
= c
.clientProtocol
991 state
.DidResume
= c
.didResume
992 state
.NegotiatedProtocolIsMutual
= !c
.clientProtocolFallback
993 state
.CipherSuite
= c
.cipherSuite
994 state
.PeerCertificates
= c
.peerCertificates
995 state
.VerifiedChains
= c
.verifiedChains
996 state
.ServerName
= c
.serverName
1002 // OCSPResponse returns the stapled OCSP response from the TLS server, if
1003 // any. (Only valid for client connections.)
1004 func (c
*Conn
) OCSPResponse() []byte {
1005 c
.handshakeMutex
.Lock()
1006 defer c
.handshakeMutex
.Unlock()
1008 return c
.ocspResponse
1011 // VerifyHostname checks that the peer certificate chain is valid for
1012 // connecting to host. If so, it returns nil; if not, it returns an error
1013 // describing the problem.
1014 func (c
*Conn
) VerifyHostname(host
string) error
{
1015 c
.handshakeMutex
.Lock()
1016 defer c
.handshakeMutex
.Unlock()
1018 return errors
.New("tls: VerifyHostname called on TLS server connection")
1020 if !c
.handshakeComplete
{
1021 return errors
.New("tls: handshake has not yet been performed")
1023 return c
.peerCertificates
[0].VerifyHostname(host
)