| 1 |
// Package easyssh provides a simple implementation of some SSH protocol |
| 2 |
// features in Go. You can simply run a command on a remote server or get a file |
| 3 |
// even simpler than native console SSH client. You don't need to think about |
| 4 |
// Dials, sessions, defers, or public keys... Let easyssh think about it! |
| 5 |
package easyssh |
| 6 |
|
| 7 |
import ( |
| 8 |
"bufio" |
| 9 |
"fmt" |
| 10 |
"io" |
| 11 |
"log" |
| 12 |
"net" |
| 13 |
"os" |
| 14 |
"path/filepath" |
| 15 |
"sync" |
| 16 |
"time" |
| 17 |
|
| 18 |
"github.com/ScaleFT/sshkeys" |
| 19 |
"golang.org/x/crypto/ssh" |
| 20 |
"golang.org/x/crypto/ssh/agent" |
| 21 |
) |
| 22 |
|
| 23 |
var defaultTimeout = 60 * time.Second |
| 24 |
|
| 25 |
type Protocol string |
| 26 |
|
| 27 |
const ( |
| 28 |
PROTOCOL_TCP Protocol = "tcp" |
| 29 |
PROTOCOL_TCP4 Protocol = "tcp4" |
| 30 |
PROTOCOL_TCP6 Protocol = "tcp6" |
| 31 |
) |
| 32 |
|
| 33 |
type ( |
| 34 |
// MakeConfig Contains main authority information. |
| 35 |
// User field should be a name of user on remote server (ex. john in ssh [email protected]). |
| 36 |
// Server field should be a remote machine address (ex. example.com in ssh [email protected]) |
| 37 |
// Key is a path to private key on your local machine. |
| 38 |
// Port is SSH server port on remote machine. |
| 39 |
// Note: easyssh looking for private key in user's home directory (ex. /home/john + Key). |
| 40 |
// Then ensure your Key begins from '/' (ex. /.ssh/id_rsa) |
| 41 |
MakeConfig struct { |
| 42 |
User string |
| 43 |
Server string |
| 44 |
Key string |
| 45 |
KeyPath string |
| 46 |
Port string |
| 47 |
Protocol Protocol |
| 48 |
Passphrase string |
| 49 |
Password string |
| 50 |
Timeout time.Duration |
| 51 |
Proxy DefaultConfig |
| 52 |
Ciphers []string |
| 53 |
KeyExchanges []string |
| 54 |
Fingerprint string |
| 55 |
|
| 56 |
// Enable the use of insecure ciphers and key exchange methods. |
| 57 |
// This enables the use of the the following insecure ciphers and key exchange methods: |
| 58 |
// - aes128-cbc |
| 59 |
// - aes192-cbc |
| 60 |
// - aes256-cbc |
| 61 |
// - 3des-cbc |
| 62 |
// - diffie-hellman-group-exchange-sha256 |
| 63 |
// - diffie-hellman-group-exchange-sha1 |
| 64 |
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker. |
| 65 |
UseInsecureCipher bool |
| 66 |
|
| 67 |
// RequestPty requests a pseudo-terminal from the server. |
| 68 |
RequestPty bool |
| 69 |
} |
| 70 |
|
| 71 |
// DefaultConfig for ssh proxy config |
| 72 |
DefaultConfig struct { |
| 73 |
User string |
| 74 |
Server string |
| 75 |
Key string |
| 76 |
KeyPath string |
| 77 |
Port string |
| 78 |
Protocol Protocol |
| 79 |
Passphrase string |
| 80 |
Password string |
| 81 |
Timeout time.Duration |
| 82 |
Ciphers []string |
| 83 |
KeyExchanges []string |
| 84 |
Fingerprint string |
| 85 |
|
| 86 |
// Enable the use of insecure ciphers and key exchange methods. |
| 87 |
// This enables the use of the the following insecure ciphers and key exchange methods: |
| 88 |
// - aes128-cbc |
| 89 |
// - aes192-cbc |
| 90 |
// - aes256-cbc |
| 91 |
// - 3des-cbc |
| 92 |
// - diffie-hellman-group-exchange-sha256 |
| 93 |
// - diffie-hellman-group-exchange-sha1 |
| 94 |
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker. |
| 95 |
UseInsecureCipher bool |
| 96 |
} |
| 97 |
) |
| 98 |
|
| 99 |
// returns ssh.Signer from user you running app home path + cutted key path. |
| 100 |
// (ex. pubkey,err := getKeyFile("/.ssh/id_rsa") ) |
| 101 |
func getKeyFile(keypath, passphrase string) (ssh.Signer, error) { |
| 102 |
var pubkey ssh.Signer |
| 103 |
var err error |
| 104 |
buf, err := os.ReadFile(keypath) |
| 105 |
if err != nil { |
| 106 |
return nil, err |
| 107 |
} |
| 108 |
|
| 109 |
if passphrase != "" { |
| 110 |
pubkey, err = sshkeys.ParseEncryptedPrivateKey(buf, []byte(passphrase)) |
| 111 |
} else { |
| 112 |
pubkey, err = ssh.ParsePrivateKey(buf) |
| 113 |
} |
| 114 |
|
| 115 |
if err != nil { |
| 116 |
return nil, err |
| 117 |
} |
| 118 |
|
| 119 |
return pubkey, nil |
| 120 |
} |
| 121 |
|
| 122 |
// returns *ssh.ClientConfig and io.Closer. |
| 123 |
// if io.Closer is not nil, io.Closer.Close() should be called when |
| 124 |
// *ssh.ClientConfig is no longer used. |
| 125 |
func getSSHConfig(config DefaultConfig) (*ssh.ClientConfig, io.Closer) { |
| 126 |
var sshAgent io.Closer |
| 127 |
|
| 128 |
// auths holds the detected ssh auth methods |
| 129 |
auths := []ssh.AuthMethod{} |
| 130 |
|
| 131 |
// figure out what auths are requested, what is supported |
| 132 |
if config.Password != "" { |
| 133 |
auths = append(auths, ssh.Password(config.Password)) |
| 134 |
} |
| 135 |
if config.KeyPath != "" { |
| 136 |
if pubkey, err := getKeyFile(config.KeyPath, config.Passphrase); err != nil { |
| 137 |
log.Printf("getKeyFile error: %v\n", err) |
| 138 |
} else { |
| 139 |
auths = append(auths, ssh.PublicKeys(pubkey)) |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
if config.Key != "" { |
| 144 |
var signer ssh.Signer |
| 145 |
var err error |
| 146 |
if config.Passphrase != "" { |
| 147 |
signer, err = sshkeys.ParseEncryptedPrivateKey([]byte(config.Key), []byte(config.Passphrase)) |
| 148 |
} else { |
| 149 |
signer, err = ssh.ParsePrivateKey([]byte(config.Key)) |
| 150 |
} |
| 151 |
|
| 152 |
if err != nil { |
| 153 |
log.Printf("ssh.ParsePrivateKey: %v\n", err) |
| 154 |
} else { |
| 155 |
auths = append(auths, ssh.PublicKeys(signer)) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { |
| 160 |
auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) |
| 161 |
} |
| 162 |
|
| 163 |
c := ssh.Config{} |
| 164 |
if config.UseInsecureCipher { |
| 165 |
c.SetDefaults() |
| 166 |
c.Ciphers = append(c.Ciphers, "aes128-cbc", "aes192-cbc", "aes256-cbc", "3des-cbc") |
| 167 |
c.KeyExchanges = append(c.KeyExchanges, "diffie-hellman-group-exchange-sha1", "diffie-hellman-group-exchange-sha256") |
| 168 |
} |
| 169 |
|
| 170 |
if len(config.Ciphers) > 0 { |
| 171 |
c.Ciphers = append(c.Ciphers, config.Ciphers...) |
| 172 |
} |
| 173 |
|
| 174 |
if len(config.KeyExchanges) > 0 { |
| 175 |
c.KeyExchanges = append(c.KeyExchanges, config.KeyExchanges...) |
| 176 |
} |
| 177 |
|
| 178 |
hostKeyCallback := ssh.InsecureIgnoreHostKey() |
| 179 |
if config.Fingerprint != "" { |
| 180 |
hostKeyCallback = func(hostname string, remote net.Addr, publicKey ssh.PublicKey) error { |
| 181 |
if ssh.FingerprintSHA256(publicKey) != config.Fingerprint { |
| 182 |
return fmt.Errorf("ssh: host key fingerprint mismatch") |
| 183 |
} |
| 184 |
return nil |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
return &ssh.ClientConfig{ |
| 189 |
Config: c, |
| 190 |
Timeout: config.Timeout, |
| 191 |
User: config.User, |
| 192 |
Auth: auths, |
| 193 |
HostKeyCallback: hostKeyCallback, |
| 194 |
}, sshAgent |
| 195 |
} |
| 196 |
|
| 197 |
// Connect to remote server using MakeConfig struct and returns *ssh.Session |
| 198 |
func (ssh_conf *MakeConfig) Connect() (*ssh.Session, *ssh.Client, error) { |
| 199 |
var client *ssh.Client |
| 200 |
var err error |
| 201 |
|
| 202 |
// Default protocol is: tcp. |
| 203 |
if ssh_conf.Protocol == "" { |
| 204 |
ssh_conf.Protocol = PROTOCOL_TCP |
| 205 |
} |
| 206 |
if ssh_conf.Proxy.Protocol == "" { |
| 207 |
ssh_conf.Proxy.Protocol = PROTOCOL_TCP |
| 208 |
} |
| 209 |
|
| 210 |
targetConfig, closer := getSSHConfig(DefaultConfig{ |
| 211 |
User: ssh_conf.User, |
| 212 |
Key: ssh_conf.Key, |
| 213 |
KeyPath: ssh_conf.KeyPath, |
| 214 |
Passphrase: ssh_conf.Passphrase, |
| 215 |
Password: ssh_conf.Password, |
| 216 |
Timeout: ssh_conf.Timeout, |
| 217 |
Ciphers: ssh_conf.Ciphers, |
| 218 |
KeyExchanges: ssh_conf.KeyExchanges, |
| 219 |
Fingerprint: ssh_conf.Fingerprint, |
| 220 |
UseInsecureCipher: ssh_conf.UseInsecureCipher, |
| 221 |
}) |
| 222 |
if closer != nil { |
| 223 |
defer closer.Close() |
| 224 |
} |
| 225 |
|
| 226 |
// Enable proxy command |
| 227 |
if ssh_conf.Proxy.Server != "" { |
| 228 |
proxyConfig, closer := getSSHConfig(DefaultConfig{ |
| 229 |
User: ssh_conf.Proxy.User, |
| 230 |
Key: ssh_conf.Proxy.Key, |
| 231 |
KeyPath: ssh_conf.Proxy.KeyPath, |
| 232 |
Passphrase: ssh_conf.Proxy.Passphrase, |
| 233 |
Password: ssh_conf.Proxy.Password, |
| 234 |
Timeout: ssh_conf.Proxy.Timeout, |
| 235 |
Ciphers: ssh_conf.Proxy.Ciphers, |
| 236 |
KeyExchanges: ssh_conf.Proxy.KeyExchanges, |
| 237 |
Fingerprint: ssh_conf.Proxy.Fingerprint, |
| 238 |
UseInsecureCipher: ssh_conf.Proxy.UseInsecureCipher, |
| 239 |
}) |
| 240 |
if closer != nil { |
| 241 |
defer closer.Close() |
| 242 |
} |
| 243 |
|
| 244 |
proxyClient, err := ssh.Dial(string(ssh_conf.Proxy.Protocol), net.JoinHostPort(ssh_conf.Proxy.Server, ssh_conf.Proxy.Port), proxyConfig) |
| 245 |
if err != nil { |
| 246 |
return nil, nil, err |
| 247 |
} |
| 248 |
|
| 249 |
conn, err := proxyClient.Dial(string(ssh_conf.Protocol), net.JoinHostPort(ssh_conf.Server, ssh_conf.Port)) |
| 250 |
if err != nil { |
| 251 |
return nil, nil, err |
| 252 |
} |
| 253 |
|
| 254 |
ncc, chans, reqs, err := ssh.NewClientConn(conn, net.JoinHostPort(ssh_conf.Server, ssh_conf.Port), targetConfig) |
| 255 |
if err != nil { |
| 256 |
return nil, nil, err |
| 257 |
} |
| 258 |
|
| 259 |
client = ssh.NewClient(ncc, chans, reqs) |
| 260 |
} else { |
| 261 |
client, err = ssh.Dial(string(ssh_conf.Protocol), net.JoinHostPort(ssh_conf.Server, ssh_conf.Port), targetConfig) |
| 262 |
if err != nil { |
| 263 |
return nil, nil, err |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
session, err := client.NewSession() |
| 268 |
if err != nil { |
| 269 |
return nil, nil, err |
| 270 |
} |
| 271 |
|
| 272 |
// Request a pseudo-terminal if this option is set |
| 273 |
if ssh_conf.RequestPty { |
| 274 |
modes := ssh.TerminalModes{ |
| 275 |
ssh.ECHO: 0, // disable echoing |
| 276 |
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud |
| 277 |
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud |
| 278 |
} |
| 279 |
if err := session.RequestPty("xterm", 80, 40, modes); err != nil { |
| 280 |
session.Close() |
| 281 |
return nil, nil, err |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
return session, client, nil |
| 286 |
} |
| 287 |
|
| 288 |
// Stream returns one channel that combines the stdout and stderr of the command |
| 289 |
// as it is run on the remote machine, and another that sends true when the |
| 290 |
// command is done. The sessions and channels will then be closed. |
| 291 |
func (ssh_conf *MakeConfig) Stream(command string, timeout ...time.Duration) (<-chan string, <-chan string, <-chan bool, <-chan error, error) { |
| 292 |
// continuously send the command's output over the channel |
| 293 |
stdoutChan := make(chan string) |
| 294 |
stderrChan := make(chan string) |
| 295 |
doneChan := make(chan bool) |
| 296 |
errChan := make(chan error) |
| 297 |
|
| 298 |
// connect to remote host |
| 299 |
session, client, err := ssh_conf.Connect() |
| 300 |
if err != nil { |
| 301 |
return stdoutChan, stderrChan, doneChan, errChan, err |
| 302 |
} |
| 303 |
// defer session.Close() |
| 304 |
// connect to both outputs (they are of type io.Reader) |
| 305 |
outReader, err := session.StdoutPipe() |
| 306 |
if err != nil { |
| 307 |
client.Close() |
| 308 |
session.Close() |
| 309 |
return stdoutChan, stderrChan, doneChan, errChan, err |
| 310 |
} |
| 311 |
errReader, err := session.StderrPipe() |
| 312 |
if err != nil { |
| 313 |
client.Close() |
| 314 |
session.Close() |
| 315 |
return stdoutChan, stderrChan, doneChan, errChan, err |
| 316 |
} |
| 317 |
err = session.Start(command) |
| 318 |
if err != nil { |
| 319 |
client.Close() |
| 320 |
session.Close() |
| 321 |
return stdoutChan, stderrChan, doneChan, errChan, err |
| 322 |
} |
| 323 |
|
| 324 |
// combine outputs, create a line-by-line scanner |
| 325 |
stdoutReader := io.MultiReader(outReader) |
| 326 |
stderrReader := io.MultiReader(errReader) |
| 327 |
stdoutScanner := bufio.NewScanner(stdoutReader) |
| 328 |
stderrScanner := bufio.NewScanner(stderrReader) |
| 329 |
|
| 330 |
go func(stdoutScanner, stderrScanner *bufio.Scanner, stdoutChan, stderrChan chan string, doneChan chan bool, errChan chan error) { |
| 331 |
defer close(doneChan) |
| 332 |
defer close(errChan) |
| 333 |
defer client.Close() |
| 334 |
defer session.Close() |
| 335 |
|
| 336 |
// default timeout value |
| 337 |
executeTimeout := defaultTimeout |
| 338 |
if len(timeout) > 0 { |
| 339 |
executeTimeout = timeout[0] |
| 340 |
} |
| 341 |
timeoutChan := time.After(executeTimeout) |
| 342 |
res := make(chan struct{}, 1) |
| 343 |
var resWg sync.WaitGroup |
| 344 |
resWg.Add(2) |
| 345 |
|
| 346 |
go func() { |
| 347 |
defer close(stdoutChan) |
| 348 |
for stdoutScanner.Scan() { |
| 349 |
stdoutChan <- stdoutScanner.Text() |
| 350 |
} |
| 351 |
resWg.Done() |
| 352 |
}() |
| 353 |
|
| 354 |
go func() { |
| 355 |
defer close(stderrChan) |
| 356 |
for stderrScanner.Scan() { |
| 357 |
stderrChan <- stderrScanner.Text() |
| 358 |
} |
| 359 |
resWg.Done() |
| 360 |
}() |
| 361 |
|
| 362 |
go func() { |
| 363 |
resWg.Wait() |
| 364 |
// close all of our open resources |
| 365 |
res <- struct{}{} |
| 366 |
}() |
| 367 |
|
| 368 |
select { |
| 369 |
case <-res: |
| 370 |
errChan <- session.Wait() |
| 371 |
doneChan <- true |
| 372 |
case <-timeoutChan: |
| 373 |
errChan <- fmt.Errorf("Run Command Timeout") |
| 374 |
doneChan <- false |
| 375 |
} |
| 376 |
}(stdoutScanner, stderrScanner, stdoutChan, stderrChan, doneChan, errChan) |
| 377 |
|
| 378 |
return stdoutChan, stderrChan, doneChan, errChan, err |
| 379 |
} |
| 380 |
|
| 381 |
// Run command on remote machine and returns its stdout as a string |
| 382 |
func (ssh_conf *MakeConfig) Run(command string, timeout ...time.Duration) (outStr string, errStr string, isTimeout bool, err error) { |
| 383 |
stdoutChan, stderrChan, doneChan, errChan, err := ssh_conf.Stream(command, timeout...) |
| 384 |
if err != nil { |
| 385 |
return outStr, errStr, isTimeout, err |
| 386 |
} |
| 387 |
// read from the output channel until the done signal is passed |
| 388 |
loop: |
| 389 |
for { |
| 390 |
select { |
| 391 |
case isTimeout = <-doneChan: |
| 392 |
break loop |
| 393 |
case outline, ok := <-stdoutChan: |
| 394 |
if !ok { |
| 395 |
stdoutChan = nil |
| 396 |
} |
| 397 |
if outline != "" { |
| 398 |
outStr += outline + "\n" |
| 399 |
} |
| 400 |
case errline, ok := <-stderrChan: |
| 401 |
if !ok { |
| 402 |
stderrChan = nil |
| 403 |
} |
| 404 |
if errline != "" { |
| 405 |
errStr += errline + "\n" |
| 406 |
} |
| 407 |
case err = <-errChan: |
| 408 |
} |
| 409 |
} |
| 410 |
// return the concatenation of all signals from the output channel |
| 411 |
return outStr, errStr, isTimeout, err |
| 412 |
} |
| 413 |
|
| 414 |
// WriteFile reads size bytes from the reader and writes them to a file on the remote machine |
| 415 |
func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, etargetFile string) error { |
| 416 |
session, client, err := ssh_conf.Connect() |
| 417 |
if err != nil { |
| 418 |
return err |
| 419 |
} |
| 420 |
defer client.Close() |
| 421 |
defer session.Close() |
| 422 |
|
| 423 |
targetFile := filepath.Base(etargetFile) |
| 424 |
|
| 425 |
w, err := session.StdinPipe() |
| 426 |
if err != nil { |
| 427 |
return err |
| 428 |
} |
| 429 |
|
| 430 |
copyF := func() error { |
| 431 |
_, err := fmt.Fprintln(w, "C0644", size, targetFile) |
| 432 |
if err != nil { |
| 433 |
return err |
| 434 |
} |
| 435 |
|
| 436 |
if size > 0 { |
| 437 |
_, err = io.Copy(w, reader) |
| 438 |
if err != nil { |
| 439 |
return err |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
_, err = fmt.Fprint(w, "\x00") |
| 444 |
if err != nil { |
| 445 |
return err |
| 446 |
} |
| 447 |
|
| 448 |
return nil |
| 449 |
} |
| 450 |
|
| 451 |
copyErrC := make(chan error, 1) |
| 452 |
go func() { |
| 453 |
defer w.Close() |
| 454 |
copyErrC <- copyF() |
| 455 |
}() |
| 456 |
|
| 457 |
err = session.Run(fmt.Sprintf("scp -tr %s", etargetFile)) |
| 458 |
if err != nil { |
| 459 |
return err |
| 460 |
} |
| 461 |
|
| 462 |
err = <-copyErrC |
| 463 |
return err |
| 464 |
} |
| 465 |
|
| 466 |
// Scp uploads sourceFile to remote machine like native scp console app. |
| 467 |
func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error { |
| 468 |
session, client, err := ssh_conf.Connect() |
| 469 |
if err != nil { |
| 470 |
return err |
| 471 |
} |
| 472 |
defer client.Close() |
| 473 |
defer session.Close() |
| 474 |
|
| 475 |
src, srcErr := os.Open(sourceFile) |
| 476 |
|
| 477 |
if srcErr != nil { |
| 478 |
return srcErr |
| 479 |
} |
| 480 |
defer src.Close() |
| 481 |
|
| 482 |
srcStat, statErr := src.Stat() |
| 483 |
|
| 484 |
if statErr != nil { |
| 485 |
return statErr |
| 486 |
} |
| 487 |
return ssh_conf.WriteFile(src, srcStat.Size(), etargetFile) |
| 488 |
} |