-
Notifications
You must be signed in to change notification settings - Fork 2
/
ssh.go
187 lines (160 loc) · 3.75 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
185
186
187
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"encoding/hex"
"errors"
"io"
"log"
"net"
"strconv"
"strings"
"github.com/mitchellh/packer/packer"
"golang.org/x/crypto/ssh"
)
type sshServer struct {
config *ssh.ServerConfig
listener net.Listener
username string
password string
port int
comm packer.Communicator
}
func newSSHServer() (*sshServer, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
signer, err := ssh.NewSignerFromKey(key)
if err != nil {
return nil, err
}
username := randstr(20)
password := randstr(20)
config := &ssh.ServerConfig{
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
// Don't worry about constant time compares, etc.
// This is a single-use username and password
// on a randomized port, on the loopback interface
// only, on a friendly machine.
var err error
if c.User() != username || string(pass) != password {
err = errors.New("authentication failed")
}
return nil, err
},
}
config.AddHostKey(signer)
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
port, err := strconv.Atoi(strings.TrimPrefix(l.Addr().String(), "127.0.0.1:"))
if err != nil {
return nil, err
}
server := sshServer{
config: config,
listener: l,
port: port,
username: username,
password: password,
}
return &server, nil
}
func (s *sshServer) serveOne() error {
// Accept a connection.
c, err := s.listener.Accept()
if err != nil {
return err
}
defer c.Close()
// Handshake.
_, chans, reqs, err := ssh.NewServerConn(c, s.config)
if err != nil {
return err
}
go ssh.DiscardRequests(reqs)
for newChannel := range chans {
if err := s.handleChannel(newChannel); err != nil {
return err
}
}
return nil
}
func (s *sshServer) handleChannel(newChannel ssh.NewChannel) error {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
return nil
}
channel, requests, err := newChannel.Accept()
if err != nil {
log.Println("newChannel accept failed: ", err)
return nil
}
return s.handleRequests(channel, requests)
}
type envReq struct {
Key []byte
Val []byte
}
type execReq struct {
Command []byte
}
func (s *sshServer) handleRequests(channel ssh.Channel, in <-chan *ssh.Request) error {
env := make(map[string]string)
for req := range in {
switch req.Type {
default:
log.Printf("unrecognized ssh request type=%q payload=%s wantreply=%t", req.Type, req.Payload, req.WantReply)
req.Reply(false, nil) // unhandled; tell them so
case "env":
var e envReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
env[string(e.Key)] = string(e.Val)
case "exec":
var e execReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
var cmdbuf bytes.Buffer
for k, v := range env {
cmdbuf.WriteString(k)
cmdbuf.WriteByte('=')
cmdbuf.WriteString(v)
cmdbuf.WriteByte(' ')
}
cmdbuf.Write(e.Command)
log.Printf("Running command %q", cmdbuf.String())
cmd := &packer.RemoteCmd{Command: cmdbuf.String()}
cmd.Stdout = channel
cmd.Stderr = channel.Stderr()
var rc int
if err := s.comm.Start(cmd); err != nil {
rc = 255 // TODO: What is a better choice here?
} else {
cmd.Wait()
rc = cmd.ExitStatus
}
channel.CloseWrite()
channel.SendRequest("exit-status", false, []byte{0, 0, 0, byte(rc)})
channel.Close()
}
}
return nil
}
func randstr(n int) string {
buf := make([]byte, n/2)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
panic(err)
}
return hex.EncodeToString(buf)
}