OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [crypto/] [tls/] [conn.go] - Blame information for rev 747

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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.
4
 
5
// TLS low level connection and record layer
6
 
7
package tls
8
 
9
import (
10
        "bytes"
11
        "crypto/cipher"
12
        "crypto/subtle"
13
        "crypto/x509"
14
        "errors"
15
        "io"
16
        "net"
17
        "sync"
18
        "time"
19
)
20
 
21
// A Conn represents a secured connection.
22
// It implements the net.Conn interface.
23
type Conn struct {
24
        // constant
25
        conn     net.Conn
26
        isClient bool
27
 
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
34
        cipherSuite       uint16
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
40
        // serverName contains the server name indicated by the client, if any.
41
        serverName string
42
 
43
        clientProtocol         string
44
        clientProtocolFallback bool
45
 
46
        // first permanent error
47
        errMutex sync.Mutex
48
        err      error
49
 
50
        // input/output
51
        in, out  halfConn     // in.Mutex < out.Mutex
52
        rawInput *block       // raw input, right off the wire
53
        input    *block       // application data waiting to be read
54
        hand     bytes.Buffer // handshake data waiting to be read
55
 
56
        tmp [16]byte
57
}
58
 
59
func (c *Conn) setError(err error) error {
60
        c.errMutex.Lock()
61
        defer c.errMutex.Unlock()
62
 
63
        if c.err == nil {
64
                c.err = err
65
        }
66
        return err
67
}
68
 
69
func (c *Conn) error() error {
70
        c.errMutex.Lock()
71
        defer c.errMutex.Unlock()
72
 
73
        return c.err
74
}
75
 
76
// Access to net.Conn methods.
77
// Cannot just embed net.Conn because that would
78
// export the struct field too.
79
 
80
// LocalAddr returns the local network address.
81
func (c *Conn) LocalAddr() net.Addr {
82
        return c.conn.LocalAddr()
83
}
84
 
85
// RemoteAddr returns the remote network address.
86
func (c *Conn) RemoteAddr() net.Addr {
87
        return c.conn.RemoteAddr()
88
}
89
 
90
// SetDeadline sets the read deadline associated with the connection.
91
// There is no write deadline.
92
// A zero value for t means Read will not time out.
93
func (c *Conn) SetDeadline(t time.Time) error {
94
        return c.conn.SetDeadline(t)
95
}
96
 
97
// SetReadDeadline sets the read deadline on the underlying connection.
98
// A zero value for t means Read will not time out.
99
func (c *Conn) SetReadDeadline(t time.Time) error {
100
        return c.conn.SetReadDeadline(t)
101
}
102
 
103
// SetWriteDeadline exists to satisfy the net.Conn interface
104
// but is not implemented by TLS.  It always returns an error.
105
func (c *Conn) SetWriteDeadline(t time.Time) error {
106
        return errors.New("TLS does not support SetWriteDeadline")
107
}
108
 
109
// A halfConn represents one direction of the record layer
110
// connection, either sending or receiving.
111
type halfConn struct {
112
        sync.Mutex
113
        version uint16      // protocol version
114
        cipher  interface{} // cipher algorithm
115
        mac     macFunction
116
        seq     [8]byte // 64-bit sequence number
117
        bfree   *block  // list of free blocks
118
 
119
        nextCipher interface{} // next encryption state
120
        nextMac    macFunction // next MAC algorithm
121
 
122
        // used to save allocating a new buffer for each MAC.
123
        inDigestBuf, outDigestBuf []byte
124
}
125
 
126
// prepareCipherSpec sets the encryption and MAC states
127
// that a subsequent changeCipherSpec will use.
128
func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
129
        hc.version = version
130
        hc.nextCipher = cipher
131
        hc.nextMac = mac
132
}
133
 
134
// changeCipherSpec changes the encryption and MAC states
135
// to the ones previously passed to prepareCipherSpec.
136
func (hc *halfConn) changeCipherSpec() error {
137
        if hc.nextCipher == nil {
138
                return alertInternalError
139
        }
140
        hc.cipher = hc.nextCipher
141
        hc.mac = hc.nextMac
142
        hc.nextCipher = nil
143
        hc.nextMac = nil
144
        return nil
145
}
146
 
