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
21 // A Conn represents a secured connection.
22 // It implements the net.Conn interface.
28 // constant after handshake; protected by handshakeMutex
29 handshakeMutex sync
.Mutex
// handshakeMutex < in.Mutex, out.Mutex, errMutex
30 vers
uint16 // TLS version
31 haveVers
bool // version has been negotiated
32 config
*Config
// configuration passed to constructor
33 handshakeComplete
bool
34 didResume
bool // whether this connection was a session resumption
36 ocspResponse
[]byte // stapled OCSP response
37 peerCertificates
[]*x509
.Certificate
38 // verifiedChains contains the certificate chains that we built, as
39 // opposed to the ones presented by the server.
40 verifiedChains
[][]*x509
.Certificate
41 // serverName contains the server name indicated by the client, if any.
45 clientProtocolFallback
bool
47 // first permanent error
51 in
, out halfConn
// in.Mutex < out.Mutex
52 rawInput
*block
// raw input, right off the wire
53 input
*block
// application data waiting to be read
54 hand bytes
.Buffer
// handshake data waiting to be read
64 func (e
*connErr
) setError(err error
) error
{
74 func (e
*connErr
) error() error
{
80 // Access to net.Conn methods.
81 // Cannot just embed net.Conn because that would
82 // export the struct field too.
84 // LocalAddr returns the local network address.
85 func (c
*Conn
) LocalAddr() net
.Addr
{
86 return c
.conn
.LocalAddr()
89 // RemoteAddr returns the remote network address.
90 func (c
*Conn
) RemoteAddr() net
.Addr
{
91 return c
.conn
.RemoteAddr()
94 // SetDeadline sets the read and write deadlines associated with the connection.
95 // A zero value for t means Read and Write will not time out.
96 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
97 func (c
*Conn
) SetDeadline(t time
.Time
) error
{
98 return c
.conn
.SetDeadline(t
)
101 // SetReadDeadline sets the read deadline on the underlying connection.
102 // A zero value for t means Read will not time out.
103 func (c
*Conn
) SetReadDeadline(t time
.Time
) error
{
104 return c
.conn
.SetReadDeadline(t
)
107 // SetWriteDeadline sets the write deadline on the underlying conneciton.
108 // A zero value for t means Write will not time out.
109 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
110 func (c
*Conn
) SetWriteDeadline(t time
.Time
) error
{
111 return c
.conn
.SetWriteDeadline(t
)
114 // A halfConn represents one direction of the record layer
115 // connection, either sending or receiving.
116 type halfConn
struct {
118 version
uint16 // protocol version
119 cipher
interface{} // cipher algorithm
121 seq
[8]byte // 64-bit sequence number
122 bfree
*block
// list of free blocks
124 nextCipher
interface{} // next encryption state
125 nextMac macFunction
// next MAC algorithm
127 // used to save allocating a new buffer for each MAC.
128 inDigestBuf
, outDigestBuf
[]byte
131 // prepareCipherSpec sets the encryption and MAC states
132 // that a subsequent changeCipherSpec will use.
133 func (hc
*halfConn
) prepareCipherSpec(version
uint16, cipher
interface{}, mac macFunction
) {
135 hc
.nextCipher
= cipher
139 // changeCipherSpec changes the encryption and MAC states
140 // to the ones previously passed to prepareCipherSpec.
141 func (hc
*halfConn
) changeCipherSpec() error
{
142 if hc
.nextCipher
== nil {
143 return alertInternalError
145 hc
.cipher
= hc
.nextCipher
149 for i
:= range hc
.seq
{
155 // incSeq increments the sequence number.
156 func (hc
*halfConn
) incSeq() {
157 for i
:= 7; i
>= 0; i
-- {
164 // Not allowed to let sequence number wrap.
165 // Instead, must renegotiate before it does.
166 // Not likely enough to bother.
167 panic("TLS: sequence number wraparound")
170 // resetSeq resets the sequence number to zero.
171 func (hc
*halfConn
) resetSeq() {
172 for i
:= range hc
.seq
{
177 // removePadding returns an unpadded slice, in constant time, which is a prefix
178 // of the input. It also returns a byte which is equal to 255 if the padding
179 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
180 func removePadding(payload
[]byte) ([]byte, byte) {
181 if len(payload
) < 1 {
185 paddingLen
:= payload
[len(payload
)-1]
186 t
:= uint(len(payload
)-1) - uint(paddingLen
)
187 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
188 good
:= byte(int32(^t
) >> 31)
190 toCheck
:= 255 // the maximum possible padding length
191 // The length of the padded data is public, so we can use an if here
192 if toCheck
+1 > len(payload
) {
193 toCheck
= len(payload
) - 1
196 for i
:= 0; i
< toCheck
; i
++ {
197 t
:= uint(paddingLen
) - uint(i
)
198 // if i <= paddingLen then the MSB of t is zero
199 mask
:= byte(int32(^t
) >> 31)
200 b
:= payload
[len(payload
)-1-i
]
201 good
&^= mask
&paddingLen
^ mask
&b
204 // We AND together the bits of good and replicate the result across
209 good
= uint8(int8(good
) >> 7)
211 toRemove
:= good
&paddingLen
+ 1
212 return payload
[:len(payload
)-int(toRemove
)], good
215 // removePaddingSSL30 is a replacement for removePadding in the case that the
216 // protocol version is SSLv3. In this version, the contents of the padding
217 // are random and cannot be checked.
218 func removePaddingSSL30(payload
[]byte) ([]byte, byte) {
219 if len(payload
) < 1 {
223 paddingLen
:= int(payload
[len(payload
)-1]) + 1
224 if paddingLen
> len(payload
) {
228 return payload
[:len(payload
)-paddingLen
], 255
231 func roundUp(a
, b
int) int {
235 // cbcMode is an interface for block ciphers using cipher block chaining.
236 type cbcMode
interface {
241 // decrypt checks and strips the mac and decrypts the data in b. Returns a
242 // success boolean, the number of bytes to skip from the start of the record in
243 // order to get the application payload, and an optional alert value.
244 func (hc
*halfConn
) decrypt(b
*block
) (ok
bool, prefixLen
int, alertValue alert
) {
246 payload
:= b
.data
[recordHeaderLen
:]
250 macSize
= hc
.mac
.Size()
253 paddingGood
:= byte(255)
257 if hc
.cipher
!= nil {
258 switch c
:= hc
.cipher
.(type) {
260 c
.XORKeyStream(payload
, payload
)
263 if len(payload
) < explicitIVLen
{
264 return false, 0, alertBadRecordMAC
267 payload
= payload
[8:]
269 var additionalData
[13]byte
270 copy(additionalData
[:], hc
.seq
[:])
271 copy(additionalData
[8:], b
.data
[:3])
272 n
:= len(payload
) - c
.Overhead()
273 additionalData
[11] = byte(n
>> 8)
274 additionalData
[12] = byte(n
)
276 payload
, err
= c
.Open(payload
[:0], nonce
, payload
, additionalData
[:])
278 return false, 0, alertBadRecordMAC
280 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(payload
))
282 blockSize
:= c
.BlockSize()
283 if hc
.version
>= VersionTLS11
{
284 explicitIVLen
= blockSize
287 if len(payload
)%blockSize
!= 0 ||
len(payload
) < roundUp(explicitIVLen
+macSize
+1, blockSize
) {
288 return false, 0, alertBadRecordMAC
291 if explicitIVLen
> 0 {
292 c
.SetIV(payload
[:explicitIVLen
])
293 payload
= payload
[explicitIVLen
:]
295 c
.CryptBlocks(payload
, payload
)
296 if hc
.version
== VersionSSL30
{
297 payload
, paddingGood
= removePaddingSSL30(payload
)
299 payload
, paddingGood
= removePadding(payload
)
301 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(payload
))
303 // note that we still have a timing side-channel in the
304 // MAC check, below. An attacker can align the record
305 // so that a correct padding will cause one less hash
306 // block to be calculated. Then they can iteratively
307 // decrypt a record by breaking each byte. See
308 // "Password Interception in a SSL/TLS Channel", Brice
311 // However, our behavior matches OpenSSL, so we leak
312 // only as much as they do.
314 panic("unknown cipher type")
320 if len(payload
) < macSize
{
321 return false, 0, alertBadRecordMAC
324 // strip mac off payload, b.data
325 n
:= len(payload
) - macSize
326 b
.data
[3] = byte(n
>> 8)
328 b
.resize(recordHeaderLen
+ explicitIVLen
+ n
)
329 remoteMAC
:= payload
[n
:]
330 localMAC
:= hc
.mac
.MAC(hc
.inDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], payload
[:n
])
332 if subtle
.ConstantTimeCompare(localMAC
, remoteMAC
) != 1 || paddingGood
!= 255 {
333 return false, 0, alertBadRecordMAC
335 hc
.inDigestBuf
= localMAC
339 return true, recordHeaderLen
+ explicitIVLen
, 0
342 // padToBlockSize calculates the needed padding block, if any, for a payload.
343 // On exit, prefix aliases payload and extends to the end of the last full
344 // block of payload. finalBlock is a fresh slice which contains the contents of
345 // any suffix of payload as well as the needed padding to make finalBlock a
347 func padToBlockSize(payload
[]byte, blockSize
int) (prefix
, finalBlock
[]byte) {
348 overrun
:= len(payload
) % blockSize
349 paddingLen
:= blockSize
- overrun
350 prefix
= payload
[:len(payload
)-overrun
]
351 finalBlock
= make([]byte, blockSize
)
352 copy(finalBlock
, payload
[len(payload
)-overrun
:])
353 for i
:= overrun
; i
< blockSize
; i
++ {
354 finalBlock
[i
] = byte(paddingLen
- 1)
359 // encrypt encrypts and macs the data in b.
360 func (hc
*halfConn
) encrypt(b
*block
, explicitIVLen
int) (bool, alert
) {
363 mac
:= hc
.mac
.MAC(hc
.outDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], b
.data
[recordHeaderLen
+explicitIVLen
:])
366 b
.resize(n
+ len(mac
))
367 copy(b
.data
[n
:], mac
)
368 hc
.outDigestBuf
= mac
371 payload
:= b
.data
[recordHeaderLen
:]
374 if hc
.cipher
!= nil {
375 switch c
:= hc
.cipher
.(type) {
377 c
.XORKeyStream(payload
, payload
)
379 payloadLen
:= len(b
.data
) - recordHeaderLen
- explicitIVLen
380 b
.resize(len(b
.data
) + c
.Overhead())
381 nonce
:= b
.data
[recordHeaderLen
: recordHeaderLen
+explicitIVLen
]
382 payload
:= b
.data
[recordHeaderLen
+explicitIVLen
:]
383 payload
= payload
[:payloadLen
]
385 var additionalData
[13]byte
386 copy(additionalData
[:], hc
.seq
[:])
387 copy(additionalData
[8:], b
.data
[:3])
388 additionalData
[11] = byte(payloadLen
>> 8)
389 additionalData
[12] = byte(payloadLen
)
391 c
.Seal(payload
[:0], nonce
, payload
, additionalData
[:])
393 blockSize
:= c
.BlockSize()
394 if explicitIVLen
> 0 {
395 c
.SetIV(payload
[:explicitIVLen
])
396 payload
= payload
[explicitIVLen
:]
398 prefix
, finalBlock
:= padToBlockSize(payload
, blockSize
)
399 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(prefix
) + len(finalBlock
))
400 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
:], prefix
)
401 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
+len(prefix
):], finalBlock
)
403 panic("unknown cipher type")
407 // update length to include MAC and any block padding needed.
408 n
:= len(b
.data
) - recordHeaderLen
409 b
.data
[3] = byte(n
>> 8)
416 // A block is a simple data buffer.
419 off
int // index for Read
423 // resize resizes block to be n bytes, growing if necessary.
424 func (b
*block
) resize(n
int) {
431 // reserve makes sure that block contains a capacity of at least n bytes.
432 func (b
*block
) reserve(n
int) {
433 if cap(b
.data
) >= n
{
443 data
:= make([]byte, len(b
.data
), m
)
448 // readFromUntil reads from r into b until b contains at least n bytes
449 // or else returns an error.
450 func (b
*block
) readFromUntil(r io
.Reader
, n
int) error
{
452 if len(b
.data
) >= n
{
456 // read until have enough.
459 m
, err
:= r
.Read(b
.data
[len(b
.data
):cap(b
.data
)])
460 b
.data
= b
.data
[0 : len(b
.data
)+m
]
461 if len(b
.data
) >= n
{
471 func (b
*block
) Read(p
[]byte) (n
int, err error
) {
472 n
= copy(p
, b
.data
[b
.off
:])
477 // newBlock allocates a new block, from hc's free list if possible.
478 func (hc
*halfConn
) newBlock() *block
{
489 // freeBlock returns a block to hc's free list.
490 // The protocol is such that each side only has a block or two on
491 // its free list at a time, so there's no need to worry about
492 // trimming the list, etc.
493 func (hc
*halfConn
) freeBlock(b
*block
) {
498 // splitBlock splits a block after the first n bytes,
499 // returning a block with those n bytes and a
500 // block with the remainder. the latter may be nil.
501 func (hc
*halfConn
) splitBlock(b
*block
, n
int) (*block
, *block
) {
502 if len(b
.data
) <= n
{
506 bb
.resize(len(b
.data
) - n
)
507 copy(bb
.data
, b
.data
[n
:])
512 // readRecord reads the next TLS record from the connection
513 // and updates the record layer state.
514 // c.in.Mutex <= L; c.input == nil.
515 func (c
*Conn
) readRecord(want recordType
) error
{
516 // Caller must be in sync with connection:
517 // handshake data if handshake not yet completed,
518 // else application data. (We don't support renegotiation.)
521 return c
.sendAlert(alertInternalError
)
522 case recordTypeHandshake
, recordTypeChangeCipherSpec
:
523 if c
.handshakeComplete
{
524 return c
.sendAlert(alertInternalError
)
526 case recordTypeApplicationData
:
527 if !c
.handshakeComplete
{
528 return c
.sendAlert(alertInternalError
)
533 if c
.rawInput
== nil {
534 c
.rawInput
= c
.in
.newBlock()
538 // Read header, payload.
539 if err
:= b
.readFromUntil(c
.conn
, recordHeaderLen
); err
!= nil {
540 // RFC suggests that EOF without an alertCloseNotify is
541 // an error, but popular web sites seem to do this,
542 // so we can't make it an error.
543 // if err == io.EOF {
544 // err = io.ErrUnexpectedEOF
546 if e
, ok
:= err
.(net
.Error
); !ok ||
!e
.Temporary() {
551 typ
:= recordType(b
.data
[0])
553 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
554 // start with a uint16 length where the MSB is set and the first record
555 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
557 if want
== recordTypeHandshake
&& typ
== 0x80 {
558 c
.sendAlert(alertProtocolVersion
)
559 return errors
.New("tls: unsupported SSLv2 handshake received")
562 vers
:= uint16(b
.data
[1])<<8 |
uint16(b
.data
[2])
563 n
:= int(b
.data
[3])<<8 |
int(b
.data
[4])
564 if c
.haveVers
&& vers
!= c
.vers
{
565 return c
.sendAlert(alertProtocolVersion
)
567 if n
> maxCiphertext
{
568 return c
.sendAlert(alertRecordOverflow
)
571 // First message, be extra suspicious:
572 // this might not be a TLS client.
573 // Bail out before reading a full 'body', if possible.
574 // The current max version is 3.1.
575 // If the version is >= 16.0, it's probably not real.
576 // Similarly, a clientHello message encodes in
577 // well under a kilobyte. If the length is >= 12 kB,
578 // it's probably not real.
579 if (typ
!= recordTypeAlert
&& typ
!= want
) || vers
>= 0x1000 || n
>= 0x3000 {
580 return c
.sendAlert(alertUnexpectedMessage
)
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() {
594 b
, c
.rawInput
= c
.in
.splitBlock(b
, recordHeaderLen
+n
)
595 ok
, off
, err
:= c
.in
.decrypt(b
)
597 return c
.sendAlert(err
)
600 data
:= b
.data
[b
.off
:]
601 if len(data
) > maxPlaintext
{
602 c
.sendAlert(alertRecordOverflow
)
609 c
.sendAlert(alertUnexpectedMessage
)
611 case recordTypeAlert
:
613 c
.sendAlert(alertUnexpectedMessage
)
616 if alert(data
[1]) == alertCloseNotify
{
621 case alertLevelWarning
:
625 case alertLevelError
:
626 c
.setError(&net
.OpError
{Op
: "remote error", Err
: alert(data
[1])})
628 c
.sendAlert(alertUnexpectedMessage
)
631 case recordTypeChangeCipherSpec
:
632 if typ
!= want ||
len(data
) != 1 || data
[0] != 1 {
633 c
.sendAlert(alertUnexpectedMessage
)
636 err
:= c
.in
.changeCipherSpec()
638 c
.sendAlert(err
.(alert
))
641 case recordTypeApplicationData
:
643 c
.sendAlert(alertUnexpectedMessage
)
649 case recordTypeHandshake
:
650 // TODO(rsc): Should at least pick off connection close.
652 return 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
.setError(&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
.setError(&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
.error(); 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 c
.sendAlert(alertInternalError
)
785 return nil, c
.error()
787 for c
.hand
.Len() < 4+n
{
788 if err
:= c
.error(); err
!= nil {
791 if err
:= c
.readRecord(recordTypeHandshake
); err
!= nil {
795 data
= c
.hand
.Next(4 + n
)
796 var m handshakeMessage
798 case typeClientHello
:
799 m
= new(clientHelloMsg
)
800 case typeServerHello
:
801 m
= new(serverHelloMsg
)
802 case typeCertificate
:
803 m
= new(certificateMsg
)
804 case typeCertificateRequest
:
805 m
= &certificateRequestMsg
{
806 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
808 case typeCertificateStatus
:
809 m
= new(certificateStatusMsg
)
810 case typeServerKeyExchange
:
811 m
= new(serverKeyExchangeMsg
)
812 case typeServerHelloDone
:
813 m
= new(serverHelloDoneMsg
)
814 case typeClientKeyExchange
:
815 m
= new(clientKeyExchangeMsg
)
816 case typeCertificateVerify
:
817 m
= &certificateVerifyMsg
{
818 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
820 case typeNextProtocol
:
821 m
= new(nextProtoMsg
)
825 c
.sendAlert(alertUnexpectedMessage
)
826 return nil, 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 c
.sendAlert(alertUnexpectedMessage
)
836 return nil, alertUnexpectedMessage
841 // Write writes data to the connection.
842 func (c
*Conn
) Write(b
[]byte) (int, error
) {
843 if err
:= c
.error(); err
!= nil {
847 if err
:= c
.Handshake(); err
!= nil {
848 return 0, c
.setError(err
)
854 if !c
.handshakeComplete
{
855 return 0, alertInternalError
858 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
859 // attack when using block mode ciphers due to predictable IVs.
860 // This can be prevented by splitting each Application Data
861 // record into two records, effectively randomizing the IV.
863 // http://www.openssl.org/~bodo/tls-cbc.txt
864 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
865 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
868 if len(b
) > 1 && c
.vers
<= VersionTLS10
{
869 if _
, ok
:= c
.out
.cipher
.(cipher
.BlockMode
); ok
{
870 n
, err
:= c
.writeRecord(recordTypeApplicationData
, b
[:1])
872 return n
, c
.setError(err
)
878 n
, err
:= c
.writeRecord(recordTypeApplicationData
, b
)
879 return n
+ m
, c
.setError(err
)
882 // Read can be made to time out and return a net.Error with Timeout() == true
883 // after a fixed time limit; see SetDeadline and SetReadDeadline.
884 func (c
*Conn
) Read(b
[]byte) (n
int, err error
) {
885 if err
= c
.Handshake(); err
!= nil {
892 // Some OpenSSL servers send empty records in order to randomize the
893 // CBC IV. So this loop ignores a limited number of empty records.
894 const maxConsecutiveEmptyRecords
= 100
895 for emptyRecordCount
:= 0; emptyRecordCount
<= maxConsecutiveEmptyRecords
; emptyRecordCount
++ {
896 for c
.input
== nil && c
.error() == nil {
897 if err
:= c
.readRecord(recordTypeApplicationData
); err
!= nil {
898 // Soft error, like EAGAIN
902 if err
:= c
.error(); err
!= nil {
906 n
, err
= c
.input
.Read(b
)
907 if c
.input
.off
>= len(c
.input
.data
) {
908 c
.in
.freeBlock(c
.input
)
912 if n
!= 0 || err
!= nil {
917 return 0, io
.ErrNoProgress
920 // Close closes the connection.
921 func (c
*Conn
) Close() error
{
924 c
.handshakeMutex
.Lock()
925 defer c
.handshakeMutex
.Unlock()
926 if c
.handshakeComplete
{
927 alertErr
= c
.sendAlert(alertCloseNotify
)
930 if err
:= c
.conn
.Close(); err
!= nil {
936 // Handshake runs the client or server handshake
937 // protocol if it has not yet been run.
938 // Most uses of this package need not call Handshake
939 // explicitly: the first Read or Write will call it automatically.
940 func (c
*Conn
) Handshake() error
{
941 c
.handshakeMutex
.Lock()
942 defer c
.handshakeMutex
.Unlock()
943 if err
:= c
.error(); err
!= nil {
946 if c
.handshakeComplete
{
950 return c
.clientHandshake()
952 return c
.serverHandshake()
955 // ConnectionState returns basic TLS details about the connection.
956 func (c
*Conn
) ConnectionState() ConnectionState
{
957 c
.handshakeMutex
.Lock()
958 defer c
.handshakeMutex
.Unlock()
960 var state ConnectionState
961 state
.HandshakeComplete
= c
.handshakeComplete
962 if c
.handshakeComplete
{
963 state
.NegotiatedProtocol
= c
.clientProtocol
964 state
.DidResume
= c
.didResume
965 state
.NegotiatedProtocolIsMutual
= !c
.clientProtocolFallback
966 state
.CipherSuite
= c
.cipherSuite
967 state
.PeerCertificates
= c
.peerCertificates
968 state
.VerifiedChains
= c
.verifiedChains
969 state
.ServerName
= c
.serverName
975 // OCSPResponse returns the stapled OCSP response from the TLS server, if
976 // any. (Only valid for client connections.)
977 func (c
*Conn
) OCSPResponse() []byte {
978 c
.handshakeMutex
.Lock()
979 defer c
.handshakeMutex
.Unlock()
981 return c
.ocspResponse
984 // VerifyHostname checks that the peer certificate chain is valid for
985 // connecting to host. If so, it returns nil; if not, it returns an error
986 // describing the problem.
987 func (c
*Conn
) VerifyHostname(host
string) error
{
988 c
.handshakeMutex
.Lock()
989 defer c
.handshakeMutex
.Unlock()
991 return errors
.New("VerifyHostname called on TLS server connection")
993 if !c
.handshakeComplete
{
994 return errors
.New("TLS handshake has not yet been performed")
996 return c
.peerCertificates
[0].VerifyHostname(host
)