1 // TLS low level connection and record layer
16 // A Conn represents a secured connection.
17 // It implements the net.Conn interface.
23 // constant after handshake; protected by handshakeMutex
24 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
25 vers uint16 // TLS version
26 haveVers bool // version has been negotiated
27 config *Config // configuration passed to constructor
28 handshakeComplete bool
30 ocspResponse []byte // stapled OCSP response
31 peerCertificates []*x509.Certificate
35 // first permanent error
40 in, out halfConn // in.Mutex < out.Mutex
41 rawInput *block // raw input, right off the wire
42 input *block // application data waiting to be read
43 hand bytes.Buffer // handshake data waiting to be read
48 func (c *Conn) setError(err os.Error) os.Error {
50 defer c.errMutex.Unlock()
58 func (c *Conn) error() os.Error {
60 defer c.errMutex.Unlock()
65 // Access to net.Conn methods.
66 // Cannot just embed net.Conn because that would
67 // export the struct field too.
69 // LocalAddr returns the local network address.
70 func (c *Conn) LocalAddr() net.Addr {
71 return c.conn.LocalAddr()
74 // RemoteAddr returns the remote network address.
75 func (c *Conn) RemoteAddr() net.Addr {
76 return c.conn.RemoteAddr()
79 // SetTimeout sets the read deadline associated with the connection.
80 // There is no write deadline.
81 func (c *Conn) SetTimeout(nsec int64) os.Error {
82 return c.conn.SetTimeout(nsec)
85 // SetReadTimeout sets the time (in nanoseconds) that
86 // Read will wait for data before returning os.EAGAIN.
87 // Setting nsec == 0 (the default) disables the deadline.
88 func (c *Conn) SetReadTimeout(nsec int64) os.Error {
89 return c.conn.SetReadTimeout(nsec)
92 // SetWriteTimeout exists to satisfy the net.Conn interface
93 // but is not implemented by TLS. It always returns an error.
94 func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
95 return os.NewError("TLS does not support SetWriteTimeout")
98 // A halfConn represents one direction of the record layer
99 // connection, either sending or receiving.
100 type halfConn struct {
102 crypt encryptor // encryption state
103 mac hash.Hash // MAC algorithm
104 seq [8]byte // 64-bit sequence number
105 bfree *block // list of free blocks
107 nextCrypt encryptor // next encryption state
108 nextMac hash.Hash // next MAC algorithm
111 // prepareCipherSpec sets the encryption and MAC states
112 // that a subsequent changeCipherSpec will use.
113 func (hc *halfConn) prepareCipherSpec(crypt encryptor, mac hash.Hash) {
118 // changeCipherSpec changes the encryption and MAC states
119 // to the ones previously passed to prepareCipherSpec.
120 func (hc *halfConn) changeCipherSpec() os.Error {
121 if hc.nextCrypt == nil {
122 return alertInternalError
124 hc.crypt = hc.nextCrypt
131 // incSeq increments the sequence number.
132 func (hc *halfConn) incSeq() {
133 for i := 7; i >= 0; i-- {
140 // Not allowed to let sequence number wrap.
141 // Instead, must renegotiate before it does.
142 // Not likely enough to bother.
143 panic("TLS: sequence number wraparound")
146 // resetSeq resets the sequence number to zero.
147 func (hc *halfConn) resetSeq() {
148 for i := range hc.seq {
153 // decrypt checks and strips the mac and decrypts the data in b.
154 func (hc *halfConn) decrypt(b *block) (bool, alert) {
156 payload := b.data[recordHeaderLen:]
160 hc.crypt.XORKeyStream(payload)
165 if len(payload) < hc.mac.Size() {
166 return false, alertBadRecordMAC
169 // strip mac off payload, b.data
170 n := len(payload) - hc.mac.Size()
171 b.data[3] = byte(n >> 8)
173 b.data = b.data[0 : recordHeaderLen+n]
174 remoteMAC := payload[n:]
177 hc.mac.Write(hc.seq[0:])
181 if subtle.ConstantTimeCompare(hc.mac.Sum(), remoteMAC) != 1 {
182 return false, alertBadRecordMAC
189 // encrypt encrypts and macs the data in b.
190 func (hc *halfConn) encrypt(b *block) (bool, alert) {
194 hc.mac.Write(hc.seq[0:])
199 b.resize(n + len(mac))
200 copy(b.data[n:], mac)
202 // update length to include mac
203 n = len(b.data) - recordHeaderLen
204 b.data[3] = byte(n >> 8)
210 hc.crypt.XORKeyStream(b.data[recordHeaderLen:])
216 // A block is a simple data buffer.
219 off int // index for Read
223 // resize resizes block to be n bytes, growing if necessary.
224 func (b *block) resize(n int) {
231 // reserve makes sure that block contains a capacity of at least n bytes.
232 func (b *block) reserve(n int) {
233 if cap(b.data) >= n {
243 data := make([]byte, len(b.data), m)
248 // readFromUntil reads from r into b until b contains at least n bytes
249 // or else returns an error.
250 func (b *block) readFromUntil(r io.Reader, n int) os.Error {
252 if len(b.data) >= n {
256 // read until have enough.
259 m, err := r.Read(b.data[len(b.data):cap(b.data)])
260 b.data = b.data[0 : len(b.data)+m]
261 if len(b.data) >= n {
271 func (b *block) Read(p []byte) (n int, err os.Error) {
272 n = copy(p, b.data[b.off:])
277 // newBlock allocates a new block, from hc's free list if possible.
278 func (hc *halfConn) newBlock() *block {
289 // freeBlock returns a block to hc's free list.
290 // The protocol is such that each side only has a block or two on
291 // its free list at a time, so there's no need to worry about
292 // trimming the list, etc.
293 func (hc *halfConn) freeBlock(b *block) {
298 // splitBlock splits a block after the first n bytes,
299 // returning a block with those n bytes and a
300 // block with the remaindec. the latter may be nil.
301 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
302 if len(b.data) <= n {
306 bb.resize(len(b.data) - n)
307 copy(bb.data, b.data[n:])
312 // readRecord reads the next TLS record from the connection
313 // and updates the record layer state.
314 // c.in.Mutex <= L; c.input == nil.
315 func (c *Conn) readRecord(want recordType) os.Error {
316 // Caller must be in sync with connection:
317 // handshake data if handshake not yet completed,
318 // else application data. (We don't support renegotiation.)
321 return c.sendAlert(alertInternalError)
322 case recordTypeHandshake, recordTypeChangeCipherSpec:
323 if c.handshakeComplete {
324 return c.sendAlert(alertInternalError)
326 case recordTypeApplicationData:
327 if !c.handshakeComplete {
328 return c.sendAlert(alertInternalError)
333 if c.rawInput == nil {
334 c.rawInput = c.in.newBlock()
338 // Read header, payload.
339 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
340 // RFC suggests that EOF without an alertCloseNotify is
341 // an error, but popular web sites seem to do this,
342 // so we can't make it an error.
343 // if err == os.EOF {
344 // err = io.ErrUnexpectedEOF
346 if e, ok := err.(net.Error); !ok || !e.Temporary() {
351 typ := recordType(b.data[0])
352 vers := uint16(b.data[1])<<8 | uint16(b.data[2])
353 n := int(b.data[3])<<8 | int(b.data[4])
354 if c.haveVers && vers != c.vers {
355 return c.sendAlert(alertProtocolVersion)
357 if n > maxCiphertext {
358 return c.sendAlert(alertRecordOverflow)
360 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
362 err = io.ErrUnexpectedEOF
364 if e, ok := err.(net.Error); !ok || !e.Temporary() {
371 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
372 b.off = recordHeaderLen
373 if ok, err := c.in.decrypt(b); !ok {
374 return c.sendAlert(err)
376 data := b.data[b.off:]
377 if len(data) > maxPlaintext {
378 c.sendAlert(alertRecordOverflow)
385 c.sendAlert(alertUnexpectedMessage)
387 case recordTypeAlert:
389 c.sendAlert(alertUnexpectedMessage)
392 if alert(data[1]) == alertCloseNotify {
397 case alertLevelWarning:
401 case alertLevelError:
402 c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
404 c.sendAlert(alertUnexpectedMessage)
407 case recordTypeChangeCipherSpec:
408 if typ != want || len(data) != 1 || data[0] != 1 {
409 c.sendAlert(alertUnexpectedMessage)
412 err := c.in.changeCipherSpec()
414 c.sendAlert(err.(alert))
417 case recordTypeApplicationData:
419 c.sendAlert(alertUnexpectedMessage)
425 case recordTypeHandshake:
426 // TODO(rsc): Should at least pick off connection close.
428 return c.sendAlert(alertNoRenegotiation)
439 // sendAlert sends a TLS alert message.
441 func (c *Conn) sendAlertLocked(err alert) os.Error {
442 c.tmp[0] = alertLevelError
443 if err == alertNoRenegotiation {
444 c.tmp[0] = alertLevelWarning
447 c.writeRecord(recordTypeAlert, c.tmp[0:2])
448 // closeNotify is a special case in that it isn't an error:
449 if err != alertCloseNotify {
450 return c.setError(&net.OpError{Op: "local error", Error: err})
455 // sendAlert sends a TLS alert message.
457 func (c *Conn) sendAlert(err alert) os.Error {
460 return c.sendAlertLocked(err)
463 // writeRecord writes a TLS record with the given type and payload
464 // to the connection and updates the record layer state.
466 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
467 b := c.out.newBlock()
470 if m > maxPlaintext {
473 b.resize(recordHeaderLen + m)
474 b.data[0] = byte(typ)
479 b.data[1] = byte(vers >> 8)
480 b.data[2] = byte(vers)
481 b.data[3] = byte(m >> 8)
483 copy(b.data[recordHeaderLen:], data)
485 _, err = c.conn.Write(b.data)
494 if typ == recordTypeChangeCipherSpec {
495 err = c.out.changeCipherSpec()
497 // Cannot call sendAlert directly,
498 // because we already hold c.out.Mutex.
499 c.tmp[0] = alertLevelError
500 c.tmp[1] = byte(err.(alert))
501 c.writeRecord(recordTypeAlert, c.tmp[0:2])
502 c.err = &net.OpError{Op: "local error", Error: err}
509 // readHandshake reads the next handshake message from
511 // c.in.Mutex < L; c.out.Mutex < L.
512 func (c *Conn) readHandshake() (interface{}, os.Error) {
513 for c.hand.Len() < 4 {
517 c.readRecord(recordTypeHandshake)
520 data := c.hand.Bytes()
521 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
522 if n > maxHandshake {
523 c.sendAlert(alertInternalError)
526 for c.hand.Len() < 4+n {
530 c.readRecord(recordTypeHandshake)
532 data = c.hand.Next(4 + n)
533 var m handshakeMessage
535 case typeClientHello:
536 m = new(clientHelloMsg)
537 case typeServerHello:
538 m = new(serverHelloMsg)
539 case typeCertificate:
540 m = new(certificateMsg)
541 case typeCertificateRequest:
542 m = new(certificateRequestMsg)
543 case typeCertificateStatus:
544 m = new(certificateStatusMsg)
545 case typeServerHelloDone:
546 m = new(serverHelloDoneMsg)
547 case typeClientKeyExchange:
548 m = new(clientKeyExchangeMsg)
549 case typeCertificateVerify:
550 m = new(certificateVerifyMsg)
551 case typeNextProtocol:
552 m = new(nextProtoMsg)
556 c.sendAlert(alertUnexpectedMessage)
557 return nil, alertUnexpectedMessage
560 // The handshake message unmarshallers
561 // expect to be able to keep references to data,
562 // so pass in a fresh copy that won't be overwritten.
563 data = bytes.Add(nil, data)
565 if !m.unmarshal(data) {
566 c.sendAlert(alertUnexpectedMessage)
567 return nil, alertUnexpectedMessage
572 // Write writes data to the connection.
573 func (c *Conn) Write(b []byte) (n int, err os.Error) {
574 if err = c.Handshake(); err != nil {
581 if !c.handshakeComplete {
582 return 0, alertInternalError
587 return c.writeRecord(recordTypeApplicationData, b)
590 // Read can be made to time out and return err == os.EAGAIN
591 // after a fixed time limit; see SetTimeout and SetReadTimeout.
592 func (c *Conn) Read(b []byte) (n int, err os.Error) {
593 if err = c.Handshake(); err != nil {
600 for c.input == nil && c.err == nil {
601 if err := c.readRecord(recordTypeApplicationData); err != nil {
602 // Soft error, like EAGAIN
609 n, err = c.input.Read(b)
610 if c.input.off >= len(c.input.data) {
611 c.in.freeBlock(c.input)
617 // Close closes the connection.
618 func (c *Conn) Close() os.Error {
619 if err := c.Handshake(); err != nil {
622 return c.sendAlert(alertCloseNotify)
625 // Handshake runs the client or server handshake
626 // protocol if it has not yet been run.
627 // Most uses of this package need not call Handshake
628 // explicitly: the first Read or Write will call it automatically.
629 func (c *Conn) Handshake() os.Error {
630 c.handshakeMutex.Lock()
631 defer c.handshakeMutex.Unlock()
632 if err := c.error(); err != nil {
635 if c.handshakeComplete {
639 return c.clientHandshake()
641 return c.serverHandshake()
644 // ConnectionState returns basic TLS details about the connection.
645 func (c *Conn) ConnectionState() ConnectionState {
646 c.handshakeMutex.Lock()
647 defer c.handshakeMutex.Unlock()
649 var state ConnectionState
650 state.HandshakeComplete = c.handshakeComplete
651 if c.handshakeComplete {
652 state.NegotiatedProtocol = c.clientProtocol
653 state.CipherSuite = c.cipherSuite
659 // OCSPResponse returns the stapled OCSP response from the TLS server, if
660 // any. (Only valid for client connections.)
661 func (c *Conn) OCSPResponse() []byte {
662 c.handshakeMutex.Lock()
663 defer c.handshakeMutex.Unlock()
665 return c.ocspResponse
668 // PeerCertificates returns the certificate chain that was presented by the
670 func (c *Conn) PeerCertificates() []*x509.Certificate {
671 c.handshakeMutex.Lock()
672 defer c.handshakeMutex.Unlock()
674 return c.peerCertificates
677 // VerifyHostname checks that the peer certificate chain is valid for
678 // connecting to host. If so, it returns nil; if not, it returns an os.Error
679 // describing the problem.
680 func (c *Conn) VerifyHostname(host string) os.Error {
681 c.handshakeMutex.Lock()
682 defer c.handshakeMutex.Unlock()
684 return os.ErrorString("VerifyHostname called on TLS server connection")
686 if !c.handshakeComplete {
687 return os.ErrorString("TLS handshake has not yet been performed")
689 return c.peerCertificates[0].VerifyHostname(host)