147
// incSeq increments the sequence number.
148
func (hc *halfConn) incSeq() {
149
        for i := 7; i >= 0; i-- {
150
                hc.seq[i]++
151
                if hc.seq[i] != 0 {
152
                        return
153
                }
154
        }
155
 
156
        // Not allowed to let sequence number wrap.
157
        // Instead, must renegotiate before it does.
158
        // Not likely enough to bother.
159
        panic("TLS: sequence number wraparound")
160
}
161
 
162
// resetSeq resets the sequence number to zero.
163
func (hc *halfConn) resetSeq() {
164
        for i := range hc.seq {
165
                hc.seq[i] = 0
166
        }
167
}
168
 
169
// removePadding returns an unpadded slice, in constant time, which is a prefix
170
// of the input. It also returns a byte which is equal to 255 if the padding
171
// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
172
func removePadding(payload []byte) ([]byte, byte) {
173
        if len(payload) < 1 {
174
                return payload, 0
175
        }
176
 
177
        paddingLen := payload[len(payload)-1]
178
        t := uint(len(payload)-1) - uint(paddingLen)
179
        // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
180
        good := byte(int32(^t) >> 31)
181
 
182
        toCheck := 255 // the maximum possible padding length
183
        // The length of the padded data is public, so we can use an if here
184
        if toCheck+1 > len(payload) {
185
                toCheck = len(payload) - 1
186
        }
187
 
188
        for i := 0; i < toCheck; i++ {
189
                t := uint(paddingLen) - uint(i)
190
                // if i <= paddingLen then the MSB of t is zero
191
                mask := byte(int32(^t) >> 31)
192
                b := payload[len(payload)-1-i]
193
                good &^= mask&paddingLen ^ mask&b
194
        }
195
 
196
        // We AND together the bits of good and replicate the result across
197
        // all the bits.
198
        good &= good << 4
199
        good &= good << 2
200
        good &= good << 1
201
        good = uint8(int8(good) >> 7)
202
 
203
        toRemove := good&paddingLen + 1
204
        return payload[:len(payload)-int(toRemove)], good
205
}
206
 
207
// removePaddingSSL30 is a replacement for removePadding in the case that the
208
// protocol version is SSLv3. In this version, the contents of the padding
209
// are random and cannot be checked.
210
func removePaddingSSL30(payload []byte) ([]byte, byte) {
211
        if len(payload) < 1 {
212
                return payload, 0
213
        }
214
 
215
        paddingLen := int(payload[len(payload)-1]) + 1
216
        if paddingLen > len(payload) {
217
                return payload, 0
218
        }
219
 
220
        return payload[:len(payload)-paddingLen], 255
221
}
222
 
223
func roundUp(a, b int) int {
224
        return a + (b-a%b)%b
225
}
226
 
227
// decrypt checks and strips the mac and decrypts the data in b.
228
func (hc *halfConn) decrypt(b *block) (bool, alert) {
229
        // pull out payload
230
        payload := b.data[recordHeaderLen:]
231
 
232
        macSize := 0
233
        if hc.mac != nil {
234
                macSize = hc.mac.Size()
235
        }
236
 
237
        paddingGood := byte(255)
238
 
239
        // decrypt
240
        if hc.cipher != nil {
241
                switch c := hc.cipher.(type) {
242
                case cipher.Stream:
243
                        c.XORKeyStream(payload, payload)
244
                case cipher.BlockMode:
245
                        blockSize := c.BlockSize()
246
 
247
                        if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
248
                                return false, alertBadRecordMAC
249
                        }
250
 
251
                        c.CryptBlocks(payload, payload)
252
                        if hc.version == versionSSL30 {
253
                                payload, paddingGood = removePaddingSSL30(payload)
254
                        } else {
255
                                payload, paddingGood = removePadding(payload)
256
                        }
257
                        b.resize(recordHeaderLen + len(payload))
258
 
259
                        // note that we still have a timing side-channel in the
260
                        // MAC check, below. An attacker can align the record
261
                        // so that a correct padding will cause one less hash
262
                        // block to be calculated. Then they can iteratively
263
                        // decrypt a record by breaking each byte. See
264
                        // "Password Interception in a SSL/TLS Channel", Brice
265
                        // Canvel et al.
266
                        //
267
                        // However, our behavior matches OpenSSL, so we leak
268
                        // only as much as they do.
269
                default:
270
                        panic("unknown cipher type")
271
                }
272
        }
