OSDN Git Service

Remove the types float and complex.
[pf3gnuchains/gcc-fork.git] / libgo / go / crypto / tls / conn.go
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.
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         "hash"
15         "io"
16         "net"
17         "os"
18         "sync"
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
38         clientProtocol string
39
40         // first permanent error
41         errMutex sync.Mutex
42         err      os.Error
43
44         // input/output
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
49
50         tmp [16]byte
51 }
52
53 func (c *Conn) setError(err os.Error) os.Error {
54         c.errMutex.Lock()
55         defer c.errMutex.Unlock()
56
57         if c.err == nil {
58                 c.err = err
59         }
60         return err
61 }
62
63 func (c *Conn) error() os.Error {
64         c.errMutex.Lock()
65         defer c.errMutex.Unlock()
66
67         return c.err
68 }
69
70 // Access to net.Conn methods.
71 // Cannot just embed net.Conn because that would
72 // export the struct field too.
73
74 // LocalAddr returns the local network address.
75 func (c *Conn) LocalAddr() net.Addr {
76         return c.conn.LocalAddr()
77 }
78
79 // RemoteAddr returns the remote network address.
80 func (c *Conn) RemoteAddr() net.Addr {
81         return c.conn.RemoteAddr()
82 }
83
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)
88 }
89
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)
95 }
96
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")
101 }
102
103 // A halfConn represents one direction of the record layer
104 // connection, either sending or receiving.
105 type halfConn struct {
106         sync.Mutex
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
111
112         nextCipher interface{} // next encryption state
113         nextMac    hash.Hash   // next MAC algorithm
114 }
115
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
120         hc.nextMac = mac
121 }
122
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
128         }
129         hc.cipher = hc.nextCipher
130         hc.mac = hc.nextMac
131         hc.nextCipher = nil
132         hc.nextMac = nil
133         return nil
134 }
135
136 // incSeq increments the sequence number.
137 func (hc *halfConn) incSeq() {
138         for i := 7; i >= 0; i-- {
139                 hc.seq[i]++
140                 if hc.seq[i] != 0 {
141                         return
142                 }
143         }
144
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")
149 }
150
151 // resetSeq resets the sequence number to zero.
152 func (hc *halfConn) resetSeq() {
153         for i := range hc.seq {
154                 hc.seq[i] = 0
155         }
156 }
157
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 {
163                 return payload, 0
164         }
165
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)
170
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
175         }
176
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
183         }
184
185         // We AND together the bits of good and replicate the result across
186         // all the bits.
187         good &= good << 4
188         good &= good << 2
189         good &= good << 1
190         good = uint8(int8(good) >> 7)
191
192         toRemove := good&paddingLen + 1
193         return payload[:len(payload)-int(toRemove)], good
194 }
195
196 func roundUp(a, b int) int {
197         return a + (b-a%b)%b
198 }
199
200 // decrypt checks and strips the mac and decrypts the data in b.
201 func (hc *halfConn) decrypt(b *block) (bool, alert) {
202         // pull out payload
203         payload := b.data[recordHeaderLen:]
204
205         macSize := 0
206         if hc.mac != nil {
207                 macSize = hc.mac.Size()
208         }
209
210         paddingGood := byte(255)
211
212         // decrypt
213         if hc.cipher != nil {
214                 switch c := hc.cipher.(type) {
215                 case cipher.Stream:
216                         c.XORKeyStream(payload, payload)
217                 case cipher.BlockMode:
218                         blockSize := c.BlockSize()
219
220                         if len(payload)%blockSize != 0 || len(payload) < roundUp(macSize+1, blockSize) {
221                                 return false, alertBadRecordMAC
222                         }
223
224                         c.CryptBlocks(payload, payload)
225                         payload, paddingGood = removePadding(payload)
226                         b.resize(recordHeaderLen + len(payload))
227
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
234                         // Canvel et al.
235                         //
236                         // However, our behaviour matches OpenSSL, so we leak
237                         // only as much as they do.
238                 default:
239                         panic("unknown cipher type")
240                 }
241         }
242
243         // check, strip mac
244         if hc.mac != nil {
245                 if len(payload) < macSize {
246                         return false, alertBadRecordMAC
247                 }
248
249                 // strip mac off payload, b.data
250                 n := len(payload) - macSize
251                 b.data[3] = byte(n >> 8)
252                 b.data[4] = byte(n)
253                 b.resize(recordHeaderLen + n)
254                 remoteMAC := payload[n:]
255
256                 hc.mac.Reset()
257                 hc.mac.Write(hc.seq[0:])
258                 hc.incSeq()
259                 hc.mac.Write(b.data)
260
261                 if subtle.ConstantTimeCompare(hc.mac.Sum(), remoteMAC) != 1 || paddingGood != 255 {
262                         return false, alertBadRecordMAC
263                 }
264         }
265
266         return true, 0
267 }
268
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
273 // full block.
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)
282         }
283         return
284 }
285
286 // encrypt encrypts and macs the data in b.
287 func (hc *halfConn) encrypt(b *block) (bool, alert) {
288         // mac
289         if hc.mac != nil {
290                 hc.mac.Reset()
291                 hc.mac.Write(hc.seq[0:])
292                 hc.incSeq()
293                 hc.mac.Write(b.data)
294                 mac := hc.mac.Sum()
295                 n := len(b.data)
296                 b.resize(n + len(mac))
297                 copy(b.data[n:], mac)
298         }
299
300         payload := b.data[recordHeaderLen:]
301
302         // encrypt
303         if hc.cipher != nil {
304                 switch c := hc.cipher.(type) {
305                 case cipher.Stream:
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)
312                 default:
313                         panic("unknown cipher type")
314                 }
315         }
316
317         // update length to include MAC and any block padding needed.
318         n := len(b.data) - recordHeaderLen
319         b.data[3] = byte(n >> 8)
320         b.data[4] = byte(n)
321
322         return true, 0
323 }
324
325 // A block is a simple data buffer.
326 type block struct {
327         data []byte
328         off  int // index for Read
329         link *block
330 }
331
332 // resize resizes block to be n bytes, growing if necessary.
333 func (b *block) resize(n int) {
334         if n > cap(b.data) {
335                 b.reserve(n)
336         }
337         b.data = b.data[0:n]
338 }
339
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 {
343                 return
344         }
345         m := cap(b.data)
346         if m == 0 {
347                 m = 1024
348         }
349         for m < n {
350                 m *= 2
351         }
352         data := make([]byte, len(b.data), m)
353         copy(data, b.data)
354         b.data = data
355 }
356
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 {
360         // quick case
361         if len(b.data) >= n {
362                 return nil
363         }
364
365         // read until have enough.
366         b.reserve(n)
367         for {
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 {
371                         break
372                 }
373                 if err != nil {
374                         return err
375                 }
376         }
377         return nil
378 }
379
380 func (b *block) Read(p []byte) (n int, err os.Error) {
381         n = copy(p, b.data[b.off:])
382         b.off += n
383         return
384 }
385
386 // newBlock allocates a new block, from hc's free list if possible.
387 func (hc *halfConn) newBlock() *block {
388         b := hc.bfree
389         if b == nil {
390                 return new(block)
391         }
392         hc.bfree = b.link
393         b.link = nil
394         b.resize(0)
395         return b
396 }
397
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) {
403         b.link = hc.bfree
404         hc.bfree = b
405 }
406
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 {
412                 return b, nil
413         }
414         bb := hc.newBlock()
415         bb.resize(len(b.data) - n)
416         copy(bb.data, b.data[n:])
417         b.data = b.data[0:n]
418         return b, bb
419 }
420
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.)
428         switch want {
429         default:
430                 return c.sendAlert(alertInternalError)
431         case recordTypeHandshake, recordTypeChangeCipherSpec:
432                 if c.handshakeComplete {
433                         return c.sendAlert(alertInternalError)
434                 }
435         case recordTypeApplicationData:
436                 if !c.handshakeComplete {
437                         return c.sendAlert(alertInternalError)
438                 }
439         }
440
441 Again:
442         if c.rawInput == nil {
443                 c.rawInput = c.in.newBlock()
444         }
445         b := c.rawInput
446
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
454                 // }
455                 if e, ok := err.(net.Error); !ok || !e.Temporary() {
456                         c.setError(err)
457                 }
458                 return err
459         }
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)
465         }
466         if n > maxCiphertext {
467                 return c.sendAlert(alertRecordOverflow)
468         }
469         if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
470                 if err == os.EOF {
471                         err = io.ErrUnexpectedEOF
472                 }
473                 if e, ok := err.(net.Error); !ok || !e.Temporary() {
474                         c.setError(err)
475                 }
476                 return err
477         }
478
479         // Process message.
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)
484         }
485         data := b.data[b.off:]
486         if len(data) > maxPlaintext {
487                 c.sendAlert(alertRecordOverflow)
488                 c.in.freeBlock(b)
489                 return c.error()
490         }
491
492         switch typ {
493         default:
494                 c.sendAlert(alertUnexpectedMessage)
495
496         case recordTypeAlert:
497                 if len(data) != 2 {
498                         c.sendAlert(alertUnexpectedMessage)
499                         break
500                 }
501                 if alert(data[1]) == alertCloseNotify {
502                         c.setError(os.EOF)
503                         break
504                 }
505                 switch data[0] {
506                 case alertLevelWarning:
507                         // drop on the floor
508                         c.in.freeBlock(b)
509                         goto Again
510                 case alertLevelError:
511                         c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
512                 default:
513                         c.sendAlert(alertUnexpectedMessage)
514                 }
515
516         case recordTypeChangeCipherSpec:
517                 if typ != want || len(data) != 1 || data[0] != 1 {
518                         c.sendAlert(alertUnexpectedMessage)
519                         break
520                 }
521                 err := c.in.changeCipherSpec()
522                 if err != nil {
523                         c.sendAlert(err.(alert))
524                 }
525
526         case recordTypeApplicationData:
527                 if typ != want {
528                         c.sendAlert(alertUnexpectedMessage)
529                         break
530                 }
531                 c.input = b
532                 b = nil
533
534         case recordTypeHandshake:
535                 // TODO(rsc): Should at least pick off connection close.
536                 if typ != want {
537                         return c.sendAlert(alertNoRenegotiation)
538                 }
539                 c.hand.Write(data)
540         }
541
542         if b != nil {
543                 c.in.freeBlock(b)
544         }
545         return c.error()
546 }
547
548 // sendAlert sends a TLS alert message.
549 // c.out.Mutex <= L.
550 func (c *Conn) sendAlertLocked(err alert) os.Error {
551         c.tmp[0] = alertLevelError
552         if err == alertNoRenegotiation {
553                 c.tmp[0] = alertLevelWarning
554         }
555         c.tmp[1] = byte(err)
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})
560         }
561         return nil
562 }
563
564 // sendAlert sends a TLS alert message.
565 // L < c.out.Mutex.
566 func (c *Conn) sendAlert(err alert) os.Error {
567         c.out.Lock()
568         defer c.out.Unlock()
569         return c.sendAlertLocked(err)
570 }
571
572 // writeRecord writes a TLS record with the given type and payload
573 // to the connection and updates the record layer state.
574 // c.out.Mutex <= L.
575 func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
576         b := c.out.newBlock()
577         for len(data) > 0 {
578                 m := len(data)
579                 if m > maxPlaintext {
580                         m = maxPlaintext
581                 }
582                 b.resize(recordHeaderLen + m)
583                 b.data[0] = byte(typ)
584                 vers := c.vers
585                 if vers == 0 {
586                         vers = maxVersion
587                 }
588                 b.data[1] = byte(vers >> 8)
589                 b.data[2] = byte(vers)
590                 b.data[3] = byte(m >> 8)
591                 b.data[4] = byte(m)
592                 copy(b.data[recordHeaderLen:], data)
593                 c.out.encrypt(b)
594                 _, err = c.conn.Write(b.data)
595                 if err != nil {
596                         break
597                 }
598                 n += m
599                 data = data[m:]
600         }
601         c.out.freeBlock(b)
602
603         if typ == recordTypeChangeCipherSpec {
604                 err = c.out.changeCipherSpec()
605                 if err != nil {
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}
612                         return n, c.err
613                 }
614         }
615         return
616 }
617
618 // readHandshake reads the next handshake message from
619 // the record layer.
620 // c.in.Mutex < L; c.out.Mutex < L.
621 func (c *Conn) readHandshake() (interface{}, os.Error) {
622         for c.hand.Len() < 4 {
623                 if c.err != nil {
624                         return nil, c.err
625                 }
626                 c.readRecord(recordTypeHandshake)
627         }
628
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)
633                 return nil, c.err
634         }
635         for c.hand.Len() < 4+n {
636                 if c.err != nil {
637                         return nil, c.err
638                 }
639                 c.readRecord(recordTypeHandshake)
640         }
641         data = c.hand.Next(4 + n)
642         var m handshakeMessage
643         switch data[0] {
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)
664         case typeFinished:
665                 m = new(finishedMsg)
666         default:
667                 c.sendAlert(alertUnexpectedMessage)
668                 return nil, alertUnexpectedMessage
669         }
670
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...)
675
676         if !m.unmarshal(data) {
677                 c.sendAlert(alertUnexpectedMessage)
678                 return nil, alertUnexpectedMessage
679         }
680         return m, nil
681 }
682
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 {
686                 return
687         }
688
689         c.out.Lock()
690         defer c.out.Unlock()
691
692         if !c.handshakeComplete {
693                 return 0, alertInternalError
694         }
695         if c.err != nil {
696                 return 0, c.err
697         }
698         return c.writeRecord(recordTypeApplicationData, b)
699 }
700
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 {
705                 return
706         }
707
708         c.in.Lock()
709         defer c.in.Unlock()
710
711         for c.input == nil && c.err == nil {
712                 if err := c.readRecord(recordTypeApplicationData); err != nil {
713                         // Soft error, like EAGAIN
714                         return 0, err
715                 }
716         }
717         if c.err != nil {
718                 return 0, c.err
719         }
720         n, err = c.input.Read(b)
721         if c.input.off >= len(c.input.data) {
722                 c.in.freeBlock(c.input)
723                 c.input = nil
724         }
725         return n, nil
726 }
727
728 // Close closes the connection.
729 func (c *Conn) Close() os.Error {
730         if err := c.Handshake(); err != nil {
731                 return err
732         }
733         return c.sendAlert(alertCloseNotify)
734 }
735
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 {
744                 return err
745         }
746         if c.handshakeComplete {
747                 return nil
748         }
749         if c.isClient {
750                 return c.clientHandshake()
751         }
752         return c.serverHandshake()
753 }
754
755 // ConnectionState returns basic TLS details about the connection.
756 func (c *Conn) ConnectionState() ConnectionState {
757         c.handshakeMutex.Lock()
758         defer c.handshakeMutex.Unlock()
759
760         var state ConnectionState
761         state.HandshakeComplete = c.handshakeComplete
762         if c.handshakeComplete {
763                 state.NegotiatedProtocol = c.clientProtocol
764                 state.CipherSuite = c.cipherSuite
765         }
766
767         return state
768 }
769
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()
775
776         return c.ocspResponse
777 }
778
779 // PeerCertificates returns the certificate chain that was presented by the
780 // other side.
781 func (c *Conn) PeerCertificates() []*x509.Certificate {
782         c.handshakeMutex.Lock()
783         defer c.handshakeMutex.Unlock()
784
785         return c.peerCertificates
786 }
787
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()
794         if !c.isClient {
795                 return os.ErrorString("VerifyHostname called on TLS server connection")
796         }
797         if !c.handshakeComplete {
798                 return os.ErrorString("TLS handshake has not yet been performed")
799         }
800         return c.peerCertificates[0].VerifyHostname(host)
801 }