ssh.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. package main
  17. import (
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "net"
  22. "os"
  23. "os/user"
  24. "path/filepath"
  25. "strings"
  26. "syscall"
  27. "github.com/ethereum/go-ethereum/log"
  28. "golang.org/x/crypto/ssh"
  29. "golang.org/x/crypto/ssh/terminal"
  30. )
  31. // sshClient is a small wrapper around Go's SSH client with a few utility methods
  32. // implemented on top.
  33. type sshClient struct {
  34. server string // Server name or IP without port number
  35. address string // IP address of the remote server
  36. client *ssh.Client
  37. logger log.Logger
  38. }
  39. // dial establishes an SSH connection to a remote node using the current user and
  40. // the user's configured private RSA key.
  41. func dial(server string) (*sshClient, error) {
  42. // Figure out a label for the server and a logger
  43. label := server
  44. if strings.Contains(label, ":") {
  45. label = label[:strings.Index(label, ":")]
  46. }
  47. logger := log.New("server", label)
  48. logger.Debug("Attempting to establish SSH connection")
  49. user, err := user.Current()
  50. if err != nil {
  51. return nil, err
  52. }
  53. // Configure the supported authentication methods (private key and password)
  54. var auths []ssh.AuthMethod
  55. path := filepath.Join(user.HomeDir, ".ssh", "id_rsa")
  56. if buf, err := ioutil.ReadFile(path); err != nil {
  57. log.Warn("No SSH key, falling back to passwords", "path", path, "err", err)
  58. } else {
  59. key, err := ssh.ParsePrivateKey(buf)
  60. if err != nil {
  61. log.Warn("Bad SSH key, falling back to passwords", "path", path, "err", err)
  62. } else {
  63. auths = append(auths, ssh.PublicKeys(key))
  64. }
  65. }
  66. auths = append(auths, ssh.PasswordCallback(func() (string, error) {
  67. fmt.Printf("What's the login password for %s at %s? (won't be echoed)\n> ", user.Username, server)
  68. blob, err := terminal.ReadPassword(int(syscall.Stdin))
  69. fmt.Println()
  70. return string(blob), err
  71. }))
  72. // Resolve the IP address of the remote server
  73. addr, err := net.LookupHost(label)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if len(addr) == 0 {
  78. return nil, errors.New("no IPs associated with domain")
  79. }
  80. // Try to dial in to the remote server
  81. logger.Trace("Dialing remote SSH server", "user", user.Username, "key", path)
  82. if !strings.Contains(server, ":") {
  83. server += ":22"
  84. }
  85. client, err := ssh.Dial("tcp", server, &ssh.ClientConfig{User: user.Username, Auth: auths})
  86. if err != nil {
  87. return nil, err
  88. }
  89. // Connection established, return our utility wrapper
  90. c := &sshClient{
  91. server: label,
  92. address: addr[0],
  93. client: client,
  94. logger: logger,
  95. }
  96. if err := c.init(); err != nil {
  97. client.Close()
  98. return nil, err
  99. }
  100. return c, nil
  101. }
  102. // init runs some initialization commands on the remote server to ensure it's
  103. // capable of acting as puppeth target.
  104. func (client *sshClient) init() error {
  105. client.logger.Debug("Verifying if docker is available")
  106. if out, err := client.Run("docker version"); err != nil {
  107. if len(out) == 0 {
  108. return err
  109. }
  110. return fmt.Errorf("docker configured incorrectly: %s", out)
  111. }
  112. client.logger.Debug("Verifying if docker-compose is available")
  113. if out, err := client.Run("docker-compose version"); err != nil {
  114. if len(out) == 0 {
  115. return err
  116. }
  117. return fmt.Errorf("docker-compose configured incorrectly: %s", out)
  118. }
  119. return nil
  120. }
  121. // Close terminates the connection to an SSH server.
  122. func (client *sshClient) Close() error {
  123. return client.client.Close()
  124. }
  125. // Run executes a command on the remote server and returns the combined output
  126. // along with any error status.
  127. func (client *sshClient) Run(cmd string) ([]byte, error) {
  128. // Establish a single command session
  129. session, err := client.client.NewSession()
  130. if err != nil {
  131. return nil, err
  132. }
  133. defer session.Close()
  134. // Execute the command and return any output
  135. client.logger.Trace("Running command on remote server", "cmd", cmd)
  136. return session.CombinedOutput(cmd)
  137. }
  138. // Stream executes a command on the remote server and streams all outputs into
  139. // the local stdout and stderr streams.
  140. func (client *sshClient) Stream(cmd string) error {
  141. // Establish a single command session
  142. session, err := client.client.NewSession()
  143. if err != nil {
  144. return err
  145. }
  146. defer session.Close()
  147. session.Stdout = os.Stdout
  148. session.Stderr = os.Stderr
  149. // Execute the command and return any output
  150. client.logger.Trace("Streaming command on remote server", "cmd", cmd)
  151. return session.Run(cmd)
  152. }
  153. // Upload copied the set of files to a remote server via SCP, creating any non-
  154. // existing folder in te mean time.
  155. func (client *sshClient) Upload(files map[string][]byte) ([]byte, error) {
  156. // Establish a single command session
  157. session, err := client.client.NewSession()
  158. if err != nil {
  159. return nil, err
  160. }
  161. defer session.Close()
  162. // Create a goroutine that streams the SCP content
  163. go func() {
  164. out, _ := session.StdinPipe()
  165. defer out.Close()
  166. for file, content := range files {
  167. client.logger.Trace("Uploading file to server", "file", file, "bytes", len(content))
  168. fmt.Fprintln(out, "D0755", 0, filepath.Dir(file)) // Ensure the folder exists
  169. fmt.Fprintln(out, "C0644", len(content), filepath.Base(file)) // Create the actual file
  170. out.Write(content) // Stream the data content
  171. fmt.Fprint(out, "\x00") // Transfer end with \x00
  172. fmt.Fprintln(out, "E") // Leave directory (simpler)
  173. }
  174. }()
  175. return session.CombinedOutput("/usr/bin/scp -v -tr ./")
  176. }