273
 
274
        // check, strip mac
275
        if hc.mac != nil {
276
                if len(payload) < macSize {
277
                        return false, alertBadRecordMAC
278
                }
279
 
280
                // strip mac off payload, b.data
281
                n := len(payload) - macSize
282
                b.data[3] = byte(n >> 8)
283
                b.data[4] = byte(n)
284
                b.resize(recordHeaderLen + n)
285
                remoteMAC := payload[n:]
286
                localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data)
287
                hc.incSeq()
288
 
289
                if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
290
                        return false, alertBadRecordMAC
291
                }
292
                hc.inDigestBuf = localMAC
293
        }
294
 
295
        return true, 0
296
}
297
 
298
// padToBlockSize calculates the needed padding block, if any, for a payload.
299
// On exit, prefix aliases payload and extends to the end of the last full
300
// block of payload. finalBlock is a fresh slice which contains the contents of
301
// any suffix of payload as well as the needed padding to make finalBlock a
302
// full block.
303
func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
304
        overrun := len(payload) % blockSize
305
        paddingLen := blockSize - overrun
306
        prefix = payload[:len(payload)-overrun]
307
        finalBlock = make([]byte, blockSize)
308
        copy(finalBlock, payload[len(payload)-overrun:])
309
        for i := overrun; i < blockSize; i++ {
310
                finalBlock[i] = byte(paddingLen - 1)
311
        }
312
        return
313
}
314
 
315
// encrypt encrypts and macs the data in b.
316
func (hc *halfConn) encrypt(b *block) (bool, alert) {
317
        // mac
318
        if hc.mac != nil {
319
                mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data)
320
                hc.incSeq()
321
 
322
                n := len(b.data)
323
                b.resize(n + len(mac))
324
                copy(b.data[n:], mac)
325
                hc.outDigestBuf = mac
326
        }
327
 
328
        payload := b.data[recordHeaderLen:]
329
 
330
        // encrypt
331
        if hc.cipher != nil {
332
                switch c := hc.cipher.(type) {
333
                case cipher.Stream:
334
                        c.XORKeyStream(payload, payload)
335
                case cipher.BlockMode:
336
                        prefix, finalBlock := padToBlockSize(payload, c.BlockSize())
337
                        b.resize(recordHeaderLen + len(prefix) + len(finalBlock))
338
                        c.CryptBlocks(b.data[recordHeaderLen:], prefix)
339
                        c.CryptBlocks(b.data[recordHeaderLen+len(prefix):], finalBlock)
340
                default:
341
                        panic("unknown cipher type")
342
                }
343
        }
344
 
345
        // update length to include MAC and any block padding needed.
346
        n := len(b.data) - recordHeaderLen
347
        b.data[3] = byte(n >> 8)
348
        b.data[4] = byte(n)
349
 
350
        return true, 0
351
}
352
 
353
// A block is a simple data buffer.
354
type block struct {
355
        data []byte
356
        off  int // index for Read
357
        link *block
358
}
359
 
360
// resize resizes block to be n bytes, growing if necessary.
361
func (b *block) resize(n int) {
362
        if n > cap(b.data) {
363
                b.reserve(n)
364
        }
365
        b.data = b.data[0:n]
366
}
367
 
