80
80
// LocalAddr returns the local network address.
81
81
func (c *Conn) LocalAddr() net.Addr {
82
return c.conn.LocalAddr()
82
return c.conn.LocalAddr()
85
85
// RemoteAddr returns the remote network address.
86
86
func (c *Conn) RemoteAddr() net.Addr {
87
return c.conn.RemoteAddr()
87
return c.conn.RemoteAddr()
90
90
// SetDeadline sets the read and write deadlines associated with the connection.
91
91
// A zero value for t means Read and Write will not time out.
92
92
// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
93
93
func (c *Conn) SetDeadline(t time.Time) error {
94
return c.conn.SetDeadline(t)
94
return c.conn.SetDeadline(t)
97
97
// SetReadDeadline sets the read deadline on the underlying connection.
98
98
// A zero value for t means Read will not time out.
99
99
func (c *Conn) SetReadDeadline(t time.Time) error {
100
return c.conn.SetReadDeadline(t)
100
return c.conn.SetReadDeadline(t)
103
103
// SetWriteDeadline sets the write deadline on the underlying conneciton.
104
104
// A zero value for t means Write will not time out.
105
105
// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
106
106
func (c *Conn) SetWriteDeadline(t time.Time) error {
107
return c.conn.SetWriteDeadline(t)
107
return c.conn.SetWriteDeadline(t)
110
110
// A halfConn represents one direction of the record layer
111
111
// connection, either sending or receiving.
112
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
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
127
// prepareCipherSpec sets the encryption and MAC states
128
128
// that a subsequent changeCipherSpec will use.
129
129
func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
131
hc.nextCipher = cipher
131
hc.nextCipher = cipher
135
135
// changeCipherSpec changes the encryption and MAC states
136
136
// to the ones previously passed to prepareCipherSpec.
137
137
func (hc *halfConn) changeCipherSpec() error {
138
if hc.nextCipher == nil {
139
return alertInternalError
141
hc.cipher = hc.nextCipher
145
for i := range hc.seq {
138
if hc.nextCipher == nil {
139
return alertInternalError
141
hc.cipher = hc.nextCipher
145
for i := range hc.seq {
151
151
// incSeq increments the sequence number.
152
152
func (hc *halfConn) incSeq() {
153
for i := 7; i >= 0; i-- {
153
for i := 7; i >= 0; i-- {
160
// Not allowed to let sequence number wrap.
161
// Instead, must renegotiate before it does.
162
// Not likely enough to bother.
163
panic("TLS: sequence number wraparound")
160
// Not allowed to let sequence number wrap.
161
// Instead, must renegotiate before it does.
162
// Not likely enough to bother.
163
panic("TLS: sequence number wraparound")
166
166
// resetSeq resets the sequence number to zero.
167
167
func (hc *halfConn) resetSeq() {
168
for i := range hc.seq {
168
for i := range hc.seq {
173
173
// removePadding returns an unpadded slice, in constant time, which is a prefix
174
174
// of the input. It also returns a byte which is equal to 255 if the padding
175
175
// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
176
176
func removePadding(payload []byte) ([]byte, byte) {
177
if len(payload) < 1 {
181
paddingLen := payload[len(payload)-1]
182
t := uint(len(payload)-1) - uint(paddingLen)
183
// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
184
good := byte(int32(^t) >> 31)
186
toCheck := 255 // the maximum possible padding length
187
// The length of the padded data is public, so we can use an if here
188
if toCheck+1 > len(payload) {
189
toCheck = len(payload) - 1
192
for i := 0; i < toCheck; i++ {
193
t := uint(paddingLen) - uint(i)
194
// if i <= paddingLen then the MSB of t is zero
195
mask := byte(int32(^t) >> 31)
196
b := payload[len(payload)-1-i]
197
good &^= mask&paddingLen ^ mask&b
200
// We AND together the bits of good and replicate the result across
205
good = uint8(int8(good) >> 7)
207
toRemove := good&paddingLen + 1
208
return payload[:len(payload)-int(toRemove)], good
177
if len(payload) < 1 {
181
paddingLen := payload[len(payload)-1]
182
t := uint(len(payload)-1) - uint(paddingLen)
183
// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
184
good := byte(int32(^t) >> 31)
186
toCheck := 255 // the maximum possible padding length
187
// The length of the padded data is public, so we can use an if here
188
if toCheck+1 > len(payload) {
189
toCheck = len(payload) - 1
192
for i := 0; i < toCheck; i++ {
193
t := uint(paddingLen) - uint(i)
194
// if i <= paddingLen then the MSB of t is zero
195
mask := byte(int32(^t) >> 31)
196
b := payload[len(payload)-1-i]
197
good &^= mask&paddingLen ^ mask&b
200
// We AND together the bits of good and replicate the result across
205
good = uint8(int8(good) >> 7)
207
toRemove := good&paddingLen + 1
208
return payload[:len(payload)-int(toRemove)], good
211
211
// removePaddingSSL30 is a replacement for removePadding in the case that the
212
212
// protocol version is SSLv3. In this version, the contents of the padding
213
213
// are random and cannot be checked.
214
214
func removePaddingSSL30(payload []byte) ([]byte, byte) {
215
if len(payload) < 1 {
219
paddingLen := int(payload[len(payload)-1]) + 1
220
if paddingLen > len(payload) {
224
return payload[:len(payload)-paddingLen], 255
215
if len(payload) < 1 {
219
paddingLen := int(payload[len(payload)-1]) + 1
220
if paddingLen > len(payload) {
224
return payload[:len(payload)-paddingLen], 255
227
227
func roundUp(a, b int) int {
231
231
// decrypt checks and strips the mac and decrypts the data in b.
232
232
func (hc *halfConn) decrypt(b *block) (bool, alert) {
234
payload := b.data[recordHeaderLen:]
238
macSize = hc.mac.Size()
241
paddingGood := byte(255)
244
if hc.cipher != nil {
245
switch c := hc.cipher.(type) {
247
c.XORKeyStream(payload, payload)
248
case cipher.BlockMode:
249
blockSize := c.BlockSize()
251
if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
252
return false, alertBadRecordMAC
255
c.CryptBlocks(payload, payload)
256
if hc.version == versionSSL30 {
257
payload, paddingGood = removePaddingSSL30(payload)
259
payload, paddingGood = removePadding(payload)
261
b.resize(recordHeaderLen + len(payload))
263
// note that we still have a timing side-channel in the
264
// MAC check, below. An attacker can align the record
265
// so that a correct padding will cause one less hash
266
// block to be calculated. Then they can iteratively
267
// decrypt a record by breaking each byte. See
268
// "Password Interception in a SSL/TLS Channel", Brice
271
// However, our behavior matches OpenSSL, so we leak
272
// only as much as they do.
274
panic("unknown cipher type")
280
if len(payload) < macSize {
281
return false, alertBadRecordMAC
284
// strip mac off payload, b.data
285
n := len(payload) - macSize
286
b.data[3] = byte(n >> 8)
288
b.resize(recordHeaderLen + n)
289
remoteMAC := payload[n:]
290
localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
293
if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
294
return false, alertBadRecordMAC
296
hc.inDigestBuf = localMAC
234
payload := b.data[recordHeaderLen:]
238
macSize = hc.mac.Size()
241
paddingGood := byte(255)
244
if hc.cipher != nil {
245
switch c := hc.cipher.(type) {
247
c.XORKeyStream(payload, payload)
248
case cipher.BlockMode:
249
blockSize := c.BlockSize()
251
if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
252
return false, alertBadRecordMAC
255
c.CryptBlocks(payload, payload)
256
if hc.version == versionSSL30 {
257
payload, paddingGood = removePaddingSSL30(payload)
259
payload, paddingGood = removePadding(payload)
261
b.resize(recordHeaderLen + len(payload))
263
// note that we still have a timing side-channel in the
264
// MAC check, below. An attacker can align the record
265
// so that a correct padding will cause one less hash
266
// block to be calculated. Then they can iteratively
267
// decrypt a record by breaking each byte. See
268
// "Password Interception in a SSL/TLS Channel", Brice
271
// However, our behavior matches OpenSSL, so we leak
272
// only as much as they do.
274
panic("unknown cipher type")
280
if len(payload) < macSize {
281
return false, alertBadRecordMAC
284
// strip mac off payload, b.data
285
n := len(payload) - macSize
286
b.data[3] = byte(n >> 8)
288
b.resize(recordHeaderLen + n)
289
remoteMAC := payload[n:]
290
localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
293
if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
294
return false, alertBadRecordMAC
296
hc.inDigestBuf = localMAC
302
302
// padToBlockSize calculates the needed padding block, if any, for a payload.
305
305
// any suffix of payload as well as the needed padding to make finalBlock a
307
307
func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
308
overrun := len(payload) % blockSize
309
paddingLen := blockSize - overrun
310
prefix = payload[:len(payload)-overrun]
311
finalBlock = make([]byte, blockSize)
312
copy(finalBlock, payload[len(payload)-overrun:])
313
for i := overrun; i < blockSize; i++ {
314
finalBlock[i] = byte(paddingLen - 1)
308
overrun := len(payload) % blockSize
309
paddingLen := blockSize - overrun
310
prefix = payload[:len(payload)-overrun]
311
finalBlock = make([]byte, blockSize)
312
copy(finalBlock, payload[len(payload)-overrun:])
313
for i := overrun; i < blockSize; i++ {
314
finalBlock[i] = byte(paddingLen - 1)
319
319
// encrypt encrypts and macs the data in b.
320
320
func (hc *halfConn) encrypt(b *block) (bool, alert) {
323
mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
327
b.resize(n + len(mac))
328
copy(b.data[n:], mac)
329
hc.outDigestBuf = mac
332
payload := b.data[recordHeaderLen:]
335
if hc.cipher != nil {
336
switch c := hc.cipher.(type) {
338
c.XORKeyStream(payload, payload)
339
case cipher.BlockMode:
340
prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
341
b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
342
c.CryptBlocks(b.data[recordHeaderLen:], prefix)
343
c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
345
panic("unknown cipher type")
349
// update length to include MAC and any block padding needed.
350
n := len(b.data) - recordHeaderLen
351
b.data[3] = byte(n >> 8)
323
mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
327
b.resize(n + len(mac))
328
copy(b.data[n:], mac)
329
hc.outDigestBuf = mac
332
payload := b.data[recordHeaderLen:]
335
if hc.cipher != nil {
336
switch c := hc.cipher.(type) {
338
c.XORKeyStream(payload, payload)
339
case cipher.BlockMode:
340
prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
341
b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
342
c.CryptBlocks(b.data[recordHeaderLen:], prefix)
343
c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
345
panic("unknown cipher type")
349
// update length to include MAC and any block padding needed.
350
n := len(b.data) - recordHeaderLen
351
b.data[3] = byte(n >> 8)
357
357
// A block is a simple data buffer.
358
358
type block struct {
360
off int // index for Read
360
off int // index for Read
364
364
// resize resizes block to be n bytes, growing if necessary.
365
365
func (b *block) resize(n int) {
372
372
// reserve makes sure that block contains a capacity of at least n bytes.
373
373
func (b *block) reserve(n int) {
374
if cap(b.data) >= n {
384
data := make([]byte, len(b.data), m)
374
if cap(b.data) >= n {
384
data := make([]byte, len(b.data), m)
389
389
// readFromUntil reads from r into b until b contains at least n bytes
390
390
// or else returns an error.
391
391
func (b *block) readFromUntil(r io.Reader, n int) error {
393
if len(b.data) >= n {
393
if len(b.data) >= n {
397
// read until have enough.
400
m, err := r.Read(b.data[len(b.data):cap(b.data)])
401
b.data = b.data[0 : len(b.data)+m]
402
if len(b.data) >= n {
397
// read until have enough.
400
m, err := r.Read(b.data[len(b.data):cap(b.data)])
401
b.data = b.data[0 : len(b.data)+m]
402
if len(b.data) >= n {
412
412
func (b *block) Read(p []byte) (n int, err error) {
413
n = copy(p, b.data[b.off:])
413
n = copy(p, b.data[b.off:])
418
418
// newBlock allocates a new block, from hc's free list if possible.
419
419
func (hc *halfConn) newBlock() *block {
430
430
// freeBlock returns a block to hc's free list.
432
432
// its free list at a time, so there's no need to worry about
433
433
// trimming the list, etc.
434
434
func (hc *halfConn) freeBlock(b *block) {
439
439
// splitBlock splits a block after the first n bytes,
440
440
// returning a block with those n bytes and a
441
441
// block with the remainder. the latter may be nil.
442
442
func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
443
if len(b.data) <= n {
447
bb.resize(len(b.data) - n)
448
copy(bb.data, b.data[n:])
443
if len(b.data) <= n {
447
bb.resize(len(b.data) - n)
448
copy(bb.data, b.data[n:])
453
453
// readRecord reads the next TLS record from the connection
454
454
// and updates the record layer state.
455
455
// c.in.Mutex <= L; c.input == nil.
456
456
func (c *Conn) readRecord(want recordType) error {
457
// Caller must be in sync with connection:
458
// handshake data if handshake not yet completed,
459
// else application data.
462
return c.sendAlert(alertInternalError)
463
case recordTypeHandshake, recordTypeChangeCipherSpec:
464
if c.handshakeComplete {
465
return c.sendAlert(alertInternalError)
467
case recordTypeApplicationData:
468
if !c.handshakeComplete {
469
return c.sendAlert(alertInternalError)
457
// Caller must be in sync with connection:
458
// handshake data if handshake not yet completed,
459
// else application data.
462
return c.sendAlert(alertInternalError)
463
case recordTypeHandshake, recordTypeChangeCipherSpec:
464
if c.handshakeComplete {
465
return c.sendAlert(alertInternalError)
467
case recordTypeApplicationData:
468
if !c.handshakeComplete {
469
return c.sendAlert(alertInternalError)
474
if c.rawInput == nil {
475
c.rawInput = c.in.newBlock()
479
// Read header, payload.
480
if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
481
// RFC suggests that EOF without an alertCloseNotify is
482
// an error, but popular web sites seem to do this,
483
// so we can't make it an error.
484
// if err == io.EOF {
485
// err = io.ErrUnexpectedEOF
487
if e, ok := err.(net.Error); !ok || !e.Temporary() {
492
typ := recordType(b.data[0])
493
vers := uint16(b.data[1])<<8 | uint16(b.data[2])
494
n := int(b.data[3])<<8 | int(b.data[4])
495
if c.haveVers && vers != c.vers {
496
return c.sendAlert(alertProtocolVersion)
498
if n > maxCiphertext {
499
return c.sendAlert(alertRecordOverflow)
502
// First message, be extra suspicious:
503
// this might not be a TLS client.
504
// Bail out before reading a full 'body', if possible.
505
// The current max version is 3.1.
506
// If the version is >= 16.0, it's probably not real.
507
// Similarly, a clientHello message encodes in
508
// well under a kilobyte. If the length is >= 12 kB,
509
// it's probably not real.
510
if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
511
return c.sendAlert(alertUnexpectedMessage)
514
if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
516
err = io.ErrUnexpectedEOF
518
if e, ok := err.(net.Error); !ok || !e.Temporary() {
525
b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
526
b.off = recordHeaderLen
527
if ok, err := c.in.decrypt(b); !ok {
528
return c.sendAlert(err)
530
data := b.data[b.off:]
531
if len(data) > maxPlaintext {
532
c.sendAlert(alertRecordOverflow)
539
c.sendAlert(alertUnexpectedMessage)
541
case recordTypeAlert:
543
c.sendAlert(alertUnexpectedMessage)
546
if alert(data[1]) == alertCloseNotify {
551
case alertLevelWarning:
555
case alertLevelError:
556
c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
558
c.sendAlert(alertUnexpectedMessage)
561
case recordTypeChangeCipherSpec:
562
if typ != want || len(data) != 1 || data[0] != 1 {
563
c.sendAlert(alertUnexpectedMessage)
566
err := c.in.changeCipherSpec()
568
c.sendAlert(err.(alert))
571
case recordTypeApplicationData:
573
c.sendAlert(alertUnexpectedMessage)
579
case recordTypeHandshake:
580
// TODO(rsc): Should at least pick off connection close.
581
if typ != want && !c.isClient {
582
return c.sendAlert(alertNoRenegotiation)
474
if c.rawInput == nil {
475
c.rawInput = c.in.newBlock()
479
// Read header, payload.
480
if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
481
// RFC suggests that EOF without an alertCloseNotify is
482
// an error, but popular web sites seem to do this,
483
// so we can't make it an error.
484
// if err == io.EOF {
485
// err = io.ErrUnexpectedEOF
487
if e, ok := err.(net.Error); !ok || !e.Temporary() {
492
typ := recordType(b.data[0])
493
vers := uint16(b.data[1])<<8 | uint16(b.data[2])
494
n := int(b.data[3])<<8 | int(b.data[4])
495
if c.haveVers && vers != c.vers {
496
return c.sendAlert(alertProtocolVersion)
498
if n > maxCiphertext {
499
return c.sendAlert(alertRecordOverflow)
502
// First message, be extra suspicious:
503
// this might not be a TLS client.
504
// Bail out before reading a full 'body', if possible.
505
// The current max version is 3.1.
506
// If the version is >= 16.0, it's probably not real.
507
// Similarly, a clientHello message encodes in
508
// well under a kilobyte. If the length is >= 12 kB,
509
// it's probably not real.
510
if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
511
return c.sendAlert(alertUnexpectedMessage)
514
if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
516
err = io.ErrUnexpectedEOF
518
if e, ok := err.(net.Error); !ok || !e.Temporary() {
525
b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
526
b.off = recordHeaderLen
527
if ok, err := c.in.decrypt(b); !ok {
528
return c.sendAlert(err)
530
data := b.data[b.off:]
531
if len(data) > maxPlaintext {
532
c.sendAlert(alertRecordOverflow)
539
c.sendAlert(alertUnexpectedMessage)
541
case recordTypeAlert:
543
c.sendAlert(alertUnexpectedMessage)
546
if alert(data[1]) == alertCloseNotify {
551
case alertLevelWarning:
555
case alertLevelError:
556
c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
558
c.sendAlert(alertUnexpectedMessage)
561
case recordTypeChangeCipherSpec:
562
if typ != want || len(data) != 1 || data[0] != 1 {
563
c.sendAlert(alertUnexpectedMessage)
566
err := c.in.changeCipherSpec()
568
c.sendAlert(err.(alert))
571
case recordTypeApplicationData:
573
c.sendAlert(alertUnexpectedMessage)
579
case recordTypeHandshake:
580
// TODO(rsc): Should at least pick off connection close.
581
if typ != want && !c.isClient {
582
return c.sendAlert(alertNoRenegotiation)
593
593
// sendAlert sends a TLS alert message.
594
594
// c.out.Mutex <= L.
595
595
func (c *Conn) sendAlertLocked(err alert) error {
596
c.tmp[0] = alertLevelError
597
if err == alertNoRenegotiation {
598
c.tmp[0] = alertLevelWarning
601
c.writeRecord(recordTypeAlert, c.tmp[0:2])
602
// closeNotify is a special case in that it isn't an error:
603
if err != alertCloseNotify {
604
return c.setError(&net.OpError{Op: "local error", Err: err})
596
c.tmp[0] = alertLevelError
597
if err == alertNoRenegotiation {
598
c.tmp[0] = alertLevelWarning
601
c.writeRecord(recordTypeAlert, c.tmp[0:2])
602
// closeNotify is a special case in that it isn't an error:
603
if err != alertCloseNotify {
604
return c.setError(&net.OpError{Op: "local error", Err: err})
609
609
// sendAlert sends a TLS alert message.
610
610
// L < c.out.Mutex.
611
611
func (c *Conn) sendAlert(err alert) error {
614
return c.sendAlertLocked(err)
614
return c.sendAlertLocked(err)
617
617
// writeRecord writes a TLS record with the given type and payload
618
618
// to the connection and updates the record layer state.
619
619
// c.out.Mutex <= L.
620
620
func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
621
b := c.out.newBlock()
624
if m > maxPlaintext {
627
b.resize(recordHeaderLen + m)
628
b.data[0] = byte(typ)
633
b.data[1] = byte(vers >> 8)
634
b.data[2] = byte(vers)
635
b.data[3] = byte(m >> 8)
637
copy(b.data[recordHeaderLen:], data)
639
_, err = c.conn.Write(b.data)
621
b := c.out.newBlock()
624
if m > maxPlaintext {
627
b.resize(recordHeaderLen + m)
628
b.data[0] = byte(typ)
633
b.data[1] = byte(vers >> 8)
634
b.data[2] = byte(vers)
635
b.data[3] = byte(m >> 8)
637
copy(b.data[recordHeaderLen:], data)
639
_, err = c.conn.Write(b.data)
648
if typ == recordTypeChangeCipherSpec {
649
err = c.out.changeCipherSpec()
651
// Cannot call sendAlert directly,
652
// because we already hold c.out.Mutex.
653
c.tmp[0] = alertLevelError
654
c.tmp[1] = byte(err.(alert))
655
c.writeRecord(recordTypeAlert, c.tmp[0:2])
656
c.err = &net.OpError{Op: "local error", Err: err}
648
if typ == recordTypeChangeCipherSpec {
649
err = c.out.changeCipherSpec()
651
// Cannot call sendAlert directly,
652
// because we already hold c.out.Mutex.
653
c.tmp[0] = alertLevelError
654
c.tmp[1] = byte(err.(alert))
655
c.writeRecord(recordTypeAlert, c.tmp[0:2])
656
c.err = &net.OpError{Op: "local error", Err: err}
663
663
// readHandshake reads the next handshake message from
664
664
// the record layer.
665
665
// c.in.Mutex < L; c.out.Mutex < L.
666
666
func (c *Conn) readHandshake() (interface{}, error) {
667
for c.hand.Len() < 4 {
671
if err := c.readRecord(recordTypeHandshake); err != nil {
676
data := c.hand.Bytes()
677
n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
678
if n > maxHandshake {
679
c.sendAlert(alertInternalError)
682
for c.hand.Len() < 4+n {
686
if err := c.readRecord(recordTypeHandshake); err != nil {
690
data = c.hand.Next(4 + n)
691
var m handshakeMessage
693
case typeHelloRequest:
694
m = new(helloRequestMsg)
695
case typeClientHello:
696
m = new(clientHelloMsg)
697
case typeServerHello:
698
m = new(serverHelloMsg)
699
case typeCertificate:
700
m = new(certificateMsg)
701
case typeCertificateRequest:
702
m = new(certificateRequestMsg)
703
case typeCertificateStatus:
704
m = new(certificateStatusMsg)
705
case typeServerKeyExchange:
706
m = new(serverKeyExchangeMsg)
707
case typeServerHelloDone:
708
m = new(serverHelloDoneMsg)
709
case typeClientKeyExchange:
710
m = new(clientKeyExchangeMsg)
711
case typeCertificateVerify:
712
m = new(certificateVerifyMsg)
713
case typeNextProtocol:
714
m = new(nextProtoMsg)
718
c.sendAlert(alertUnexpectedMessage)
719
return nil, alertUnexpectedMessage
722
// The handshake message unmarshallers
723
// expect to be able to keep references to data,
724
// so pass in a fresh copy that won't be overwritten.
725
data = append([]byte(nil), data...)
727
if !m.unmarshal(data) {
728
c.sendAlert(alertUnexpectedMessage)
729
return nil, alertUnexpectedMessage
667
for c.hand.Len() < 4 {
671
if err := c.readRecord(recordTypeHandshake); err != nil {
676
data := c.hand.Bytes()
677
n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
678
if n > maxHandshake {
679
c.sendAlert(alertInternalError)
682
for c.hand.Len() < 4+n {
686
if err := c.readRecord(recordTypeHandshake); err != nil {
690
data = c.hand.Next(4 + n)
691
var m handshakeMessage
693
case typeHelloRequest:
694
m = new(helloRequestMsg)
695
case typeClientHello:
696
m = new(clientHelloMsg)
697
case typeServerHello:
698
m = new(serverHelloMsg)
699
case typeCertificate:
700
m = new(certificateMsg)
701
case typeCertificateRequest:
702
m = new(certificateRequestMsg)
703
case typeCertificateStatus:
704
m = new(certificateStatusMsg)
705
case typeServerKeyExchange:
706
m = new(serverKeyExchangeMsg)
707
case typeServerHelloDone:
708
m = new(serverHelloDoneMsg)
709
case typeClientKeyExchange:
710
m = new(clientKeyExchangeMsg)
711
case typeCertificateVerify:
712
m = new(certificateVerifyMsg)
713
case typeNextProtocol:
714
m = new(nextProtoMsg)
718
c.sendAlert(alertUnexpectedMessage)
719
return nil, alertUnexpectedMessage
722
// The handshake message unmarshallers
723
// expect to be able to keep references to data,
724
// so pass in a fresh copy that won't be overwritten.
725
data = append([]byte(nil), data...)
727
if !m.unmarshal(data) {
728
c.sendAlert(alertUnexpectedMessage)
729
return nil, alertUnexpectedMessage
734
734
// Write writes data to the connection.
735
735
func (c *Conn) Write(b []byte) (int, error) {
740
if c.err = c.Handshake(); c.err != nil {
747
if !c.handshakeComplete {
748
return 0, alertInternalError
752
n, c.err = c.writeRecord(recordTypeApplicationData, b)
740
if c.err = c.Handshake(); c.err != nil {
747
if !c.handshakeComplete {
748
return 0, alertInternalError
752
n, c.err = c.writeRecord(recordTypeApplicationData, b)
756
756
func (c *Conn) handleRenegotiation() error {
757
c.handshakeComplete = false
759
panic("renegotiation should only happen for a client")
762
msg, err := c.readHandshake()
766
_, ok := msg.(*helloRequestMsg)
768
c.sendAlert(alertUnexpectedMessage)
769
return alertUnexpectedMessage
757
c.handshakeComplete = false
759
panic("renegotiation should only happen for a client")
762
msg, err := c.readHandshake()
766
_, ok := msg.(*helloRequestMsg)
768
c.sendAlert(alertUnexpectedMessage)
769
return alertUnexpectedMessage
775
775
// Read can be made to time out and return a net.Error with Timeout() == true
776
776
// after a fixed time limit; see SetDeadline and SetReadDeadline.
777
777
func (c *Conn) Read(b []byte) (n int, err error) {
778
if err = c.Handshake(); err != nil {
785
for c.input == nil && c.err == nil {
786
if err := c.readRecord(recordTypeApplicationData); err != nil {
787
// Soft error, like EAGAIN
790
if c.hand.Len() > 0 {
791
// We received handshake bytes, indicating the start of
793
if err := c.handleRenegotiation(); err != nil {
802
n, err = c.input.Read(b)
803
if c.input.off >= len(c.input.data) {
804
c.in.freeBlock(c.input)
778
if err = c.Handshake(); err != nil {
785
for c.input == nil && c.err == nil {
786
if err := c.readRecord(recordTypeApplicationData); err != nil {
787
// Soft error, like EAGAIN
790
if c.hand.Len() > 0 {
791
// We received handshake bytes, indicating the start of
793
if err := c.handleRenegotiation(); err != nil {
802
n, err = c.input.Read(b)
803
if c.input.off >= len(c.input.data) {
804
c.in.freeBlock(c.input)
810
810
// Close closes the connection.
811
811
func (c *Conn) Close() error {
814
c.handshakeMutex.Lock()
815
defer c.handshakeMutex.Unlock()
816
if c.handshakeComplete {
817
alertErr = c.sendAlert(alertCloseNotify)
820
if err := c.conn.Close(); err != nil {
814
c.handshakeMutex.Lock()
815
defer c.handshakeMutex.Unlock()
816
if c.handshakeComplete {
817
alertErr = c.sendAlert(alertCloseNotify)
820
if err := c.conn.Close(); err != nil {
826
826
// Handshake runs the client or server handshake