11package main
22
33import (
4+ "bytes"
45 "crypto"
56 "crypto/rand"
67 "crypto/rsa"
@@ -56,6 +57,13 @@ func getIssuer(keyFile, certFile string, autoCreate bool) (*issuer, error) {
5657 return nil , fmt .Errorf ("reading CA certificate from %s: %s" , certFile , err )
5758 }
5859
60+ equal , err := publicKeysEqual (key .Public (), cert .PublicKey )
61+ if err != nil {
62+ return nil , fmt .Errorf ("comparing public keys: %s" , err )
63+ } else if ! equal {
64+ return nil , fmt .Errorf ("public key in CA certificate %s doesn't match private key in %s" ,
65+ certFile , keyFile )
66+ }
5967 return & issuer {key , cert }, nil
6068}
6169
@@ -166,6 +174,18 @@ func parseIPs(ipAddresses []string) ([]net.IP, error) {
166174 return parsed , nil
167175}
168176
177+ func publicKeysEqual (a , b interface {}) (bool , error ) {
178+ aBytes , err := x509 .MarshalPKIXPublicKey (a )
179+ if err != nil {
180+ return false , err
181+ }
182+ bBytes , err := x509 .MarshalPKIXPublicKey (b )
183+ if err != nil {
184+ return false , err
185+ }
186+ return bytes .Compare (aBytes , bBytes ) == 0 , nil
187+ }
188+
169189func sign (iss * issuer , domains []string , ipAddresses []string ) (* x509.Certificate , error ) {
170190 var cn string
171191 if len (domains ) > 0 {
@@ -197,7 +217,6 @@ func sign(iss *issuer, domains []string, ipAddresses []string) (*x509.Certificat
197217 Subject : pkix.Name {
198218 CommonName : cn ,
199219 },
200- PublicKey : key .Public (),
201220 SerialNumber : serial ,
202221 NotBefore : time .Now (),
203222 NotAfter : time .Now ().AddDate (90 , 0 , 0 ),
@@ -207,7 +226,7 @@ func sign(iss *issuer, domains []string, ipAddresses []string) (*x509.Certificat
207226 BasicConstraintsValid : true ,
208227 IsCA : false ,
209228 }
210- der , err := x509 .CreateCertificate (rand .Reader , template , iss .cert , iss . key .Public (), iss .key )
229+ der , err := x509 .CreateCertificate (rand .Reader , template , iss .cert , key .Public (), iss .key )
211230 if err != nil {
212231 return nil , err
213232 }
@@ -267,6 +286,9 @@ will not overwrite existing keys or certificates.
267286 os .Exit (1 )
268287 }
269288 issuer , err := getIssuer (* caKey , * caCert , true )
289+ if err != nil {
290+ return err
291+ }
270292 _ , err = sign (issuer , split (* domains ), split (* ipAddresses ))
271293 return err
272294}
0 commit comments