11package main
22
33import (
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
1822var (
19- port string
20- keyFile string
23+ port string
24+ keyFile string
25+ generateKey bool
2126)
2227
2328func 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
73104func NewSessionScreen (s ssh.Session ) (tcell.Screen , error ) {
0 commit comments