github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/kisexp/xdchain/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  			for {
   133  				text, err := bufio.NewReader(os.Stdin).ReadString('\n')
   134  				switch {
   135  				case err != nil:
   136  					return err
   137  				case strings.TrimSpace(text) == "yes":
   138  					pubkey = key.Marshal()
   139  					return nil
   140  				case strings.TrimSpace(text) == "no":
   141  					return errors.New("users says no")
   142  				default:
   143  					fmt.Println("Please answer 'yes' or 'no'")
   144  					continue
   145  				}
   146  			}
   147  		}
   148  		// If a public key exists for this SSH server, check that it matches
   149  		if bytes.Equal(pubkey, key.Marshal()) {
   150  			return nil
   151  		}
   152  		// We have a mismatch, forbid connecting
   153  		return errors.New("ssh key mismatch, readd the machine to update")
   154  	}
   155  	client, err := ssh.Dial("tcp", hostport, &ssh.ClientConfig{User: username, Auth: auths, HostKeyCallback: keycheck})
   156  	if err != nil {
   157  		return nil, err
   158  	}
   159  	// Connection established, return our utility wrapper
   160  	c := &sshClient{
   161  		server:  hostname,
   162  		address: addr[0],
   163  		pubkey:  pubkey,
   164  		client:  client,
   165  		logger:  logger,
   166  	}
   167  	if err := c.init(); err != nil {
   168  		client.Close()
   169  		return nil, err
   170  	}
   171  	return c, nil
   172  }
   173  
   174  // init runs some initialization commands on the remote server to ensure it's
   175  // capable of acting as puppeth target.
   176  func (client *sshClient) init() error {
   177  	client.logger.Debug("Verifying if docker is available")
   178  	if out, err := client.Run("docker version"); err != nil {
   179  		if len(out) == 0 {
   180  			return err
   181  		}
   182  		return fmt.Errorf("docker configured incorrectly: %s", out)
   183  	}
   184  	client.logger.Debug("Verifying if docker-compose is available")
   185  	if out, err := client.Run("docker-compose version"); err != nil {
   186  		if len(out) == 0 {
   187  			return err
   188  		}
   189  		return fmt.Errorf("docker-compose configured incorrectly: %s", out)
   190  	}
   191  	return nil
   192  }
   193  
   194  // Close terminates the connection to an SSH server.
   195  func (client *sshClient) Close() error {
   196  	return client.client.Close()
   197  }
   198  
   199  // Run executes a command on the remote server and returns the combined output
   200  // along with any error status.
   201  func (client *sshClient) Run(cmd string) ([]byte, error) {
   202  	// Establish a single command session
   203  	session, err := client.client.NewSession()
   204  	if err != nil {
   205  		return nil, err
   206  	}
   207  	defer session.Close()
   208  
   209  	// Execute the command and return any output
   210  	client.logger.Trace("Running command on remote server", "cmd", cmd)
   211  	return session.CombinedOutput(cmd)
   212  }
   213  
   214  // Stream executes a command on the remote server and streams all outputs into
   215  // the local stdout and stderr streams.
   216  func (client *sshClient) Stream(cmd string) error {
   217  	// Establish a single command session
   218  	session, err := client.client.NewSession()
   219  	if err != nil {
   220  		return err
   221  	}
   222  	defer session.Close()
   223  
   224  	session.Stdout = os.Stdout
   225  	session.Stderr = os.Stderr
   226  
   227  	// Execute the command and return any output
   228  	client.logger.Trace("Streaming command on remote server", "cmd", cmd)
   229  	return session.Run(cmd)
   230  }
   231  
   232  // Upload copies the set of files to a remote server via SCP, creating any non-
   233  // existing folders in the mean time.
   234  func (client *sshClient) Upload(files map[string][]byte) ([]byte, error) {
   235  	// Establish a single command session
   236  	session, err := client.client.NewSession()
   237  	if err != nil {
   238  		return nil, err
   239  	}
   240  	defer session.Close()
   241  
   242  	// Create a goroutine that streams the SCP content
   243  	go func() {
   244  		out, _ := session.StdinPipe()
   245  		defer out.Close()
   246  
   247  		for file, content := range files {
   248  			client.logger.Trace("Uploading file to server", "file", file, "bytes", len(content))
   249  
   250  			fmt.Fprintln(out, "D0755", 0, filepath.Dir(file))             // Ensure the folder exists
   251  			fmt.Fprintln(out, "C0644", len(content), filepath.Base(file)) // Create the actual file
   252  			out.Write(content)                                            // Stream the data content
   253  			fmt.Fprint(out, "\x00")                                       // Transfer end with \x00
   254  			fmt.Fprintln(out, "E")                                        // Leave directory (simpler)
   255  		}
   256  	}()
   257  	return session.CombinedOutput("/usr/bin/scp -v -tr ./")
   258  }