ssh.go 8.4 KB

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