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