368
// reserve makes sure that block contains a capacity of at least n bytes.
369
func (b *block) reserve(n int) {
370
        if cap(b.data) >= n {
371
                return
372
        }
373
        m := cap(b.data)
374
        if m == 0 {
375
                m = 1024
376
        }
377
        for m < n {
378
                m *= 2
379
        }
380
        data := make([]byte, len(b.data), m)
381
        copy(data, b.data)
382
        b.data = data
383
}
384
 
385
// readFromUntil reads from r into b until b contains at least n bytes
386
// or else returns an error.
387
func (b *block) readFromUntil(r io.Reader, n int) error {
388
        // quick case
389
        if len(b.data) >= n {
390
                return nil
391
        }
392
 
393
        // read until have enough.
394
        b.reserve(n)
395
        for {
396
                m, err := r.Read(b.data[len(b.data):cap(b.data)])
397
                b.data = b.data[0 : len(b.data)+m]
398
                if len(b.data) >= n {
399
                        break
400
                }
401
                if err != nil {
402
                        return err
403
                }
404
        }
405
        return nil
406
}
407
 
408
func (b *block) Read(p []byte) (n int, err error) {
409
        n = copy(p, b.data[b.off:])
410
        b.off += n
411
        return
412
}
413
 
414
// newBlock allocates a new block, from hc's free list if possible.
415
func (hc *halfConn) newBlock() *block {
416
        b := hc.bfree
417
        if b == nil {
418
                return new(block)
419
        }
420
        hc.bfree = b.link
421
        b.link = nil
422
        b.resize(0)
423
        return b
424
}
425
 
426
// freeBlock returns a block to hc's free list.
427
// The protocol is such that each side only has a block or two on
428
// its free list at a time, so there's no need to worry about
429
// trimming the list, etc.
430
func (hc *halfConn) freeBlock(b *block) {
431
        b.link = hc.bfree
432
        hc.bfree = b
433
}
434
 
435
// splitBlock splits a block after the first n bytes,
436
// returning a block with those n bytes and a
437
// block with the remainder.  the latter may be nil.
438
func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
439
        if len(b.data) <= n {
440
                return b, nil
441
        }
442
        bb := hc.newBlock()
443
        bb.resize(len(b.data) - n)
444
        copy(bb.data, b.data[n:])
445
        b.data = b.data[0:n]
446
        return b, bb
447
}
448
 
449
// readRecord reads the next TLS record from the connection
450
// and updates the record layer state.
451
// c.in.Mutex <= L; c.input == nil.
452
func (c *Conn) readRecord(want recordType) error {
453
        // Caller must be in sync with connection:
454
        // handshake data if handshake not yet completed,
455
        // else application data.  (We don't support renegotiation.)
456
        switch want {
457
        default:
458
                return c.sendAlert(alertInternalError)
459
        case recordTypeHandshake, recordTypeChangeCipherSpec:
460
                if c.handshakeComplete {
461
                        return c.sendAlert(alertInternalError)
462
                }
463
        case recordTypeApplicationData:
464
                if !c.handshakeComplete {
465
                        return c.sendAlert(alertInternalError)
466
                }
467
        }
468
 
469
Again:
470
        if c.rawInput == nil {
471
                c.rawInput = c.in.newBlock()
472
        }
473
        b := c.rawInput
474
 
475
        // Read header, payload.
476
        if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
477
                // RFC suggests that EOF without an alertCloseNotify is
478
                // an error, but popular web sites seem to do this,
479
                // so we can't make it an error.
480
                // if err == io.EOF {
481
                //      err = io.ErrUnexpectedEOF
482
                // }
483
                if e, ok := err.(net.Error); !ok || !e.Temporary() {
484
                        c.setError(err)
485
                }
486
                return err
487
        }
488
        typ := recordType(b.data[0])
489
        vers := uint16(b.data[1])<<8 | uint16(b.data[2])
490
        n := int(b.data[3])<<8 | int(b.data[4])
491
        if c.haveVers && vers != c.vers {
492
                return c.sendAlert(alertProtocolVersion)
493
        }
