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