github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/cmd/puppeth/ssh.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum 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 // go-ethereum 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 go-ethereum. 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 "golang.org/x/crypto/ssh" 32 "golang.org/x/crypto/ssh/agent" 33 "golang.org/x/crypto/ssh/terminal" 34 35 "github.com/scroll-tech/go-ethereum/log" 36 ) 37 38 // sshClient is a small wrapper around Go's SSH client with a few utility methods 39 // implemented on top. 40 type sshClient struct { 41 server string // Server name or IP without port number 42 address string // IP address of the remote server 43 pubkey []byte // RSA public key to authenticate the server 44 client *ssh.Client 45 logger log.Logger 46 } 47 48 const EnvSSHAuthSock = "SSH_AUTH_SOCK" 49 50 // dial establishes an SSH connection to a remote node using the current user and 51 // the user's configured private RSA key. If that fails, password authentication 52 // is fallen back to. server can be a string like user:identity@server:port. 53 func dial(server string, pubkey []byte) (*sshClient, error) { 54 // Figure out username, identity, hostname and port 55 hostname := "" 56 hostport := server 57 username := "" 58 identity := "id_rsa" // default 59 60 if strings.Contains(server, "@") { 61 prefix := server[:strings.Index(server, "@")] 62 if strings.Contains(prefix, ":") { 63 username = prefix[:strings.Index(prefix, ":")] 64 identity = prefix[strings.Index(prefix, ":")+1:] 65 } else { 66 username = prefix 67 } 68 hostport = server[strings.Index(server, "@")+1:] 69 } 70 if strings.Contains(hostport, ":") { 71 hostname = hostport[:strings.Index(hostport, ":")] 72 } else { 73 hostname = hostport 74 hostport += ":22" 75 } 76 logger := log.New("server", server) 77 logger.Debug("Attempting to establish SSH connection") 78 79 user, err := user.Current() 80 if err != nil { 81 return nil, err 82 } 83 if username == "" { 84 username = user.Username 85 } 86 87 // Configure the supported authentication methods (ssh agent, private key and password) 88 var ( 89 auths []ssh.AuthMethod 90 conn net.Conn 91 ) 92 if conn, err = net.Dial("unix", os.Getenv(EnvSSHAuthSock)); err != nil { 93 log.Warn("Unable to dial SSH agent, falling back to private keys", "err", err) 94 } else { 95 client := agent.NewClient(conn) 96 auths = append(auths, ssh.PublicKeysCallback(client.Signers)) 97 } 98 if err != nil { 99 path := filepath.Join(user.HomeDir, ".ssh", identity) 100 if buf, err := ioutil.ReadFile(path); err != nil { 101 log.Warn("No SSH key, falling back to passwords", "path", path, "err", err) 102 } else { 103 key, err := ssh.ParsePrivateKey(buf) 104 if err != nil { 105 fmt.Printf("What's the decryption password for %s? (won't be echoed)\n>", path) 106 blob, err := terminal.ReadPassword(int(os.Stdin.Fd())) 107 fmt.Println() 108 if err != nil { 109 log.Warn("Couldn't read password", "err", err) 110 } 111 key, err := ssh.ParsePrivateKeyWithPassphrase(buf, blob) 112 if err != nil { 113 log.Warn("Failed to decrypt SSH key, falling back to passwords", "path", path, "err", err) 114 } else { 115 auths = append(auths, ssh.PublicKeys(key)) 116 } 117 } else { 118 auths = append(auths, ssh.PublicKeys(key)) 119 } 120 } 121 auths = append(auths, ssh.PasswordCallback(func() (string, error) { 122 fmt.Printf("What's the login password for %s at %s? (won't be echoed)\n> ", username, server) 123 blob, err := terminal.ReadPassword(int(os.Stdin.Fd())) 124 125 fmt.Println() 126 return string(blob), err 127 })) 128 } 129 // Resolve the IP address of the remote server 130 addr, err := net.LookupHost(hostname) 131 if err != nil { 132 return nil, err 133 } 134 if len(addr) == 0 { 135 return nil, errors.New("no IPs associated with domain") 136 } 137 // Try to dial in to the remote server 138 logger.Trace("Dialing remote SSH server", "user", username) 139 keycheck := func(hostname string, remote net.Addr, key ssh.PublicKey) error { 140 // If no public key is known for SSH, ask the user to confirm 141 if pubkey == nil { 142 fmt.Println() 143 fmt.Printf("The authenticity of host '%s (%s)' can't be established.\n", hostname, remote) 144 fmt.Printf("SSH key fingerprint is %s [MD5]\n", ssh.FingerprintLegacyMD5(key)) 145 fmt.Printf("Are you sure you want to continue connecting (yes/no)? ") 146 147 for { 148 text, err := bufio.NewReader(os.Stdin).ReadString('\n') 149 switch { 150 case err != nil: 151 return err 152 case strings.TrimSpace(text) == "yes": 153 pubkey = key.Marshal() 154 return nil 155 case strings.TrimSpace(text) == "no": 156 return errors.New("users says no") 157 default: 158 fmt.Println("Please answer 'yes' or 'no'") 159 continue 160 } 161 } 162 } 163 // If a public key exists for this SSH server, check that it matches 164 if bytes.Equal(pubkey, key.Marshal()) { 165 return nil 166 } 167 // We have a mismatch, forbid connecting 168 return errors.New("ssh key mismatch, readd the machine to update") 169 } 170 client, err := ssh.Dial("tcp", hostport, &ssh.ClientConfig{User: username, Auth: auths, HostKeyCallback: keycheck}) 171 if err != nil { 172 return nil, err 173 } 174 // Connection established, return our utility wrapper 175 c := &sshClient{ 176 server: hostname, 177 address: addr[0], 178 pubkey: pubkey, 179 client: client, 180 logger: logger, 181 } 182 if err := c.init(); err != nil { 183 client.Close() 184 return nil, err 185 } 186 return c, nil 187 } 188 189 // init runs some initialization commands on the remote server to ensure it's 190 // capable of acting as puppeth target. 191 func (client *sshClient) init() error { 192 client.logger.Debug("Verifying if docker is available") 193 if out, err := client.Run("docker version"); err != nil { 194 if len(out) == 0 { 195 return err 196 } 197 return fmt.Errorf("docker configured incorrectly: %s", out) 198 } 199 client.logger.Debug("Verifying if docker-compose is available") 200 if out, err := client.Run("docker-compose version"); err != nil { 201 if len(out) == 0 { 202 return err 203 } 204 return fmt.Errorf("docker-compose configured incorrectly: %s", out) 205 } 206 return nil 207 } 208 209 // Close terminates the connection to an SSH server. 210 func (client *sshClient) Close() error { 211 return client.client.Close() 212 } 213 214 // Run executes a command on the remote server and returns the combined output 215 // along with any error status. 216 func (client *sshClient) Run(cmd string) ([]byte, error) { 217 // Establish a single command session 218 session, err := client.client.NewSession() 219 if err != nil { 220 return nil, err 221 } 222 defer session.Close() 223 224 // Execute the command and return any output 225 client.logger.Trace("Running command on remote server", "cmd", cmd) 226 return session.CombinedOutput(cmd) 227 } 228 229 // Stream executes a command on the remote server and streams all outputs into 230 // the local stdout and stderr streams. 231 func (client *sshClient) Stream(cmd string) error { 232 // Establish a single command session 233 session, err := client.client.NewSession() 234 if err != nil { 235 return err 236 } 237 defer session.Close() 238 239 session.Stdout = os.Stdout 240 session.Stderr = os.Stderr 241 242 // Execute the command and return any output 243 client.logger.Trace("Streaming command on remote server", "cmd", cmd) 244 return session.Run(cmd) 245 } 246 247 // Upload copies the set of files to a remote server via SCP, creating any non- 248 // existing folders in the mean time. 249 func (client *sshClient) Upload(files map[string][]byte) ([]byte, error) { 250 // Establish a single command session 251 session, err := client.client.NewSession() 252 if err != nil { 253 return nil, err 254 } 255 defer session.Close() 256 257 // Create a goroutine that streams the SCP content 258 go func() { 259 out, _ := session.StdinPipe() 260 defer out.Close() 261 262 for file, content := range files { 263 client.logger.Trace("Uploading file to server", "file", file, "bytes", len(content)) 264 265 fmt.Fprintln(out, "D0755", 0, filepath.Dir(file)) // Ensure the folder exists 266 fmt.Fprintln(out, "C0644", len(content), filepath.Base(file)) // Create the actual file 267 out.Write(content) // Stream the data content 268 fmt.Fprint(out, "\x00") // Transfer end with \x00 269 fmt.Fprintln(out, "E") // Leave directory (simpler) 270 } 271 }() 272 return session.CombinedOutput("/usr/bin/scp -v -tr ./") 273 }