2021-05-02 22:49:16 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
2021-05-03 21:04:48 +00:00
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/tls"
|
2021-05-02 22:49:16 +00:00
|
|
|
"crypto/x509"
|
|
|
|
"crypto/x509/pkix"
|
|
|
|
"encoding/pem"
|
|
|
|
"math/big"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2021-05-03 21:04:48 +00: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 22:49:16 +00:00
|
|
|
if err != nil {
|
2023-03-07 12:27:46 +00:00
|
|
|
log.WithError(err).Warning("Failed to generate private key")
|
2021-05-03 21:04:48 +00:00
|
|
|
return tls.Certificate{}, err
|
2021-05-02 22:49:16 +00: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 {
|
2023-03-07 12:27:46 +00:00
|
|
|
log.WithError(err).Warning("Failed to generate serial number")
|
2021-05-03 21:04:48 +00:00
|
|
|
return tls.Certificate{}, err
|
2021-05-02 22:49:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template := x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
Subject: pkix.Name{
|
2021-05-03 21:04:48 +00:00
|
|
|
Organization: []string{"authentik"},
|
|
|
|
CommonName: "authentik default certificate",
|
2021-05-02 22:49:16 +00:00
|
|
|
},
|
|
|
|
NotBefore: notBefore,
|
|
|
|
NotAfter: notAfter,
|
|
|
|
|
|
|
|
KeyUsage: keyUsage,
|
|
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
|
|
BasicConstraintsValid: true,
|
|
|
|
}
|
|
|
|
|
2021-05-03 21:04:48 +00:00
|
|
|
template.DNSNames = []string{"*"}
|
2021-05-02 22:49:16 +00:00
|
|
|
|
2021-05-03 21:04:48 +00:00
|
|
|
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
2021-05-02 22:49:16 +00:00
|
|
|
if err != nil {
|
2021-05-03 21:04:48 +00:00
|
|
|
log.Warning(err)
|
2021-05-02 22:49:16 +00:00
|
|
|
}
|
2021-05-03 21:04:48 +00:00
|
|
|
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
2021-05-02 22:49:16 +00:00
|
|
|
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
|
|
|
if err != nil {
|
2021-05-03 21:04:48 +00:00
|
|
|
log.Warning(err)
|
2021-05-02 22:49:16 +00:00
|
|
|
}
|
2021-05-03 21:04:48 +00:00
|
|
|
privPemByes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
|
|
|
|
return tls.X509KeyPair(pemBytes, privPemByes)
|
2021-05-02 22:49:16 +00:00
|
|
|
}
|