github.com/haraldrudell/parl@v0.4.176/parlca/ensure.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parlca 7 8 import ( 9 "crypto/x509" 10 "math/big" 11 "os" 12 "strings" 13 "time" 14 15 "github.com/haraldrudell/parl/perrors" 16 ) 17 18 func EnsureTemplate(cert *x509.Certificate) { 19 if cert.SerialNumber == nil { 20 cert.SerialNumber = big.NewInt(1) 21 } 22 if len(cert.Subject.Country) == 0 { 23 cert.Subject.Country = []string{DefaultCountry} 24 } 25 if cert.Subject.CommonName == "" { 26 if host, err := os.Hostname(); err != nil { 27 panic(perrors.Errorf("os.Hostname: '%w'", err)) 28 } else { 29 if index := strings.Index(host, "."); index != -1 { 30 host = host[:index] 31 } 32 cert.Subject.CommonName = host 33 } 34 } 35 if cert.NotBefore.IsZero() { 36 nowUTC := time.Now().UTC() 37 year, month, day := nowUTC.Date() 38 cert.NotBefore = time.Date(year, month, day, 0, 0, 0, 0, nowUTC.Location()) 39 } 40 if cert.NotAfter.IsZero() { 41 notBeforeUTC := cert.NotBefore.UTC() 42 year, month, day := notBeforeUTC.Date() 43 cert.NotAfter = time.Date(year+notAfterYears, month, day, 0, 0, -1, 0, notBeforeUTC.Location()) 44 } 45 cert.BasicConstraintsValid = true 46 } 47 48 func EnsureSelfSigned(cert *x509.Certificate) { 49 if cert.Issuer.CommonName == "" { 50 if host, err := os.Hostname(); err != nil { 51 panic(perrors.Errorf("os.Hostname: '%w'", err)) 52 } else { 53 if index := strings.Index(host, "."); index != -1 { 54 host = host[:index] 55 } 56 cert.Issuer.CommonName = host + caSubjectSuffix 57 } 58 } 59 if len(cert.Issuer.Country) == 0 { 60 cert.Issuer.Country = []string{DefaultCountry} 61 } 62 if len(cert.Subject.Country) == 0 { 63 cert.Subject = cert.Issuer 64 } 65 cert.IsCA = true 66 cert.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign 67 EnsureTemplate(cert) 68 } 69 70 func EnsureServer(cert *x509.Certificate) { 71 EnsureTemplate(cert) 72 cert.KeyUsage = x509.KeyUsageDigitalSignature 73 cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} 74 } 75 76 func EnsureClient(cert *x509.Certificate) { 77 EnsureTemplate(cert) 78 cert.KeyUsage = x509.KeyUsageDigitalSignature 79 cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} 80 }