Skip to content

Commit

Permalink
Allow overwriting new client private keys.
Browse files Browse the repository at this point in the history
  • Loading branch information
sgielen committed Jun 13, 2021
1 parent 060ec5b commit fd19a4d
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions security/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func NewCA(dir string, name string) error {
if err := ks.StorePrivateKey(keyfn); err != nil {
return err
}
if err := pemToFile(filepath.Join(dir, "ca.crt"), "CERTIFICATE", ca, 0644); err != nil {
if err := pemToFile(filepath.Join(dir, "ca.crt"), "CERTIFICATE", ca, 0644, false); err != nil {
os.Remove(keyfn)
return err
}
Expand Down Expand Up @@ -172,16 +172,21 @@ func NewKey() (KeySerializer, error) {

// StorePrivateKey writes the private key to disk.
func (s KeySerializer) StorePrivateKey(fn string) error {
return pemToFile(fn, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(s.priv), 0600)
return pemToFile(fn, "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(s.priv), 0600, true)
}

// SerializePublicKey returns the encoded public key.
func (s KeySerializer) SerializePublicKey() ([]byte, error) {
return x509.MarshalPKIXPublicKey(&s.priv.PublicKey)
}

func pemToFile(fn, pemType string, data []byte, mode os.FileMode) error {
fh, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_TRUNC, mode)
func pemToFile(fn, pemType string, data []byte, mode os.FileMode, overwrite bool) error {
flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
if !overwrite {
flags |= os.O_EXCL
}

fh, err := os.OpenFile(fn, flags, mode)
if err != nil {
return err
}
Expand Down

0 comments on commit fd19a4d

Please sign in to comment.