| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 7 | xssh "golang.org/x/crypto/ssh" |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 8 | "k8s.io/klog/v2" |
| 9 | |
| 10 | "source.monogon.dev/cloud/shepherd/manager" |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 11 | "source.monogon.dev/go/net/ssh" |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 12 | ) |
| 13 | |
| 14 | type sshConfig struct { |
| 15 | User string |
| 16 | Pass string |
| 17 | SSHKey manager.SSHKey |
| 18 | } |
| 19 | |
| 20 | func (sc *sshConfig) check() error { |
| 21 | if sc.User == "" { |
| 22 | return fmt.Errorf("-ssh_user must be set") |
| 23 | } |
| 24 | |
| 25 | if sc.Pass == "" && sc.SSHKey.KeyPersistPath == "" { |
| 26 | //TODO: The flag name -ssh_key_path could change, which would make this |
| 27 | // error very confusing. |
| 28 | return fmt.Errorf("-ssh_pass or -ssh_key_path must be set") |
| 29 | } |
| 30 | |
| 31 | return nil |
| 32 | } |
| 33 | |
| 34 | func (sc *sshConfig) RegisterFlags() { |
| 35 | flag.StringVar(&sc.User, "ssh_user", "", "SSH username to log into the machines") |
| 36 | flag.StringVar(&sc.Pass, "ssh_pass", "", "SSH password to log into the machines") |
| 37 | sc.SSHKey.RegisterFlags() |
| 38 | } |
| 39 | |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 40 | func (sc *sshConfig) NewClient() (*ssh.DirectClient, error) { |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 41 | if err := sc.check(); err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 45 | c := ssh.DirectClient{ |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 46 | Username: sc.User, |
| 47 | } |
| 48 | |
| 49 | switch { |
| 50 | case sc.Pass != "": |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 51 | c.AuthMethod = xssh.Password(sc.Pass) |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 52 | case sc.SSHKey.KeyPersistPath != "": |
| 53 | signer, err := sc.SSHKey.Signer() |
| 54 | if err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | |
| 58 | pubKey, err := sc.SSHKey.PublicKey() |
| 59 | if err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | |
| 63 | klog.Infof("Using ssh key auth with public key: %s", pubKey) |
| 64 | |
| Tim Windelschmidt | 5f5f330 | 2024-02-22 23:50:24 +0100 | [diff] [blame] | 65 | c.AuthMethod = xssh.PublicKeys(signer) |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 66 | } |
| 67 | return &c, nil |
| 68 | } |