ssh.go 8.4 KB

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