2018-12-11 22:01:50 +01:00
|
|
|
package tls
|
2018-08-27 22:21:45 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
2021-09-20 07:43:22 +02:00
|
|
|
"fmt"
|
2018-12-11 22:01:50 +01:00
|
|
|
"net"
|
2021-09-20 07:43:22 +02:00
|
|
|
"os"
|
2018-12-11 22:01:50 +01:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
func TLSConnecterFromConfig(in *config.TLSConnect) (*TLSConnecter, error) {
|
|
|
|
dialer := net.Dialer{
|
|
|
|
Timeout: in.DialTimeout,
|
|
|
|
}
|
|
|
|
|
2020-07-19 23:59:33 +02:00
|
|
|
if fakeCertificateLoading {
|
|
|
|
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 {
|
2021-09-20 07:43:22 +02:00
|
|
|
fmt.Fprintf(os.Stderr, "tls connecter error %T\n\t%s\n\t%v\n\t%#v\n\n", err, err, err, err)
|
2018-10-19 16:08:20 +02:00
|
|
|
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
|
|
|
}
|