github.com/waltonchain/waltonchain_gwtc_src@v1.1.4-0.20201225072101-8a298c95a819/cmd/puppeth/ssh.go (about)

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