2018-12-11 22:01:50 +01:00
|
|
|
package tls
|
2018-08-27 22:21:45 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
2018-12-11 22:01:50 +01:00
|
|
|
"net"
|
|
|
|
|
2018-08-27 22:21:45 +02:00
|
|
|
"github.com/pkg/errors"
|
2019-03-22 19:41:12 +01:00
|
|
|
|
2018-08-27 22:21:45 +02:00
|
|
|
"github.com/zrepl/zrepl/config"
|
|
|
|
"github.com/zrepl/zrepl/tlsconf"
|
2018-12-11 22:01:50 +01:00
|
|
|
"github.com/zrepl/zrepl/transport"
|
2018-08-27 22:21:45 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type TLSConnecter struct {
|
|
|
|
Address string
|
|
|
|
dialer net.Dialer
|
|
|
|
tlsConfig *tls.Config
|
|
|
|
}
|
|
|
|
|
2022-03-30 04:39:10 +02:00
|
|
|
func TLSConnecterFromConfig(in *config.TLSConnect, parseFlags config.ParseFlags) (*TLSConnecter, error) {
|
2018-08-27 22:21:45 +02:00
|
|
|
dialer := net.Dialer{
|
|
|
|
Timeout: in.DialTimeout,
|
|
|
|
}
|
|
|
|
|
2022-03-30 04:39:10 +02:00
|
|
|
if parseFlags&config.ParseFlagsNoCertCheck != 0 {
|
2020-07-19 23:59:33 +02:00
|
|
|
return &TLSConnecter{in.Address, dialer, nil}, nil
|
|
|
|
}
|
|
|
|
|
2018-08-27 22:21:45 +02:00
|
|
|
ca, err := tlsconf.ParseCAFile(in.Ca)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "cannot parse ca file")
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := tls.LoadX509KeyPair(in.Cert, in.Key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "cannot parse cert/key pair")
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsConfig, err := tlsconf.ClientAuthClient(in.ServerCN, ca, cert)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "cannot build tls config")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &TLSConnecter{in.Address, dialer, tlsConfig}, nil
|
|
|
|
}
|
|
|
|
|
2018-12-11 22:01:50 +01:00
|
|
|
func (c *TLSConnecter) Connect(dialCtx context.Context) (transport.Wire, error) {
|
|
|
|
conn, err := c.dialer.DialContext(dialCtx, "tcp", c.Address)
|
2018-10-19 16:08:20 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-12-11 22:01:50 +01:00
|
|
|
tcpConn := conn.(*net.TCPConn)
|
|
|
|
tlsConn := tls.Client(conn, c.tlsConfig)
|
|
|
|
return newWireAdaptor(tlsConn, tcpConn), nil
|
2018-08-27 22:21:45 +02:00
|
|
|
}
|