ssh.go 7.7 KB

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