forked from kubernetes/minikube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_mock.go
169 lines (146 loc) · 4.39 KB
/
ssh_mock.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
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tests
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"fmt"
"io"
"net"
"strconv"
"sync/atomic"
"github.com/golang/glog"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// SSHServer provides a mock SSH Server for testing. Commands are stored, not executed.
type SSHServer struct {
Config *ssh.ServerConfig
// Commands stores the raw commands executed against the server.
Commands map[string]int
Connected bool
Transfers *bytes.Buffer
// Only access this with atomic ops
hadASessionRequested int32
// commandsToOutput can be used to mock what the SSHServer returns for a given command
// Only access this with atomic ops
commandToOutput atomic.Value
}
// NewSSHServer returns a NewSSHServer instance, ready for use.
func NewSSHServer() (*SSHServer, error) {
s := &SSHServer{}
s.Transfers = &bytes.Buffer{}
s.Config = &ssh.ServerConfig{
NoClientAuth: true,
}
s.Commands = make(map[string]int)
private, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
return nil, errors.Wrap(err, "Error generating RSA key")
}
signer, err := ssh.NewSignerFromKey(private)
if err != nil {
return nil, errors.Wrap(err, "Error creating signer from key")
}
s.Config.AddHostKey(signer)
s.SetSessionRequested(false)
s.SetCommandToOutput(map[string]string{})
return s, nil
}
type execRequest struct {
Command string
}
// Start starts the mock SSH Server, and returns the port it's listening on.
func (s *SSHServer) Start() (int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, errors.Wrap(err, "Error creating tcp listener for ssh server")
}
// Main loop, listen for connections and store the commands.
go func() {
for {
nConn, err := listener.Accept()
go func() {
if err != nil {
return
}
_, chans, reqs, err := ssh.NewServerConn(nConn, s.Config)
if err != nil {
return
}
// The incoming Request channel must be serviced.
go ssh.DiscardRequests(reqs)
// Service the incoming Channel channel.
for newChannel := range chans {
if newChannel.ChannelType() == "session" {
s.SetSessionRequested(true)
}
channel, requests, err := newChannel.Accept()
s.Connected = true
if err != nil {
return
}
req := <-requests
req.Reply(true, nil)
//Note: string(req.Payload) adds additional characters to start of input, execRequest used to solve this issue
var cmd execRequest
if err := ssh.Unmarshal(req.Payload, &cmd); err != nil {
glog.Errorln("Unmarshall encountered error: %s", err)
return
}
s.Commands[cmd.Command] = 1
// Write specified command output as mocked ssh output
if val, err := s.GetCommandToOutput(cmd.Command); err == nil {
channel.Write([]byte(val))
}
channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
// Store anything that comes in over stdin.
io.Copy(s.Transfers, channel)
channel.Close()
}
}()
}
}()
// Parse and return the port.
_, p, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
return 0, errors.Wrap(err, "Error splitting host port")
}
port, err := strconv.Atoi(p)
if err != nil {
return 0, errors.Wrap(err, "Error converting port string to integer")
}
return port, nil
}
func (s *SSHServer) SetCommandToOutput(cmdToOutput map[string]string) {
s.commandToOutput.Store(cmdToOutput)
}
func (s *SSHServer) GetCommandToOutput(cmd string) (string, error) {
cmdMap := s.commandToOutput.Load().(map[string]string)
val, ok := cmdMap[cmd]
if !ok {
return "", fmt.Errorf("unavailable command %s", cmd)
}
return val, nil
}
func (s *SSHServer) SetSessionRequested(b bool) {
var i int32
if b {
i = 1
}
atomic.StoreInt32(&s.hadASessionRequested, i)
}
func (s *SSHServer) IsSessionRequested() bool {
return atomic.LoadInt32(&s.hadASessionRequested) != 0
}