Skip to content

Commit

Permalink
Make sure generate-key-pair doesn't overwrite existing key-pair (#623)
Browse files Browse the repository at this point in the history
* Make sure generate-key-pair doesn't overwrite key-pair by mistake by replicating ssh-keygen behaviour.

Also create public key with 0644 permission.

Signed-off-by: Pradeep Chhetri <pradeepchhetri4444@gmail.com>

* Fix lint errors

Signed-off-by: Pradeep Chhetri <pradeepchhetri4444@gmail.com>
  • Loading branch information
chhetripradeep committed Sep 6, 2021
1 parent 40830f1 commit 5abd51e
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions cmd/cosign/cli/generate_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,29 @@ func GenerateKeyPairCmd(ctx context.Context, kmsVal string, args []string) error
if err != nil {
return err
}

if fileExists("cosign.key") {
var overwrite string
fmt.Fprint(os.Stderr, "File cosign.key already exists. Overwrite (y/n)? ")
fmt.Scanf("%s", &overwrite)
switch overwrite {
case "y", "Y":
case "n", "N":
return nil
default:
fmt.Fprintln(os.Stderr, "Invalid input")
return nil
}
}
// TODO: make sure the perms are locked down first.
if err := ioutil.WriteFile("cosign.key", keys.PrivateBytes, 0600); err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Private key written to cosign.key")

if err := ioutil.WriteFile("cosign.pub", keys.PublicBytes, 0600); err != nil {
if err := ioutil.WriteFile("cosign.pub", keys.PublicBytes, 0644); err != nil {
return err
}
} // #nosec G306
fmt.Fprintln(os.Stderr, "Public key written to cosign.pub")
return nil
}
Expand Down Expand Up @@ -153,7 +167,8 @@ func getPassFromTerm(confirm bool) ([]byte, error) {
if !confirm {
return pw1, nil
}
fmt.Fprint(os.Stderr, "Enter again: ")
fmt.Fprintln(os.Stderr)
fmt.Fprint(os.Stderr, "Enter password for private key again: ")
pw2, err := term.ReadPassword(0)
fmt.Fprintln(os.Stderr)
if err != nil {
Expand All @@ -165,3 +180,11 @@ func getPassFromTerm(confirm bool) ([]byte, error) {
}
return pw1, nil
}

func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

0 comments on commit 5abd51e

Please sign in to comment.