2023-01-08 01:28:39 +00:00
|
|
|
package sshui
|
|
|
|
|
|
|
|
import (
|
2023-01-08 21:18:02 +00:00
|
|
|
"fmt"
|
2023-01-08 19:44:13 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2023-01-08 01:28:39 +00:00
|
|
|
|
|
|
|
"github.com/gliderlabs/ssh"
|
|
|
|
|
|
|
|
"git.tcp.direct/kayos/ziggs/internal/config"
|
2023-01-08 19:44:13 +00:00
|
|
|
"git.tcp.direct/kayos/ziggs/internal/data"
|
2023-01-08 01:28:39 +00:00
|
|
|
)
|
|
|
|
|
2023-01-08 21:18:02 +00:00
|
|
|
func newHostKey() error {
|
2023-01-08 23:39:36 +00:00
|
|
|
privateKey, err := generatePrivateKey()
|
2023-01-08 21:18:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
dir, _ := filepath.Split(config.Filename)
|
|
|
|
newFile := filepath.Join(dir, "host_rsa")
|
|
|
|
if err = os.WriteFile(newFile, encodePrivateKeyToPEM(privateKey), 0600); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
config.Snek.Set("ssh.host_key", newFile)
|
|
|
|
config.SSHHostKey = newFile
|
|
|
|
if err = config.Snek.WriteConfig(); err != nil {
|
|
|
|
return fmt.Errorf("viper config save error: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-08 19:44:13 +00:00
|
|
|
func ServeSSH() error {
|
2023-01-08 01:28:39 +00:00
|
|
|
var opts []ssh.Option
|
|
|
|
|
2023-01-08 21:18:02 +00:00
|
|
|
if config.SSHHostKey == "" {
|
|
|
|
if err := newHostKey(); err != nil {
|
2023-01-08 19:44:13 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-01-08 01:28:39 +00:00
|
|
|
}
|
|
|
|
|
2023-01-08 21:18:02 +00:00
|
|
|
opts = append(opts, ssh.HostKeyFile(config.SSHHostKey))
|
|
|
|
|
2023-01-08 01:28:39 +00:00
|
|
|
opts = append(opts, ssh.PasswordAuth(func(ctx ssh.Context, password string) bool {
|
2023-01-08 19:44:13 +00:00
|
|
|
attempt := data.NewUserPass(false, ctx.User(), password)
|
|
|
|
err := attempt.Authenticate()
|
|
|
|
return err == nil
|
2023-01-08 01:28:39 +00:00
|
|
|
}))
|
|
|
|
|
2023-01-08 21:18:02 +00:00
|
|
|
opts = append(opts, ssh.PublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool {
|
|
|
|
attempt := data.NewPubKey(ctx.User(), key)
|
|
|
|
err := attempt.Authenticate()
|
|
|
|
return err == nil
|
|
|
|
}))
|
|
|
|
|
2023-01-08 19:44:13 +00:00
|
|
|
return ssh.ListenAndServe(config.SSHListen, nil, opts...)
|
2023-01-08 01:28:39 +00:00
|
|
|
}
|