proxy: replace certificate generation with cert package

This commit is contained in:
Oliver Gugger
2019-11-29 17:46:43 +01:00
parent c2e9d540ba
commit 51c7deac05

View File

@@ -1,21 +1,13 @@
package proxy_test package proxy_test
import ( import (
"bytes"
"context" "context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math/big"
"net" "net"
"net/http" "net/http"
"os"
"path" "path"
"strings" "strings"
"testing" "testing"
@@ -24,6 +16,7 @@ import (
"github.com/lightninglabs/kirin/auth" "github.com/lightninglabs/kirin/auth"
"github.com/lightninglabs/kirin/proxy" "github.com/lightninglabs/kirin/proxy"
proxytest "github.com/lightninglabs/kirin/proxy/testdata" proxytest "github.com/lightninglabs/kirin/proxy/testdata"
"github.com/lightningnetwork/lnd/cert"
"github.com/lightningnetwork/lnd/macaroons" "github.com/lightningnetwork/lnd/macaroons"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
@@ -41,16 +34,6 @@ const (
testHTTPResponseBody = "HTTP Hello" testHTTPResponseBody = "HTTP Hello"
) )
var (
serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128)
tlsCipherSuites = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
}
)
// helloServer is a simple server that implements the GreeterServer interface. // helloServer is a simple server that implements the GreeterServer interface.
type helloServer struct{} type helloServer struct{}
@@ -157,7 +140,7 @@ func TestProxyGRPC(t *testing.T) {
} }
certFile := path.Join(tempDirName, "proxy.cert") certFile := path.Join(tempDirName, "proxy.cert")
keyFile := path.Join(tempDirName, "proxy.key") keyFile := path.Join(tempDirName, "proxy.key")
certPool, creds, cert, err := genCertPair(certFile, keyFile) certPool, creds, certData, err := genCertPair(certFile, keyFile)
if err != nil { if err != nil {
t.Fatalf("unable to create cert pair: %v", err) t.Fatalf("unable to create cert pair: %v", err)
} }
@@ -189,11 +172,7 @@ func TestProxyGRPC(t *testing.T) {
defer server.Close() defer server.Close()
// Start the target backend service also on TLS. // Start the target backend service also on TLS.
tlsConf := &tls.Config{ tlsConf := cert.TLSConfFromCert(certData)
Certificates: []tls.Certificate{cert},
CipherSuites: tlsCipherSuites,
MinVersion: tls.VersionTLS12,
}
serverOpts := []grpc.ServerOption{ serverOpts := []grpc.ServerOption{
grpc.Creds(credentials.NewTLS(tlsConf)), grpc.Creds(credentials.NewTLS(tlsConf)),
} }
@@ -291,142 +270,28 @@ func startBackendGRPC(grpcServer *grpc.Server) error {
func genCertPair(certFile, keyFile string) (*x509.CertPool, func genCertPair(certFile, keyFile string) (*x509.CertPool,
credentials.TransportCredentials, tls.Certificate, error) { credentials.TransportCredentials, tls.Certificate, error) {
org := "kirin autogenerated cert" crt := tls.Certificate{}
cert := tls.Certificate{} err := cert.GenCertPair(
now := time.Now() "kirin autogenerated cert", certFile, keyFile, nil, nil,
validUntil := now.Add(1 * time.Hour) cert.DefaultAutogenValidity,
// Generate a serial number that's below the serialNumberLimit.
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, cert, fmt.Errorf("failed to generate serial "+
"number: %s", err)
}
// Collect the host's IP addresses, including loopback, in a slice.
ipAddresses := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
// addIP appends an IP address only if it isn't already in the slice.
addIP := func(ipAddr net.IP) {
for _, ip := range ipAddresses {
if ip.Equal(ipAddr) {
return
}
}
ipAddresses = append(ipAddresses, ipAddr)
}
// Add all the interface IPs that aren't already in the slice.
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, nil, cert, err
}
for _, a := range addrs {
ipAddr, _, err := net.ParseCIDR(a.String())
if err == nil {
addIP(ipAddr)
}
}
// Collect the host's names into a slice.
host, err := os.Hostname()
if err != nil {
return nil, nil, cert, err
}
dnsNames := []string{host}
if host != "localhost" {
dnsNames = append(dnsNames, "localhost")
}
// Generate a private key for the certificate.
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, cert, err
}
// Construct the certificate template.
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{org},
CommonName: host,
},
NotBefore: now.Add(-time.Hour * 24),
NotAfter: validUntil,
KeyUsage: x509.KeyUsageKeyEncipherment |
x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
IsCA: true, // so can sign self.
BasicConstraintsValid: true,
DNSNames: dnsNames,
IPAddresses: ipAddresses,
}
derBytes, err := x509.CreateCertificate(
rand.Reader, &template, &template, &priv.PublicKey, priv,
) )
if err != nil { if err != nil {
return nil, nil, cert, fmt.Errorf("failed to create "+ return nil, nil, crt, fmt.Errorf("unable to generate cert "+
"certificate: %v", err) "pair: %v", err)
} }
certBuf := &bytes.Buffer{} crt, x509Cert, err := cert.LoadCert(certFile, keyFile)
err = pem.Encode(
certBuf,
&pem.Block{Type: "CERTIFICATE",
Bytes: derBytes,
},
)
if err != nil { if err != nil {
return nil, nil, cert, fmt.Errorf("failed to encode "+ return nil, nil, crt, fmt.Errorf("unable to load cert: %v", err)
"certificate: %v", err)
}
keybytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return nil, nil, cert, fmt.Errorf("unable to encode privkey: "+
"%v", err)
}
keyBuf := &bytes.Buffer{}
err = pem.Encode(
keyBuf,
&pem.Block{
Type: "EC PRIVATE KEY",
Bytes: keybytes,
},
)
if err != nil {
return nil, nil, cert, fmt.Errorf("failed to encode private "+
"key: %v", err)
}
cert, err = tls.X509KeyPair(certBuf.Bytes(), keyBuf.Bytes())
if err != nil {
return nil, nil, cert, fmt.Errorf("failed to create key pair: "+
"%v", err)
}
// Write cert and key files.
if err = ioutil.WriteFile(certFile, certBuf.Bytes(), 0644); err != nil {
return nil, nil, cert, fmt.Errorf("unable to write cert file "+
"at %v: %v", certFile, err)
}
if err = ioutil.WriteFile(keyFile, keyBuf.Bytes(), 0600); err != nil {
os.Remove(certFile)
return nil, nil, cert, fmt.Errorf("unable to write key file "+
"at %v: %v", keyFile, err)
} }
cp := x509.NewCertPool() cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(certBuf.Bytes()) { cp.AddCert(x509Cert)
return nil, nil, cert, fmt.Errorf("credentials: failed to " +
"append certificate")
}
creds, err := credentials.NewClientTLSFromFile(certFile, "") creds, err := credentials.NewClientTLSFromFile(certFile, "")
if err != nil { if err != nil {
return nil, nil, cert, fmt.Errorf("unable to load cert file: "+ return nil, nil, crt, fmt.Errorf("unable to load cert file: "+
"%v", err) "%v", err)
} }
return cp, creds, cert, nil return cp, creds, crt, nil
} }