blob: bf2e996220a9f81cc1cad028b397fc66d51631ec [file] [log] [blame]
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +02001package main
2
3import (
4 "flag"
5 "fmt"
6
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +01007 xssh "golang.org/x/crypto/ssh"
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +02008 "k8s.io/klog/v2"
9
10 "source.monogon.dev/cloud/shepherd/manager"
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010011 "source.monogon.dev/go/net/ssh"
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020012)
13
14type sshConfig struct {
15 User string
16 Pass string
17 SSHKey manager.SSHKey
18}
19
20func (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
34func (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 Windelschmidt5f5f3302024-02-22 23:50:24 +010040func (sc *sshConfig) NewClient() (*ssh.DirectClient, error) {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020041 if err := sc.check(); err != nil {
42 return nil, err
43 }
44
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010045 c := ssh.DirectClient{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020046 Username: sc.User,
47 }
48
49 switch {
50 case sc.Pass != "":
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020051 c.AuthMethods = []xssh.AuthMethod{xssh.Password(sc.Pass)}
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020052 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 Windelschmidtd0e39cb2024-09-16 16:14:00 +020065 c.AuthMethods = []xssh.AuthMethod{xssh.PublicKeys(signer)}
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020066 }
67 return &c, nil
68}