gproxy: listen on tls

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-05-03 23:04:48 +02:00
parent 812be495a5
commit 6725569ba8
5 changed files with 118 additions and 49 deletions

View File

@ -1,24 +1,24 @@
package crypto package crypto
import ( import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand" "crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"math/big" "math/big"
"net"
"os"
"time" "time"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
func GenerateKeypair(hosts []string) { // GenerateSelfSignedCert Generate a self-signed TLS Certificate, to be used as fallback
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) func GenerateSelfSignedCert() (tls.Certificate, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil { if err != nil {
log.Fatalf("Failed to generate private key: %v", err) log.Fatalf("Failed to generate private key: %v", err)
return tls.Certificate{}, err
} }
keyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment keyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment
@ -30,12 +30,14 @@ func GenerateKeypair(hosts []string) {
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil { if err != nil {
log.Fatalf("Failed to generate serial number: %v", err) log.Fatalf("Failed to generate serial number: %v", err)
return tls.Certificate{}, err
} }
template := x509.Certificate{ template := x509.Certificate{
SerialNumber: serialNumber, SerialNumber: serialNumber,
Subject: pkix.Name{ Subject: pkix.Name{
Organization: []string{"BeryJu.org"}, Organization: []string{"authentik"},
CommonName: "authentik default certificate",
}, },
NotBefore: notBefore, NotBefore: notBefore,
NotAfter: notAfter, NotAfter: notAfter,
@ -45,46 +47,17 @@ func GenerateKeypair(hosts []string) {
BasicConstraintsValid: true, BasicConstraintsValid: true,
} }
for _, h := range hosts { template.DNSNames = []string{"*"}
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, priv, priv) derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil { if err != nil {
log.Fatalf("Failed to create certificate: %v", err) log.Warning(err)
}
certOut, err := os.Create("cert.pem")
if err != nil {
log.Fatalf("Failed to open cert.pem for writing: %v", err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Fatalf("Failed to write data to cert.pem: %v", err)
}
if err := certOut.Close(); err != nil {
log.Fatalf("Error closing cert.pem: %v", err)
}
log.Print("wrote cert.pem\n")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v", err)
return
} }
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
privBytes, err := x509.MarshalPKCS8PrivateKey(priv) privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil { if err != nil {
log.Fatalf("Unable to marshal private key: %v", err) log.Warning(err)
} }
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { privPemByes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
log.Fatalf("Failed to write data to key.pem: %v", err) return tls.X509KeyPair(pemBytes, privPemByes)
}
if err := keyOut.Close(); err != nil {
log.Fatalf("Error closing key.pem: %v", err)
}
log.Print("wrote key.pem\n")
return
} }

View File

@ -1,6 +1,9 @@
package web package web
import ( import (
"context"
"errors"
"net"
"net/http" "net/http"
"sync" "sync"
@ -16,6 +19,8 @@ type WebServer struct {
LegacyProxy bool LegacyProxy bool
stop chan struct{} // channel for waiting shutdown
m *mux.Router m *mux.Router
lh *mux.Router lh *mux.Router
log *log.Entry log *log.Entry
@ -49,12 +54,45 @@ func (ws *WebServer) Run() {
}() }()
go func() { go func() {
defer wg.Done() defer wg.Done()
// ws.listenTLS() ws.listenTLS()
}() }()
wg.Done() wg.Done()
} }
func (ws *WebServer) listenPlain() { func (ws *WebServer) listenPlain() {
ln, err := net.Listen("tcp", config.G.Web.Listen)
if err != nil {
ws.log.WithError(err).Fatalf("failed to listen")
}
ws.log.WithField("addr", config.G.Web.Listen).Info("Running")
ws.serve(ln)
ws.log.WithField("addr", config.G.Web.Listen).Info("Running") ws.log.WithField("addr", config.G.Web.Listen).Info("Running")
http.ListenAndServe(config.G.Web.Listen, ws.m) http.ListenAndServe(config.G.Web.Listen, ws.m)
} }
func (ws *WebServer) serve(listener net.Listener) {
srv := &http.Server{
Handler: ws.m,
}
// See https://golang.org/pkg/net/http/#Server.Shutdown
idleConnsClosed := make(chan struct{})
go func() {
<-ws.stop // wait notification for stopping server
// We received an interrupt signal, shut down.
if err := srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
ws.log.Printf("HTTP server Shutdown: %v", err)
}
close(idleConnsClosed)
}()
err := srv.Serve(listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
ws.log.Errorf("ERROR: http.Serve() - %s", err)
}
<-idleConnsClosed
}

32
internal/web/web_ssl.go Normal file
View File

@ -0,0 +1,32 @@
package web
import (
"crypto/tls"
"net"
"goauthentik.io/internal/config"
"goauthentik.io/internal/crypto"
)
// ServeHTTPS constructs a net.Listener and starts handling HTTPS requests
func (ws *WebServer) listenTLS() {
cert, err := crypto.GenerateSelfSignedCert()
if err != nil {
ws.log.WithError(err).Error("failed to generate default cert")
}
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
}
ln, err := net.Listen("tcp", config.G.Web.ListenTLS)
if err != nil {
ws.log.WithError(err).Fatalf("failed to listen")
}
ws.log.WithField("addr", config.G.Web.ListenTLS).Info("Running")
tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, tlsConfig)
ws.serve(tlsListener)
ws.log.Printf("closing %s", tlsListener.Addr())
}

31
internal/web/web_utils.go Normal file
View File

@ -0,0 +1,31 @@
package web
import (
"log"
"net"
"time"
)
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
tc, err := ln.AcceptTCP()
if err != nil {
return nil, err
}
err = tc.SetKeepAlive(true)
if err != nil {
log.Printf("Error setting Keep-Alive: %v", err)
}
err = tc.SetKeepAlivePeriod(3 * time.Minute)
if err != nil {
log.Printf("Error setting Keep-Alive period: %v", err)
}
return tc, nil
}

View File

@ -1,5 +0,0 @@
package main
func main() {
}