ssh.go 7.3 KB

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