494
        if n > maxCiphertext {
495
                return c.sendAlert(alertRecordOverflow)
496
        }
497
        if !c.haveVers {
498
                // First message, be extra suspicious:
499
                // this might not be a TLS client.
500
                // Bail out before reading a full 'body', if possible.
501
                // The current max version is 3.1.
502
                // If the version is >= 16.0, it's probably not real.
503
                // Similarly, a clientHello message encodes in
504
                // well under a kilobyte.  If the length is >= 12 kB,
505
                // it's probably not real.
506
                if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 {
507
                        return c.sendAlert(alertUnexpectedMessage)
508
                }
509
        }
510
        if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
511
                if err == io.EOF {
512
                        err = io.ErrUnexpectedEOF
513
                }
514
                if e, ok := err.(net.Error); !ok || !e.Temporary() {
515
                        c.setError(err)
516
                }
517
                return err
518
        }
519
 
520
        // Process message.
521
        b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
522
        b.off = recordHeaderLen
523
        if ok, err := c.in.decrypt(b); !ok {
524
                return c.sendAlert(err)
525
        }
526
        data := b.data[b.off:]
527
        if len(data) > maxPlaintext {
528
                c.sendAlert(alertRecordOverflow)
529
                c.in.freeBlock(b)
530
                return c.error()
531
        }
532
 
533
        switch typ {
534
        default:
535
                c.sendAlert(alertUnexpectedMessage)
536
 
537
        case recordTypeAlert:
538
                if len(data) != 2 {
539
                        c.sendAlert(alertUnexpectedMessage)
540
                        break
541
                }
542
                if alert(data[1]) == alertCloseNotify {
543
                        c.setError(io.EOF)
544
                        break
545
                }
546
                switch data[0] {
547
                case alertLevelWarning:
548
                        // drop on the floor
549
                        c.in.freeBlock(b)
550
                        goto Again
551
                case alertLevelError:
552
                        c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
553
                default:
554
                        c.sendAlert(alertUnexpectedMessage)
555
                }
556
 
557
        case recordTypeChangeCipherSpec:
558
                if typ != want || len(data) != 1 || data[0] != 1 {
559
                        c.sendAlert(alertUnexpectedMessage)
560
                        break
561
                }
562
                err := c.in.changeCipherSpec()
563
                if err != nil {
564
                        c.sendAlert(err.(alert))
565
                }
566
 
567
        case recordTypeApplicationData:
568
                if typ != want {
569
                        c.sendAlert(alertUnexpectedMessage)
570
                        break
571
                }
572
                c.input = b
573
                b = nil
574
 
575
        case recordTypeHandshake:
576
                // TODO(rsc): Should at least pick off connection close.
577
                if typ != want {
578
                        return c.sendAlert(alertNoRenegotiation)
579
                }
580
                c.hand.Write(data)
581
        }
582
 
583
        if b != nil {
584
                c.in.freeBlock(b)
585
        }
586
        return c.error()
587
}
588
 
589
// sendAlert sends a TLS alert message.
590
// c.out.Mutex <= L.
591
func (c *Conn) sendAlertLocked(err alert) error {
592
        c.tmp[0] = alertLevelError
593
        if err == alertNoRenegotiation {
594
                c.tmp[0] = alertLevelWarning
595
        }
596
        c.tmp[1] = byte(err)
597
        c.writeRecord(recordTypeAlert, c.tmp[0:2])
598
        // closeNotify is a special case in that it isn't an error:
599
        if err != alertCloseNotify {
600
                return c.setError(&net.OpError{Op: "local error", Err: err})
601
        }
602
        return nil
603
}
604
 
605
// sendAlert sends a TLS alert message.
606
// L < c.out.Mutex.
607
func (c *Conn) sendAlert(err alert) error {
608
        c.out.Lock()
609
        defer c.out.Unlock()
610
        return c.sendAlertLocked(err)
611
}
612
 
613
// writeRecord writes a TLS record with the given type and payload
614
// to the connection and updates the record layer state.
615
// c.out.Mutex <= L.
616
func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
617
        b := c.out.newBlock()
