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
23 // A Conn represents a secured connection.
24 // It implements the net.Conn interface.
30 // constant after handshake; protected by handshakeMutex
31 handshakeMutex sync
.Mutex
// handshakeMutex < in.Mutex, out.Mutex, errMutex
32 // handshakeCond, if not nil, indicates that a goroutine is committed
33 // to running the handshake for this Conn. Other goroutines that need
34 // to wait for the handshake can wait on this, under handshakeMutex.
35 handshakeCond
*sync
.Cond
36 handshakeErr error
// error resulting from handshake
37 vers
uint16 // TLS version
38 haveVers
bool // version has been negotiated
39 config
*Config
// configuration passed to constructor
40 // handshakeComplete is true if the connection is currently transferring
41 // application data (i.e. is not currently processing a handshake).
42 handshakeComplete
bool
43 // handshakes counts the number of handshakes performed on the
44 // connection so far. If renegotiation is disabled then this is either
47 didResume
bool // whether this connection was a session resumption
49 ocspResponse
[]byte // stapled OCSP response
50 scts
[][]byte // signed certificate timestamps from server
51 peerCertificates
[]*x509
.Certificate
52 // verifiedChains contains the certificate chains that we built, as
53 // opposed to the ones presented by the server.
54 verifiedChains
[][]*x509
.Certificate
55 // serverName contains the server name indicated by the client, if any.
57 // secureRenegotiation is true if the server echoed the secure
58 // renegotiation extension. (This is meaningless as a server because
59 // renegotiation is not supported in that case.)
60 secureRenegotiation
bool
62 // clientFinishedIsFirst is true if the client sent the first Finished
63 // message during the most recent handshake. This is recorded because
64 // the first transmitted Finished message is the tls-unique
65 // channel-binding value.
66 clientFinishedIsFirst
bool
68 // closeNotifyErr is any error from sending the alertCloseNotify record.
70 // closeNotifySent is true if the Conn attempted to send an
71 // alertCloseNotify record.
74 // clientFinished and serverFinished contain the Finished message sent
75 // by the client or server in the most recent handshake. This is
76 // retained to support the renegotiation extension and tls-unique
78 clientFinished
[12]byte
79 serverFinished
[12]byte
82 clientProtocolFallback
bool
85 in
, out halfConn
// in.Mutex < out.Mutex
86 rawInput
*block
// raw input, right off the wire
87 input
*block
// application data waiting to be read
88 hand bytes
.Buffer
// handshake data waiting to be read
89 buffering
bool // whether records are buffered in sendBuf
90 sendBuf
[]byte // a buffer of records waiting to be sent
92 // bytesSent counts the bytes of application data sent.
93 // packetsSent counts packets.
97 // activeCall is an atomic int32; the low bit is whether Close has
98 // been called. the rest of the bits are the number of goroutines
105 // Access to net.Conn methods.
106 // Cannot just embed net.Conn because that would
107 // export the struct field too.
109 // LocalAddr returns the local network address.
110 func (c
*Conn
) LocalAddr() net
.Addr
{
111 return c
.conn
.LocalAddr()
114 // RemoteAddr returns the remote network address.
115 func (c
*Conn
) RemoteAddr() net
.Addr
{
116 return c
.conn
.RemoteAddr()
119 // SetDeadline sets the read and write deadlines associated with the connection.
120 // A zero value for t means Read and Write will not time out.
121 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
122 func (c
*Conn
) SetDeadline(t time
.Time
) error
{
123 return c
.conn
.SetDeadline(t
)
126 // SetReadDeadline sets the read deadline on the underlying connection.
127 // A zero value for t means Read will not time out.
128 func (c
*Conn
) SetReadDeadline(t time
.Time
) error
{
129 return c
.conn
.SetReadDeadline(t
)
132 // SetWriteDeadline sets the write deadline on the underlying connection.
133 // A zero value for t means Write will not time out.
134 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
135 func (c
*Conn
) SetWriteDeadline(t time
.Time
) error
{
136 return c
.conn
.SetWriteDeadline(t
)
139 // A halfConn represents one direction of the record layer
140 // connection, either sending or receiving.
141 type halfConn
struct {
144 err error
// first permanent error
145 version
uint16 // protocol version
146 cipher
interface{} // cipher algorithm
148 seq
[8]byte // 64-bit sequence number
149 bfree
*block
// list of free blocks
150 additionalData
[13]byte // to avoid allocs; interface method args escape
152 nextCipher
interface{} // next encryption state
153 nextMac macFunction
// next MAC algorithm
155 // used to save allocating a new buffer for each MAC.
156 inDigestBuf
, outDigestBuf
[]byte
159 func (hc
*halfConn
) setErrorLocked(err error
) error
{
164 // prepareCipherSpec sets the encryption and MAC states
165 // that a subsequent changeCipherSpec will use.
166 func (hc
*halfConn
) prepareCipherSpec(version
uint16, cipher
interface{}, mac macFunction
) {
168 hc
.nextCipher
= cipher
172 // changeCipherSpec changes the encryption and MAC states
173 // to the ones previously passed to prepareCipherSpec.
174 func (hc
*halfConn
) changeCipherSpec() error
{
175 if hc
.nextCipher
== nil {
176 return alertInternalError
178 hc
.cipher
= hc
.nextCipher
182 for i
:= range hc
.seq
{
188 // incSeq increments the sequence number.
189 func (hc
*halfConn
) incSeq() {
190 for i
:= 7; i
>= 0; i
-- {
197 // Not allowed to let sequence number wrap.
198 // Instead, must renegotiate before it does.
199 // Not likely enough to bother.
200 panic("TLS: sequence number wraparound")
203 // extractPadding returns, in constant time, the length of the padding to remove
204 // from the end of payload. It also returns a byte which is equal to 255 if the
205 // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
206 func extractPadding(payload
[]byte) (toRemove
int, good
byte) {
207 if len(payload
) < 1 {
211 paddingLen
:= payload
[len(payload
)-1]
212 t
:= uint(len(payload
)-1) - uint(paddingLen
)
213 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
214 good
= byte(int32(^t
) >> 31)
216 toCheck
:= 255 // the maximum possible padding length
217 // The length of the padded data is public, so we can use an if here
218 if toCheck
+1 > len(payload
) {
219 toCheck
= len(payload
) - 1
222 for i
:= 0; i
< toCheck
; i
++ {
223 t
:= uint(paddingLen
) - uint(i
)
224 // if i <= paddingLen then the MSB of t is zero
225 mask
:= byte(int32(^t
) >> 31)
226 b
:= payload
[len(payload
)-1-i
]
227 good
&^= mask
&paddingLen
^ mask
&b
230 // We AND together the bits of good and replicate the result across
235 good
= uint8(int8(good
) >> 7)
237 toRemove
= int(paddingLen
) + 1
241 // extractPaddingSSL30 is a replacement for extractPadding in the case that the
242 // protocol version is SSLv3. In this version, the contents of the padding
243 // are random and cannot be checked.
244 func extractPaddingSSL30(payload
[]byte) (toRemove
int, good
byte) {
245 if len(payload
) < 1 {
249 paddingLen
:= int(payload
[len(payload
)-1]) + 1
250 if paddingLen
> len(payload
) {
254 return paddingLen
, 255
257 func roundUp(a
, b
int) int {
261 // cbcMode is an interface for block ciphers using cipher block chaining.
262 type cbcMode
interface {
267 // decrypt checks and strips the mac and decrypts the data in b. Returns a
268 // success boolean, the number of bytes to skip from the start of the record in
269 // order to get the application payload, and an optional alert value.
270 func (hc
*halfConn
) decrypt(b
*block
) (ok
bool, prefixLen
int, alertValue alert
) {
272 payload
:= b
.data
[recordHeaderLen
:]
276 macSize
= hc
.mac
.Size()
279 paddingGood
:= byte(255)
284 if hc
.cipher
!= nil {
285 switch c
:= hc
.cipher
.(type) {
287 c
.XORKeyStream(payload
, payload
)
289 explicitIVLen
= c
.explicitNonceLen()
290 if len(payload
) < explicitIVLen
{
291 return false, 0, alertBadRecordMAC
293 nonce
:= payload
[:explicitIVLen
]
294 payload
= payload
[explicitIVLen
:]
300 copy(hc
.additionalData
[:], hc
.seq
[:])
301 copy(hc
.additionalData
[8:], b
.data
[:3])
302 n
:= len(payload
) - c
.Overhead()
303 hc
.additionalData
[11] = byte(n
>> 8)
304 hc
.additionalData
[12] = byte(n
)
306 payload
, err
= c
.Open(payload
[:0], nonce
, payload
, hc
.additionalData
[:])
308 return false, 0, alertBadRecordMAC
310 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(payload
))
312 blockSize
:= c
.BlockSize()
313 if hc
.version
>= VersionTLS11
{
314 explicitIVLen
= blockSize
317 if len(payload
)%blockSize
!= 0 ||
len(payload
) < roundUp(explicitIVLen
+macSize
+1, blockSize
) {
318 return false, 0, alertBadRecordMAC
321 if explicitIVLen
> 0 {
322 c
.SetIV(payload
[:explicitIVLen
])
323 payload
= payload
[explicitIVLen
:]
325 c
.CryptBlocks(payload
, payload
)
326 if hc
.version
== VersionSSL30
{
327 paddingLen
, paddingGood
= extractPaddingSSL30(payload
)
329 paddingLen
, paddingGood
= extractPadding(payload
)
331 // To protect against CBC padding oracles like Lucky13, the data
332 // past paddingLen (which is secret) is passed to the MAC
333 // function as extra data, to be fed into the HMAC after
334 // computing the digest. This makes the MAC constant time as
335 // long as the digest computation is constant time and does not
336 // affect the subsequent write.
339 panic("unknown cipher type")
345 if len(payload
) < macSize
{
346 return false, 0, alertBadRecordMAC
349 // strip mac off payload, b.data
350 n
:= len(payload
) - macSize
- paddingLen
351 n
= subtle
.ConstantTimeSelect(int(uint32(n
)>>31), 0, n
) // if n < 0 { n = 0 }
352 b
.data
[3] = byte(n
>> 8)
354 remoteMAC
:= payload
[n
: n
+macSize
]
355 localMAC
:= hc
.mac
.MAC(hc
.inDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], payload
[:n
], payload
[n
+macSize
:])
357 if subtle
.ConstantTimeCompare(localMAC
, remoteMAC
) != 1 || paddingGood
!= 255 {
358 return false, 0, alertBadRecordMAC
360 hc
.inDigestBuf
= localMAC
362 b
.resize(recordHeaderLen
+ explicitIVLen
+ n
)
366 return true, recordHeaderLen
+ explicitIVLen
, 0
369 // padToBlockSize calculates the needed padding block, if any, for a payload.
370 // On exit, prefix aliases payload and extends to the end of the last full
371 // block of payload. finalBlock is a fresh slice which contains the contents of
372 // any suffix of payload as well as the needed padding to make finalBlock a
374 func padToBlockSize(payload
[]byte, blockSize
int) (prefix
, finalBlock
[]byte) {
375 overrun
:= len(payload
) % blockSize
376 paddingLen
:= blockSize
- overrun
377 prefix
= payload
[:len(payload
)-overrun
]
378 finalBlock
= make([]byte, blockSize
)
379 copy(finalBlock
, payload
[len(payload
)-overrun
:])
380 for i
:= overrun
; i
< blockSize
; i
++ {
381 finalBlock
[i
] = byte(paddingLen
- 1)
386 // encrypt encrypts and macs the data in b.
387 func (hc
*halfConn
) encrypt(b
*block
, explicitIVLen
int) (bool, alert
) {
390 mac
:= hc
.mac
.MAC(hc
.outDigestBuf
, hc
.seq
[0:], b
.data
[:recordHeaderLen
], b
.data
[recordHeaderLen
+explicitIVLen
:], nil)
393 b
.resize(n
+ len(mac
))
394 copy(b
.data
[n
:], mac
)
395 hc
.outDigestBuf
= mac
398 payload
:= b
.data
[recordHeaderLen
:]
401 if hc
.cipher
!= nil {
402 switch c
:= hc
.cipher
.(type) {
404 c
.XORKeyStream(payload
, payload
)
406 payloadLen
:= len(b
.data
) - recordHeaderLen
- explicitIVLen
407 b
.resize(len(b
.data
) + c
.Overhead())
408 nonce
:= b
.data
[recordHeaderLen
: recordHeaderLen
+explicitIVLen
]
412 payload
:= b
.data
[recordHeaderLen
+explicitIVLen
:]
413 payload
= payload
[:payloadLen
]
415 copy(hc
.additionalData
[:], hc
.seq
[:])
416 copy(hc
.additionalData
[8:], b
.data
[:3])
417 hc
.additionalData
[11] = byte(payloadLen
>> 8)
418 hc
.additionalData
[12] = byte(payloadLen
)
420 c
.Seal(payload
[:0], nonce
, payload
, hc
.additionalData
[:])
422 blockSize
:= c
.BlockSize()
423 if explicitIVLen
> 0 {
424 c
.SetIV(payload
[:explicitIVLen
])
425 payload
= payload
[explicitIVLen
:]
427 prefix
, finalBlock
:= padToBlockSize(payload
, blockSize
)
428 b
.resize(recordHeaderLen
+ explicitIVLen
+ len(prefix
) + len(finalBlock
))
429 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
:], prefix
)
430 c
.CryptBlocks(b
.data
[recordHeaderLen
+explicitIVLen
+len(prefix
):], finalBlock
)
432 panic("unknown cipher type")
436 // update length to include MAC and any block padding needed.
437 n
:= len(b
.data
) - recordHeaderLen
438 b
.data
[3] = byte(n
>> 8)
445 // A block is a simple data buffer.
448 off
int // index for Read
452 // resize resizes block to be n bytes, growing if necessary.
453 func (b
*block
) resize(n
int) {
460 // reserve makes sure that block contains a capacity of at least n bytes.
461 func (b
*block
) reserve(n
int) {
462 if cap(b
.data
) >= n
{
472 data
:= make([]byte, len(b
.data
), m
)
477 // readFromUntil reads from r into b until b contains at least n bytes
478 // or else returns an error.
479 func (b
*block
) readFromUntil(r io
.Reader
, n
int) error
{
481 if len(b
.data
) >= n
{
485 // read until have enough.
488 m
, err
:= r
.Read(b
.data
[len(b
.data
):cap(b
.data
)])
489 b
.data
= b
.data
[0 : len(b
.data
)+m
]
490 if len(b
.data
) >= n
{
491 // TODO(bradfitz,agl): slightly suspicious
492 // that we're throwing away r.Read's err here.
502 func (b
*block
) Read(p
[]byte) (n
int, err error
) {
503 n
= copy(p
, b
.data
[b
.off
:])
508 // newBlock allocates a new block, from hc's free list if possible.
509 func (hc
*halfConn
) newBlock() *block
{
520 // freeBlock returns a block to hc's free list.
521 // The protocol is such that each side only has a block or two on
522 // its free list at a time, so there's no need to worry about
523 // trimming the list, etc.
524 func (hc
*halfConn
) freeBlock(b
*block
) {
529 // splitBlock splits a block after the first n bytes,
530 // returning a block with those n bytes and a
531 // block with the remainder. the latter may be nil.
532 func (hc
*halfConn
) splitBlock(b
*block
, n
int) (*block
, *block
) {
533 if len(b
.data
) <= n
{
537 bb
.resize(len(b
.data
) - n
)
538 copy(bb
.data
, b
.data
[n
:])
543 // RecordHeaderError results when a TLS record header is invalid.
544 type RecordHeaderError
struct {
545 // Msg contains a human readable string that describes the error.
547 // RecordHeader contains the five bytes of TLS record header that
548 // triggered the error.
552 func (e RecordHeaderError
) Error() string { return "tls: " + e
.Msg
}
554 func (c
*Conn
) newRecordHeaderError(msg
string) (err RecordHeaderError
) {
556 copy(err
.RecordHeader
[:], c
.rawInput
.data
)
560 // readRecord reads the next TLS record from the connection
561 // and updates the record layer state.
562 // c.in.Mutex <= L; c.input == nil.
563 func (c
*Conn
) readRecord(want recordType
) error
{
564 // Caller must be in sync with connection:
565 // handshake data if handshake not yet completed,
566 // else application data.
569 c
.sendAlert(alertInternalError
)
570 return c
.in
.setErrorLocked(errors
.New("tls: unknown record type requested"))
571 case recordTypeHandshake
, recordTypeChangeCipherSpec
:
572 if c
.handshakeComplete
{
573 c
.sendAlert(alertInternalError
)
574 return c
.in
.setErrorLocked(errors
.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
576 case recordTypeApplicationData
:
577 if !c
.handshakeComplete
{
578 c
.sendAlert(alertInternalError
)
579 return c
.in
.setErrorLocked(errors
.New("tls: application data record requested while in handshake"))
584 if c
.rawInput
== nil {
585 c
.rawInput
= c
.in
.newBlock()
589 // Read header, payload.
590 if err
:= b
.readFromUntil(c
.conn
, recordHeaderLen
); err
!= nil {
591 // RFC suggests that EOF without an alertCloseNotify is
592 // an error, but popular web sites seem to do this,
593 // so we can't make it an error.
594 // if err == io.EOF {
595 // err = io.ErrUnexpectedEOF
597 if e
, ok
:= err
.(net
.Error
); !ok ||
!e
.Temporary() {
598 c
.in
.setErrorLocked(err
)
602 typ
:= recordType(b
.data
[0])
604 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
605 // start with a uint16 length where the MSB is set and the first record
606 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
608 if want
== recordTypeHandshake
&& typ
== 0x80 {
609 c
.sendAlert(alertProtocolVersion
)
610 return c
.in
.setErrorLocked(c
.newRecordHeaderError("unsupported SSLv2 handshake received"))
613 vers
:= uint16(b
.data
[1])<<8 |
uint16(b
.data
[2])
614 n
:= int(b
.data
[3])<<8 |
int(b
.data
[4])
615 if c
.haveVers
&& vers
!= c
.vers
{
616 c
.sendAlert(alertProtocolVersion
)
617 msg
:= fmt
.Sprintf("received record with version %x when expecting version %x", vers
, c
.vers
)
618 return c
.in
.setErrorLocked(c
.newRecordHeaderError(msg
))
620 if n
> maxCiphertext
{
621 c
.sendAlert(alertRecordOverflow
)
622 msg
:= fmt
.Sprintf("oversized record received with length %d", n
)
623 return c
.in
.setErrorLocked(c
.newRecordHeaderError(msg
))
626 // First message, be extra suspicious: this might not be a TLS
627 // client. Bail out before reading a full 'body', if possible.
628 // The current max version is 3.3 so if the version is >= 16.0,
629 // it's probably not real.
630 if (typ
!= recordTypeAlert
&& typ
!= want
) || vers
>= 0x1000 {
631 c
.sendAlert(alertUnexpectedMessage
)
632 return c
.in
.setErrorLocked(c
.newRecordHeaderError("first record does not look like a TLS handshake"))
635 if err
:= b
.readFromUntil(c
.conn
, recordHeaderLen
+n
); err
!= nil {
637 err
= io
.ErrUnexpectedEOF
639 if e
, ok
:= err
.(net
.Error
); !ok ||
!e
.Temporary() {
640 c
.in
.setErrorLocked(err
)
646 b
, c
.rawInput
= c
.in
.splitBlock(b
, recordHeaderLen
+n
)
647 ok
, off
, alertValue
:= c
.in
.decrypt(b
)
650 return c
.in
.setErrorLocked(c
.sendAlert(alertValue
))
653 data
:= b
.data
[b
.off
:]
654 if len(data
) > maxPlaintext
{
655 err
:= c
.sendAlert(alertRecordOverflow
)
657 return c
.in
.setErrorLocked(err
)
662 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
664 case recordTypeAlert
:
666 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
669 if alert(data
[1]) == alertCloseNotify
{
670 c
.in
.setErrorLocked(io
.EOF
)
674 case alertLevelWarning
:
678 case alertLevelError
:
679 c
.in
.setErrorLocked(&net
.OpError
{Op
: "remote error", Err
: alert(data
[1])})
681 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
684 case recordTypeChangeCipherSpec
:
685 if typ
!= want ||
len(data
) != 1 || data
[0] != 1 {
686 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
689 err
:= c
.in
.changeCipherSpec()
691 c
.in
.setErrorLocked(c
.sendAlert(err
.(alert
)))
694 case recordTypeApplicationData
:
696 c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
702 case recordTypeHandshake
:
703 // TODO(rsc): Should at least pick off connection close.
704 if typ
!= want
&& !(c
.isClient
&& c
.config
.Renegotiation
!= RenegotiateNever
) {
705 return c
.in
.setErrorLocked(c
.sendAlert(alertNoRenegotiation
))
716 // sendAlert sends a TLS alert message.
718 func (c
*Conn
) sendAlertLocked(err alert
) error
{
720 case alertNoRenegotiation
, alertCloseNotify
:
721 c
.tmp
[0] = alertLevelWarning
723 c
.tmp
[0] = alertLevelError
727 _
, writeErr
:= c
.writeRecordLocked(recordTypeAlert
, c
.tmp
[0:2])
728 if err
== alertCloseNotify
{
729 // closeNotify is a special case in that it isn't an error.
733 return c
.out
.setErrorLocked(&net
.OpError
{Op
: "local error", Err
: err
})
736 // sendAlert sends a TLS alert message.
738 func (c
*Conn
) sendAlert(err alert
) error
{
741 return c
.sendAlertLocked(err
)
745 // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
746 // size (MSS). A constant is used, rather than querying the kernel for
747 // the actual MSS, to avoid complexity. The value here is the IPv6
748 // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
749 // bytes) and a TCP header with timestamps (32 bytes).
750 tcpMSSEstimate
= 1208
752 // recordSizeBoostThreshold is the number of bytes of application data
753 // sent after which the TLS record size will be increased to the
755 recordSizeBoostThreshold
= 128 * 1024
758 // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
759 // next application data record. There is the following trade-off:
761 // - For latency-sensitive applications, such as web browsing, each TLS
762 // record should fit in one TCP segment.
763 // - For throughput-sensitive applications, such as large file transfers,
764 // larger TLS records better amortize framing and encryption overheads.
766 // A simple heuristic that works well in practice is to use small records for
767 // the first 1MB of data, then use larger records for subsequent data, and
768 // reset back to smaller records after the connection becomes idle. See "High
769 // Performance Web Networking", Chapter 4, or:
770 // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
772 // In the interests of simplicity and determinism, this code does not attempt
773 // to reset the record size once the connection is idle, however.
776 func (c
*Conn
) maxPayloadSizeForWrite(typ recordType
, explicitIVLen
int) int {
777 if c
.config
.DynamicRecordSizingDisabled || typ
!= recordTypeApplicationData
{
781 if c
.bytesSent
>= recordSizeBoostThreshold
{
785 // Subtract TLS overheads to get the maximum payload size.
787 if c
.out
.mac
!= nil {
788 macSize
= c
.out
.mac
.Size()
791 payloadBytes
:= tcpMSSEstimate
- recordHeaderLen
- explicitIVLen
792 if c
.out
.cipher
!= nil {
793 switch ciph
:= c
.out
.cipher
.(type) {
795 payloadBytes
-= macSize
797 payloadBytes
-= ciph
.Overhead()
799 blockSize
:= ciph
.BlockSize()
800 // The payload must fit in a multiple of blockSize, with
801 // room for at least one padding byte.
802 payloadBytes
= (payloadBytes
& ^(blockSize
- 1)) - 1
803 // The MAC is appended before padding so affects the
804 // payload size directly.
805 payloadBytes
-= macSize
807 panic("unknown cipher type")
811 // Allow packet growth in arithmetic progression up to max.
815 return maxPlaintext
// avoid overflow in multiply below
818 n
:= payloadBytes
* int(pkt
+1)
819 if n
> maxPlaintext
{
826 func (c
*Conn
) write(data
[]byte) (int, error
) {
828 c
.sendBuf
= append(c
.sendBuf
, data
...)
829 return len(data
), nil
832 n
, err
:= c
.conn
.Write(data
)
833 c
.bytesSent
+= int64(n
)
837 func (c
*Conn
) flush() (int, error
) {
838 if len(c
.sendBuf
) == 0 {
842 n
, err
:= c
.conn
.Write(c
.sendBuf
)
843 c
.bytesSent
+= int64(n
)
849 // writeRecordLocked writes a TLS record with the given type and payload to the
850 // connection and updates the record layer state.
852 func (c
*Conn
) writeRecordLocked(typ recordType
, data
[]byte) (int, error
) {
853 b
:= c
.out
.newBlock()
854 defer c
.out
.freeBlock(b
)
859 explicitIVIsSeq
:= false
862 if c
.out
.version
>= VersionTLS11
{
864 if cbc
, ok
= c
.out
.cipher
.(cbcMode
); ok
{
865 explicitIVLen
= cbc
.BlockSize()
868 if explicitIVLen
== 0 {
869 if c
, ok
:= c
.out
.cipher
.(aead
); ok
{
870 explicitIVLen
= c
.explicitNonceLen()
872 // The AES-GCM construction in TLS has an
873 // explicit nonce so that the nonce can be
874 // random. However, the nonce is only 8 bytes
875 // which is too small for a secure, random
876 // nonce. Therefore we use the sequence number
878 explicitIVIsSeq
= explicitIVLen
> 0
882 if maxPayload
:= c
.maxPayloadSizeForWrite(typ
, explicitIVLen
); m
> maxPayload
{
885 b
.resize(recordHeaderLen
+ explicitIVLen
+ m
)
886 b
.data
[0] = byte(typ
)
889 // Some TLS servers fail if the record version is
890 // greater than TLS 1.0 for the initial ClientHello.
893 b
.data
[1] = byte(vers
>> 8)
894 b
.data
[2] = byte(vers
)
895 b
.data
[3] = byte(m
>> 8)
897 if explicitIVLen
> 0 {
898 explicitIV
:= b
.data
[recordHeaderLen
: recordHeaderLen
+explicitIVLen
]
900 copy(explicitIV
, c
.out
.seq
[:])
902 if _
, err
:= io
.ReadFull(c
.config
.rand(), explicitIV
); err
!= nil {
907 copy(b
.data
[recordHeaderLen
+explicitIVLen
:], data
)
908 c
.out
.encrypt(b
, explicitIVLen
)
909 if _
, err
:= c
.write(b
.data
); err
!= nil {
916 if typ
== recordTypeChangeCipherSpec
{
917 if err
:= c
.out
.changeCipherSpec(); err
!= nil {
918 return n
, c
.sendAlertLocked(err
.(alert
))
925 // writeRecord writes a TLS record with the given type and payload to the
926 // connection and updates the record layer state.
928 func (c
*Conn
) writeRecord(typ recordType
, data
[]byte) (int, error
) {
932 return c
.writeRecordLocked(typ
, data
)
935 // readHandshake reads the next handshake message from
937 // c.in.Mutex < L; c.out.Mutex < L.
938 func (c
*Conn
) readHandshake() (interface{}, error
) {
939 for c
.hand
.Len() < 4 {
940 if err
:= c
.in
.err
; err
!= nil {
943 if err
:= c
.readRecord(recordTypeHandshake
); err
!= nil {
948 data
:= c
.hand
.Bytes()
949 n
:= int(data
[1])<<16 |
int(data
[2])<<8 |
int(data
[3])
950 if n
> maxHandshake
{
951 c
.sendAlertLocked(alertInternalError
)
952 return nil, c
.in
.setErrorLocked(fmt
.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n
, maxHandshake
))
954 for c
.hand
.Len() < 4+n
{
955 if err
:= c
.in
.err
; err
!= nil {
958 if err
:= c
.readRecord(recordTypeHandshake
); err
!= nil {
962 data
= c
.hand
.Next(4 + n
)
963 var m handshakeMessage
965 case typeHelloRequest
:
966 m
= new(helloRequestMsg
)
967 case typeClientHello
:
968 m
= new(clientHelloMsg
)
969 case typeServerHello
:
970 m
= new(serverHelloMsg
)
971 case typeNewSessionTicket
:
972 m
= new(newSessionTicketMsg
)
973 case typeCertificate
:
974 m
= new(certificateMsg
)
975 case typeCertificateRequest
:
976 m
= &certificateRequestMsg
{
977 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
979 case typeCertificateStatus
:
980 m
= new(certificateStatusMsg
)
981 case typeServerKeyExchange
:
982 m
= new(serverKeyExchangeMsg
)
983 case typeServerHelloDone
:
984 m
= new(serverHelloDoneMsg
)
985 case typeClientKeyExchange
:
986 m
= new(clientKeyExchangeMsg
)
987 case typeCertificateVerify
:
988 m
= &certificateVerifyMsg
{
989 hasSignatureAndHash
: c
.vers
>= VersionTLS12
,
991 case typeNextProtocol
:
992 m
= new(nextProtoMsg
)
996 return nil, c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
999 // The handshake message unmarshalers
1000 // expect to be able to keep references to data,
1001 // so pass in a fresh copy that won't be overwritten.
1002 data
= append([]byte(nil), data
...)
1004 if !m
.unmarshal(data
) {
1005 return nil, c
.in
.setErrorLocked(c
.sendAlert(alertUnexpectedMessage
))
1011 errClosed
= errors
.New("tls: use of closed connection")
1012 errShutdown
= errors
.New("tls: protocol is shutdown")
1015 // Write writes data to the connection.
1016 func (c
*Conn
) Write(b
[]byte) (int, error
) {
1017 // interlock with Close below
1019 x
:= atomic
.LoadInt32(&c
.activeCall
)
1023 if atomic
.CompareAndSwapInt32(&c
.activeCall
, x
, x
+2) {
1024 defer atomic
.AddInt32(&c
.activeCall
, -2)
1029 if err
:= c
.Handshake(); err
!= nil {
1034 defer c
.out
.Unlock()
1036 if err
:= c
.out
.err
; err
!= nil {
1040 if !c
.handshakeComplete
{
1041 return 0, alertInternalError
1044 if c
.closeNotifySent
{
1045 return 0, errShutdown
1048 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
1049 // attack when using block mode ciphers due to predictable IVs.
1050 // This can be prevented by splitting each Application Data
1051 // record into two records, effectively randomizing the IV.
1053 // http://www.openssl.org/~bodo/tls-cbc.txt
1054 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
1055 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
1058 if len(b
) > 1 && c
.vers
<= VersionTLS10
{
1059 if _
, ok
:= c
.out
.cipher
.(cipher
.BlockMode
); ok
{
1060 n
, err
:= c
.writeRecordLocked(recordTypeApplicationData
, b
[:1])
1062 return n
, c
.out
.setErrorLocked(err
)
1068 n
, err
:= c
.writeRecordLocked(recordTypeApplicationData
, b
)
1069 return n
+ m
, c
.out
.setErrorLocked(err
)
1072 // handleRenegotiation processes a HelloRequest handshake message.
1074 func (c
*Conn
) handleRenegotiation() error
{
1075 msg
, err
:= c
.readHandshake()
1080 _
, ok
:= msg
.(*helloRequestMsg
)
1082 c
.sendAlert(alertUnexpectedMessage
)
1083 return alertUnexpectedMessage
1087 return c
.sendAlert(alertNoRenegotiation
)
1090 switch c
.config
.Renegotiation
{
1091 case RenegotiateNever
:
1092 return c
.sendAlert(alertNoRenegotiation
)
1093 case RenegotiateOnceAsClient
:
1094 if c
.handshakes
> 1 {
1095 return c
.sendAlert(alertNoRenegotiation
)
1097 case RenegotiateFreelyAsClient
:
1100 c
.sendAlert(alertInternalError
)
1101 return errors
.New("tls: unknown Renegotiation value")
1104 c
.handshakeMutex
.Lock()
1105 defer c
.handshakeMutex
.Unlock()
1107 c
.handshakeComplete
= false
1108 if c
.handshakeErr
= c
.clientHandshake(); c
.handshakeErr
== nil {
1111 return c
.handshakeErr
1114 // Read can be made to time out and return a net.Error with Timeout() == true
1115 // after a fixed time limit; see SetDeadline and SetReadDeadline.
1116 func (c
*Conn
) Read(b
[]byte) (n
int, err error
) {
1117 if err
= c
.Handshake(); err
!= nil {
1121 // Put this after Handshake, in case people were calling
1122 // Read(nil) for the side effect of the Handshake.
1129 // Some OpenSSL servers send empty records in order to randomize the
1130 // CBC IV. So this loop ignores a limited number of empty records.
1131 const maxConsecutiveEmptyRecords
= 100
1132 for emptyRecordCount
:= 0; emptyRecordCount
<= maxConsecutiveEmptyRecords
; emptyRecordCount
++ {
1133 for c
.input
== nil && c
.in
.err
== nil {
1134 if err
:= c
.readRecord(recordTypeApplicationData
); err
!= nil {
1135 // Soft error, like EAGAIN
1138 if c
.hand
.Len() > 0 {
1139 // We received handshake bytes, indicating the
1140 // start of a renegotiation.
1141 if err
:= c
.handleRenegotiation(); err
!= nil {
1146 if err
:= c
.in
.err
; err
!= nil {
1150 n
, err
= c
.input
.Read(b
)
1151 if c
.input
.off
>= len(c
.input
.data
) {
1152 c
.in
.freeBlock(c
.input
)
1156 // If a close-notify alert is waiting, read it so that
1157 // we can return (n, EOF) instead of (n, nil), to signal
1158 // to the HTTP response reading goroutine that the
1159 // connection is now closed. This eliminates a race
1160 // where the HTTP response reading goroutine would
1161 // otherwise not observe the EOF until its next read,
1162 // by which time a client goroutine might have already
1163 // tried to reuse the HTTP connection for a new
1165 // See https://codereview.appspot.com/76400046
1166 // and https://golang.org/issue/3514
1167 if ri
:= c
.rawInput
; ri
!= nil &&
1168 n
!= 0 && err
== nil &&
1169 c
.input
== nil && len(ri
.data
) > 0 && recordType(ri
.data
[0]) == recordTypeAlert
{
1170 if recErr
:= c
.readRecord(recordTypeApplicationData
); recErr
!= nil {
1171 err
= recErr
// will be io.EOF on closeNotify
1175 if n
!= 0 || err
!= nil {
1180 return 0, io
.ErrNoProgress
1183 // Close closes the connection.
1184 func (c
*Conn
) Close() error
{
1185 // Interlock with Conn.Write above.
1188 x
= atomic
.LoadInt32(&c
.activeCall
)
1192 if atomic
.CompareAndSwapInt32(&c
.activeCall
, x
, x|
1) {
1197 // io.Writer and io.Closer should not be used concurrently.
1198 // If Close is called while a Write is currently in-flight,
1199 // interpret that as a sign that this Close is really just
1200 // being used to break the Write and/or clean up resources and
1201 // avoid sending the alertCloseNotify, which may block
1202 // waiting on handshakeMutex or the c.out mutex.
1203 return c
.conn
.Close()
1208 c
.handshakeMutex
.Lock()
1209 if c
.handshakeComplete
{
1210 alertErr
= c
.closeNotify()
1212 c
.handshakeMutex
.Unlock()
1214 if err
:= c
.conn
.Close(); err
!= nil {
1220 var errEarlyCloseWrite
= errors
.New("tls: CloseWrite called before handshake complete")
1222 // CloseWrite shuts down the writing side of the connection. It should only be
1223 // called once the handshake has completed and does not call CloseWrite on the
1224 // underlying connection. Most callers should just use Close.
1225 func (c
*Conn
) CloseWrite() error
{
1226 c
.handshakeMutex
.Lock()
1227 defer c
.handshakeMutex
.Unlock()
1228 if !c
.handshakeComplete
{
1229 return errEarlyCloseWrite
1232 return c
.closeNotify()
1235 func (c
*Conn
) closeNotify() error
{
1237 defer c
.out
.Unlock()
1239 if !c
.closeNotifySent
{
1240 c
.closeNotifyErr
= c
.sendAlertLocked(alertCloseNotify
)
1241 c
.closeNotifySent
= true
1243 return c
.closeNotifyErr
1246 // Handshake runs the client or server handshake
1247 // protocol if it has not yet been run.
1248 // Most uses of this package need not call Handshake
1249 // explicitly: the first Read or Write will call it automatically.
1250 func (c
*Conn
) Handshake() error
{
1251 // c.handshakeErr and c.handshakeComplete are protected by
1252 // c.handshakeMutex. In order to perform a handshake, we need to lock
1253 // c.in also and c.handshakeMutex must be locked after c.in.
1255 // However, if a Read() operation is hanging then it'll be holding the
1256 // lock on c.in and so taking it here would cause all operations that
1257 // need to check whether a handshake is pending (such as Write) to
1260 // Thus we first take c.handshakeMutex to check whether a handshake is
1263 // If so then, previously, this code would unlock handshakeMutex and
1264 // then lock c.in and handshakeMutex in the correct order to run the
1265 // handshake. The problem was that it was possible for a Read to
1266 // complete the handshake once handshakeMutex was unlocked and then
1267 // keep c.in while waiting for network data. Thus a concurrent
1268 // operation could be blocked on c.in.
1270 // Thus handshakeCond is used to signal that a goroutine is committed
1271 // to running the handshake and other goroutines can wait on it if they
1272 // need. handshakeCond is protected by handshakeMutex.
1273 c
.handshakeMutex
.Lock()
1274 defer c
.handshakeMutex
.Unlock()
1277 if err
:= c
.handshakeErr
; err
!= nil {
1280 if c
.handshakeComplete
{
1283 if c
.handshakeCond
== nil {
1287 c
.handshakeCond
.Wait()
1290 // Set handshakeCond to indicate that this goroutine is committing to
1291 // running the handshake.
1292 c
.handshakeCond
= sync
.NewCond(&c
.handshakeMutex
)
1293 c
.handshakeMutex
.Unlock()
1298 c
.handshakeMutex
.Lock()
1300 // The handshake cannot have completed when handshakeMutex was unlocked
1301 // because this goroutine set handshakeCond.
1302 if c
.handshakeErr
!= nil || c
.handshakeComplete
{
1303 panic("handshake should not have been able to complete after handshakeCond was set")
1307 c
.handshakeErr
= c
.clientHandshake()
1309 c
.handshakeErr
= c
.serverHandshake()
1311 if c
.handshakeErr
== nil {
1314 // If an error occurred during the hadshake try to flush the
1315 // alert that might be left in the buffer.
1319 if c
.handshakeErr
== nil && !c
.handshakeComplete
{
1320 panic("handshake should have had a result.")
1323 // Wake any other goroutines that are waiting for this handshake to
1325 c
.handshakeCond
.Broadcast()
1326 c
.handshakeCond
= nil
1328 return c
.handshakeErr
1331 // ConnectionState returns basic TLS details about the connection.
1332 func (c
*Conn
) ConnectionState() ConnectionState
{
1333 c
.handshakeMutex
.Lock()
1334 defer c
.handshakeMutex
.Unlock()
1336 var state ConnectionState
1337 state
.HandshakeComplete
= c
.handshakeComplete
1338 state
.ServerName
= c
.serverName
1340 if c
.handshakeComplete
{
1341 state
.Version
= c
.vers
1342 state
.NegotiatedProtocol
= c
.clientProtocol
1343 state
.DidResume
= c
.didResume
1344 state
.NegotiatedProtocolIsMutual
= !c
.clientProtocolFallback
1345 state
.CipherSuite
= c
.cipherSuite
1346 state
.PeerCertificates
= c
.peerCertificates
1347 state
.VerifiedChains
= c
.verifiedChains
1348 state
.SignedCertificateTimestamps
= c
.scts
1349 state
.OCSPResponse
= c
.ocspResponse
1351 if c
.clientFinishedIsFirst
{
1352 state
.TLSUnique
= c
.clientFinished
[:]
1354 state
.TLSUnique
= c
.serverFinished
[:]
1362 // OCSPResponse returns the stapled OCSP response from the TLS server, if
1363 // any. (Only valid for client connections.)
1364 func (c
*Conn
) OCSPResponse() []byte {
1365 c
.handshakeMutex
.Lock()
1366 defer c
.handshakeMutex
.Unlock()
1368 return c
.ocspResponse
1371 // VerifyHostname checks that the peer certificate chain is valid for
1372 // connecting to host. If so, it returns nil; if not, it returns an error
1373 // describing the problem.
1374 func (c
*Conn
) VerifyHostname(host
string) error
{
1375 c
.handshakeMutex
.Lock()
1376 defer c
.handshakeMutex
.Unlock()
1378 return errors
.New("tls: VerifyHostname called on TLS server connection")
1380 if !c
.handshakeComplete
{
1381 return errors
.New("tls: handshake has not yet been performed")
1383 if len(c
.verifiedChains
) == 0 {
1384 return errors
.New("tls: handshake did not verify certificate chain")
1386 return c
.peerCertificates
[0].VerifyHostname(host
)