|
| 1 | +package sshutils |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/rand" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + |
| 8 | + "github.com/ScaleFT/sshkeys" |
| 9 | + "github.com/keybase/bot-sshca/src/shared" |
| 10 | + "golang.org/x/crypto/ed25519" |
| 11 | + "golang.org/x/crypto/ssh" |
| 12 | +) |
| 13 | + |
| 14 | +// Generate a new SSH key. Places the private key at filename and the public key at filename.pub. |
| 15 | +// We use ed25519 keys since they may be more secure (and are smaller). The go crypto ssh library |
| 16 | +// does not support marshalling ed25519 keys so we use ScaleFT/sshkeys to marshal them to the |
| 17 | +// correct on disk format for SSH |
| 18 | +func generateNewSSHKey(filename string) error { |
| 19 | + // Generate the key |
| 20 | + pub, private, err := ed25519.GenerateKey(rand.Reader) |
| 21 | + if err != nil { |
| 22 | + return fmt.Errorf("failed to generate ed25519 key: %v", err) |
| 23 | + } |
| 24 | + |
| 25 | + // Write the private key |
| 26 | + bytes, err := sshkeys.Marshal(private, &sshkeys.MarshalOptions{Format: sshkeys.FormatOpenSSHv1}) |
| 27 | + if err != nil { |
| 28 | + return fmt.Errorf("failed to marshal ed25519 key: %v", err) |
| 29 | + } |
| 30 | + err = ioutil.WriteFile(filename, bytes, 0600) |
| 31 | + if err != nil { |
| 32 | + return fmt.Errorf("failed to write ssh private key to %s: %v", filename, err) |
| 33 | + } |
| 34 | + |
| 35 | + // Write the public key |
| 36 | + publicKey, err := ssh.NewPublicKey(pub) |
| 37 | + if err != nil { |
| 38 | + return fmt.Errorf("failed to create public key from ed25519 key: %v", err) |
| 39 | + } |
| 40 | + bytes = ssh.MarshalAuthorizedKey(publicKey) |
| 41 | + err = ioutil.WriteFile(shared.KeyPathToPubKey(filename), bytes, 0600) |
| 42 | + if err != nil { |
| 43 | + return fmt.Errorf("failed to write ssh public key to %s: %v", shared.KeyPathToPubKey(filename), err) |
| 44 | + } |
| 45 | + |
| 46 | + return nil |
| 47 | +} |
0 commit comments