618
        for len(data) > 0 {
619
                m := len(data)
620
                if m > maxPlaintext {
621
                        m = maxPlaintext
622
                }
623
                b.resize(recordHeaderLen + m)
624
                b.data[0] = byte(typ)
625
                vers := c.vers
626
                if vers == 0 {
627
                        vers = maxVersion
628
                }
629
                b.data[1] = byte(vers >> 8)
630
                b.data[2] = byte(vers)
631
                b.data[3] = byte(m >> 8)
632
                b.data[4] = byte(m)
633
                copy(b.data[recordHeaderLen:], data)
634
                c.out.encrypt(b)
635
                _, err = c.conn.Write(b.data)
636
                if err != nil {
637
                        break
638
                }
639
                n += m
640
                data = data[m:]
641
        }
642
        c.out.freeBlock(b)
643
 
644
        if typ == recordTypeChangeCipherSpec {
645
                err = c.out.changeCipherSpec()
646
                if err != nil {
647
                        // Cannot call sendAlert directly,
648
                        // because we already hold c.out.Mutex.
649
                        c.tmp[0] = alertLevelError
650
                        c.tmp[1] = byte(err.(alert))
651
                        c.writeRecord(recordTypeAlert, c.tmp[0:2])
652
                        c.err = &net.OpError{Op: "local error", Err: err}
653
                        return n, c.err
654
                }
655
        }
656
        return
657
}
658
 
659
// readHandshake reads the next handshake message from
660
// the record layer.
661
// c.in.Mutex < L; c.out.Mutex < L.
662
func (c *Conn) readHandshake() (interface{}, error) {
663
        for c.hand.Len() < 4 {
664
                if c.err != nil {
665
                        return nil, c.err
666
                }
667
                if err := c.readRecord(recordTypeHandshake); err != nil {
668
                        return nil, err
669
                }
670
        }
671
 
672
        data := c.hand.Bytes()
673
        n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
674
        if n > maxHandshake {
675
                c.sendAlert(alertInternalError)
676
                return nil, c.err
677
        }
678
        for c.hand.Len() < 4+n {
679
                if c.err != nil {
680
                        return nil, c.err
681
                }
682
                if err := c.readRecord(recordTypeHandshake); err != nil {
683
                        return nil, err
684
                }
685
        }
686
        data = c.hand.Next(4 + n)
687
        var m handshakeMessage
688
        switch data[0] {
689
        case typeClientHello:
690
                m = new(clientHelloMsg)
691
        case typeServerHello:
692
                m = new(serverHelloMsg)
693
        case typeCertificate:
694
                m = new(certificateMsg)
695
        case typeCertificateRequest:
696
                m = new(certificateRequestMsg)
697
        case typeCertificateStatus:
698
                m = new(certificateStatusMsg)
699
        case typeServerKeyExchange:
700
                m = new(serverKeyExchangeMsg)
701
        case typeServerHelloDone:
702
                m = new(serverHelloDoneMsg)
703
        case typeClientKeyExchange:
704
                m = new(clientKeyExchangeMsg)
705
        case typeCertificateVerify:
706
                m = new(certificateVerifyMsg)
707
        case typeNextProtocol:
708
                m = new(nextProtoMsg)
709
        case typeFinished:
710
                m = new(finishedMsg)
711
        default:
712
                c.sendAlert(alertUnexpectedMessage)
713
                return nil, alertUnexpectedMessage
714
        }
715
 
716
        // The handshake message unmarshallers
717
        // expect to be able to keep references to data,
718
        // so pass in a fresh copy that won't be overwritten.
719
        data = append([]byte(nil), data...)
720
 
721
        if !m.unmarshal(data) {
722
                c.sendAlert(alertUnexpectedMessage)
723
                return nil, alertUnexpectedMessage
724
        }
725
        return m, nil
726
}
727
 
