ssh.go 8.0 KB

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