89 lines
1.6 KiB
Go
89 lines
1.6 KiB
Go
package tls
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"io/ioutil"
|
|
"net"
|
|
"os"
|
|
"time"
|
|
|
|
"git.giftfish.de/ston1th/vipman/pkg/config"
|
|
"github.com/hashicorp/raft"
|
|
)
|
|
|
|
var (
|
|
ciphers = []uint16{
|
|
tls.TLS_CHACHA20_POLY1305_SHA256,
|
|
}
|
|
curves = []tls.CurveID{
|
|
tls.X25519,
|
|
}
|
|
)
|
|
|
|
func loadCertPool(file string) (p *x509.CertPool, err error) {
|
|
if file == "" {
|
|
return
|
|
}
|
|
f, err := os.Open(file)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
buf, err := ioutil.ReadAll(f)
|
|
if err != nil {
|
|
return
|
|
}
|
|
certs, err := x509.ParseCertificates(buf)
|
|
if err != nil {
|
|
return
|
|
}
|
|
p = x509.NewCertPool()
|
|
for _, c := range certs {
|
|
p.AddCert(c)
|
|
}
|
|
return
|
|
}
|
|
|
|
type stream struct {
|
|
net.Listener
|
|
insecure bool
|
|
ca *x509.CertPool
|
|
}
|
|
|
|
func NewStream(cfg *config.Raft) (s *stream, err error) {
|
|
cert, err := tls.LoadX509KeyPair(cfg.TLS.Cert, cfg.TLS.Key)
|
|
if err != nil {
|
|
return
|
|
}
|
|
ca, err := loadCertPool(cfg.TLS.CA)
|
|
if err != nil {
|
|
return
|
|
}
|
|
l, err := tls.Listen("tcp", cfg.Address, &tls.Config{
|
|
MinVersion: tls.VersionTLS13,
|
|
CipherSuites: ciphers,
|
|
CurvePreferences: curves,
|
|
PreferServerCipherSuites: true,
|
|
Certificates: []tls.Certificate{cert},
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
s = &stream{l, cfg.TLS.Insecure, ca}
|
|
return
|
|
}
|
|
|
|
func (s *stream) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) {
|
|
return tls.DialWithDialer(
|
|
&net.Dialer{Timeout: timeout},
|
|
"tcp", string(address),
|
|
&tls.Config{
|
|
MinVersion: tls.VersionTLS13,
|
|
CipherSuites: ciphers,
|
|
CurvePreferences: curves,
|
|
InsecureSkipVerify: s.insecure,
|
|
RootCAs: s.ca,
|
|
},
|
|
)
|
|
}
|