/
ssh.go
184 lines (161 loc) · 4.48 KB
/
ssh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package client
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"github.com/ubclaunchpad/inertia/cfg"
"golang.org/x/crypto/ssh"
)
// SSHSession can run remote commands over SSH
type SSHSession interface {
Run(cmd string) (*bytes.Buffer, *bytes.Buffer, error)
RunStream(cmd string, interactive bool) error
RunSession(commands ...string) error
CopyFile(f io.Reader, remotePath string, permissions string) error
}
// SSHRunner runs commands over SSH and captures results.
type SSHRunner struct {
user string
ip string
sshPort string
pemPath string
pemPassphrase string
}
// NewSSHRunner returns a new SSHRunner
func NewSSHRunner(r *cfg.RemoteVPS, keyPassphrase string) *SSHRunner {
if r != nil {
return &SSHRunner{
user: r.User,
ip: r.IP,
sshPort: r.SSHPort,
pemPath: r.PEM,
pemPassphrase: keyPassphrase,
}
}
return &SSHRunner{}
}
// Run runs a command remotely.
func (r *SSHRunner) Run(cmd string) (cmdout *bytes.Buffer, cmderr *bytes.Buffer, err error) {
session, err := getSSHSession(r.pemPath, r.ip, r.sshPort, r.user, r.pemPassphrase)
if err != nil {
return nil, nil, err
}
defer session.Close()
// Capture result.
var stdout, stderr bytes.Buffer
session.Stdout = &stdout
session.Stderr = &stderr
// Execute command.
err = session.Run(cmd)
return &stdout, &stderr, err
}
// RunStream remotely executes given command, streaming its output
// and opening up an optionally interactive session
func (r *SSHRunner) RunStream(cmd string, interactive bool) error {
session, err := getSSHSession(r.pemPath, r.ip, r.sshPort, r.user, r.pemPassphrase)
if err != nil {
return err
}
defer session.Close()
// Pipe input and outputs.
session.Stdout = os.Stdout
session.Stderr = os.Stderr
if interactive {
session.Stdin = os.Stdin
}
// Execute command.
return session.Run(cmd)
}
// RunSession sets up a SSH shell to the remote
func (r *SSHRunner) RunSession(commands ...string) error {
var (
target = fmt.Sprintf("%s@%s", r.user, r.ip)
args = append([]string{
"-p", r.sshPort,
"-i", r.pemPath,
target},
commands...)
cmd = exec.Command("ssh", args...)
)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
return cmd.Run()
}
// CopyFile copies given reader to remote
func (r *SSHRunner) CopyFile(file io.Reader, remotePath string, permissions string) error {
// Open and read file
contents, err := ioutil.ReadAll(file)
if err != nil {
return err
}
reader := bytes.NewReader(contents)
// Set up
filename := filepath.Base(remotePath)
directory := filepath.Dir(remotePath)
session, err := getSSHSession(r.pemPath, r.ip, r.sshPort, r.user, r.pemPassphrase)
if err != nil {
return err
}
defer session.Close()
// Send file contents
go func() {
w, _ := session.StdinPipe()
defer w.Close()
fmt.Fprintln(w, "C"+permissions, len(contents), filename)
io.Copy(w, reader)
fmt.Fprintln(w, "\x00")
}()
session.Run("mkdir -p " + directory + "; /usr/bin/scp -t " + directory)
return nil
}
// Stubbed out for testing.
func getSSHSession(PEM, IP, sshPort, user, passphrase string) (*ssh.Session, error) {
privateKey, err := ioutil.ReadFile(PEM)
if err != nil {
return nil, err
}
cfg, err := getSSHConfig(privateKey, user, passphrase)
if err != nil {
return nil, err
}
client, err := ssh.Dial("tcp", IP+":"+sshPort, cfg)
if err != nil {
return nil, err
}
// Create a session. It is one session per command.
return client.NewSession()
}
// getSSHConfig returns SSH configuration for the remote.
func getSSHConfig(privateKey []byte, user, passphrase string) (*ssh.ClientConfig, error) {
var key ssh.Signer
var err error
if passphrase == "" {
if key, err = ssh.ParsePrivateKey(privateKey); err != nil {
return nil, fmt.Errorf("failed to parse key without passphrase: %s", err.Error())
}
} else {
if key, err = ssh.ParsePrivateKeyWithPassphrase(privateKey, []byte(passphrase)); err != nil {
return nil, fmt.Errorf("failed to parse key with passphrase: %s", err.Error())
}
}
// Authentication
return &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
// TODO: We need to replace this with a callback
// to verify the host key. A security vulnerability
// comes from the fact that we receive a public key
// from the server and we add it to our GitHub.
// This gives the server readonly access to our
// GitHub account. We need to know who we're
// connecting to.
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}, nil
}