Skip to content

Commit 42686eb

Browse files
committed
Added Session Ticket Key rotation
1 parent b7d0883 commit 42686eb

File tree

3 files changed

+85
-6
lines changed

3 files changed

+85
-6
lines changed

README.md

-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1 @@
11
# tlsutil
2-
3-
Example of creating a tls.Config
4-
5-
```
6-
cfg, err := NewTLSConfig(WithTLS12(),
7-
WithKeyPair("localhost.pem", "localhost.key"))

keyrotation.go

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package tlsutil
2+
3+
import (
4+
"crypto/rand"
5+
"crypto/tls"
6+
"io"
7+
"time"
8+
9+
"github.com/renthraysk/group"
10+
)
11+
12+
type KeyRotator struct {
13+
cfg *tls.Config
14+
duration time.Duration
15+
keys [][32]byte
16+
stop chan chan struct{}
17+
}
18+
19+
func (r *KeyRotator) read(key []byte) (int, error) {
20+
if r.cfg.Rand != nil {
21+
return io.ReadFull(r.cfg.Rand, key)
22+
}
23+
return rand.Read(key)
24+
}
25+
26+
func (r *KeyRotator) rotate() error {
27+
var key [32]byte
28+
29+
if len(r.keys) < cap(r.keys) {
30+
r.keys = r.keys[:len(r.keys)+1]
31+
}
32+
copy(r.keys[1:], r.keys[:])
33+
34+
_, err := r.read(key[:])
35+
if err == nil {
36+
r.keys[0] = key
37+
}
38+
r.cfg.SetSessionTicketKeys(r.keys)
39+
return err
40+
}
41+
42+
func (r *KeyRotator) Start() error {
43+
timer := time.NewTicker(r.duration)
44+
defer timer.Stop()
45+
for {
46+
select {
47+
case <-timer.C:
48+
r.rotate()
49+
50+
case q := <-r.stop:
51+
close(q)
52+
return nil
53+
}
54+
}
55+
}
56+
57+
func (r *KeyRotator) Stop(err error) {
58+
q := make(chan struct{})
59+
r.stop <- q
60+
<-q
61+
}
62+
63+
// WithSessionTicketKeyRotation
64+
func WithSessionTicketKeyRotation(g *group.Group, n int, d time.Duration) Option {
65+
return func(cfg *tls.Config) error {
66+
r := &KeyRotator{
67+
cfg: cfg,
68+
duration: d,
69+
keys: make([][32]byte, 0, n),
70+
stop: make(chan chan struct{}),
71+
}
72+
if err := r.rotate(); err != nil {
73+
cfg.SessionTicketsDisabled = true
74+
return nil
75+
}
76+
g.Add(r)
77+
return nil
78+
}
79+
}

tlsutil.go

+6
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ func Wrap(opts ...Option) Option {
2323
}
2424
}
2525

26+
func WithError(err error) Option {
27+
return func(cfg *tls.Config) error {
28+
return err
29+
}
30+
}
31+
2632
// WithKeyPair load a certificate from a certFile, keyFile pair, and append to tls.Config's Certificates
2733
func WithKeyPair(certFile, keyFile string) Option {
2834
return func(cfg *tls.Config) error {

0 commit comments

Comments
 (0)