728
// Write writes data to the connection.
729
func (c *Conn) Write(b []byte) (n int, err error) {
730
        if err = c.Handshake(); err != nil {
731
                return
732
        }
733
 
734
        c.out.Lock()
735
        defer c.out.Unlock()
736
 
737
        if !c.handshakeComplete {
738
                return 0, alertInternalError
739
        }
740
        if c.err != nil {
741
                return 0, c.err
742
        }
743
        return c.writeRecord(recordTypeApplicationData, b)
744
}
745
 
746
// Read can be made to time out and return a net.Error with Timeout() == true
747
// after a fixed time limit; see SetDeadline and SetReadDeadline.
748
func (c *Conn) Read(b []byte) (n int, err error) {
749
        if err = c.Handshake(); err != nil {
750
                return
751
        }
752
 
753
        c.in.Lock()
754
        defer c.in.Unlock()
755
 
756
        for c.input == nil && c.err == nil {
757
                if err := c.readRecord(recordTypeApplicationData); err != nil {
758
                        // Soft error, like EAGAIN
759
                        return 0, err
760
                }
761
        }
762
        if c.err != nil {
763
                return 0, c.err
764
        }
765
        n, err = c.input.Read(b)
766
        if c.input.off >= len(c.input.data) {
767
                c.in.freeBlock(c.input)
768
                c.input = nil
769
        }
770
        return n, nil
771
}
772
 
773
// Close closes the connection.
774
func (c *Conn) Close() error {
775
        var alertErr error
776
 
777
        c.handshakeMutex.Lock()
778
        defer c.handshakeMutex.Unlock()
779
        if c.handshakeComplete {
780
                alertErr = c.sendAlert(alertCloseNotify)
781
        }
782
 
783
        if err := c.conn.Close(); err != nil {
784
                return err
785
        }
786
        return alertErr
787
}
788
 
789
// Handshake runs the client or server handshake
790
// protocol if it has not yet been run.
791
// Most uses of this package need not call Handshake
792
// explicitly: the first Read or Write will call it automatically.
793
func (c *Conn) Handshake() error {
794
        c.handshakeMutex.Lock()
795
        defer c.handshakeMutex.Unlock()
796
        if err := c.error(); err != nil {
797
                return err
798
        }
799
        if c.handshakeComplete {
800
                return nil
801
        }
802
        if c.isClient {
803
                return c.clientHandshake()
804
        }
805
        return c.serverHandshake()
806
}
807
 
808
// ConnectionState returns basic TLS details about the connection.
809
func (c *Conn) ConnectionState() ConnectionState {
810
        c.handshakeMutex.Lock()
811
        defer c.handshakeMutex.Unlock()
812
 
813
        var state ConnectionState
814
        state.HandshakeComplete = c.handshakeComplete
815
        if c.handshakeComplete {
816
                state.NegotiatedProtocol = c.clientProtocol
817
                state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
818
                state.CipherSuite = c.cipherSuite
819
                state.PeerCertificates = c.peerCertificates
820
                state.VerifiedChains = c.verifiedChains
821
                state.ServerName = c.serverName
822
        }
823
 
824
        return state
825
}
826
 
827
// OCSPResponse returns the stapled OCSP response from the TLS server, if
828
// any. (Only valid for client connections.)
829
func (c *Conn) OCSPResponse() []byte {
830
        c.handshakeMutex.Lock()
831
        defer c.handshakeMutex.Unlock()
832
 
833
        return c.ocspResponse
834
}
835
 
836
// VerifyHostname checks that the peer certificate chain is valid for
837
// connecting to host.  If so, it returns nil; if not, it returns an error
838
// describing the problem.
839
func (c *Conn) VerifyHostname(host string) error {
840
        c.handshakeMutex.Lock()
841
        defer c.handshakeMutex.Unlock()
842
        if !c.isClient {
843
                return errors.New("VerifyHostname called on TLS server connection")
844
        }
845
        if !c.handshakeComplete {
846
                return errors.New("TLS handshake has not yet been performed")
847
        }
848
        return c.peerCertificates[0].VerifyHostname(host)
849
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.