blob: dceafc438417124a30022117591c672ac6bd4941 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +02004package main
5
6import (
7 "flag"
8 "fmt"
9
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010010 xssh "golang.org/x/crypto/ssh"
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020011 "k8s.io/klog/v2"
12
13 "source.monogon.dev/cloud/shepherd/manager"
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010014 "source.monogon.dev/go/net/ssh"
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020015)
16
17type sshConfig struct {
18 User string
19 Pass string
20 SSHKey manager.SSHKey
21}
22
23func (sc *sshConfig) check() error {
24 if sc.User == "" {
25 return fmt.Errorf("-ssh_user must be set")
26 }
27
28 if sc.Pass == "" && sc.SSHKey.KeyPersistPath == "" {
29 //TODO: The flag name -ssh_key_path could change, which would make this
30 // error very confusing.
31 return fmt.Errorf("-ssh_pass or -ssh_key_path must be set")
32 }
33
34 return nil
35}
36
37func (sc *sshConfig) RegisterFlags() {
38 flag.StringVar(&sc.User, "ssh_user", "", "SSH username to log into the machines")
39 flag.StringVar(&sc.Pass, "ssh_pass", "", "SSH password to log into the machines")
40 sc.SSHKey.RegisterFlags()
41}
42
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010043func (sc *sshConfig) NewClient() (*ssh.DirectClient, error) {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020044 if err := sc.check(); err != nil {
45 return nil, err
46 }
47
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010048 c := ssh.DirectClient{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020049 Username: sc.User,
50 }
51
52 switch {
53 case sc.Pass != "":
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020054 c.AuthMethods = []xssh.AuthMethod{xssh.Password(sc.Pass)}
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020055 case sc.SSHKey.KeyPersistPath != "":
56 signer, err := sc.SSHKey.Signer()
57 if err != nil {
58 return nil, err
59 }
60
61 pubKey, err := sc.SSHKey.PublicKey()
62 if err != nil {
63 return nil, err
64 }
65
66 klog.Infof("Using ssh key auth with public key: %s", pubKey)
67
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020068 c.AuthMethods = []xssh.AuthMethod{xssh.PublicKeys(signer)}
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020069 }
70 return &c, nil
71}