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
40 // first permanent error
45 in, out halfConn // in.Mutex < out.Mutex
46 rawInput *block // raw input, right off the wire
47 input *block // application data waiting to be read
48 hand bytes.Buffer // handshake data waiting to be read
53 func (c *Conn) setError(err os.Error) os.Error {
55 defer c.errMutex.Unlock()
63 func (c *Conn) error() os.Error {
65 defer c.errMutex.Unlock()
70 // Access to net.Conn methods.
71 // Cannot just embed net.Conn because that would
72 // export the struct field too.
74 // LocalAddr returns the local network address.
75 func (c *Conn) LocalAddr() net.Addr {
76 return c.conn.LocalAddr()
79 // RemoteAddr returns the remote network address.
80 func (c *Conn) RemoteAddr() net.Addr {
81 return c.conn.RemoteAddr()
84 // SetTimeout sets the read deadline associated with the connection.
85 // There is no write deadline.
86 func (c *Conn) SetTimeout(nsec int64) os.Error {
87 return c.conn.SetTimeout(nsec)
90 // SetReadTimeout sets the time (in nanoseconds) that
91 // Read will wait for data before returning os.EAGAIN.
92 // Setting nsec == 0 (the default) disables the deadline.
93 func (c *Conn) SetReadTimeout(nsec int64) os.Error {
94 return c.conn.SetReadTimeout(nsec)
97 // SetWriteTimeout exists to satisfy the net.Conn interface
98 // but is not implemented by TLS. It always returns an error.
99 func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
100 return os.NewError("TLS does not support SetWriteTimeout")
103 // A halfConn represents one direction of the record layer
104 // connection, either sending or receiving.
105 type halfConn struct {
107 cipher interface{} // cipher algorithm
108 mac hash.Hash // MAC algorithm
109 seq [8]byte // 64-bit sequence number
110 bfree *block // list of free blocks
112 nextCipher interface{} // next encryption state
113 nextMac hash.Hash // next MAC algorithm
116 // prepareCipherSpec sets the encryption and MAC states
117 // that a subsequent changeCipherSpec will use.
118 func (hc *halfConn) prepareCipherSpec(cipher interface{}, mac hash.Hash) {
119 hc.nextCipher = cipher
123 // changeCipherSpec changes the encryption and MAC states
124 // to the ones previously passed to prepareCipherSpec.
125 func (hc *halfConn) changeCipherSpec() os.Error {
126 if hc.nextCipher == nil {
127 return alertInternalError
129 hc.cipher = hc.nextCipher
136 // incSeq increments the sequence number.
137 func (hc *halfConn) incSeq() {
138 for i := 7; i >= 0; i-- {
145 // Not allowed to let sequence number wrap.
146 // Instead, must renegotiate before it does.
147 // Not likely enough to bother.
148 panic("TLS: sequence number wraparound")
151 // resetSeq resets the sequence number to zero.
152 func (hc *halfConn) resetSeq() {
153 for i := range hc.seq {
158 // removePadding returns an unpadded slice, in constant time, which is a prefix
159 // of the input. It also returns a byte which is equal to 255 if the padding
160 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
161 func removePadding(payload []byte) ([]byte, byte) {
162 if len(payload) < 1 {
166 paddingLen := payload[len(payload)-1]
167 t := uint(len(payload)-1) - uint(paddingLen)
168 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
169 good := byte(int32(^t) >> 31)
171 toCheck := 255 // the maximum possible padding length
172 // The length of the padded data is public, so we can use an if here
173 if toCheck+1 > len(payload) {
174 toCheck = len(payload) - 1
177 for i := 0; i < toCheck; i++ {
178 t := uint(paddingLen) - uint(i)
179 // if i <= paddingLen then the MSB of t is zero
180 mask := byte(int32(^t) >> 31)
181 b := payload[len(payload)-1-i]
182 good &^= mask&paddingLen ^ mask&b
185 // We AND together the bits of good and replicate the result across
190 good = uint8(int8(good) >> 7)
192 toRemove := good&paddingLen + 1
193 return payload[:len(payload)-int(toRemove)], good
196 func roundUp(a, b int) int {
200 // decrypt checks and strips the mac and decrypts the data in b.
201 func (hc *halfConn) decrypt(b *block) (bool, alert) {
203 payload := b.data[recordHeaderLen:]
207 macSize = hc.mac.Size()
210 paddingGood := byte(255)
213 if hc.cipher != nil {
214 switch c := hc.cipher.(type) {
216 c.XORKeyStream(payload, payload)
217 case cipher.BlockMode:
218 blockSize := c.BlockSize()
220 if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
221 return false, alertBadRecordMAC
224 c.CryptBlocks(payload, payload)
225 payload, paddingGood = removePadding(payload)
226 b.resize(recordHeaderLen + len(payload))
228 // note that we still have a timing side-channel in the
229 // MAC check, below. An attacker can align the record
230 // so that a correct padding will cause one less hash
231 // block to be calculated. Then they can iteratively
232 // decrypt a record by breaking each byte. See
233 // "Password Interception in a SSL/TLS Channel", Brice
236 // However, our behaviour matches OpenSSL, so we leak
237 // only as much as they do.
239 panic("unknown cipher type")
245 if len(payload) < macSize {
246 return false, alertBadRecordMAC
249 // strip mac off payload, b.data
250 n := len(payload) - macSize
251 b.data[3] = byte(n >> 8)
253 b.resize(recordHeaderLen + n)
254 remoteMAC := payload[n:]
257 hc.mac.Write(hc.seq[0:])
261 if subtle.ConstantTimeCompare(hc.mac.Sum(), remoteMAC) != 1 || paddingGood != 255 {
262 return false, alertBadRecordMAC
269 // padToBlockSize calculates the needed padding block, if any, for a payload.
270 // On exit, prefix aliases payload and extends to the end of the last full
271 // block of payload. finalBlock is a fresh slice which contains the contents of
272 // any suffix of payload as well as the needed padding to make finalBlock a
274 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
275 overrun := len(payload) % blockSize
276 paddingLen := blockSize - overrun
277 prefix = payload[:len(payload)-overrun]
278 finalBlock = make([]byte, blockSize)
279 copy(finalBlock, payload[len(payload)-overrun:])
280 for i := overrun; i < blockSize; i++ {
281 finalBlock[i] = byte(paddingLen - 1)
286 // encrypt encrypts and macs the data in b.
287 func (hc *halfConn) encrypt(b *block) (bool, alert) {
291 hc.mac.Write(hc.seq[0:])
296 b.resize(n + len(mac))
297 copy(b.data[n:], mac)
300 payload := b.data[recordHeaderLen:]
303 if hc.cipher != nil {
304 switch c := hc.cipher.(type) {
306 c.XORKeyStream(payload, payload)
307 case cipher.BlockMode:
308 prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
309 b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
310 c.CryptBlocks(b.data[recordHeaderLen:], prefix)
311 c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
313 panic("unknown cipher type")
317 // update length to include MAC and any block padding needed.
318 n := len(b.data) - recordHeaderLen
319 b.data[3] = byte(n >> 8)
325 // A block is a simple data buffer.
328 off int // index for Read
332 // resize resizes block to be n bytes, growing if necessary.
333 func (b *block) resize(n int) {
340 // reserve makes sure that block contains a capacity of at least n bytes.
341 func (b *block) reserve(n int) {
342 if cap(b.data) >= n {
352 data := make([]byte, len(b.data), m)
357 // readFromUntil reads from r into b until b contains at least n bytes
358 // or else returns an error.
359 func (b *block) readFromUntil(r io.Reader, n int) os.Error {
361 if len(b.data) >= n {
365 // read until have enough.
368 m, err := r.Read(b.data[len(b.data):cap(b.data)])
369 b.data = b.data[0 : len(b.data)+m]
370 if len(b.data) >= n {
380 func (b *block) Read(p []byte) (n int, err os.Error) {
381 n = copy(p, b.data[b.off:])
386 // newBlock allocates a new block, from hc's free list if possible.
387 func (hc *halfConn) newBlock() *block {
398 // freeBlock returns a block to hc's free list.
399 // The protocol is such that each side only has a block or two on
400 // its free list at a time, so there's no need to worry about
401 // trimming the list, etc.
402 func (hc *halfConn) freeBlock(b *block) {
407 // splitBlock splits a block after the first n bytes,
408 // returning a block with those n bytes and a
409 // block with the remaindec. the latter may be nil.
410 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
411 if len(b.data) <= n {
415 bb.resize(len(b.data) - n)
416 copy(bb.data, b.data[n:])
421 // readRecord reads the next TLS record from the connection
422 // and updates the record layer state.
423 // c.in.Mutex <= L; c.input == nil.
424 func (c *Conn) readRecord(want recordType) os.Error {
425 // Caller must be in sync with connection:
426 // handshake data if handshake not yet completed,
427 // else application data. (We don't support renegotiation.)
430 return c.sendAlert(alertInternalError)
431 case recordTypeHandshake, recordTypeChangeCipherSpec:
432 if c.handshakeComplete {
433 return c.sendAlert(alertInternalError)
435 case recordTypeApplicationData:
436 if !c.handshakeComplete {
437 return c.sendAlert(alertInternalError)
442 if c.rawInput == nil {
443 c.rawInput = c.in.newBlock()
447 // Read header, payload.
448 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
449 // RFC suggests that EOF without an alertCloseNotify is
450 // an error, but popular web sites seem to do this,
451 // so we can't make it an error.
452 // if err == os.EOF {
453 // err = io.ErrUnexpectedEOF
455 if e, ok := err.(net.Error); !ok || !e.Temporary() {
460 typ := recordType(b.data[0])
461 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
462 n := int(b.data[3])<<8 | int(b.data[4])
463 if c.haveVers && vers != c.vers {
464 return c.sendAlert(alertProtocolVersion)
466 if n > maxCiphertext {
467 return c.sendAlert(alertRecordOverflow)
469 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
471 err = io.ErrUnexpectedEOF
473 if e, ok := err.(net.Error); !ok || !e.Temporary() {
480 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
481 b.off = recordHeaderLen
482 if ok, err := c.in.decrypt(b); !ok {
483 return c.sendAlert(err)
485 data := b.data[b.off:]
486 if len(data) > maxPlaintext {
487 c.sendAlert(alertRecordOverflow)
494 c.sendAlert(alertUnexpectedMessage)
496 case recordTypeAlert:
498 c.sendAlert(alertUnexpectedMessage)
501 if alert(data[1]) == alertCloseNotify {
506 case alertLevelWarning:
510 case alertLevelError:
511 c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
513 c.sendAlert(alertUnexpectedMessage)
516 case recordTypeChangeCipherSpec:
517 if typ != want || len(data) != 1 || data[0] != 1 {
518 c.sendAlert(alertUnexpectedMessage)
521 err := c.in.changeCipherSpec()
523 c.sendAlert(err.(alert))
526 case recordTypeApplicationData:
528 c.sendAlert(alertUnexpectedMessage)
534 case recordTypeHandshake:
535 // TODO(rsc): Should at least pick off connection close.
537 return c.sendAlert(alertNoRenegotiation)
548 // sendAlert sends a TLS alert message.
550 func (c *Conn) sendAlertLocked(err alert) os.Error {
551 c.tmp[0] = alertLevelError
552 if err == alertNoRenegotiation {
553 c.tmp[0] = alertLevelWarning
556 c.writeRecord(recordTypeAlert, c.tmp[0:2])
557 // closeNotify is a special case in that it isn't an error:
558 if err != alertCloseNotify {
559 return c.setError(&net.OpError{Op: "local error", Error: err})
564 // sendAlert sends a TLS alert message.
566 func (c *Conn) sendAlert(err alert) os.Error {
569 return c.sendAlertLocked(err)
572 // writeRecord writes a TLS record with the given type and payload
573 // to the connection and updates the record layer state.
575 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
576 b := c.out.newBlock()
579 if m > maxPlaintext {
582 b.resize(recordHeaderLen + m)
583 b.data[0] = byte(typ)
588 b.data[1] = byte(vers >> 8)
589 b.data[2] = byte(vers)
590 b.data[3] = byte(m >> 8)
592 copy(b.data[recordHeaderLen:], data)
594 _, err = c.conn.Write(b.data)
603 if typ == recordTypeChangeCipherSpec {
604 err = c.out.changeCipherSpec()
606 // Cannot call sendAlert directly,
607 // because we already hold c.out.Mutex.
608 c.tmp[0] = alertLevelError
609 c.tmp[1] = byte(err.(alert))
610 c.writeRecord(recordTypeAlert, c.tmp[0:2])
611 c.err = &net.OpError{Op: "local error", Error: err}
618 // readHandshake reads the next handshake message from
620 // c.in.Mutex < L; c.out.Mutex < L.
621 func (c *Conn) readHandshake() (interface{}, os.Error) {
622 for c.hand.Len() < 4 {
626 c.readRecord(recordTypeHandshake)
629 data := c.hand.Bytes()
630 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
631 if n > maxHandshake {
632 c.sendAlert(alertInternalError)
635 for c.hand.Len() < 4+n {
639 c.readRecord(recordTypeHandshake)
641 data = c.hand.Next(4 + n)
642 var m handshakeMessage
644 case typeClientHello:
645 m = new(clientHelloMsg)
646 case typeServerHello:
647 m = new(serverHelloMsg)
648 case typeCertificate:
649 m = new(certificateMsg)
650 case typeCertificateRequest:
651 m = new(certificateRequestMsg)
652 case typeCertificateStatus:
653 m = new(certificateStatusMsg)
654 case typeServerKeyExchange:
655 m = new(serverKeyExchangeMsg)
656 case typeServerHelloDone:
657 m = new(serverHelloDoneMsg)
658 case typeClientKeyExchange:
659 m = new(clientKeyExchangeMsg)
660 case typeCertificateVerify:
661 m = new(certificateVerifyMsg)
662 case typeNextProtocol:
663 m = new(nextProtoMsg)
667 c.sendAlert(alertUnexpectedMessage)
668 return nil, alertUnexpectedMessage
671 // The handshake message unmarshallers
672 // expect to be able to keep references to data,
673 // so pass in a fresh copy that won't be overwritten.
674 data = append([]byte(nil), data...)
676 if !m.unmarshal(data) {
677 c.sendAlert(alertUnexpectedMessage)
678 return nil, alertUnexpectedMessage
683 // Write writes data to the connection.
684 func (c *Conn) Write(b []byte) (n int, err os.Error) {
685 if err = c.Handshake(); err != nil {
692 if !c.handshakeComplete {
693 return 0, alertInternalError
698 return c.writeRecord(recordTypeApplicationData, b)
701 // Read can be made to time out and return err == os.EAGAIN
702 // after a fixed time limit; see SetTimeout and SetReadTimeout.
703 func (c *Conn) Read(b []byte) (n int, err os.Error) {
704 if err = c.Handshake(); err != nil {
711 for c.input == nil && c.err == nil {
712 if err := c.readRecord(recordTypeApplicationData); err != nil {
713 // Soft error, like EAGAIN
720 n, err = c.input.Read(b)
721 if c.input.off >= len(c.input.data) {
722 c.in.freeBlock(c.input)
728 // Close closes the connection.
729 func (c *Conn) Close() os.Error {
730 if err := c.Handshake(); err != nil {
733 return c.sendAlert(alertCloseNotify)
736 // Handshake runs the client or server handshake
737 // protocol if it has not yet been run.
738 // Most uses of this package need not call Handshake
739 // explicitly: the first Read or Write will call it automatically.
740 func (c *Conn) Handshake() os.Error {
741 c.handshakeMutex.Lock()
742 defer c.handshakeMutex.Unlock()
743 if err := c.error(); err != nil {
746 if c.handshakeComplete {
750 return c.clientHandshake()
752 return c.serverHandshake()
755 // ConnectionState returns basic TLS details about the connection.
756 func (c *Conn) ConnectionState() ConnectionState {
757 c.handshakeMutex.Lock()
758 defer c.handshakeMutex.Unlock()
760 var state ConnectionState
761 state.HandshakeComplete = c.handshakeComplete
762 if c.handshakeComplete {
763 state.NegotiatedProtocol = c.clientProtocol
764 state.CipherSuite = c.cipherSuite
770 // OCSPResponse returns the stapled OCSP response from the TLS server, if
771 // any. (Only valid for client connections.)
772 func (c *Conn) OCSPResponse() []byte {
773 c.handshakeMutex.Lock()
774 defer c.handshakeMutex.Unlock()
776 return c.ocspResponse
779 // PeerCertificates returns the certificate chain that was presented by the
781 func (c *Conn) PeerCertificates() []*x509.Certificate {
782 c.handshakeMutex.Lock()
783 defer c.handshakeMutex.Unlock()
785 return c.peerCertificates
788 // VerifyHostname checks that the peer certificate chain is valid for
789 // connecting to host. If so, it returns nil; if not, it returns an os.Error
790 // describing the problem.
791 func (c *Conn) VerifyHostname(host string) os.Error {
792 c.handshakeMutex.Lock()
793 defer c.handshakeMutex.Unlock()
795 return os.ErrorString("VerifyHostname called on TLS server connection")
797 if !c.handshakeComplete {
798 return os.ErrorString("TLS handshake has not yet been performed")
800 return c.peerCertificates[0].VerifyHostname(host)