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
152 // incSeq increments the sequence number.
153 func (hc *halfConn) incSeq() {
154 for i := 7; i >= 0; i-- {
161 // Not allowed to let sequence number wrap.
162 // Instead, must renegotiate before it does.
163 // Not likely enough to bother.
164 panic("TLS: sequence number wraparound")
167 // resetSeq resets the sequence number to zero.
168 func (hc *halfConn) resetSeq() {
169 for i := range hc.seq {
174 // removePadding returns an unpadded slice, in constant time, which is a prefix
175 // of the input. It also returns a byte which is equal to 255 if the padding
176 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
177 func removePadding(payload []byte) ([]byte, byte) {
178 if len(payload) < 1 {
182 paddingLen := payload[len(payload)-1]
183 t := uint(len(payload)-1) - uint(paddingLen)
184 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
185 good := byte(int32(^t) >> 31)
187 toCheck := 255 // the maximum possible padding length
188 // The length of the padded data is public, so we can use an if here
189 if toCheck+1 > len(payload) {
190 toCheck = len(payload) - 1
193 for i := 0; i < toCheck; i++ {
194 t := uint(paddingLen) - uint(i)
195 // if i <= paddingLen then the MSB of t is zero
196 mask := byte(int32(^t) >> 31)
197 b := payload[len(payload)-1-i]
198 good &^= mask&paddingLen ^ mask&b
201 // We AND together the bits of good and replicate the result across
206 good = uint8(int8(good) >> 7)
208 toRemove := good&paddingLen + 1
209 return payload[:len(payload)-int(toRemove)], good
212 // removePaddingSSL30 is a replacement for removePadding in the case that the
213 // protocol version is SSLv3. In this version, the contents of the padding
214 // are random and cannot be checked.
215 func removePaddingSSL30(payload []byte) ([]byte, byte) {
216 if len(payload) < 1 {
220 paddingLen := int(payload[len(payload)-1]) + 1
221 if paddingLen > len(payload) {
225 return payload[:len(payload)-paddingLen], 255
228 func roundUp(a, b int) int {
232 // decrypt checks and strips the mac and decrypts the data in b.
233 func (hc *halfConn) decrypt(b *block) (bool, alert) {
235 payload := b.data[recordHeaderLen:]
239 macSize = hc.mac.Size()
242 paddingGood := byte(255)
245 if hc.cipher != nil {
246 switch c := hc.cipher.(type) {
248 c.XORKeyStream(payload, payload)
249 case cipher.BlockMode:
250 blockSize := c.BlockSize()
252 if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
253 return false, alertBadRecordMAC
256 c.CryptBlocks(payload, payload)
257 if hc.version == versionSSL30 {
258 payload, paddingGood = removePaddingSSL30(payload)
260 payload, paddingGood = removePadding(payload)
262 b.resize(recordHeaderLen + len(payload))
264 // note that we still have a timing side-channel in the
265 // MAC check, below. An attacker can align the record
266 // so that a correct padding will cause one less hash
267 // block to be calculated. Then they can iteratively
268 // decrypt a record by breaking each byte. See
269 // "Password Interception in a SSL/TLS Channel", Brice
272 // However, our behavior matches OpenSSL, so we leak
273 // only as much as they do.
275 panic("unknown cipher type")
281 if len(payload) < macSize {
282 return false, alertBadRecordMAC
285 // strip mac off payload, b.data
286 n := len(payload) - macSize
287 b.data[3] = byte(n >> 8)
289 b.resize(recordHeaderLen + n)
290 remoteMAC := payload[n:]
291 localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
294 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
295 return false, alertBadRecordMAC
297 hc.inDigestBuf = localMAC
303 // padToBlockSize calculates the needed padding block, if any, for a payload.
304 // On exit, prefix aliases payload and extends to the end of the last full
305 // block of payload. finalBlock is a fresh slice which contains the contents of
306 // any suffix of payload as well as the needed padding to make finalBlock a
308 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
309 overrun := len(payload) % blockSize
310 paddingLen := blockSize - overrun
311 prefix = payload[:len(payload)-overrun]
312 finalBlock = make([]byte, blockSize)
313 copy(finalBlock, payload[len(payload)-overrun:])
314 for i := overrun; i < blockSize; i++ {
315 finalBlock[i] = byte(paddingLen - 1)
320 // encrypt encrypts and macs the data in b.
321 func (hc *halfConn) encrypt(b *block) (bool, alert) {
324 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
328 b.resize(n + len(mac))
329 copy(b.data[n:], mac)
330 hc.outDigestBuf = mac
333 payload := b.data[recordHeaderLen:]
336 if hc.cipher != nil {
337 switch c := hc.cipher.(type) {
339 c.XORKeyStream(payload, payload)
340 case cipher.BlockMode:
341 prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
342 b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
343 c.CryptBlocks(b.data[recordHeaderLen:], prefix)
344 c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
346 panic("unknown cipher type")
350 // update length to include MAC and any block padding needed.
351 n := len(b.data) - recordHeaderLen
352 b.data[3] = byte(n >> 8)
358 // A block is a simple data buffer.
361 off int // index for Read
365 // resize resizes block to be n bytes, growing if necessary.
366 func (b *block) resize(n int) {
373 // reserve makes sure that block contains a capacity of at least n bytes.
374 func (b *block) reserve(n int) {
375 if cap(b.data) >= n {
385 data := make([]byte, len(b.data), m)
390 // readFromUntil reads from r into b until b contains at least n bytes
391 // or else returns an error.
392 func (b *block) readFromUntil(r io.Reader, n int) error {
394 if len(b.data) >= n {
398 // read until have enough.
401 m, err := r.Read(b.data[len(b.data):cap(b.data)])
402 b.data = b.data[0 : len(b.data)+m]
403 if len(b.data) >= n {
413 func (b *block) Read(p []byte) (n int, err error) {
414 n = copy(p, b.data[b.off:])
419 // newBlock allocates a new block, from hc's free list if possible.
420 func (hc *halfConn) newBlock() *block {
431 // freeBlock returns a block to hc's free list.
432 // The protocol is such that each side only has a block or two on
433 // its free list at a time, so there's no need to worry about
434 // trimming the list, etc.
435 func (hc *halfConn) freeBlock(b *block) {
440 // splitBlock splits a block after the first n bytes,
441 // returning a block with those n bytes and a
442 // block with the remainder. the latter may be nil.
443 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
444 if len(b.data) <= n {
448 bb.resize(len(b.data) - n)
449 copy(bb.data, b.data[n:])
454 // readRecord reads the next TLS record from the connection
455 // and updates the record layer state.
456 // c.in.Mutex <= L; c.input == nil.
457 func (c *Conn) readRecord(want recordType) error {
458 // Caller must be in sync with connection:
459 // handshake data if handshake not yet completed,
460 // else application data. (We don't support renegotiation.)
463 return c.sendAlert(alertInternalError)
464 case recordTypeHandshake, recordTypeChangeCipherSpec:
465 if c.handshakeComplete {
466 return c.sendAlert(alertInternalError)
468 case recordTypeApplicationData:
469 if !c.handshakeComplete {
470 return c.sendAlert(alertInternalError)
475 if c.rawInput == nil {
476 c.rawInput = c.in.newBlock()
480 // Read header, payload.
481 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
482 // RFC suggests that EOF without an alertCloseNotify is
483 // an error, but popular web sites seem to do this,
484 // so we can't make it an error.
485 // if err == io.EOF {
486 // err = io.ErrUnexpectedEOF
488 if e, ok := err.(net.Error); !ok || !e.Temporary() {
493 typ := recordType(b.data[0])
495 // No valid TLS record has a type of 0x80, however SSLv2 handshakes
496 // start with a uint16 length where the MSB is set and the first record
497 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
499 if want == recordTypeHandshake && typ == 0x80 {
500 c.sendAlert(alertProtocolVersion)
501 return errors.New("tls: unsupported SSLv2 handshake received")
504 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
505 n := int(b.data[3])<<8 | int(b.data[4])
506 if c.haveVers && vers != c.vers {
507 return c.sendAlert(alertProtocolVersion)
509 if n > maxCiphertext {
510 return c.sendAlert(alertRecordOverflow)
513 // First message, be extra suspicious:
514 // this might not be a TLS client.
515 // Bail out before reading a full 'body', if possible.
516 // The current max version is 3.1.
517 // If the version is >= 16.0, it's probably not real.
518 // Similarly, a clientHello message encodes in
519 // well under a kilobyte. If the length is >= 12 kB,
520 // it's probably not real.
521 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
522 return c.sendAlert(alertUnexpectedMessage)
525 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
527 err = io.ErrUnexpectedEOF
529 if e, ok := err.(net.Error); !ok || !e.Temporary() {
536 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
537 b.off = recordHeaderLen
538 if ok, err := c.in.decrypt(b); !ok {
539 return c.sendAlert(err)
541 data := b.data[b.off:]
542 if len(data) > maxPlaintext {
543 c.sendAlert(alertRecordOverflow)
550 c.sendAlert(alertUnexpectedMessage)
552 case recordTypeAlert:
554 c.sendAlert(alertUnexpectedMessage)
557 if alert(data[1]) == alertCloseNotify {
562 case alertLevelWarning:
566 case alertLevelError:
567 c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
569 c.sendAlert(alertUnexpectedMessage)
572 case recordTypeChangeCipherSpec:
573 if typ != want || len(data) != 1 || data[0] != 1 {
574 c.sendAlert(alertUnexpectedMessage)
577 err := c.in.changeCipherSpec()
579 c.sendAlert(err.(alert))
582 case recordTypeApplicationData:
584 c.sendAlert(alertUnexpectedMessage)
590 case recordTypeHandshake:
591 // TODO(rsc): Should at least pick off connection close.
593 return c.sendAlert(alertNoRenegotiation)
604 // sendAlert sends a TLS alert message.
606 func (c *Conn) sendAlertLocked(err alert) error {
608 case alertNoRenegotiation, alertCloseNotify:
609 c.tmp[0] = alertLevelWarning
611 c.tmp[0] = alertLevelError
614 c.writeRecord(recordTypeAlert, c.tmp[0:2])
615 // closeNotify is a special case in that it isn't an error:
616 if err != alertCloseNotify {
617 return c.setError(&net.OpError{Op: "local error", Err: err})
622 // sendAlert sends a TLS alert message.
624 func (c *Conn) sendAlert(err alert) error {
627 return c.sendAlertLocked(err)
630 // writeRecord writes a TLS record with the given type and payload
631 // to the connection and updates the record layer state.
633 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
634 b := c.out.newBlock()
637 if m > maxPlaintext {
640 b.resize(recordHeaderLen + m)
641 b.data[0] = byte(typ)
646 b.data[1] = byte(vers >> 8)
647 b.data[2] = byte(vers)
648 b.data[3] = byte(m >> 8)
650 copy(b.data[recordHeaderLen:], data)
652 _, err = c.conn.Write(b.data)
661 if typ == recordTypeChangeCipherSpec {
662 err = c.out.changeCipherSpec()
664 // Cannot call sendAlert directly,
665 // because we already hold c.out.Mutex.
666 c.tmp[0] = alertLevelError
667 c.tmp[1] = byte(err.(alert))
668 c.writeRecord(recordTypeAlert, c.tmp[0:2])
669 return n, c.setError(&net.OpError{Op: "local error", Err: err})
675 // readHandshake reads the next handshake message from
677 // c.in.Mutex < L; c.out.Mutex < L.
678 func (c *Conn) readHandshake() (interface{}, error) {
679 for c.hand.Len() < 4 {
680 if err := c.error(); err != nil {
683 if err := c.readRecord(recordTypeHandshake); err != nil {
688 data := c.hand.Bytes()
689 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
690 if n > maxHandshake {
691 c.sendAlert(alertInternalError)
692 return nil, c.error()
694 for c.hand.Len() < 4+n {
695 if err := c.error(); err != nil {
698 if err := c.readRecord(recordTypeHandshake); err != nil {
702 data = c.hand.Next(4 + n)
703 var m handshakeMessage
705 case typeClientHello:
706 m = new(clientHelloMsg)
707 case typeServerHello:
708 m = new(serverHelloMsg)
709 case typeCertificate:
710 m = new(certificateMsg)
711 case typeCertificateRequest:
712 m = new(certificateRequestMsg)
713 case typeCertificateStatus:
714 m = new(certificateStatusMsg)
715 case typeServerKeyExchange:
716 m = new(serverKeyExchangeMsg)
717 case typeServerHelloDone:
718 m = new(serverHelloDoneMsg)
719 case typeClientKeyExchange:
720 m = new(clientKeyExchangeMsg)
721 case typeCertificateVerify:
722 m = new(certificateVerifyMsg)
723 case typeNextProtocol:
724 m = new(nextProtoMsg)
728 c.sendAlert(alertUnexpectedMessage)
729 return nil, alertUnexpectedMessage
732 // The handshake message unmarshallers
733 // expect to be able to keep references to data,
734 // so pass in a fresh copy that won't be overwritten.
735 data = append([]byte(nil), data...)
737 if !m.unmarshal(data) {
738 c.sendAlert(alertUnexpectedMessage)
739 return nil, alertUnexpectedMessage
744 // Write writes data to the connection.
745 func (c *Conn) Write(b []byte) (int, error) {
746 if err := c.error(); err != nil {
750 if err := c.Handshake(); err != nil {
751 return 0, c.setError(err)
757 if !c.handshakeComplete {
758 return 0, alertInternalError
761 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
762 // attack when using block mode ciphers due to predictable IVs.
763 // This can be prevented by splitting each Application Data
764 // record into two records, effectively randomizing the IV.
766 // http://www.openssl.org/~bodo/tls-cbc.txt
767 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
768 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
771 if len(b) > 1 && c.vers <= versionTLS10 {
772 if _, ok := c.out.cipher.(cipher.BlockMode); ok {
773 n, err := c.writeRecord(recordTypeApplicationData, b[:1])
775 return n, c.setError(err)
781 n, err := c.writeRecord(recordTypeApplicationData, b)
782 return n + m, c.setError(err)
785 // Read can be made to time out and return a net.Error with Timeout() == true
786 // after a fixed time limit; see SetDeadline and SetReadDeadline.
787 func (c *Conn) Read(b []byte) (n int, err error) {
788 if err = c.Handshake(); err != nil {
795 for c.input == nil && c.error() == nil {
796 if err := c.readRecord(recordTypeApplicationData); err != nil {
797 // Soft error, like EAGAIN
801 if err := c.error(); err != nil {
804 n, err = c.input.Read(b)
805 if c.input.off >= len(c.input.data) {
806 c.in.freeBlock(c.input)
812 // Close closes the connection.
813 func (c *Conn) Close() error {
816 c.handshakeMutex.Lock()
817 defer c.handshakeMutex.Unlock()
818 if c.handshakeComplete {
819 alertErr = c.sendAlert(alertCloseNotify)
822 if err := c.conn.Close(); err != nil {
828 // Handshake runs the client or server handshake
829 // protocol if it has not yet been run.
830 // Most uses of this package need not call Handshake
831 // explicitly: the first Read or Write will call it automatically.
832 func (c *Conn) Handshake() error {
833 c.handshakeMutex.Lock()
834 defer c.handshakeMutex.Unlock()
835 if err := c.error(); err != nil {
838 if c.handshakeComplete {
842 return c.clientHandshake()
844 return c.serverHandshake()
847 // ConnectionState returns basic TLS details about the connection.
848 func (c *Conn) ConnectionState() ConnectionState {
849 c.handshakeMutex.Lock()
850 defer c.handshakeMutex.Unlock()
852 var state ConnectionState
853 state.HandshakeComplete = c.handshakeComplete
854 if c.handshakeComplete {
855 state.NegotiatedProtocol = c.clientProtocol
856 state.DidResume = c.didResume
857 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
858 state.CipherSuite = c.cipherSuite
859 state.PeerCertificates = c.peerCertificates
860 state.VerifiedChains = c.verifiedChains
861 state.ServerName = c.serverName
867 // OCSPResponse returns the stapled OCSP response from the TLS server, if
868 // any. (Only valid for client connections.)
869 func (c *Conn) OCSPResponse() []byte {
870 c.handshakeMutex.Lock()
871 defer c.handshakeMutex.Unlock()
873 return c.ocspResponse
876 // VerifyHostname checks that the peer certificate chain is valid for
877 // connecting to host. If so, it returns nil; if not, it returns an error
878 // describing the problem.
879 func (c *Conn) VerifyHostname(host string) error {
880 c.handshakeMutex.Lock()
881 defer c.handshakeMutex.Unlock()
883 return errors.New("VerifyHostname called on TLS server connection")
885 if !c.handshakeComplete {
886 return errors.New("TLS handshake has not yet been performed")
888 return c.peerCertificates[0].VerifyHostname(host)