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