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.
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
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.
49 clientProtocolFallback bool
52 channelID *ecdsa.PublicKey
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
61 sendHandshakeSeq uint16
62 recvHandshakeSeq uint16
63 handMsg []byte // pending assembled handshake message
64 handMsgLen int // handshake message length, not including the header
69 // Access to net.Conn methods.
70 // Cannot just embed net.Conn because that would
71 // export the struct field too.
73 // LocalAddr returns the local network address.
74 func (c *Conn) LocalAddr() net.Addr {
75 return c.conn.LocalAddr()
78 // RemoteAddr returns the remote network address.
79 func (c *Conn) RemoteAddr() net.Addr {
80 return c.conn.RemoteAddr()
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)
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)
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)
103 // A halfConn represents one direction of the record layer
104 // connection, either sending or receiving.
105 type halfConn struct {
108 err error // first permanent error
109 version uint16 // protocol version
111 cipher interface{} // cipher algorithm
113 seq [8]byte // 64-bit sequence number
114 bfree *block // list of free blocks
116 nextCipher interface{} // next encryption state
117 nextMac macFunction // next MAC algorithm
119 // used to save allocating a new buffer for each MAC.
120 inDigestBuf, outDigestBuf []byte
125 func (hc *halfConn) setErrorLocked(err error) error {
130 func (hc *halfConn) error() error {
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) {
141 hc.nextCipher = cipher
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
151 hc.cipher = hc.nextCipher
160 // incSeq increments the sequence number.
161 func (hc *halfConn) incSeq() {
164 // Increment up to the epoch in DTLS.
167 for i := 7; i >= limit; i-- {
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")
180 // incEpoch resets the sequence number. In DTLS, it increments the
181 // epoch half of the sequence number.
182 func (hc *halfConn) incEpoch() {
185 for i := 1; i >= 0; i-- {
191 panic("TLS: epoch number wraparound")
196 seq := hc.seq[limit:]
202 func (hc *halfConn) recordHeaderLen() int {
204 return dtlsRecordHeaderLen
206 return tlsRecordHeaderLen
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 {
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)
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
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
236 // We AND together the bits of good and replicate the result across
241 good = uint8(int8(good) >> 7)
243 toRemove := good&paddingLen + 1
244 return payload[:len(payload)-int(toRemove)], good
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 {
255 paddingLen := int(payload[len(payload)-1]) + 1
256 if paddingLen > len(payload) {
260 return payload[:len(payload)-paddingLen], 255
263 func roundUp(a, b int) int {
267 // cbcMode is an interface for block ciphers using cipher block chaining.
268 type cbcMode interface {
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()
280 payload := b.data[recordHeaderLen:]
284 macSize = hc.mac.Size()
287 paddingGood := byte(255)
292 // DTLS sequence numbers are explicit.
297 if hc.cipher != nil {
298 switch c := hc.cipher.(type) {
300 c.XORKeyStream(payload, payload)
303 if len(payload) < explicitIVLen {
304 return false, 0, alertBadRecordMAC
307 payload = payload[8:]
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)
316 payload, err = c.Open(payload[:0], nonce, payload, additionalData[:])
318 return false, 0, alertBadRecordMAC
320 b.resize(recordHeaderLen + explicitIVLen + len(payload))
322 blockSize := c.BlockSize()
323 if hc.version >= VersionTLS11 || hc.isDTLS {
324 explicitIVLen = blockSize
327 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
328 return false, 0, alertBadRecordMAC
331 if explicitIVLen > 0 {
332 c.SetIV(payload[:explicitIVLen])
333 payload = payload[explicitIVLen:]
335 c.CryptBlocks(payload, payload)
336 if hc.version == VersionSSL30 {
337 payload, paddingGood = removePaddingSSL30(payload)
339 payload, paddingGood = removePadding(payload)
341 b.resize(recordHeaderLen + explicitIVLen + len(payload))
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
351 // However, our behavior matches OpenSSL, so we leak
352 // only as much as they do.
354 panic("unknown cipher type")
360 if len(payload) < macSize {
361 return false, 0, alertBadRecordMAC
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])
372 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
373 return false, 0, alertBadRecordMAC
375 hc.inDigestBuf = localMAC
379 return true, recordHeaderLen + explicitIVLen, 0
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
387 func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) {
388 overrun := len(payload) % blockSize
389 prefix = payload[:len(payload)-overrun]
391 paddingLen := blockSize - overrun
392 finalSize := blockSize
393 if config.Bugs.MaxPadding {
394 for paddingLen+blockSize <= 256 {
395 paddingLen += blockSize
399 finalBlock = make([]byte, finalSize)
400 for i := range finalBlock {
401 finalBlock[i] = byte(paddingLen - 1)
403 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 {
404 finalBlock[overrun] ^= 0xff
406 copy(finalBlock, payload[len(payload)-overrun:])
410 // encrypt encrypts and macs the data in b.
411 func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
412 recordHeaderLen := hc.recordHeaderLen()
416 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:])
419 b.resize(n + len(mac))
420 copy(b.data[n:], mac)
421 hc.outDigestBuf = mac
424 payload := b.data[recordHeaderLen:]
427 if hc.cipher != nil {
428 switch c := hc.cipher.(type) {
430 c.XORKeyStream(payload, payload)
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]
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)
444 c.Seal(payload[:0], nonce, payload, additionalData[:])
446 blockSize := c.BlockSize()
447 if explicitIVLen > 0 {
448 c.SetIV(payload[:explicitIVLen])
449 payload = payload[explicitIVLen:]
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)
456 panic("unknown cipher type")
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)
469 // A block is a simple data buffer.
472 off int // index for Read
476 // resize resizes block to be n bytes, growing if necessary.
477 func (b *block) resize(n int) {
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 {
496 data := make([]byte, len(b.data), m)
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 {
505 if len(b.data) >= n {
509 // read until have enough.
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.
526 func (b *block) Read(p []byte) (n int, err error) {
527 n = copy(p, b.data[b.off:])
532 // newBlock allocates a new block, from hc's free list if possible.
533 func (hc *halfConn) newBlock() *block {
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) {
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 {
561 bb.resize(len(b.data) - n)
562 copy(bb.data, b.data[n:])
567 func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) {
569 return c.dtlsDoReadRecord(want)
572 recordHeaderLen := tlsRecordHeaderLen
574 if c.rawInput == nil {
575 c.rawInput = c.in.newBlock()
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
587 if e, ok := err.(net.Error); !ok || !e.Temporary() {
588 c.in.setErrorLocked(err)
592 typ := recordType(b.data[0])
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
598 if want == recordTypeHandshake && typ == 0x80 {
599 c.sendAlert(alertProtocolVersion)
600 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received"))
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))
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))
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"))
627 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
629 err = io.ErrUnexpectedEOF
631 if e, ok := err.(net.Error); !ok || !e.Temporary() {
632 c.in.setErrorLocked(err)
638 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
639 ok, off, err := c.in.decrypt(b)
641 c.in.setErrorLocked(c.sendAlert(err))
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.)
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"))
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"))
671 typ, b, err := c.doReadRecord(want)
675 data := b.data[b.off:]
676 if len(data) > maxPlaintext {
677 err := c.sendAlert(alertRecordOverflow)
679 return c.in.setErrorLocked(err)
684 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
686 case recordTypeAlert:
688 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
691 if alert(data[1]) == alertCloseNotify {
692 c.in.setErrorLocked(io.EOF)
696 case alertLevelWarning:
700 case alertLevelError:
701 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
703 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
706 case recordTypeChangeCipherSpec:
707 if typ != want || len(data) != 1 || data[0] != 1 {
708 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
711 err := c.in.changeCipherSpec(c.config)
713 c.in.setErrorLocked(c.sendAlert(err.(alert)))
716 case recordTypeApplicationData:
718 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
724 case recordTypeHandshake:
725 // TODO(rsc): Should at least pick off connection close.
727 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
738 // sendAlert sends a TLS alert message.
740 func (c *Conn) sendAlertLocked(err alert) error {
742 case alertNoRenegotiation, alertCloseNotify:
743 c.tmp[0] = alertLevelWarning
745 c.tmp[0] = alertLevelError
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})
756 // sendAlert sends a TLS alert message.
758 func (c *Conn) sendAlert(err alert) error {
761 return c.sendAlertLocked(err)
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)
773 // writeRecord writes a TLS record with the given type and payload
774 // to the connection and updates the record layer state.
776 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
778 return c.dtlsWriteRecord(typ, data)
781 recordHeaderLen := tlsRecordHeaderLen
782 b := c.out.newBlock()
784 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello
787 if m > maxPlaintext {
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
795 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 {
800 explicitIVIsSeq := false
804 if c.out.version >= VersionTLS11 {
806 if cbc, ok = c.out.cipher.(cbcMode); ok {
807 explicitIVLen = cbc.BlockSize()
810 if explicitIVLen == 0 {
811 if _, ok := c.out.cipher.(cipher.AEAD); ok {
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
819 explicitIVIsSeq = true
822 b.resize(recordHeaderLen + explicitIVLen + m)
823 b.data[0] = byte(typ)
826 // Some TLS servers fail if the record version is
827 // greater than TLS 1.0 for the initial ClientHello.
830 b.data[1] = byte(vers >> 8)
831 b.data[2] = byte(vers)
832 b.data[3] = byte(m >> 8)
834 if explicitIVLen > 0 {
835 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
837 copy(explicitIV, c.out.seq[:])
839 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil {
844 copy(b.data[recordHeaderLen+explicitIVLen:], data)
845 c.out.encrypt(b, explicitIVLen)
846 _, err = c.conn.Write(b.data)
855 if typ == recordTypeChangeCipherSpec {
856 err = c.out.changeCipherSpec(c.config)
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})
869 func (c *Conn) doReadHandshake() ([]byte, error) {
871 return c.dtlsDoReadHandshake()
874 for c.hand.Len() < 4 {
875 if err := c.in.err; err != nil {
878 if err := c.readRecord(recordTypeHandshake); err != nil {
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))
888 for c.hand.Len() < 4+n {
889 if err := c.in.err; err != nil {
892 if err := c.readRecord(recordTypeHandshake); err != nil {
896 return c.hand.Next(4 + n), nil
899 // readHandshake reads the next handshake message from
901 // c.in.Mutex < L; c.out.Mutex < L.
902 func (c *Conn) readHandshake() (interface{}, error) {
903 data, err := c.doReadHandshake()
908 var m handshakeMessage
910 case typeClientHello:
914 case typeServerHello:
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,
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,
938 case typeNextProtocol:
939 m = new(nextProtoMsg)
942 case typeHelloVerifyRequest:
943 m = new(helloVerifyRequestMsg)
944 case typeEncryptedExtensions:
945 m = new(encryptedExtensionsMsg)
947 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
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...)
955 if !m.unmarshal(data) {
956 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
961 // Write writes data to the connection.
962 func (c *Conn) Write(b []byte) (int, error) {
963 if err := c.Handshake(); err != nil {
970 if err := c.out.err; err != nil {
974 if !c.handshakeComplete {
975 return 0, alertInternalError
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.
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
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])
992 return n, c.out.setErrorLocked(err)
998 n, err := c.writeRecord(recordTypeApplicationData, b)
999 return n + m, c.out.setErrorLocked(err)
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 {
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
1022 if err := c.in.err; err != nil {
1026 n, err = c.input.Read(b)
1027 if c.input.off >= len(c.input.data) || c.isDTLS {
1028 c.in.freeBlock(c.input)
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
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
1051 if n != 0 || err != nil {
1056 return 0, io.ErrNoProgress
1059 // Close closes the connection.
1060 func (c *Conn) Close() error {
1063 c.handshakeMutex.Lock()
1064 defer c.handshakeMutex.Unlock()
1065 if c.handshakeComplete {
1066 alertErr = c.sendAlert(alertCloseNotify)
1069 if err := c.conn.Close(); err != nil {
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 {
1085 if c.handshakeComplete {
1090 c.handshakeErr = c.clientHandshake()
1092 c.handshakeErr = c.serverHandshake()
1094 return c.handshakeErr
1097 // ConnectionState returns basic TLS details about the connection.
1098 func (c *Conn) ConnectionState() ConnectionState {
1099 c.handshakeMutex.Lock()
1100 defer c.handshakeMutex.Unlock()
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
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()
1126 return c.ocspResponse
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()
1136 return errors.New("tls: VerifyHostname called on TLS server connection")
1138 if !c.handshakeComplete {
1139 return errors.New("tls: handshake has not yet been performed")
1141 return c.peerCertificates[0].VerifyHostname(host)