Debian Codegraph @

conn.go

raw symbols SCIP
1 package mint
2
3 import (
4 "crypto"
5 "crypto/x509"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "io"
10 "net"
11 "reflect"
12 "sync"
13 "time"
14 )
15
16 type Certificate struct {
17 Chain []*x509.Certificate
18 PrivateKey crypto.Signer
19 }
20
21 type PreSharedKey struct {
22 CipherSuite CipherSuite
23 IsResumption bool
24 Identity []byte
25 Key []byte
26 NextProto string
27 ReceivedAt time.Time
28 ExpiresAt time.Time
29 TicketAgeAdd uint32
30 }
31
32 type PreSharedKeyCache interface {
33 Get(string) (PreSharedKey, bool)
34 Put(string, PreSharedKey)
35 Size() int
36 }
37
38 // A CookieHandler can be used to give the application more fine-grained control over Cookies.
39 // Generate receives the Conn as an argument, so the CookieHandler can decide when to send the cookie based on that, and offload state to the client by encoding that into the Cookie.
40 // When the client echoes the Cookie, Validate is called. The application can then recover the state from the cookie.
41 type CookieHandler interface {
42 // Generate a byte string that is sent as a part of a cookie to the client in the HelloRetryRequest
43 // If Generate returns nil, mint will not send a HelloRetryRequest.
44 Generate(*Conn) ([]byte, error)
45 // Validate is called when receiving a ClientHello containing a Cookie.
46 // If validation failed, the handshake is aborted.
47 Validate(*Conn, []byte) bool
48 }
49
50 type PSKMapCache map[string]PreSharedKey
51
52 func (cache PSKMapCache) Get(key string) (psk PreSharedKey, ok bool) {
53 psk, ok = cache[key]
54 return
55 }
56
57 func (cache *PSKMapCache) Put(key string, psk PreSharedKey) {
58 (*cache)[key] = psk
59 }
60
61 func (cache PSKMapCache) Size() int {
62 return len(cache)
63 }
64
65 // Config is the struct used to pass configuration settings to a TLS client or
66 // server instance. The settings for client and server are pretty different,
67 // but we just throw them all in here.
68 type Config struct {
69 // Client fields
70 ServerName string
71
72 // Server fields
73 SendSessionTickets bool
74 TicketLifetime uint32
75 TicketLen int
76 EarlyDataLifetime uint32
77 AllowEarlyData bool
78 // Require the client to echo a cookie.
79 RequireCookie bool
80 // A CookieHandler can be used to set and validate a cookie.
81 // The cookie returned by the CookieHandler will be part of the cookie sent on the wire, and encoded using the CookieProtector.
82 // If no CookieHandler is set, mint will always send a cookie.
83 // The CookieHandler can be used to decide on a per-connection basis, if a cookie should be sent.
84 CookieHandler CookieHandler
85 // The CookieProtector is used to encrypt / decrypt cookies.
86 // It should make sure that the Cookie cannot be read and tampered with by the client.
87 // If non-blocking mode is used, and cookies are required, this field has to be set.
88 // In blocking mode, a default cookie protector is used, if this is unused.
89 CookieProtector CookieProtector
90 // The ExtensionHandler is used to add custom extensions.
91 ExtensionHandler AppExtensionHandler
92 RequireClientAuth bool
93
94 // Time returns the current time as the number of seconds since the epoch.
95 // If Time is nil, TLS uses time.Now.
96 Time func() time.Time
97 // RootCAs defines the set of root certificate authorities
98 // that clients use when verifying server certificates.
99 // If RootCAs is nil, TLS uses the host's root CA set.
100 RootCAs *x509.CertPool
101 // InsecureSkipVerify controls whether a client verifies the
102 // server's certificate chain and host name.
103 // If InsecureSkipVerify is true, TLS accepts any certificate
104 // presented by the server and any host name in that certificate.
105 // In this mode, TLS is susceptible to man-in-the-middle attacks.
106 // This should be used only for testing.
107 InsecureSkipVerify bool
108
109 // Shared fields
110 Certificates []*Certificate
111 // VerifyPeerCertificate, if not nil, is called after normal
112 // certificate verification by either a TLS client or server. It
113 // receives the raw ASN.1 certificates provided by the peer and also
114 // any verified chains that normal processing found. If it returns a
115 // non-nil error, the handshake is aborted and that error results.
116 //
117 // If normal verification fails then the handshake will abort before
118 // considering this callback. If normal verification is disabled by
119 // setting InsecureSkipVerify then this callback will be considered but
120 // the verifiedChains argument will always be nil.
121 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
122
123 CipherSuites []CipherSuite
124 Groups []NamedGroup
125 SignatureSchemes []SignatureScheme
126 NextProtos []string
127 PSKs PreSharedKeyCache
128 PSKModes []PSKKeyExchangeMode
129 NonBlocking bool
130 UseDTLS bool
131
132 RecordLayer RecordLayerFactory
133
134 // The same config object can be shared among different connections, so it
135 // needs its own mutex
136 mutex sync.RWMutex
137 }
138
139 // Clone returns a shallow clone of c. It is safe to clone a Config that is
140 // being used concurrently by a TLS client or server.
141 func (c *Config) Clone() *Config {
142 c.mutex.Lock()
143 defer c.mutex.Unlock()
144
145 return &Config{
146 ServerName: c.ServerName,
147
148 SendSessionTickets: c.SendSessionTickets,
149 TicketLifetime: c.TicketLifetime,
150 TicketLen: c.TicketLen,
151 EarlyDataLifetime: c.EarlyDataLifetime,
152 AllowEarlyData: c.AllowEarlyData,
153 RequireCookie: c.RequireCookie,
154 CookieHandler: c.CookieHandler,
155 CookieProtector: c.CookieProtector,
156 ExtensionHandler: c.ExtensionHandler,
157 RequireClientAuth: c.RequireClientAuth,
158 Time: c.Time,
159 RootCAs: c.RootCAs,
160 InsecureSkipVerify: c.InsecureSkipVerify,
161
162 Certificates: c.Certificates,
163 VerifyPeerCertificate: c.VerifyPeerCertificate,
164 CipherSuites: c.CipherSuites,
165 Groups: c.Groups,
166 SignatureSchemes: c.SignatureSchemes,
167 NextProtos: c.NextProtos,
168 PSKs: c.PSKs,
169 PSKModes: c.PSKModes,
170 NonBlocking: c.NonBlocking,
171 UseDTLS: c.UseDTLS,
172 }
173 }
174
175 func (c *Config) Init(isClient bool) error {
176 c.mutex.Lock()
177 defer c.mutex.Unlock()
178
179 // Set defaults
180 if len(c.CipherSuites) == 0 {
181 c.CipherSuites = defaultSupportedCipherSuites
182 }
183 if len(c.Groups) == 0 {
184 c.Groups = defaultSupportedGroups
185 }
186 if len(c.SignatureSchemes) == 0 {
187 c.SignatureSchemes = defaultSignatureSchemes
188 }
189 if c.TicketLen == 0 {
190 c.TicketLen = defaultTicketLen
191 }
192 if !reflect.ValueOf(c.PSKs).IsValid() {
193 c.PSKs = &PSKMapCache{}
194 }
195 if len(c.PSKModes) == 0 {
196 c.PSKModes = defaultPSKModes
197 }
198 return nil
199 }
200
201 func (c *Config) ValidForServer() bool {
202 return (reflect.ValueOf(c.PSKs).IsValid() && c.PSKs.Size() > 0) ||
203 (len(c.Certificates) > 0 &&
204 len(c.Certificates[0].Chain) > 0 &&
205 c.Certificates[0].PrivateKey != nil)
206 }
207
208 func (c *Config) ValidForClient() bool {
209 return len(c.ServerName) > 0
210 }
211
212 func (c *Config) time() time.Time {
213 t := c.Time
214 if t == nil {
215 t = time.Now
216 }
217 return t()
218 }
219
220 var (
221 defaultSupportedCipherSuites = []CipherSuite{
222 TLS_AES_128_GCM_SHA256,
223 TLS_AES_256_GCM_SHA384,
224 }
225
226 defaultSupportedGroups = []NamedGroup{
227 P256,
228 P384,
229 FFDHE2048,
230 X25519,
231 }
232
233 defaultSignatureSchemes = []SignatureScheme{
234 RSA_PSS_SHA256,
235 RSA_PSS_SHA384,
236 RSA_PSS_SHA512,
237 ECDSA_P256_SHA256,
238 ECDSA_P384_SHA384,
239 ECDSA_P521_SHA512,
240 }
241
242 defaultTicketLen = 16
243
244 defaultPSKModes = []PSKKeyExchangeMode{
245 PSKModeKE,
246 PSKModeDHEKE,
247 }
248 )
249
250 type ConnectionState struct {
251 HandshakeState State
252 CipherSuite CipherSuiteParams // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
253 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
254 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
255 NextProto string // Selected ALPN proto
256 UsingPSK bool // Are we using PSK.
257 UsingEarlyData bool // Did we negotiate 0-RTT.
258 }
259
260 // Conn implements the net.Conn interface, as with "crypto/tls"
261 // * Read, Write, and Close are provided locally
262 // * LocalAddr, RemoteAddr, and Set*Deadline are forwarded to the inner Conn
263 type Conn struct {
264 config *Config
265 conn net.Conn
266 isClient bool
267
268 state stateConnected
269 hState HandshakeState
270 handshakeMutex sync.Mutex
271 handshakeAlert Alert
272 handshakeComplete bool
273
274 readBuffer []byte
275 in, out RecordLayer
276 hsCtx *HandshakeContext
277 }
278
279 func NewConn(conn net.Conn, config *Config, isClient bool) *Conn {
280 c := &Conn{conn: conn, config: config, isClient: isClient, hsCtx: &HandshakeContext{}}
281 if !config.UseDTLS {
282 if config.RecordLayer == nil {
283 c.in = NewRecordLayerTLS(c.conn, DirectionRead)
284 c.out = NewRecordLayerTLS(c.conn, DirectionWrite)
285 } else {
286 c.in = config.RecordLayer.NewLayer(c.conn, DirectionRead)
287 c.out = config.RecordLayer.NewLayer(c.conn, DirectionWrite)
288 }
289 c.hsCtx.hIn = NewHandshakeLayerTLS(c.hsCtx, c.in)
290 c.hsCtx.hOut = NewHandshakeLayerTLS(c.hsCtx, c.out)
291 } else {
292 c.in = NewRecordLayerDTLS(c.conn, DirectionRead)
293 c.out = NewRecordLayerDTLS(c.conn, DirectionWrite)
294 c.hsCtx.hIn = NewHandshakeLayerDTLS(c.hsCtx, c.in)
295 c.hsCtx.hOut = NewHandshakeLayerDTLS(c.hsCtx, c.out)
296 c.hsCtx.timeoutMS = initialTimeout
297 c.hsCtx.timers = newTimerSet()
298 c.hsCtx.waitingNextFlight = true
299 }
300 c.in.SetLabel(c.label())
301 c.out.SetLabel(c.label())
302 c.hsCtx.hIn.nonblocking = c.config.NonBlocking
303 return c
304 }
305
306 // Read up
307 func (c *Conn) consumeRecord() error {
308 pt, err := c.in.ReadRecord()
309 if pt == nil {
310 logf(logTypeIO, "extendBuffer returns error %v", err)
311 return err
312 }
313
314 switch pt.contentType {
315 case RecordTypeHandshake:
316 logf(logTypeHandshake, "Received post-handshake message")
317 // We do not support fragmentation of post-handshake handshake messages.
318 // TODO: Factor this more elegantly; coalesce with handshakeLayer.ReadMessage()
319 start := 0
320 headerLen := handshakeHeaderLenTLS
321 if c.config.UseDTLS {
322 headerLen = handshakeHeaderLenDTLS
323 }
324 for start < len(pt.fragment) {
325 if len(pt.fragment[start:]) < headerLen {
326 return fmt.Errorf("Post-handshake handshake message too short for header")
327 }
328
329 hm := &HandshakeMessage{}
330 hm.msgType = HandshakeType(pt.fragment[start])
331 hmLen := (int(pt.fragment[start+1]) << 16) + (int(pt.fragment[start+2]) << 8) + int(pt.fragment[start+3])
332
333 if len(pt.fragment[start+headerLen:]) < hmLen {
334 return fmt.Errorf("Post-handshake handshake message too short for body")
335 }
336 hm.body = pt.fragment[start+headerLen : start+headerLen+hmLen]
337
338 // XXX: If we want to support more advanced cases, e.g., post-handshake
339 // authentication, we'll need to allow transitions other than
340 // Connected -> Connected
341 state, actions, alert := c.state.ProcessMessage(hm)
342 if alert != AlertNoAlert {
343 logf(logTypeHandshake, "Error in state transition: %v", alert)
344 c.sendAlert(alert)
345 return io.EOF
346 }
347
348 for _, action := range actions {
349 alert = c.takeAction(action)
350 if alert != AlertNoAlert {
351 logf(logTypeHandshake, "Error during handshake actions: %v", alert)
352 c.sendAlert(alert)
353 return io.EOF
354 }
355 }
356
357 var connected bool
358 c.state, connected = state.(stateConnected)
359 if !connected {
360 logf(logTypeHandshake, "Disconnected after state transition: %v", alert)
361 c.sendAlert(alert)
362 return io.EOF
363 }
364
365 start += headerLen + hmLen
366 }
367 case RecordTypeAlert:
368 logf(logTypeIO, "extended buffer (for alert): [%d] %x", len(c.readBuffer), c.readBuffer)
369 if len(pt.fragment) != 2 {
370 c.sendAlert(AlertUnexpectedMessage)
371 return io.EOF
372 }
373 if Alert(pt.fragment[1]) == AlertCloseNotify {
374 return io.EOF
375 }
376
377 switch pt.fragment[0] {
378 case AlertLevelWarning:
379 // drop on the floor
380 case AlertLevelError:
381 return Alert(pt.fragment[1])
382 default:
383 c.sendAlert(AlertUnexpectedMessage)
384 return io.EOF
385 }
386
387 case RecordTypeAck:
388 if !c.hsCtx.hIn.datagram {
389 logf(logTypeHandshake, "Received ACK in TLS mode")
390 return AlertUnexpectedMessage
391 }
392 return c.hsCtx.processAck(pt.fragment)
393
394 case RecordTypeApplicationData:
395 c.readBuffer = append(c.readBuffer, pt.fragment...)
396 logf(logTypeIO, "extended buffer: [%d] %x", len(c.readBuffer), c.readBuffer)
397
398 }
399
400 return err
401 }
402
403 func readPartial(in *[]byte, buffer []byte) int {
404 logf(logTypeIO, "conn.Read input buffer now has len %d", len((*in)))
405 read := copy(buffer, *in)
406 *in = (*in)[read:]
407
408 logf(logTypeVerbose, "Returning %v", string(buffer))
409 return read
410 }
411
412 // Read application data up to the size of buffer. Handshake and alert records
413 // are consumed by the Conn object directly.
414 func (c *Conn) Read(buffer []byte) (int, error) {
415 if _, connected := c.hState.(stateConnected); !connected {
416 // Clients can't call Read prior to handshake completion.
417 if c.isClient {
418 return 0, errors.New("Read called before the handshake completed")
419 }
420
421 // Neither can servers that don't allow early data.
422 if !c.config.AllowEarlyData {
423 return 0, errors.New("Read called before the handshake completed")
424 }
425
426 // If there's no early data, then return WouldBlock
427 if len(c.hsCtx.earlyData) == 0 {
428 return 0, AlertWouldBlock
429 }
430
431 return readPartial(&c.hsCtx.earlyData, buffer), nil
432 }
433
434 // The handshake is now connected.
435 logf(logTypeHandshake, "conn.Read with buffer = %d", len(buffer))
436 if alert := c.Handshake(); alert != AlertNoAlert {
437 return 0, alert
438 }
439
440 if len(buffer) == 0 {
441 return 0, nil
442 }
443
444 // Run our timers.
445 if c.config.UseDTLS {
446 if err := c.hsCtx.timers.check(time.Now()); err != nil {
447 return 0, AlertInternalError
448 }
449 }
450
451 // Lock the input channel
452 c.in.Lock()
453 defer c.in.Unlock()
454 for len(c.readBuffer) == 0 {
455 err := c.consumeRecord()
456
457 // err can be nil if consumeRecord processed a non app-data
458 // record.
459 if err != nil {
460 if c.config.NonBlocking || err != AlertWouldBlock {
461 logf(logTypeIO, "conn.Read returns err=%v", err)
462 return 0, err
463 }
464 }
465 }
466
467 return readPartial(&c.readBuffer, buffer), nil
468 }
469
470 // Write application data
471 func (c *Conn) Write(buffer []byte) (int, error) {
472 // Lock the output channel
473 c.out.Lock()
474 defer c.out.Unlock()
475
476 if !c.Writable() {
477 return 0, errors.New("Write called before the handshake completed (and early data not in use)")
478 }
479
480 // Send full-size fragments
481 var start int
482 sent := 0
483 for start = 0; len(buffer)-start >= maxFragmentLen; start += maxFragmentLen {
484 err := c.out.WriteRecord(&TLSPlaintext{
485 contentType: RecordTypeApplicationData,
486 fragment: buffer[start : start+maxFragmentLen],
487 })
488
489 if err != nil {
490 return sent, err
491 }
492 sent += maxFragmentLen
493 }
494
495 // Send a final partial fragment if necessary
496 if start < len(buffer) {
497 err := c.out.WriteRecord(&TLSPlaintext{
498 contentType: RecordTypeApplicationData,
499 fragment: buffer[start:],
500 })
501
502 if err != nil {
503 return sent, err
504 }
505 sent += len(buffer[start:])
506 }
507 return sent, nil
508 }
509
510 // sendAlert sends a TLS alert message.
511 // c.out.Mutex <= L.
512 func (c *Conn) sendAlert(err Alert) error {
513 c.handshakeMutex.Lock()
514 defer c.handshakeMutex.Unlock()
515
516 var level int
517 switch err {
518 case AlertNoRenegotiation, AlertCloseNotify:
519 level = AlertLevelWarning
520 default:
521 level = AlertLevelError
522 }
523
524 buf := []byte{byte(err), byte(level)}
525 c.out.WriteRecord(&TLSPlaintext{
526 contentType: RecordTypeAlert,
527 fragment: buf,
528 })
529
530 // close_notify and end_of_early_data are not actually errors
531 if level == AlertLevelWarning {
532 return &net.OpError{Op: "local error", Err: err}
533 }
534
535 return c.Close()
536 }
537
538 // Close closes the connection.
539 func (c *Conn) Close() error {
540 // XXX crypto/tls has an interlock with Write here. Do we need that?
541
542 return c.conn.Close()
543 }
544
545 // LocalAddr returns the local network address.
546 func (c *Conn) LocalAddr() net.Addr {
547 return c.conn.LocalAddr()
548 }
549
550 // RemoteAddr returns the remote network address.
551 func (c *Conn) RemoteAddr() net.Addr {
552 return c.conn.RemoteAddr()
553 }
554
555 // SetDeadline sets the read and write deadlines associated with the connection.
556 // A zero value for t means Read and Write will not time out.
557 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
558 func (c *Conn) SetDeadline(t time.Time) error {
559 return c.conn.SetDeadline(t)
560 }
561
562 // SetReadDeadline sets the read deadline on the underlying connection.
563 // A zero value for t means Read will not time out.
564 func (c *Conn) SetReadDeadline(t time.Time) error {
565 return c.conn.SetReadDeadline(t)
566 }
567
568 // SetWriteDeadline sets the write deadline on the underlying connection.
569 // A zero value for t means Write will not time out.
570 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
571 func (c *Conn) SetWriteDeadline(t time.Time) error {
572 return c.conn.SetWriteDeadline(t)
573 }
574
575 func (c *Conn) takeAction(actionGeneric HandshakeAction) Alert {
576 label := "[server]"
577 if c.isClient {
578 label = "[client]"
579 }
580
581 switch action := actionGeneric.(type) {
582 case QueueHandshakeMessage:
583 logf(logTypeHandshake, "%s queuing handshake message type=%v", label, action.Message.msgType)
584 err := c.hsCtx.hOut.QueueMessage(action.Message)
585 if err != nil {
586 logf(logTypeHandshake, "%s Error writing handshake message: %v", label, err)
587 return AlertInternalError
588 }
589
590 case SendQueuedHandshake:
591 _, err := c.hsCtx.hOut.SendQueuedMessages()
592 if err != nil {
593 logf(logTypeHandshake, "%s Error writing handshake message: %v", label, err)
594 return AlertInternalError
595 }
596 if c.config.UseDTLS {
597 c.hsCtx.timers.start(retransmitTimerLabel,
598 c.hsCtx.handshakeRetransmit,
599 c.hsCtx.timeoutMS)
600 }
601 case RekeyIn:
602 logf(logTypeHandshake, "%s Rekeying in to %s: %+v", label, action.epoch.label(), action.KeySet)
603 // Check that we don't have an input data in the handshake frame parser.
604 if len(c.hsCtx.hIn.frame.remainder) > 0 {
605 logf(logTypeHandshake, "%s Rekey with data still in handshake buffers", label)
606 return AlertDecodeError
607 }
608 err := c.in.Rekey(action.epoch, action.KeySet.Cipher, &action.KeySet)
609 if err != nil {
610 logf(logTypeHandshake, "%s Unable to rekey inbound: %v", label, err)
611 return AlertInternalError
612 }
613
614 case RekeyOut:
615 logf(logTypeHandshake, "%s Rekeying out to %s: %+v", label, action.epoch.label(), action.KeySet)
616 err := c.out.Rekey(action.epoch, action.KeySet.Cipher, &action.KeySet)
617 if err != nil {
618 logf(logTypeHandshake, "%s Unable to rekey outbound: %v", label, err)
619 return AlertInternalError
620 }
621
622 case ResetOut:
623 logf(logTypeHandshake, "%s Rekeying out to %s seq=%v", label, EpochClear, action.seq)
624 c.out.ResetClear(action.seq)
625
626 case StorePSK:
627 logf(logTypeHandshake, "%s Storing new session ticket with identity [%x]", label, action.PSK.Identity)
628 if c.isClient {
629 // Clients look up PSKs based on server name
630 c.config.PSKs.Put(c.config.ServerName, action.PSK)
631 } else {
632 // Servers look them up based on the identity in the extension
633 c.config.PSKs.Put(hex.EncodeToString(action.PSK.Identity), action.PSK)
634 }
635
636 default:
637 logf(logTypeHandshake, "%s Unknown action type", label)
638 assert(false)
639 return AlertInternalError
640 }
641
642 return AlertNoAlert
643 }
644
645 func (c *Conn) HandshakeSetup() Alert {
646 var state HandshakeState
647 var actions []HandshakeAction
648 var alert Alert
649
650 if err := c.config.Init(c.isClient); err != nil {
651 logf(logTypeHandshake, "Error initializing config: %v", err)
652 return AlertInternalError
653 }
654
655 opts := ConnectionOptions{
656 ServerName: c.config.ServerName,
657 NextProtos: c.config.NextProtos,
658 }
659
660 if c.isClient {
661 state, actions, alert = clientStateStart{Config: c.config, Opts: opts, hsCtx: c.hsCtx}.Next(nil)
662 if alert != AlertNoAlert {
663 logf(logTypeHandshake, "Error initializing client state: %v", alert)
664 return alert
665 }
666
667 for _, action := range actions {
668 alert = c.takeAction(action)
669 if alert != AlertNoAlert {
670 logf(logTypeHandshake, "Error during handshake actions: %v", alert)
671 return alert
672 }
673 }
674 } else {
675 if c.config.RequireCookie && c.config.CookieProtector == nil {
676 logf(logTypeHandshake, "RequireCookie set, but no CookieProtector provided. Using default cookie protector. Stateless Retry not possible.")
677 if c.config.NonBlocking {
678 logf(logTypeHandshake, "Not possible in non-blocking mode.")
679 return AlertInternalError
680 }
681 var err error
682 c.config.CookieProtector, err = NewDefaultCookieProtector()
683 if err != nil {
684 logf(logTypeHandshake, "Error initializing cookie source: %v", alert)
685 return AlertInternalError
686 }
687 }
688 state = serverStateStart{Config: c.config, conn: c, hsCtx: c.hsCtx}
689 }
690
691 c.hState = state
692 return AlertNoAlert
693 }
694
695 type handshakeMessageReader interface {
696 ReadMessage() (*HandshakeMessage, Alert)
697 }
698
699 type handshakeMessageReaderImpl struct {
700 hsCtx *HandshakeContext
701 }
702
703 var _ handshakeMessageReader = &handshakeMessageReaderImpl{}
704
705 func (r *handshakeMessageReaderImpl) ReadMessage() (*HandshakeMessage, Alert) {
706 var hm *HandshakeMessage
707 var err error
708 for {
709 hm, err = r.hsCtx.hIn.ReadMessage()
710 if err == AlertWouldBlock {
711 return nil, AlertWouldBlock
712 }
713 if err != nil {
714 logf(logTypeHandshake, "Error reading message: %v", err)
715 return nil, AlertCloseNotify
716 }
717 if hm != nil {
718 break
719 }
720 }
721
722 return hm, AlertNoAlert
723 }
724
725 // Handshake causes a TLS handshake on the connection. The `isClient` member
726 // determines whether a client or server handshake is performed. If a
727 // handshake has already been performed, then its result will be returned.
728 func (c *Conn) Handshake() Alert {
729 label := "[server]"
730 if c.isClient {
731 label = "[client]"
732 }
733
734 // TODO Lock handshakeMutex
735 // TODO Remove CloseNotify hack
736 if c.handshakeAlert != AlertNoAlert && c.handshakeAlert != AlertCloseNotify {
737 logf(logTypeHandshake, "Pre-existing handshake error: %v", c.handshakeAlert)
738 return c.handshakeAlert
739 }
740 if c.handshakeComplete {
741 return AlertNoAlert
742 }
743
744 if c.hState == nil {
745 logf(logTypeHandshake, "%s First time through handshake (or after stateless retry), setting up", label)
746 alert := c.HandshakeSetup()
747 if alert != AlertNoAlert || (c.isClient && c.config.NonBlocking) {
748 return alert
749 }
750 }
751
752 logf(logTypeHandshake, "(Re-)entering handshake, state=%v", c.hState)
753 state := c.hState
754 _, connected := state.(stateConnected)
755
756 hmr := &handshakeMessageReaderImpl{hsCtx: c.hsCtx}
757 for !connected {
758 var alert Alert
759 var actions []HandshakeAction
760
761 // Advance the state machine
762 state, actions, alert = state.Next(hmr)
763 if alert == AlertWouldBlock {
764 logf(logTypeHandshake, "%s Would block reading message: %s", label, alert)
765 // If we blocked, then run our timers to see if any have expired.
766 if c.hsCtx.hIn.datagram {
767 if err := c.hsCtx.timers.check(time.Now()); err != nil {
768 return AlertInternalError
769 }
770 }
771 return AlertWouldBlock
772 }
773 if alert == AlertCloseNotify {
774 logf(logTypeHandshake, "%s Error reading message: %s", label, alert)
775 c.sendAlert(AlertCloseNotify)
776 return AlertCloseNotify
777 }
778 if alert != AlertNoAlert && alert != AlertStatelessRetry {
779 logf(logTypeHandshake, "Error in state transition: %v", alert)
780 return alert
781 }
782
783 for index, action := range actions {
784 logf(logTypeHandshake, "%s taking next action (%d)", label, index)
785 if alert := c.takeAction(action); alert != AlertNoAlert {
786 logf(logTypeHandshake, "Error during handshake actions: %v", alert)
787 c.sendAlert(alert)
788 return alert
789 }
790 }
791
792 c.hState = state
793 logf(logTypeHandshake, "state is now %s", c.GetHsState())
794 _, connected = state.(stateConnected)
795 if connected {
796 c.state = state.(stateConnected)
797 c.handshakeComplete = true
798
799 if !c.isClient {
800 // Send NewSessionTicket if configured to
801 if c.config.SendSessionTickets {
802 actions, alert := c.state.NewSessionTicket(
803 c.config.TicketLen,
804 c.config.TicketLifetime,
805 c.config.EarlyDataLifetime)
806
807 for _, action := range actions {
808 alert = c.takeAction(action)
809 if alert != AlertNoAlert {
810 logf(logTypeHandshake, "Error during handshake actions: %v", alert)
811 c.sendAlert(alert)
812 return alert
813 }
814 }
815 }
816
817 // If there is early data, move it into the main buffer
818 if c.hsCtx.earlyData != nil {
819 c.readBuffer = c.hsCtx.earlyData
820 c.hsCtx.earlyData = nil
821 }
822
823 } else {
824 assert(c.hsCtx.earlyData == nil)
825 }
826 }
827
828 if c.config.NonBlocking {
829 if alert == AlertStatelessRetry {
830 return AlertStatelessRetry
831 }
832 return AlertNoAlert
833 }
834 }
835
836 return AlertNoAlert
837 }
838
839 func (c *Conn) SendKeyUpdate(requestUpdate bool) error {
840 if !c.handshakeComplete {
841 return fmt.Errorf("Cannot update keys until after handshake")
842 }
843
844 request := KeyUpdateNotRequested
845 if requestUpdate {
846 request = KeyUpdateRequested
847 }
848
849 // Create the key update and update state
850 actions, alert := c.state.KeyUpdate(request)
851 if alert != AlertNoAlert {
852 c.sendAlert(alert)
853 return fmt.Errorf("Alert while generating key update: %v", alert)
854 }
855
856 // Take actions (send key update and rekey)
857 for _, action := range actions {
858 alert = c.takeAction(action)
859 if alert != AlertNoAlert {
860 c.sendAlert(alert)
861 return fmt.Errorf("Alert during key update actions: %v", alert)
862 }
863 }
864
865 return nil
866 }
867
868 func (c *Conn) GetHsState() State {
869 if c.hState == nil {
870 return StateInit
871 }
872 return c.hState.State()
873 }
874
875 func (c *Conn) ComputeExporter(label string, context []byte, keyLength int) ([]byte, error) {
876 _, connected := c.hState.(stateConnected)
877 if !connected {
878 return nil, fmt.Errorf("Cannot compute exporter when state is not connected")
879 }
880
881 if c.state.exporterSecret == nil {
882 return nil, fmt.Errorf("Internal error: no exporter secret")
883 }
884
885 h0 := c.state.cryptoParams.Hash.New().Sum(nil)
886 tmpSecret := deriveSecret(c.state.cryptoParams, c.state.exporterSecret, label, h0)
887
888 hc := c.state.cryptoParams.Hash.New().Sum(context)
889 return HkdfExpandLabel(c.state.cryptoParams.Hash, tmpSecret, "exporter", hc, keyLength), nil
890 }
891
892 func (c *Conn) ConnectionState() ConnectionState {
893 state := ConnectionState{
894 HandshakeState: c.GetHsState(),
895 }
896
897 if c.handshakeComplete {
898 state.CipherSuite = cipherSuiteMap[c.state.Params.CipherSuite]
899 state.NextProto = c.state.Params.NextProto
900 state.VerifiedChains = c.state.verifiedChains
901 state.PeerCertificates = c.state.peerCertificates
902 state.UsingPSK = c.state.Params.UsingPSK
903 state.UsingEarlyData = c.state.Params.UsingEarlyData
904 }
905
906 return state
907 }
908
909 func (c *Conn) Writable() bool {
910 // If we're connected, we're writable.
911 if _, connected := c.hState.(stateConnected); connected {
912 return true
913 }
914
915 // If we're a client in 0-RTT, then we're writable.
916 if c.isClient && c.out.Epoch() == EpochEarlyData {
917 return true
918 }
919
920 return false
921 }
922
923 func (c *Conn) label() string {
924 if c.isClient {
925 return "client"
926 }
927 return "server"
928 }