blob: 59cefca18d46b48112422330758282855ab27faf [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
Jan Schär0175d7a2025-03-26 12:57:23 +000010 "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"
14)
15
16type sshConfig struct {
17 User string
18 Pass string
19 SSHKey manager.SSHKey
20}
21
22func (sc *sshConfig) check() error {
23 if sc.User == "" {
24 return fmt.Errorf("-ssh_user must be set")
25 }
26
27 if sc.Pass == "" && sc.SSHKey.KeyPersistPath == "" {
28 //TODO: The flag name -ssh_key_path could change, which would make this
29 // error very confusing.
30 return fmt.Errorf("-ssh_pass or -ssh_key_path must be set")
31 }
32
33 return nil
34}
35
36func (sc *sshConfig) RegisterFlags() {
37 flag.StringVar(&sc.User, "ssh_user", "", "SSH username to log into the machines")
38 flag.StringVar(&sc.Pass, "ssh_pass", "", "SSH password to log into the machines")
39 sc.SSHKey.RegisterFlags()
40}
41
Jan Schär0175d7a2025-03-26 12:57:23 +000042func (sc *sshConfig) Configure(config *ssh.ClientConfig) error {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020043 if err := sc.check(); err != nil {
Jan Schär0175d7a2025-03-26 12:57:23 +000044 return err
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020045 }
46
Jan Schär0175d7a2025-03-26 12:57:23 +000047 config.User = sc.User
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020048
49 switch {
50 case sc.Pass != "":
Jan Schär0175d7a2025-03-26 12:57:23 +000051 config.Auth = []ssh.AuthMethod{ssh.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 {
Jan Schär0175d7a2025-03-26 12:57:23 +000055 return err
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020056 }
57
58 pubKey, err := sc.SSHKey.PublicKey()
59 if err != nil {
Jan Schär0175d7a2025-03-26 12:57:23 +000060 return err
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020061 }
62
63 klog.Infof("Using ssh key auth with public key: %s", pubKey)
64
Jan Schär0175d7a2025-03-26 12:57:23 +000065 config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020066 }
Jan Schär0175d7a2025-03-26 12:57:23 +000067
68 // Ignore the host key, since it's likely the first time anything logs into
69 // this device, and also because there's no way of knowing its fingerprint.
70 config.HostKeyCallback = ssh.InsecureIgnoreHostKey()
71
72 return nil
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020073}