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
20 // A Conn represents a secured connection.
21 // It implements the net.Conn interface.
27 // constant after handshake; protected by handshakeMutex
28 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
29 vers uint16 // TLS version
30 haveVers bool // version has been negotiated
31 config *Config // configuration passed to constructor
32 handshakeComplete bool
34 ocspResponse []byte // stapled OCSP response
35 peerCertificates []*x509.Certificate
36 // verifiedChains contains the certificate chains that we built, as
37 // opposed to the ones presented by the server.
38 verifiedChains [][]*x509.Certificate
39 // serverName contains the server name indicated by the client, if any.
43 clientProtocolFallback bool
45 // first permanent error
50 in, out halfConn // in.Mutex < out.Mutex
51 rawInput *block // raw input, right off the wire
52 input *block // application data waiting to be read
53 hand bytes.Buffer // handshake data waiting to be read
58 func (c *Conn) setError(err os.Error) os.Error {
60 defer c.errMutex.Unlock()
68 func (c *Conn) error() os.Error {
70 defer c.errMutex.Unlock()
75 // Access to net.Conn methods.
76 // Cannot just embed net.Conn because that would
77 // export the struct field too.
79 // LocalAddr returns the local network address.
80 func (c *Conn) LocalAddr() net.Addr {
81 return c.conn.LocalAddr()
84 // RemoteAddr returns the remote network address.
85 func (c *Conn) RemoteAddr() net.Addr {
86 return c.conn.RemoteAddr()
89 // SetTimeout sets the read deadline associated with the connection.
90 // There is no write deadline.
91 func (c *Conn) SetTimeout(nsec int64) os.Error {
92 return c.conn.SetTimeout(nsec)
95 // SetReadTimeout sets the time (in nanoseconds) that
96 // Read will wait for data before returning os.EAGAIN.
97 // Setting nsec == 0 (the default) disables the deadline.
98 func (c *Conn) SetReadTimeout(nsec int64) os.Error {
99 return c.conn.SetReadTimeout(nsec)
102 // SetWriteTimeout exists to satisfy the net.Conn interface
103 // but is not implemented by TLS. It always returns an error.
104 func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
105 return os.NewError("TLS does not support SetWriteTimeout")
108 // A halfConn represents one direction of the record layer
109 // connection, either sending or receiving.
110 type halfConn struct {
112 version uint16 // protocol version
113 cipher interface{} // cipher algorithm
115 seq [8]byte // 64-bit sequence number
116 bfree *block // list of free blocks
118 nextCipher interface{} // next encryption state
119 nextMac macFunction // next MAC algorithm
122 // prepareCipherSpec sets the encryption and MAC states
123 // that a subsequent changeCipherSpec will use.
124 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
126 hc.nextCipher = cipher
130 // changeCipherSpec changes the encryption and MAC states
131 // to the ones previously passed to prepareCipherSpec.
132 func (hc *halfConn) changeCipherSpec() os.Error {
133 if hc.nextCipher == nil {
134 return alertInternalError
136 hc.cipher = hc.nextCipher
143 // incSeq increments the sequence number.
144 func (hc *halfConn) incSeq() {
145 for i := 7; i >= 0; i-- {
152 // Not allowed to let sequence number wrap.
153 // Instead, must renegotiate before it does.
154 // Not likely enough to bother.
155 panic("TLS: sequence number wraparound")
158 // resetSeq resets the sequence number to zero.
159 func (hc *halfConn) resetSeq() {
160 for i := range hc.seq {
165 // removePadding returns an unpadded slice, in constant time, which is a prefix
166 // of the input. It also returns a byte which is equal to 255 if the padding
167 // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
168 func removePadding(payload []byte) ([]byte, byte) {
169 if len(payload) < 1 {
173 paddingLen := payload[len(payload)-1]
174 t := uint(len(payload)-1) - uint(paddingLen)
175 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
176 good := byte(int32(^t) >> 31)
178 toCheck := 255 // the maximum possible padding length
179 // The length of the padded data is public, so we can use an if here
180 if toCheck+1 > len(payload) {
181 toCheck = len(payload) - 1
184 for i := 0; i < toCheck; i++ {
185 t := uint(paddingLen) - uint(i)
186 // if i <= paddingLen then the MSB of t is zero
187 mask := byte(int32(^t) >> 31)
188 b := payload[len(payload)-1-i]
189 good &^= mask&paddingLen ^ mask&b
192 // We AND together the bits of good and replicate the result across
197 good = uint8(int8(good) >> 7)
199 toRemove := good&paddingLen + 1
200 return payload[:len(payload)-int(toRemove)], good
203 // removePaddingSSL30 is a replacement for removePadding in the case that the
204 // protocol version is SSLv3. In this version, the contents of the padding
205 // are random and cannot be checked.
206 func removePaddingSSL30(payload []byte) ([]byte, byte) {
207 if len(payload) < 1 {
211 paddingLen := int(payload[len(payload)-1]) + 1
212 if paddingLen > len(payload) {
216 return payload[:len(payload)-paddingLen], 255
219 func roundUp(a, b int) int {
223 // decrypt checks and strips the mac and decrypts the data in b.
224 func (hc *halfConn) decrypt(b *block) (bool, alert) {
226 payload := b.data[recordHeaderLen:]
230 macSize = hc.mac.Size()
233 paddingGood := byte(255)
236 if hc.cipher != nil {
237 switch c := hc.cipher.(type) {
239 c.XORKeyStream(payload, payload)
240 case cipher.BlockMode:
241 blockSize := c.BlockSize()
243 if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
244 return false, alertBadRecordMAC
247 c.CryptBlocks(payload, payload)
248 if hc.version == versionSSL30 {
249 payload, paddingGood = removePaddingSSL30(payload)
251 payload, paddingGood = removePadding(payload)
253 b.resize(recordHeaderLen + len(payload))
255 // note that we still have a timing side-channel in the
256 // MAC check, below. An attacker can align the record
257 // so that a correct padding will cause one less hash
258 // block to be calculated. Then they can iteratively
259 // decrypt a record by breaking each byte. See
260 // "Password Interception in a SSL/TLS Channel", Brice
263 // However, our behavior matches OpenSSL, so we leak
264 // only as much as they do.
266 panic("unknown cipher type")
272 if len(payload) < macSize {
273 return false, alertBadRecordMAC
276 // strip mac off payload, b.data
277 n := len(payload) - macSize
278 b.data[3] = byte(n >> 8)
280 b.resize(recordHeaderLen + n)
281 remoteMAC := payload[n:]
282 localMAC := hc.mac.MAC(hc.seq[0:], b.data)
285 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
286 return false, alertBadRecordMAC
293 // padToBlockSize calculates the needed padding block, if any, for a payload.
294 // On exit, prefix aliases payload and extends to the end of the last full
295 // block of payload. finalBlock is a fresh slice which contains the contents of
296 // any suffix of payload as well as the needed padding to make finalBlock a
298 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
299 overrun := len(payload) % blockSize
300 paddingLen := blockSize - overrun
301 prefix = payload[:len(payload)-overrun]
302 finalBlock = make([]byte, blockSize)
303 copy(finalBlock, payload[len(payload)-overrun:])
304 for i := overrun; i < blockSize; i++ {
305 finalBlock[i] = byte(paddingLen - 1)
310 // encrypt encrypts and macs the data in b.
311 func (hc *halfConn) encrypt(b *block) (bool, alert) {
314 mac := hc.mac.MAC(hc.seq[0:], b.data)
318 b.resize(n + len(mac))
319 copy(b.data[n:], mac)
322 payload := b.data[recordHeaderLen:]
325 if hc.cipher != nil {
326 switch c := hc.cipher.(type) {
328 c.XORKeyStream(payload, payload)
329 case cipher.BlockMode:
330 prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
331 b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
332 c.CryptBlocks(b.data[recordHeaderLen:], prefix)
333 c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
335 panic("unknown cipher type")
339 // update length to include MAC and any block padding needed.
340 n := len(b.data) - recordHeaderLen
341 b.data[3] = byte(n >> 8)
347 // A block is a simple data buffer.
350 off int // index for Read
354 // resize resizes block to be n bytes, growing if necessary.
355 func (b *block) resize(n int) {
362 // reserve makes sure that block contains a capacity of at least n bytes.
363 func (b *block) reserve(n int) {
364 if cap(b.data) >= n {
374 data := make([]byte, len(b.data), m)
379 // readFromUntil reads from r into b until b contains at least n bytes
380 // or else returns an error.
381 func (b *block) readFromUntil(r io.Reader, n int) os.Error {
383 if len(b.data) >= n {
387 // read until have enough.
390 m, err := r.Read(b.data[len(b.data):cap(b.data)])
391 b.data = b.data[0 : len(b.data)+m]
392 if len(b.data) >= n {
402 func (b *block) Read(p []byte) (n int, err os.Error) {
403 n = copy(p, b.data[b.off:])
408 // newBlock allocates a new block, from hc's free list if possible.
409 func (hc *halfConn) newBlock() *block {
420 // freeBlock returns a block to hc's free list.
421 // The protocol is such that each side only has a block or two on
422 // its free list at a time, so there's no need to worry about
423 // trimming the list, etc.
424 func (hc *halfConn) freeBlock(b *block) {
429 // splitBlock splits a block after the first n bytes,
430 // returning a block with those n bytes and a
431 // block with the remainder. the latter may be nil.
432 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
433 if len(b.data) <= n {
437 bb.resize(len(b.data) - n)
438 copy(bb.data, b.data[n:])
443 // readRecord reads the next TLS record from the connection
444 // and updates the record layer state.
445 // c.in.Mutex <= L; c.input == nil.
446 func (c *Conn) readRecord(want recordType) os.Error {
447 // Caller must be in sync with connection:
448 // handshake data if handshake not yet completed,
449 // else application data. (We don't support renegotiation.)
452 return c.sendAlert(alertInternalError)
453 case recordTypeHandshake, recordTypeChangeCipherSpec:
454 if c.handshakeComplete {
455 return c.sendAlert(alertInternalError)
457 case recordTypeApplicationData:
458 if !c.handshakeComplete {
459 return c.sendAlert(alertInternalError)
464 if c.rawInput == nil {
465 c.rawInput = c.in.newBlock()
469 // Read header, payload.
470 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
471 // RFC suggests that EOF without an alertCloseNotify is
472 // an error, but popular web sites seem to do this,
473 // so we can't make it an error.
474 // if err == os.EOF {
475 // err = io.ErrUnexpectedEOF
477 if e, ok := err.(net.Error); !ok || !e.Temporary() {
482 typ := recordType(b.data[0])
483 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
484 n := int(b.data[3])<<8 | int(b.data[4])
485 if c.haveVers && vers != c.vers {
486 return c.sendAlert(alertProtocolVersion)
488 if n > maxCiphertext {
489 return c.sendAlert(alertRecordOverflow)
492 // First message, be extra suspicious:
493 // this might not be a TLS client.
494 // Bail out before reading a full 'body', if possible.
495 // The current max version is 3.1.
496 // If the version is >= 16.0, it's probably not real.
497 // Similarly, a clientHello message encodes in
498 // well under a kilobyte. If the length is >= 12 kB,
499 // it's probably not real.
500 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
501 return c.sendAlert(alertUnexpectedMessage)
504 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
506 err = io.ErrUnexpectedEOF
508 if e, ok := err.(net.Error); !ok || !e.Temporary() {
515 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
516 b.off = recordHeaderLen
517 if ok, err := c.in.decrypt(b); !ok {
518 return c.sendAlert(err)
520 data := b.data[b.off:]
521 if len(data) > maxPlaintext {
522 c.sendAlert(alertRecordOverflow)
529 c.sendAlert(alertUnexpectedMessage)
531 case recordTypeAlert:
533 c.sendAlert(alertUnexpectedMessage)
536 if alert(data[1]) == alertCloseNotify {
541 case alertLevelWarning:
545 case alertLevelError:
546 c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
548 c.sendAlert(alertUnexpectedMessage)
551 case recordTypeChangeCipherSpec:
552 if typ != want || len(data) != 1 || data[0] != 1 {
553 c.sendAlert(alertUnexpectedMessage)
556 err := c.in.changeCipherSpec()
558 c.sendAlert(err.(alert))
561 case recordTypeApplicationData:
563 c.sendAlert(alertUnexpectedMessage)
569 case recordTypeHandshake:
570 // TODO(rsc): Should at least pick off connection close.
572 return c.sendAlert(alertNoRenegotiation)
583 // sendAlert sends a TLS alert message.
585 func (c *Conn) sendAlertLocked(err alert) os.Error {
586 c.tmp[0] = alertLevelError
587 if err == alertNoRenegotiation {
588 c.tmp[0] = alertLevelWarning
591 c.writeRecord(recordTypeAlert, c.tmp[0:2])
592 // closeNotify is a special case in that it isn't an error:
593 if err != alertCloseNotify {
594 return c.setError(&net.OpError{Op: "local error", Error: err})
599 // sendAlert sends a TLS alert message.
601 func (c *Conn) sendAlert(err alert) os.Error {
604 return c.sendAlertLocked(err)
607 // writeRecord writes a TLS record with the given type and payload
608 // to the connection and updates the record layer state.
610 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
611 b := c.out.newBlock()
614 if m > maxPlaintext {
617 b.resize(recordHeaderLen + m)
618 b.data[0] = byte(typ)
623 b.data[1] = byte(vers >> 8)
624 b.data[2] = byte(vers)
625 b.data[3] = byte(m >> 8)
627 copy(b.data[recordHeaderLen:], data)
629 _, err = c.conn.Write(b.data)
638 if typ == recordTypeChangeCipherSpec {
639 err = c.out.changeCipherSpec()
641 // Cannot call sendAlert directly,
642 // because we already hold c.out.Mutex.
643 c.tmp[0] = alertLevelError
644 c.tmp[1] = byte(err.(alert))
645 c.writeRecord(recordTypeAlert, c.tmp[0:2])
646 c.err = &net.OpError{Op: "local error", Error: err}
653 // readHandshake reads the next handshake message from
655 // c.in.Mutex < L; c.out.Mutex < L.
656 func (c *Conn) readHandshake() (interface{}, os.Error) {
657 for c.hand.Len() < 4 {
661 if err := c.readRecord(recordTypeHandshake); err != nil {
666 data := c.hand.Bytes()
667 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
668 if n > maxHandshake {
669 c.sendAlert(alertInternalError)
672 for c.hand.Len() < 4+n {
676 if err := c.readRecord(recordTypeHandshake); err != nil {
680 data = c.hand.Next(4 + n)
681 var m handshakeMessage
683 case typeClientHello:
684 m = new(clientHelloMsg)
685 case typeServerHello:
686 m = new(serverHelloMsg)
687 case typeCertificate:
688 m = new(certificateMsg)
689 case typeCertificateRequest:
690 m = new(certificateRequestMsg)
691 case typeCertificateStatus:
692 m = new(certificateStatusMsg)
693 case typeServerKeyExchange:
694 m = new(serverKeyExchangeMsg)
695 case typeServerHelloDone:
696 m = new(serverHelloDoneMsg)
697 case typeClientKeyExchange:
698 m = new(clientKeyExchangeMsg)
699 case typeCertificateVerify:
700 m = new(certificateVerifyMsg)
701 case typeNextProtocol:
702 m = new(nextProtoMsg)
706 c.sendAlert(alertUnexpectedMessage)
707 return nil, alertUnexpectedMessage
710 // The handshake message unmarshallers
711 // expect to be able to keep references to data,
712 // so pass in a fresh copy that won't be overwritten.
713 data = append([]byte(nil), data...)
715 if !m.unmarshal(data) {
716 c.sendAlert(alertUnexpectedMessage)
717 return nil, alertUnexpectedMessage
722 // Write writes data to the connection.
723 func (c *Conn) Write(b []byte) (n int, err os.Error) {
724 if err = c.Handshake(); err != nil {
731 if !c.handshakeComplete {
732 return 0, alertInternalError
737 return c.writeRecord(recordTypeApplicationData, b)
740 // Read can be made to time out and return err == os.EAGAIN
741 // after a fixed time limit; see SetTimeout and SetReadTimeout.
742 func (c *Conn) Read(b []byte) (n int, err os.Error) {
743 if err = c.Handshake(); err != nil {
750 for c.input == nil && c.err == nil {
751 if err := c.readRecord(recordTypeApplicationData); err != nil {
752 // Soft error, like EAGAIN
759 n, err = c.input.Read(b)
760 if c.input.off >= len(c.input.data) {
761 c.in.freeBlock(c.input)
767 // Close closes the connection.
768 func (c *Conn) Close() os.Error {
769 var alertErr os.Error
771 c.handshakeMutex.Lock()
772 defer c.handshakeMutex.Unlock()
773 if c.handshakeComplete {
774 alertErr = c.sendAlert(alertCloseNotify)
777 if err := c.conn.Close(); err != nil {
783 // Handshake runs the client or server handshake
784 // protocol if it has not yet been run.
785 // Most uses of this package need not call Handshake
786 // explicitly: the first Read or Write will call it automatically.
787 func (c *Conn) Handshake() os.Error {
788 c.handshakeMutex.Lock()
789 defer c.handshakeMutex.Unlock()
790 if err := c.error(); err != nil {
793 if c.handshakeComplete {
797 return c.clientHandshake()
799 return c.serverHandshake()
802 // ConnectionState returns basic TLS details about the connection.
803 func (c *Conn) ConnectionState() ConnectionState {
804 c.handshakeMutex.Lock()
805 defer c.handshakeMutex.Unlock()
807 var state ConnectionState
808 state.HandshakeComplete = c.handshakeComplete
809 if c.handshakeComplete {
810 state.NegotiatedProtocol = c.clientProtocol
811 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
812 state.CipherSuite = c.cipherSuite
813 state.PeerCertificates = c.peerCertificates
814 state.VerifiedChains = c.verifiedChains
815 state.ServerName = c.serverName
821 // OCSPResponse returns the stapled OCSP response from the TLS server, if
822 // any. (Only valid for client connections.)
823 func (c *Conn) OCSPResponse() []byte {
824 c.handshakeMutex.Lock()
825 defer c.handshakeMutex.Unlock()
827 return c.ocspResponse
830 // VerifyHostname checks that the peer certificate chain is valid for
831 // connecting to host. If so, it returns nil; if not, it returns an os.Error
832 // describing the problem.
833 func (c *Conn) VerifyHostname(host string) os.Error {
834 c.handshakeMutex.Lock()
835 defer c.handshakeMutex.Unlock()
837 return os.NewError("VerifyHostname called on TLS server connection")
839 if !c.handshakeComplete {
840 return os.NewError("TLS handshake has not yet been performed")
842 return c.peerCertificates[0].VerifyHostname(host)