Skip to content

Commit 1cebd68

Browse files
committed
add ability to generate ssh key on the fly
1 parent bdb1602 commit 1cebd68

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

main.go

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package main
22

33
import (
4+
"crypto/rand"
5+
"crypto/rsa"
6+
"crypto/x509"
7+
"encoding/pem"
48
"errors"
59
"fmt"
610
"log"
@@ -16,8 +20,9 @@ import (
1620
)
1721

1822
var (
19-
port string
20-
keyFile string
23+
port string
24+
keyFile string
25+
generateKey bool
2126
)
2227

2328
func main() {
@@ -31,6 +36,7 @@ func main() {
3136

3237
rootCmd.Flags().StringVar(&port, "port", "2222", "Port to listen on")
3338
rootCmd.Flags().StringVar(&keyFile, "key-file", "", "Path to SSH host key file")
39+
rootCmd.Flags().BoolVar(&generateKey, "generate-key", false, "Generate SSH key")
3440

3541
if err := rootCmd.Execute(); err != nil {
3642
log.Fatal(err)
@@ -64,10 +70,35 @@ func serve() {
6470
}
6571
hostKeyFile = filepath.Join(home, ".ssh", "id_rsa")
6672
}
73+
if generateKey {
74+
if err := generatePrivateKey(hostKeyFile); err != nil {
75+
log.Fatal(err)
76+
}
77+
}
78+
79+
log.Fatal(ssh.ListenAndServe(":"+port, nil, ssh.HostKeyFile(hostKeyFile)))
80+
}
81+
82+
func generatePrivateKey(keyPath string) error {
83+
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
84+
if err != nil {
85+
return err
86+
}
87+
88+
privateKeyFile, err := os.Create(keyPath)
89+
if err != nil {
90+
return err
91+
}
92+
defer privateKeyFile.Close()
6793

68-
log.Fatal(ssh.ListenAndServe(":"+port, nil,
69-
ssh.HostKeyFile(hostKeyFile),
70-
))
94+
privateKeyPEM := &pem.Block{
95+
Type: "RSA PRIVATE KEY",
96+
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
97+
}
98+
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
99+
return err
100+
}
101+
return nil
71102
}
72103

73104
func NewSessionScreen(s ssh.Session) (tcell.Screen, error) {

0 commit comments

Comments
 (0)