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 ssh
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/ssh"
)
func TestRunner(t *testing.T) {
dir := t.TempDir()
clientKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
require.NoError(t, err)
clientKeyFile := filepath.Join(dir, "private.key")
writePrivateKey(t, clientKeyFile, clientKey)
cancel, runner, _ := createListenerAndSSHServer(t, clientKey, clientKeyFile)
assert.NoError(t, err)
defer runner.Close()
bin, _, err := runner.Run("echo hello")
assert.NoError(t, err)
assert.Equal(t, "hello", bin)
cancel()
// Expect error when sending data over close ssh server channel
assert.Error(t, runner.CopyDataPrivileged([]byte(`hello world`), "/hello", 0644))
_, runner, totalConn := createListenerAndSSHServer(t, clientKey, clientKeyFile)
assert.NoError(t, runner.CopyDataPrivileged([]byte(`hello world`), "/hello", 0644))
assert.NoError(t, runner.CopyDataPrivileged([]byte(`hello world`), "/hello", 0644))
assert.NoError(t, runner.CopyDataPrivileged([]byte(`hello world`), "/hello", 0644))
assert.NoError(t, runner.CopyData([]byte(`hello world`), "/home/core/hello", 0644))
assert.Equal(t, 1, *totalConn)
}
func createListenerAndSSHServer(t *testing.T, clientKey *ecdsa.PrivateKey, clientKeyFile string) (context.CancelFunc, *Runner, *int) {
listener, err := net.Listen("tcp", "127.0.0.1:")
require.NoError(t, err)
addr := listener.Addr().String()
runner, err := CreateRunner(ipFor(addr), portFor(addr), clientKeyFile)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
totalConn := createSSHServer(ctx, t, listener, clientKey, func(input string) (byte, string) {
escaped := fmt.Sprintf("%q", input)
if escaped == `"echo hello"` {
return 0, "hello"
}
if escaped == `"sudo install -m 0644 /dev/null /hello && cat <<EOF | base64 --decode | sudo tee /hello\naGVsbG8gd29ybGQ=\nEOF"` {
return 0, ""
}
if escaped == `"install -m 0644 /dev/null /home/core/hello && cat <<EOF | base64 --decode | tee /home/core/hello\naGVsbG8gd29ybGQ=\nEOF"` {
return 0, ""
}
return 1, fmt.Sprintf("unexpected command: %q", input)
})
return cancel, runner, totalConn
}
func createSSHServer(ctx context.Context, t *testing.T, listener net.Listener, clientKey *ecdsa.PrivateKey, fun func(string) (byte, string)) *int {
totalConn := 0
config := &ssh.ServerConfig{
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
pub, err := ssh.NewPublicKey(&clientKey.PublicKey)
if err != nil {
return nil, err
}
if bytes.Equal(pubKey.Marshal(), pub.Marshal()) && c.User() == "core" {
return &ssh.Permissions{
Extensions: map[string]string{
"pubkey-fp": ssh.FingerprintSHA256(pubKey),
},
}, nil
}
return nil, fmt.Errorf("unknown public key for %q", c.User())
},
}
serverKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
require.NoError(t, err)
signer, err := ssh.NewSignerFromKey(serverKey)
require.NoError(t, err)
config.AddHostKey(signer)
go func() {
for {
nConn, err := listener.Accept()
if err != nil {
logrus.Debugf("cannot accept connection: %v", err)
return
}
totalConn++
conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
require.NoError(t, err)
defer conn.Close()
logrus.Debugf("logged in with key %s\n", conn.Permissions.Extensions["pubkey-fp"])
go ssh.DiscardRequests(reqs)
for newChannel := range chans {
select {
case <-ctx.Done():
return
default:
if newChannel.ChannelType() != "session" {
_ = newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
require.NoError(t, err)
go func(in <-chan *ssh.Request) {
for req := range in {
command := string(req.Payload[4 : req.Payload[3]+4])
logrus.Debugf("received command: %s", command)
_ = req.Reply(req.Type == "exec", nil)
ret, out := fun(command)
_, _ = channel.Write([]byte(out))
_, _ = channel.SendRequest("exit-status", false, []byte{0, 0, 0, ret})
_ = channel.Close()
}
}(requests)
}
}
}
}()
return &totalConn
}
func writePrivateKey(t *testing.T, clientKeyFile string, clientKey *ecdsa.PrivateKey) {
privateKeyFile, err := os.OpenFile(clientKeyFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
require.NoError(t, err)
defer privateKeyFile.Close()
bytes, _ := x509.MarshalPKCS8PrivateKey(clientKey)
require.NoError(t, pem.Encode(privateKeyFile, &pem.Block{
Type: "PRIVATE KEY",
Bytes: bytes,
}))
}
func ipFor(addr string) string {
return strings.Split(addr, ":")[0]
}
func portFor(addr string) int {
port, _ := strconv.Atoi(strings.Split(addr, ":")[1])
return port
}
func TestGenerateSSHKey(t *testing.T) {
tmpDir := t.TempDir()
filename := filepath.Join(tmpDir, "sshkey")
if err := GenerateSSHKey(filename); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filename); err != nil {
t.Fatalf("expected ssh key at %s", filename)
}
}
|