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
35 ocspResponse []byte // stapled OCSP response
36 peerCertificates []*x509.Certificate
37 // verifiedChains contains the certificate chains that we built, as
38 // opposed to the ones presented by the server.
39 verifiedChains [][]*x509.Certificate
40 // serverName contains the server name indicated by the client, if any.
44 clientProtocolFallback bool
46 // 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
59 func (c *Conn) setError(err error) error {
61 defer c.errMutex.Unlock()
69 func (c *Conn) error() error {
71 defer c.errMutex.Unlock()
76 // Access to net.Conn methods.
77 // Cannot just embed net.Conn because that would
78 // export the struct field too.
80 // LocalAddr returns the local network address.
81 func (c *Conn) LocalAddr() net.Addr {
82 return c.conn.LocalAddr()
85 // RemoteAddr returns the remote network address.
86 func (c *Conn) RemoteAddr() net.Addr {
87 return c.conn.RemoteAddr()
90 // SetDeadline sets the read and write deadlines associated with the connection.
91 // A zero value for t means Read and Write will not time out.
92 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
93 func (c *Conn) SetDeadline(t time.Time) error {
94 return c.conn.SetDeadline(t)
97 // SetReadDeadline sets the read deadline on the underlying connection.
98 // A zero value for t means Read will not time out.
99 func (c *Conn) SetReadDeadline(t time.Time) error {
100 return c.conn.SetReadDeadline(t)
103 // SetWriteDeadline sets the write deadline on the underlying conneciton.
104 // A zero value for t means Write will not time out.
105 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
106 func (c *Conn) SetWriteDeadline(t time.Time) error {
107 return c.conn.SetWriteDeadline(t)
110 // A halfConn represents one direction of the record layer
111 // connection, either sending or receiving.
112 type halfConn struct {
114 version uint16 // protocol version
115 cipher interface{} // cipher algorithm
117 seq [8]byte // 64-bit sequence number
118 bfree *block // list of free blocks
120 nextCipher interface{} // next encryption state
121 nextMac macFunction // next MAC algorithm
123 // used to save allocating a new buffer for each MAC.
124 inDigestBuf, outDigestBuf []byte
127 // prepareCipherSpec sets the encryption and MAC states
128 // that a subsequent changeCipherSpec will use.
129 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
131 hc.nextCipher = cipher
135 // changeCipherSpec changes the encryption and MAC states
136 // to the ones previously passed to prepareCipherSpec.
137 func (hc *halfConn) changeCipherSpec() error {
138 if hc.nextCipher == nil {
139 return alertInternalError
141 hc.cipher = hc.nextCipher
148 // incSeq increments the sequence number.
149 func (hc *halfConn) incSeq() {
150 for i := 7; i >= 0; i-- {
157 // Not allowed to let sequence number wrap.
158 // Instead, must renegotiate before it does.
159 // Not likely enough to bother.
160 panic("TLS: sequence number wraparound")
163 // resetSeq resets the sequence number to zero.
164 func (hc *halfConn) resetSeq() {
165 for i := range hc.seq {
170 // removePadding returns an unpadded slice, in constant time, which is a prefix
171 // of the input. It also returns a byte which is equal to 255 if the padding
172 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
173 func removePadding(payload []byte) ([]byte, byte) {
174 if len(payload) < 1 {
178 paddingLen := payload[len(payload)-1]
179 t := uint(len(payload)-1) - uint(paddingLen)
180 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
181 good := byte(int32(^t) >> 31)
183 toCheck := 255 // the maximum possible padding length
184 // The length of the padded data is public, so we can use an if here
185 if toCheck+1 > len(payload) {
186 toCheck = len(payload) - 1
189 for i := 0; i < toCheck; i++ {
190 t := uint(paddingLen) - uint(i)
191 // if i <= paddingLen then the MSB of t is zero
192 mask := byte(int32(^t) >> 31)
193 b := payload[len(payload)-1-i]
194 good &^= mask&paddingLen ^ mask&b
197 // We AND together the bits of good and replicate the result across
202 good = uint8(int8(good) >> 7)
204 toRemove := good&paddingLen + 1
205 return payload[:len(payload)-int(toRemove)], good
208 // removePaddingSSL30 is a replacement for removePadding in the case that the
209 // protocol version is SSLv3. In this version, the contents of the padding
210 // are random and cannot be checked.
211 func removePaddingSSL30(payload []byte) ([]byte, byte) {
212 if len(payload) < 1 {
216 paddingLen := int(payload[len(payload)-1]) + 1
217 if paddingLen > len(payload) {
221 return payload[:len(payload)-paddingLen], 255
224 func roundUp(a, b int) int {
228 // decrypt checks and strips the mac and decrypts the data in b.
229 func (hc *halfConn) decrypt(b *block) (bool, alert) {
231 payload := b.data[recordHeaderLen:]
235 macSize = hc.mac.Size()
238 paddingGood := byte(255)
241 if hc.cipher != nil {
242 switch c := hc.cipher.(type) {
244 c.XORKeyStream(payload, payload)
245 case cipher.BlockMode:
246 blockSize := c.BlockSize()
248 if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
249 return false, alertBadRecordMAC
252 c.CryptBlocks(payload, payload)
253 if hc.version == versionSSL30 {
254 payload, paddingGood = removePaddingSSL30(payload)
256 payload, paddingGood = removePadding(payload)
258 b.resize(recordHeaderLen + len(payload))
260 // note that we still have a timing side-channel in the
261 // MAC check, below. An attacker can align the record
262 // so that a correct padding will cause one less hash
263 // block to be calculated. Then they can iteratively
264 // decrypt a record by breaking each byte. See
265 // "Password Interception in a SSL/TLS Channel", Brice
268 // However, our behavior matches OpenSSL, so we leak
269 // only as much as they do.
271 panic("unknown cipher type")
277 if len(payload) < macSize {
278 return false, alertBadRecordMAC
281 // strip mac off payload, b.data
282 n := len(payload) - macSize
283 b.data[3] = byte(n >> 8)
285 b.resize(recordHeaderLen + n)
286 remoteMAC := payload[n:]
287 localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
290 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
291 return false, alertBadRecordMAC
293 hc.inDigestBuf = localMAC
299 // padToBlockSize calculates the needed padding block, if any, for a payload.
300 // On exit, prefix aliases payload and extends to the end of the last full
301 // block of payload. finalBlock is a fresh slice which contains the contents of
302 // any suffix of payload as well as the needed padding to make finalBlock a
304 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
305 overrun := len(payload) % blockSize
306 paddingLen := blockSize - overrun
307 prefix = payload[:len(payload)-overrun]
308 finalBlock = make([]byte, blockSize)
309 copy(finalBlock, payload[len(payload)-overrun:])
310 for i := overrun; i < blockSize; i++ {
311 finalBlock[i] = byte(paddingLen - 1)
316 // encrypt encrypts and macs the data in b.
317 func (hc *halfConn) encrypt(b *block) (bool, alert) {
320 mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
324 b.resize(n + len(mac))
325 copy(b.data[n:], mac)
326 hc.outDigestBuf = mac
329 payload := b.data[recordHeaderLen:]
332 if hc.cipher != nil {
333 switch c := hc.cipher.(type) {
335 c.XORKeyStream(payload, payload)
336 case cipher.BlockMode:
337 prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
338 b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
339 c.CryptBlocks(b.data[recordHeaderLen:], prefix)
340 c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
342 panic("unknown cipher type")
346 // update length to include MAC and any block padding needed.
347 n := len(b.data) - recordHeaderLen
348 b.data[3] = byte(n >> 8)
354 // A block is a simple data buffer.
357 off int // index for Read
361 // resize resizes block to be n bytes, growing if necessary.
362 func (b *block) resize(n int) {
369 // reserve makes sure that block contains a capacity of at least n bytes.
370 func (b *block) reserve(n int) {
371 if cap(b.data) >= n {
381 data := make([]byte, len(b.data), m)
386 // readFromUntil reads from r into b until b contains at least n bytes
387 // or else returns an error.
388 func (b *block) readFromUntil(r io.Reader, n int) error {
390 if len(b.data) >= n {
394 // read until have enough.
397 m, err := r.Read(b.data[len(b.data):cap(b.data)])
398 b.data = b.data[0 : len(b.data)+m]
399 if len(b.data) >= n {
409 func (b *block) Read(p []byte) (n int, err error) {
410 n = copy(p, b.data[b.off:])
415 // newBlock allocates a new block, from hc's free list if possible.
416 func (hc *halfConn) newBlock() *block {
427 // freeBlock returns a block to hc's free list.
428 // The protocol is such that each side only has a block or two on
429 // its free list at a time, so there's no need to worry about
430 // trimming the list, etc.
431 func (hc *halfConn) freeBlock(b *block) {
436 // splitBlock splits a block after the first n bytes,
437 // returning a block with those n bytes and a
438 // block with the remainder. the latter may be nil.
439 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
440 if len(b.data) <= n {
444 bb.resize(len(b.data) - n)
445 copy(bb.data, b.data[n:])
450 // readRecord reads the next TLS record from the connection
451 // and updates the record layer state.
452 // c.in.Mutex <= L; c.input == nil.
453 func (c *Conn) readRecord(want recordType) error {
454 // Caller must be in sync with connection:
455 // handshake data if handshake not yet completed,
456 // else application data. (We don't support renegotiation.)
459 return c.sendAlert(alertInternalError)
460 case recordTypeHandshake, recordTypeChangeCipherSpec:
461 if c.handshakeComplete {
462 return c.sendAlert(alertInternalError)
464 case recordTypeApplicationData:
465 if !c.handshakeComplete {
466 return c.sendAlert(alertInternalError)
471 if c.rawInput == nil {
472 c.rawInput = c.in.newBlock()
476 // Read header, payload.
477 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
478 // RFC suggests that EOF without an alertCloseNotify is
479 // an error, but popular web sites seem to do this,
480 // so we can't make it an error.
481 // if err == io.EOF {
482 // err = io.ErrUnexpectedEOF
484 if e, ok := err.(net.Error); !ok || !e.Temporary() {
489 typ := recordType(b.data[0])
490 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
491 n := int(b.data[3])<<8 | int(b.data[4])
492 if c.haveVers && vers != c.vers {
493 return c.sendAlert(alertProtocolVersion)
495 if n > maxCiphertext {
496 return c.sendAlert(alertRecordOverflow)
499 // First message, be extra suspicious:
500 // this might not be a TLS client.
501 // Bail out before reading a full 'body', if possible.
502 // The current max version is 3.1.
503 // If the version is >= 16.0, it's probably not real.
504 // Similarly, a clientHello message encodes in
505 // well under a kilobyte. If the length is >= 12 kB,
506 // it's probably not real.
507 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
508 return c.sendAlert(alertUnexpectedMessage)
511 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
513 err = io.ErrUnexpectedEOF
515 if e, ok := err.(net.Error); !ok || !e.Temporary() {
522 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
523 b.off = recordHeaderLen
524 if ok, err := c.in.decrypt(b); !ok {
525 return c.sendAlert(err)
527 data := b.data[b.off:]
528 if len(data) > maxPlaintext {
529 c.sendAlert(alertRecordOverflow)
536 c.sendAlert(alertUnexpectedMessage)
538 case recordTypeAlert:
540 c.sendAlert(alertUnexpectedMessage)
543 if alert(data[1]) == alertCloseNotify {
548 case alertLevelWarning:
552 case alertLevelError:
553 c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
555 c.sendAlert(alertUnexpectedMessage)
558 case recordTypeChangeCipherSpec:
559 if typ != want || len(data) != 1 || data[0] != 1 {
560 c.sendAlert(alertUnexpectedMessage)
563 err := c.in.changeCipherSpec()
565 c.sendAlert(err.(alert))
568 case recordTypeApplicationData:
570 c.sendAlert(alertUnexpectedMessage)
576 case recordTypeHandshake:
577 // TODO(rsc): Should at least pick off connection close.
579 return c.sendAlert(alertNoRenegotiation)
590 // sendAlert sends a TLS alert message.
592 func (c *Conn) sendAlertLocked(err alert) error {
593 c.tmp[0] = alertLevelError
594 if err == alertNoRenegotiation {
595 c.tmp[0] = alertLevelWarning
598 c.writeRecord(recordTypeAlert, c.tmp[0:2])
599 // closeNotify is a special case in that it isn't an error:
600 if err != alertCloseNotify {
601 return c.setError(&net.OpError{Op: "local error", Err: err})
606 // sendAlert sends a TLS alert message.
608 func (c *Conn) sendAlert(err alert) error {
611 return c.sendAlertLocked(err)
614 // writeRecord writes a TLS record with the given type and payload
615 // to the connection and updates the record layer state.
617 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
618 b := c.out.newBlock()
621 if m > maxPlaintext {
624 b.resize(recordHeaderLen + m)
625 b.data[0] = byte(typ)
630 b.data[1] = byte(vers >> 8)
631 b.data[2] = byte(vers)
632 b.data[3] = byte(m >> 8)
634 copy(b.data[recordHeaderLen:], data)
636 _, err = c.conn.Write(b.data)
645 if typ == recordTypeChangeCipherSpec {
646 err = c.out.changeCipherSpec()
648 // Cannot call sendAlert directly,
649 // because we already hold c.out.Mutex.
650 c.tmp[0] = alertLevelError
651 c.tmp[1] = byte(err.(alert))
652 c.writeRecord(recordTypeAlert, c.tmp[0:2])
653 c.err = &net.OpError{Op: "local error", Err: err}
660 // readHandshake reads the next handshake message from
662 // c.in.Mutex < L; c.out.Mutex < L.
663 func (c *Conn) readHandshake() (interface{}, error) {
664 for c.hand.Len() < 4 {
668 if err := c.readRecord(recordTypeHandshake); err != nil {
673 data := c.hand.Bytes()
674 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
675 if n > maxHandshake {
676 c.sendAlert(alertInternalError)
679 for c.hand.Len() < 4+n {
683 if err := c.readRecord(recordTypeHandshake); err != nil {
687 data = c.hand.Next(4 + n)
688 var m handshakeMessage
690 case typeClientHello:
691 m = new(clientHelloMsg)
692 case typeServerHello:
693 m = new(serverHelloMsg)
694 case typeCertificate:
695 m = new(certificateMsg)
696 case typeCertificateRequest:
697 m = new(certificateRequestMsg)
698 case typeCertificateStatus:
699 m = new(certificateStatusMsg)
700 case typeServerKeyExchange:
701 m = new(serverKeyExchangeMsg)
702 case typeServerHelloDone:
703 m = new(serverHelloDoneMsg)
704 case typeClientKeyExchange:
705 m = new(clientKeyExchangeMsg)
706 case typeCertificateVerify:
707 m = new(certificateVerifyMsg)
708 case typeNextProtocol:
709 m = new(nextProtoMsg)
713 c.sendAlert(alertUnexpectedMessage)
714 return nil, alertUnexpectedMessage
717 // The handshake message unmarshallers
718 // expect to be able to keep references to data,
719 // so pass in a fresh copy that won't be overwritten.
720 data = append([]byte(nil), data...)
722 if !m.unmarshal(data) {
723 c.sendAlert(alertUnexpectedMessage)
724 return nil, alertUnexpectedMessage
729 // Write writes data to the connection.
730 func (c *Conn) Write(b []byte) (int, error) {
735 if c.err = c.Handshake(); c.err != nil {
742 if !c.handshakeComplete {
743 return 0, alertInternalError
747 n, c.err = c.writeRecord(recordTypeApplicationData, b)
751 // Read can be made to time out and return a net.Error with Timeout() == true
752 // after a fixed time limit; see SetDeadline and SetReadDeadline.
753 func (c *Conn) Read(b []byte) (n int, err error) {
754 if err = c.Handshake(); err != nil {
761 for c.input == nil && c.err == nil {
762 if err := c.readRecord(recordTypeApplicationData); err != nil {
763 // Soft error, like EAGAIN
770 n, err = c.input.Read(b)
771 if c.input.off >= len(c.input.data) {
772 c.in.freeBlock(c.input)
778 // Close closes the connection.
779 func (c *Conn) Close() error {
782 c.handshakeMutex.Lock()
783 defer c.handshakeMutex.Unlock()
784 if c.handshakeComplete {
785 alertErr = c.sendAlert(alertCloseNotify)
788 if err := c.conn.Close(); err != nil {
794 // Handshake runs the client or server handshake
795 // protocol if it has not yet been run.
796 // Most uses of this package need not call Handshake
797 // explicitly: the first Read or Write will call it automatically.
798 func (c *Conn) Handshake() error {
799 c.handshakeMutex.Lock()
800 defer c.handshakeMutex.Unlock()
801 if err := c.error(); err != nil {
804 if c.handshakeComplete {
808 return c.clientHandshake()
810 return c.serverHandshake()
813 // ConnectionState returns basic TLS details about the connection.
814 func (c *Conn) ConnectionState() ConnectionState {
815 c.handshakeMutex.Lock()
816 defer c.handshakeMutex.Unlock()
818 var state ConnectionState
819 state.HandshakeComplete = c.handshakeComplete
820 if c.handshakeComplete {
821 state.NegotiatedProtocol = c.clientProtocol
822 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
823 state.CipherSuite = c.cipherSuite
824 state.PeerCertificates = c.peerCertificates
825 state.VerifiedChains = c.verifiedChains
826 state.ServerName = c.serverName
832 // OCSPResponse returns the stapled OCSP response from the TLS server, if
833 // any. (Only valid for client connections.)
834 func (c *Conn) OCSPResponse() []byte {
835 c.handshakeMutex.Lock()
836 defer c.handshakeMutex.Unlock()
838 return c.ocspResponse
841 // VerifyHostname checks that the peer certificate chain is valid for
842 // connecting to host. If so, it returns nil; if not, it returns an error
843 // describing the problem.
844 func (c *Conn) VerifyHostname(host string) error {
845 c.handshakeMutex.Lock()
846 defer c.handshakeMutex.Unlock()
848 return errors.New("VerifyHostname called on TLS server connection")
850 if !c.handshakeComplete {
851 return errors.New("TLS handshake has not yet been performed")
853 return c.peerCertificates[0].VerifyHostname(host)