2021-05-02 23:49:16 +01:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2021-05-03 22:04:48 +01:00
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/tls"
|
2021-05-02 23:49:16 +01:00
|
|
|
"crypto/x509"
|
|
|
|
"crypto/x509/pkix"
|
|
|
|
"encoding/pem"
|
|
|
|
"math/big"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2021-05-03 22:04:48 +01:00
|
|
|
// GenerateSelfSignedCert Generate a self-signed TLS Certificate, to be used as fallback
|
|
|
|
func GenerateSelfSignedCert() (tls.Certificate, error) {
|
|
|
|
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
2021-05-02 23:49:16 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to generate private key: %v", err)
|
2021-05-03 22:04:48 +01:00
|
|
|
return tls.Certificate{}, err
|
2021-05-02 23:49:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
keyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment
|
|
|
|
|
|
|
|
notBefore := time.Now()
|
|
|
|
notAfter := notBefore.Add(365 * 24 * time.Hour)
|
|
|
|
|
|
|
|
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
|
|
|
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to generate serial number: %v", err)
|
2021-05-03 22:04:48 +01:00
|
|
|
return tls.Certificate{}, err
|
2021-05-02 23:49:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
template := x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
Subject: pkix.Name{
|
2021-05-03 22:04:48 +01:00
|
|
|
Organization: []string{"authentik"},
|
|
|
|
CommonName: "authentik default certificate",
|
2021-05-02 23:49:16 +01:00
|
|
|
},
|
|
|
|
NotBefore: notBefore,
|
|
|
|
NotAfter: notAfter,
|
|
|
|
|
|
|
|
KeyUsage: keyUsage,
|
|
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
|
|
BasicConstraintsValid: true,
|
|
|
|
}
|
|
|
|
|
2021-05-03 22:04:48 +01:00
|
|
|
template.DNSNames = []string{"*"}
|
2021-05-02 23:49:16 +01:00
|
|
|
|
2021-05-03 22:04:48 +01:00
|
|
|
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
2021-05-02 23:49:16 +01:00
|
|
|
if err != nil {
|
2021-05-03 22:04:48 +01:00
|
|
|
log.Warning(err)
|
2021-05-02 23:49:16 +01:00
|
|
|
}
|
2021-05-03 22:04:48 +01:00
|
|
|
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
2021-05-02 23:49:16 +01:00
|
|
|
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
|
|
|
if err != nil {
|
2021-05-03 22:04:48 +01:00
|
|
|
log.Warning(err)
|
2021-05-02 23:49:16 +01:00
|
|
|
}
|
2021-05-03 22:04:48 +01:00
|
|
|
privPemByes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
|
|
|
|
return tls.X509KeyPair(pemBytes, privPemByes)
|
2021-05-02 23:49:16 +01:00
|
|
|
}
|