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
42 clientProtocolFallback bool
44 // first permanent error
49 in, out halfConn // in.Mutex < out.Mutex
50 rawInput *block // raw input, right off the wire
51 input *block // application data waiting to be read
52 hand bytes.Buffer // handshake data waiting to be read
57 func (c *Conn) setError(err os.Error) os.Error {
59 defer c.errMutex.Unlock()
67 func (c *Conn) error() os.Error {
69 defer c.errMutex.Unlock()
74 // Access to net.Conn methods.
75 // Cannot just embed net.Conn because that would
76 // export the struct field too.
78 // LocalAddr returns the local network address.
79 func (c *Conn) LocalAddr() net.Addr {
80 return c.conn.LocalAddr()
83 // RemoteAddr returns the remote network address.
84 func (c *Conn) RemoteAddr() net.Addr {
85 return c.conn.RemoteAddr()
88 // SetTimeout sets the read deadline associated with the connection.
89 // There is no write deadline.
90 func (c *Conn) SetTimeout(nsec int64) os.Error {
91 return c.conn.SetTimeout(nsec)
94 // SetReadTimeout sets the time (in nanoseconds) that
95 // Read will wait for data before returning os.EAGAIN.
96 // Setting nsec == 0 (the default) disables the deadline.
97 func (c *Conn) SetReadTimeout(nsec int64) os.Error {
98 return c.conn.SetReadTimeout(nsec)
101 // SetWriteTimeout exists to satisfy the net.Conn interface
102 // but is not implemented by TLS. It always returns an error.
103 func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
104 return os.NewError("TLS does not support SetWriteTimeout")
107 // A halfConn represents one direction of the record layer
108 // connection, either sending or receiving.
109 type halfConn struct {
111 cipher interface{} // cipher algorithm
112 mac hash.Hash // MAC algorithm
113 seq [8]byte // 64-bit sequence number
114 bfree *block // list of free blocks
116 nextCipher interface{} // next encryption state
117 nextMac hash.Hash // next MAC algorithm
120 // prepareCipherSpec sets the encryption and MAC states
121 // that a subsequent changeCipherSpec will use.
122 func (hc *halfConn) prepareCipherSpec(cipher interface{}, mac hash.Hash) {
123 hc.nextCipher = cipher
127 // changeCipherSpec changes the encryption and MAC states
128 // to the ones previously passed to prepareCipherSpec.
129 func (hc *halfConn) changeCipherSpec() os.Error {
130 if hc.nextCipher == nil {
131 return alertInternalError
133 hc.cipher = hc.nextCipher
140 // incSeq increments the sequence number.
141 func (hc *halfConn) incSeq() {
142 for i := 7; i >= 0; i-- {
149 // Not allowed to let sequence number wrap.
150 // Instead, must renegotiate before it does.
151 // Not likely enough to bother.
152 panic("TLS: sequence number wraparound")
155 // resetSeq resets the sequence number to zero.
156 func (hc *halfConn) resetSeq() {
157 for i := range hc.seq {
162 // removePadding returns an unpadded slice, in constant time, which is a prefix
163 // of the input. It also returns a byte which is equal to 255 if the padding
164 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
165 func removePadding(payload []byte) ([]byte, byte) {
166 if len(payload) < 1 {
170 paddingLen := payload[len(payload)-1]
171 t := uint(len(payload)-1) - uint(paddingLen)
172 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
173 good := byte(int32(^t) >> 31)
175 toCheck := 255 // the maximum possible padding length
176 // The length of the padded data is public, so we can use an if here
177 if toCheck+1 > len(payload) {
178 toCheck = len(payload) - 1
181 for i := 0; i < toCheck; i++ {
182 t := uint(paddingLen) - uint(i)
183 // if i <= paddingLen then the MSB of t is zero
184 mask := byte(int32(^t) >> 31)
185 b := payload[len(payload)-1-i]
186 good &^= mask&paddingLen ^ mask&b
189 // We AND together the bits of good and replicate the result across
194 good = uint8(int8(good) >> 7)
196 toRemove := good&paddingLen + 1
197 return payload[:len(payload)-int(toRemove)], good
200 func roundUp(a, b int) int {
204 // decrypt checks and strips the mac and decrypts the data in b.
205 func (hc *halfConn) decrypt(b *block) (bool, alert) {
207 payload := b.data[recordHeaderLen:]
211 macSize = hc.mac.Size()
214 paddingGood := byte(255)
217 if hc.cipher != nil {
218 switch c := hc.cipher.(type) {
220 c.XORKeyStream(payload, payload)
221 case cipher.BlockMode:
222 blockSize := c.BlockSize()
224 if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
225 return false, alertBadRecordMAC
228 c.CryptBlocks(payload, payload)
229 payload, paddingGood = removePadding(payload)
230 b.resize(recordHeaderLen + len(payload))
232 // note that we still have a timing side-channel in the
233 // MAC check, below. An attacker can align the record
234 // so that a correct padding will cause one less hash
235 // block to be calculated. Then they can iteratively
236 // decrypt a record by breaking each byte. See
237 // "Password Interception in a SSL/TLS Channel", Brice
240 // However, our behavior matches OpenSSL, so we leak
241 // only as much as they do.
243 panic("unknown cipher type")
249 if len(payload) < macSize {
250 return false, alertBadRecordMAC
253 // strip mac off payload, b.data
254 n := len(payload) - macSize
255 b.data[3] = byte(n >> 8)
257 b.resize(recordHeaderLen + n)
258 remoteMAC := payload[n:]
261 hc.mac.Write(hc.seq[0:])
265 if subtle.ConstantTimeCompare(hc.mac.Sum(), remoteMAC) != 1 || paddingGood != 255 {
266 return false, alertBadRecordMAC
273 // padToBlockSize calculates the needed padding block, if any, for a payload.
274 // On exit, prefix aliases payload and extends to the end of the last full
275 // block of payload. finalBlock is a fresh slice which contains the contents of
276 // any suffix of payload as well as the needed padding to make finalBlock a
278 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
279 overrun := len(payload) % blockSize
280 paddingLen := blockSize - overrun
281 prefix = payload[:len(payload)-overrun]
282 finalBlock = make([]byte, blockSize)
283 copy(finalBlock, payload[len(payload)-overrun:])
284 for i := overrun; i < blockSize; i++ {
285 finalBlock[i] = byte(paddingLen - 1)
290 // encrypt encrypts and macs the data in b.
291 func (hc *halfConn) encrypt(b *block) (bool, alert) {
295 hc.mac.Write(hc.seq[0:])
300 b.resize(n + len(mac))
301 copy(b.data[n:], mac)
304 payload := b.data[recordHeaderLen:]
307 if hc.cipher != nil {
308 switch c := hc.cipher.(type) {
310 c.XORKeyStream(payload, payload)
311 case cipher.BlockMode:
312 prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
313 b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
314 c.CryptBlocks(b.data[recordHeaderLen:], prefix)
315 c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
317 panic("unknown cipher type")
321 // update length to include MAC and any block padding needed.
322 n := len(b.data) - recordHeaderLen
323 b.data[3] = byte(n >> 8)
329 // A block is a simple data buffer.
332 off int // index for Read
336 // resize resizes block to be n bytes, growing if necessary.
337 func (b *block) resize(n int) {
344 // reserve makes sure that block contains a capacity of at least n bytes.
345 func (b *block) reserve(n int) {
346 if cap(b.data) >= n {
356 data := make([]byte, len(b.data), m)
361 // readFromUntil reads from r into b until b contains at least n bytes
362 // or else returns an error.
363 func (b *block) readFromUntil(r io.Reader, n int) os.Error {
365 if len(b.data) >= n {
369 // read until have enough.
372 m, err := r.Read(b.data[len(b.data):cap(b.data)])
373 b.data = b.data[0 : len(b.data)+m]
374 if len(b.data) >= n {
384 func (b *block) Read(p []byte) (n int, err os.Error) {
385 n = copy(p, b.data[b.off:])
390 // newBlock allocates a new block, from hc's free list if possible.
391 func (hc *halfConn) newBlock() *block {
402 // freeBlock returns a block to hc's free list.
403 // The protocol is such that each side only has a block or two on
404 // its free list at a time, so there's no need to worry about
405 // trimming the list, etc.
406 func (hc *halfConn) freeBlock(b *block) {
411 // splitBlock splits a block after the first n bytes,
412 // returning a block with those n bytes and a
413 // block with the remainder. the latter may be nil.
414 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
415 if len(b.data) <= n {
419 bb.resize(len(b.data) - n)
420 copy(bb.data, b.data[n:])
425 // readRecord reads the next TLS record from the connection
426 // and updates the record layer state.
427 // c.in.Mutex <= L; c.input == nil.
428 func (c *Conn) readRecord(want recordType) os.Error {
429 // Caller must be in sync with connection:
430 // handshake data if handshake not yet completed,
431 // else application data. (We don't support renegotiation.)
434 return c.sendAlert(alertInternalError)
435 case recordTypeHandshake, recordTypeChangeCipherSpec:
436 if c.handshakeComplete {
437 return c.sendAlert(alertInternalError)
439 case recordTypeApplicationData:
440 if !c.handshakeComplete {
441 return c.sendAlert(alertInternalError)
446 if c.rawInput == nil {
447 c.rawInput = c.in.newBlock()
451 // Read header, payload.
452 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
453 // RFC suggests that EOF without an alertCloseNotify is
454 // an error, but popular web sites seem to do this,
455 // so we can't make it an error.
456 // if err == os.EOF {
457 // err = io.ErrUnexpectedEOF
459 if e, ok := err.(net.Error); !ok || !e.Temporary() {
464 typ := recordType(b.data[0])
465 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
466 n := int(b.data[3])<<8 | int(b.data[4])
467 if c.haveVers && vers != c.vers {
468 return c.sendAlert(alertProtocolVersion)
470 if n > maxCiphertext {
471 return c.sendAlert(alertRecordOverflow)
473 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
475 err = io.ErrUnexpectedEOF
477 if e, ok := err.(net.Error); !ok || !e.Temporary() {
484 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
485 b.off = recordHeaderLen
486 if ok, err := c.in.decrypt(b); !ok {
487 return c.sendAlert(err)
489 data := b.data[b.off:]
490 if len(data) > maxPlaintext {
491 c.sendAlert(alertRecordOverflow)
498 c.sendAlert(alertUnexpectedMessage)
500 case recordTypeAlert:
502 c.sendAlert(alertUnexpectedMessage)
505 if alert(data[1]) == alertCloseNotify {
510 case alertLevelWarning:
514 case alertLevelError:
515 c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
517 c.sendAlert(alertUnexpectedMessage)
520 case recordTypeChangeCipherSpec:
521 if typ != want || len(data) != 1 || data[0] != 1 {
522 c.sendAlert(alertUnexpectedMessage)
525 err := c.in.changeCipherSpec()
527 c.sendAlert(err.(alert))
530 case recordTypeApplicationData:
532 c.sendAlert(alertUnexpectedMessage)
538 case recordTypeHandshake:
539 // TODO(rsc): Should at least pick off connection close.
541 return c.sendAlert(alertNoRenegotiation)
552 // sendAlert sends a TLS alert message.
554 func (c *Conn) sendAlertLocked(err alert) os.Error {
555 c.tmp[0] = alertLevelError
556 if err == alertNoRenegotiation {
557 c.tmp[0] = alertLevelWarning
560 c.writeRecord(recordTypeAlert, c.tmp[0:2])
561 // closeNotify is a special case in that it isn't an error:
562 if err != alertCloseNotify {
563 return c.setError(&net.OpError{Op: "local error", Error: err})
568 // sendAlert sends a TLS alert message.
570 func (c *Conn) sendAlert(err alert) os.Error {
573 return c.sendAlertLocked(err)
576 // writeRecord writes a TLS record with the given type and payload
577 // to the connection and updates the record layer state.
579 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
580 b := c.out.newBlock()
583 if m > maxPlaintext {
586 b.resize(recordHeaderLen + m)
587 b.data[0] = byte(typ)
592 b.data[1] = byte(vers >> 8)
593 b.data[2] = byte(vers)
594 b.data[3] = byte(m >> 8)
596 copy(b.data[recordHeaderLen:], data)
598 _, err = c.conn.Write(b.data)
607 if typ == recordTypeChangeCipherSpec {
608 err = c.out.changeCipherSpec()
610 // Cannot call sendAlert directly,
611 // because we already hold c.out.Mutex.
612 c.tmp[0] = alertLevelError
613 c.tmp[1] = byte(err.(alert))
614 c.writeRecord(recordTypeAlert, c.tmp[0:2])
615 c.err = &net.OpError{Op: "local error", Error: err}
622 // readHandshake reads the next handshake message from
624 // c.in.Mutex < L; c.out.Mutex < L.
625 func (c *Conn) readHandshake() (interface{}, os.Error) {
626 for c.hand.Len() < 4 {
630 c.readRecord(recordTypeHandshake)
633 data := c.hand.Bytes()
634 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
635 if n > maxHandshake {
636 c.sendAlert(alertInternalError)
639 for c.hand.Len() < 4+n {
643 c.readRecord(recordTypeHandshake)
645 data = c.hand.Next(4 + n)
646 var m handshakeMessage
648 case typeClientHello:
649 m = new(clientHelloMsg)
650 case typeServerHello:
651 m = new(serverHelloMsg)
652 case typeCertificate:
653 m = new(certificateMsg)
654 case typeCertificateRequest:
655 m = new(certificateRequestMsg)
656 case typeCertificateStatus:
657 m = new(certificateStatusMsg)
658 case typeServerKeyExchange:
659 m = new(serverKeyExchangeMsg)
660 case typeServerHelloDone:
661 m = new(serverHelloDoneMsg)
662 case typeClientKeyExchange:
663 m = new(clientKeyExchangeMsg)
664 case typeCertificateVerify:
665 m = new(certificateVerifyMsg)
666 case typeNextProtocol:
667 m = new(nextProtoMsg)
671 c.sendAlert(alertUnexpectedMessage)
672 return nil, alertUnexpectedMessage
675 // The handshake message unmarshallers
676 // expect to be able to keep references to data,
677 // so pass in a fresh copy that won't be overwritten.
678 data = append([]byte(nil), data...)
680 if !m.unmarshal(data) {
681 c.sendAlert(alertUnexpectedMessage)
682 return nil, alertUnexpectedMessage
687 // Write writes data to the connection.
688 func (c *Conn) Write(b []byte) (n int, err os.Error) {
689 if err = c.Handshake(); err != nil {
696 if !c.handshakeComplete {
697 return 0, alertInternalError
702 return c.writeRecord(recordTypeApplicationData, b)
705 // Read can be made to time out and return err == os.EAGAIN
706 // after a fixed time limit; see SetTimeout and SetReadTimeout.
707 func (c *Conn) Read(b []byte) (n int, err os.Error) {
708 if err = c.Handshake(); err != nil {
715 for c.input == nil && c.err == nil {
716 if err := c.readRecord(recordTypeApplicationData); err != nil {
717 // Soft error, like EAGAIN
724 n, err = c.input.Read(b)
725 if c.input.off >= len(c.input.data) {
726 c.in.freeBlock(c.input)
732 // Close closes the connection.
733 func (c *Conn) Close() os.Error {
734 if err := c.Handshake(); err != nil {
737 return c.sendAlert(alertCloseNotify)
740 // Handshake runs the client or server handshake
741 // protocol if it has not yet been run.
742 // Most uses of this package need not call Handshake
743 // explicitly: the first Read or Write will call it automatically.
744 func (c *Conn) Handshake() os.Error {
745 c.handshakeMutex.Lock()
746 defer c.handshakeMutex.Unlock()
747 if err := c.error(); err != nil {
750 if c.handshakeComplete {
754 return c.clientHandshake()
756 return c.serverHandshake()
759 // ConnectionState returns basic TLS details about the connection.
760 func (c *Conn) ConnectionState() ConnectionState {
761 c.handshakeMutex.Lock()
762 defer c.handshakeMutex.Unlock()
764 var state ConnectionState
765 state.HandshakeComplete = c.handshakeComplete
766 if c.handshakeComplete {
767 state.NegotiatedProtocol = c.clientProtocol
768 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
769 state.CipherSuite = c.cipherSuite
770 state.PeerCertificates = c.peerCertificates
771 state.VerifiedChains = c.verifiedChains
777 // OCSPResponse returns the stapled OCSP response from the TLS server, if
778 // any. (Only valid for client connections.)
779 func (c *Conn) OCSPResponse() []byte {
780 c.handshakeMutex.Lock()
781 defer c.handshakeMutex.Unlock()
783 return c.ocspResponse
786 // VerifyHostname checks that the peer certificate chain is valid for
787 // connecting to host. If so, it returns nil; if not, it returns an os.Error
788 // describing the problem.
789 func (c *Conn) VerifyHostname(host string) os.Error {
790 c.handshakeMutex.Lock()
791 defer c.handshakeMutex.Unlock()
793 return os.NewError("VerifyHostname called on TLS server connection")
795 if !c.handshakeComplete {
796 return os.NewError("TLS handshake has not yet been performed")
798 return c.peerCertificates[0].VerifyHostname(host)