github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/cmd/puppeth/ssh.go (about) 1 // Copyright 2017 The Spectrum Authors 2 // This file is part of Spectrum. 3 // 4 // Spectrum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Spectrum is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Spectrum. If not, see <http://www.gnu.org/licenses/>. 16 17 package main 18 19 import ( 20 "bufio" 21 "bytes" 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "net" 26 "os" 27 "os/user" 28 "path/filepath" 29 "strings" 30 31 "github.com/SmartMeshFoundation/Spectrum/log" 32 "golang.org/x/crypto/ssh" 33 "golang.org/x/crypto/ssh/terminal" 34 ) 35 36 // sshClient is a small wrapper around Go's SSH client with a few utility methods 37 // implemented on top. 38 type sshClient struct { 39 server string // Server name or IP without port number 40 address string // IP address of the remote server 41 pubkey []byte // RSA public key to authenticate the server 42 client *ssh.Client 43 logger log.Logger 44 } 45 46 // dial establishes an SSH connection to a remote node using the current user and 47 // the user's configured private RSA key. If that fails, password authentication 48 // is fallen back to. The caller may override the login user via user@server:port. 49 func dial(server string, pubkey []byte) (*sshClient, error) { 50 // Figure out a label for the server and a logger 51 label := server 52 if strings.Contains(label, ":") { 53 label = label[:strings.Index(label, ":")] 54 } 55 login := "" 56 if strings.Contains(server, "@") { 57 login = label[:strings.Index(label, "@")] 58 label = label[strings.Index(label, "@")+1:] 59 server = server[strings.Index(server, "@")+1:] 60 } 61 logger := log.New("server", label) 62 logger.Debug("Attempting to establish SSH connection") 63 64 user, err := user.Current() 65 if err != nil { 66 return nil, err 67 } 68 if login == "" { 69 login = user.Username 70 } 71 // Configure the supported authentication methods (private key and password) 72 var auths []ssh.AuthMethod 73 74 path := filepath.Join(user.HomeDir, ".ssh", "id_rsa") 75 if buf, err := ioutil.ReadFile(path); err != nil { 76 log.Warn("No SSH key, falling back to passwords", "path", path, "err", err) 77 } else { 78 key, err := ssh.ParsePrivateKey(buf) 79 if err != nil { 80 fmt.Printf("What's the decryption password for %s? (won't be echoed)\n>", path) 81 blob, err := terminal.ReadPassword(int(os.Stdin.Fd())) 82 fmt.Println() 83 if err != nil { 84 log.Warn("Couldn't read password", "err", err) 85 } 86 key, err := ssh.ParsePrivateKeyWithPassphrase(buf, blob) 87 if err != nil { 88 log.Warn("Failed to decrypt SSH key, falling back to passwords", "path", path, "err", err) 89 } else { 90 auths = append(auths, ssh.PublicKeys(key)) 91 } 92 } else { 93 auths = append(auths, ssh.PublicKeys(key)) 94 } 95 } 96 auths = append(auths, ssh.PasswordCallback(func() (string, error) { 97 fmt.Printf("What's the login password for %s at %s? (won't be echoed)\n> ", login, server) 98 blob, err := terminal.ReadPassword(int(os.Stdin.Fd())) 99 100 fmt.Println() 101 return string(blob), err 102 })) 103 // Resolve the IP address of the remote server 104 addr, err := net.LookupHost(label) 105 if err != nil { 106 return nil, err 107 } 108 if len(addr) == 0 { 109 return nil, errors.New("no IPs associated with domain") 110 } 111 // Try to dial in to the remote server 112 logger.Trace("Dialing remote SSH server", "user", login) 113 if !strings.Contains(server, ":") { 114 server += ":22" 115 } 116 keycheck := func(hostname string, remote net.Addr, key ssh.PublicKey) error { 117 // If no public key is known for SSH, ask the user to confirm 118 if pubkey == nil { 119 fmt.Println() 120 fmt.Printf("The authenticity of host '%s (%s)' can't be established.\n", hostname, remote) 121 fmt.Printf("SSH key fingerprint is %s [MD5]\n", ssh.FingerprintLegacyMD5(key)) 122 fmt.Printf("Are you sure you want to continue connecting (yes/no)? ") 123 124 text, err := bufio.NewReader(os.Stdin).ReadString('\n') 125 switch { 126 case err != nil: 127 return err 128 case strings.TrimSpace(text) == "yes": 129 pubkey = key.Marshal() 130 return nil 131 default: 132 return fmt.Errorf("unknown auth choice: %v", text) 133 } 134 } 135 // If a public key exists for this SSH server, check that it matches 136 if bytes.Equal(pubkey, key.Marshal()) { 137 return nil 138 } 139 // We have a mismatch, forbid connecting 140 return errors.New("ssh key mismatch, readd the machine to update") 141 } 142 client, err := ssh.Dial("tcp", server, &ssh.ClientConfig{User: login, Auth: auths, HostKeyCallback: keycheck}) 143 if err != nil { 144 return nil, err 145 } 146 // Connection established, return our utility wrapper 147 c := &sshClient{ 148 server: label, 149 address: addr[0], 150 pubkey: pubkey, 151 client: client, 152 logger: logger, 153 } 154 if err := c.init(); err != nil { 155 client.Close() 156 return nil, err 157 } 158 return c, nil 159 } 160 161 // init runs some initialization commands on the remote server to ensure it's 162 // capable of acting as puppeth target. 163 func (client *sshClient) init() error { 164 client.logger.Debug("Verifying if docker is available") 165 if out, err := client.Run("docker version"); err != nil { 166 if len(out) == 0 { 167 return err 168 } 169 return fmt.Errorf("docker configured incorrectly: %s", out) 170 } 171 client.logger.Debug("Verifying if docker-compose is available") 172 if out, err := client.Run("docker-compose version"); err != nil { 173 if len(out) == 0 { 174 return err 175 } 176 return fmt.Errorf("docker-compose configured incorrectly: %s", out) 177 } 178 return nil 179 } 180 181 // Close terminates the connection to an SSH server. 182 func (client *sshClient) Close() error { 183 return client.client.Close() 184 } 185 186 // Run executes a command on the remote server and returns the combined output 187 // along with any error status. 188 func (client *sshClient) Run(cmd string) ([]byte, error) { 189 // Establish a single command session 190 session, err := client.client.NewSession() 191 if err != nil { 192 return nil, err 193 } 194 defer session.Close() 195 196 // Execute the command and return any output 197 client.logger.Trace("Running command on remote server", "cmd", cmd) 198 return session.CombinedOutput(cmd) 199 } 200 201 // Stream executes a command on the remote server and streams all outputs into 202 // the local stdout and stderr streams. 203 func (client *sshClient) Stream(cmd string) error { 204 // Establish a single command session 205 session, err := client.client.NewSession() 206 if err != nil { 207 return err 208 } 209 defer session.Close() 210 211 session.Stdout = os.Stdout 212 session.Stderr = os.Stderr 213 214 // Execute the command and return any output 215 client.logger.Trace("Streaming command on remote server", "cmd", cmd) 216 return session.Run(cmd) 217 } 218 219 // Upload copies the set of files to a remote server via SCP, creating any non- 220 // existing folders in the mean time. 221 func (client *sshClient) Upload(files map[string][]byte) ([]byte, error) { 222 // Establish a single command session 223 session, err := client.client.NewSession() 224 if err != nil { 225 return nil, err 226 } 227 defer session.Close() 228 229 // Create a goroutine that streams the SCP content 230 go func() { 231 out, _ := session.StdinPipe() 232 defer out.Close() 233 234 for file, content := range files { 235 client.logger.Trace("Uploading file to server", "file", file, "bytes", len(content)) 236 237 fmt.Fprintln(out, "D0755", 0, filepath.Dir(file)) // Ensure the folder exists 238 fmt.Fprintln(out, "C0644", len(content), filepath.Base(file)) // Create the actual file 239 out.Write(content) // Stream the data content 240 fmt.Fprint(out, "\x00") // Transfer end with \x00 241 fmt.Fprintln(out, "E") // Leave directory (simpler) 242 } 243 }() 244 return session.CombinedOutput("/usr/bin/scp -v -tr ./") 245 }