-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimsim.go
401 lines (365 loc) · 8.24 KB
/
simsim.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright 2018 Axel Wagner
//
// 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 main
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"github.com/kr/pty"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/ssh"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
if err := run(); err != nil {
log.Fatal(err)
}
}
var newGroup = flag.String("group", "", "Primary group of newly created users")
func run() error {
listen := flag.String("listen", "0.0.0.0:22", "Port to listen on")
flag.Parse()
cfg := ssh.ServerConfig{
PublicKeyCallback: checkPublicKey,
AuthLogCallback: logAuth,
}
if err := ed25519key(&cfg); err != nil {
return err
}
l, err := net.Listen("tcp", *listen)
if err != nil {
return err
}
for {
c, err := l.Accept()
if err != nil {
return err
}
go serveConn(c, cfg)
}
}
func ed25519key(cfg *ssh.ServerConfig) error {
buf, err := ioutil.ReadFile("ed25519.key")
if err == nil {
return pemKey(cfg, buf)
}
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return err
}
sig, err := ssh.NewSignerFromSigner(priv)
if err != nil {
return err
}
w := new(bytes.Buffer)
w.WriteString("openssh-key-v1\x00")
key := struct {
Pub []byte
Priv []byte
Comment string
Pad []byte `ssh:"rest"`
}{pub, priv, "", nil}
pk1 := struct {
Check1 uint32
Check2 uint32
Keytype string
Rest []byte `ssh:"rest"`
}{0, 0, ssh.KeyAlgoED25519, ssh.Marshal(key)}
k := struct {
CipherName string
KdfName string
KdfOpts string
NumKeys uint32
PubKey []byte
PrivKeyBlock []byte
}{"none", "none", "", 1, nil, ssh.Marshal(&pk1)}
w.Write(ssh.Marshal(k))
buf = pem.EncodeToMemory(&pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: w.Bytes()})
if err := ioutil.WriteFile("ed25519.key", buf, 0600); err != nil {
return err
}
cfg.AddHostKey(sig)
return nil
}
func pemKey(cfg *ssh.ServerConfig, b []byte) error {
k, err := ssh.ParsePrivateKey(b)
if err != nil {
return err
}
cfg.AddHostKey(k)
return nil
}
func logAuth(md ssh.ConnMetadata, method string, err error) {
if err == nil {
log.Printf("Successful %q login for %q from %v", method, md.User(), md.RemoteAddr())
return
}
log.Printf("Failed %q login for %q from %v: %v", method, md.User(), md.RemoteAddr(), err)
}
func checkPublicKey(md ssh.ConnMetadata, pub ssh.PublicKey) (*ssh.Permissions, error) {
username := strings.ToLower(md.User())
for _, r := range username {
if r < 'a' || r > 'z' {
return nil, errors.New("invalid user name")
}
}
u, err := lookupUser(username)
if err != nil {
if _, err = createUser(username, ssh.MarshalAuthorizedKey(pub)); err != nil {
return nil, err
}
return permissions, nil
}
f, err := os.Open(filepath.Join(u.HomeDir, ".ssh", "authorized_keys"))
if err != nil {
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
k, _, _, _, err := ssh.ParseAuthorizedKey(s.Bytes())
if err != nil {
return nil, err
}
if k.Type() != pub.Type() {
continue
}
if bytes.Compare(k.Marshal(), pub.Marshal()) == 0 {
return permissions, nil
}
}
if err := s.Err(); err != nil {
return nil, err
}
return nil, errors.New("unauthorized")
}
var permissions = &ssh.Permissions{}
func serveConn(c net.Conn, cfg ssh.ServerConfig) {
defer c.Close()
sc, ch, reqs, err := ssh.NewServerConn(c, &cfg)
if err != nil {
log.Println(err)
return
}
defer sc.Close()
u, err := lookupUser(strings.ToLower(sc.User()))
if err != nil {
log.Println(err)
return
}
for {
select {
case nch, ok := <-ch:
if !ok {
log.Println("conn closed")
return
}
log.Printf("NewChannel(%q): %q", nch.ChannelType(), nch.ExtraData())
switch nch.ChannelType() {
case "session":
ch, reqs, err := nch.Accept()
go serveSession(u, ch, reqs, err)
default:
nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("channel type %q not supported", nch.ChannelType()))
}
case req, ok := <-reqs:
if !ok {
log.Println("conn closed")
return
}
log.Printf("Request(%q, %v): %q", req.Type, req.WantReply, req.Payload)
if err := req.Reply(false, []byte(fmt.Sprintf("request type %q not supported", req.Type))); err != nil {
log.Println(err)
return
}
}
}
}
func serveSession(u *user, ch ssh.Channel, reqs <-chan *ssh.Request, err error) {
defer func() {
ch.Close()
for range reqs {
}
}()
if err != nil {
log.Println(err)
return
}
var (
env []string
allocPty *requestPTY
)
done := make(chan struct{})
for {
var req *ssh.Request
select {
case r, ok := <-reqs:
if !ok {
return
}
req = r
case <-done:
return
}
r, err := parseRequest(req.Type, req.Payload)
if err != nil {
log.Println(err)
req.Reply(false, []byte(err.Error()))
continue
}
switch r := r.(type) {
case *requestEnv:
env = append(env, fmt.Sprintf("%s=%s", r.Name, r.Value))
case *requestPTY:
if allocPty != nil {
err = errors.New("duplicate pty-req")
}
allocPty = r
env = append(env, "TERM="+r.Term)
case *requestExec:
cmd := exec.Command("/bin/sh", "-c", r.Command)
err = runCommand(ch, cmd, env, u, allocPty, done)
if err == nil {
defer cmd.Process.Kill()
}
case *requestShell:
shell := u.Shell
if shell == "" {
shell = "/bin/bash"
}
cmd := exec.Command(shell, "-l")
err = runCommand(ch, cmd, env, u, allocPty, done)
if err == nil {
defer cmd.Process.Kill()
}
default:
err = fmt.Errorf("request type %T not handled")
}
if err != nil {
req.Reply(false, []byte(err.Error()))
} else if req.WantReply {
req.Reply(true, nil)
}
}
}
func runCommand(ch ssh.Channel, cmd *exec.Cmd, env []string, u *user, allocPty *requestPTY, done chan struct{}) error {
cmd.Dir = u.HomeDir
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: uint32(u.Uid),
Gid: uint32(u.Gid),
},
Setsid: true,
}
for _, g := range u.Groups {
cmd.SysProcAttr.Credential.Groups = append(cmd.SysProcAttr.Credential.Groups, uint32(g.Gid))
}
var (
err error
closer func() error
)
if allocPty != nil {
var f *os.File
f, err = pty.StartWithSize(cmd, &pty.Winsize{Rows: uint16(allocPty.Rows), Cols: uint16(allocPty.Columns), X: uint16(allocPty.Height), Y: uint16(allocPty.Width)})
closer = f.Close
go io.Copy(ch, f)
go io.Copy(f, ch)
} else {
stdin, e := cmd.StdinPipe()
if e != nil {
return err
}
stdout, e := cmd.StdoutPipe()
if e != nil {
return err
}
stderr, e := cmd.StderrPipe()
if e != nil {
return err
}
closer = func() error {
stdin.Close()
stdout.Close()
stderr.Close()
return nil
}
err = cmd.Start()
go io.Copy(stdin, ch)
go io.Copy(ch, stdout)
go io.Copy(ch, stderr)
}
if err == nil {
go func() {
if err := cmd.Wait(); err != nil {
log.Println(err)
}
if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {
st := &struct{ Status uint32 }{uint32(ws.ExitStatus())}
ch.SendRequest("exit-status", false, ssh.Marshal(st))
}
if closer != nil {
closer()
}
close(done)
}()
}
return err
}
type requestPTY struct {
Term string
Columns uint32
Rows uint32
Width uint32
Height uint32
Modes string
}
type requestEnv struct {
Name string
Value string
}
type requestShell struct {
}
type requestExec struct {
Command string
}
func parseRequest(t string, b []byte) (interface{}, error) {
var r interface{}
switch t {
case "pty-req":
r = new(requestPTY)
case "env":
r = new(requestEnv)
case "exec":
r = new(requestExec)
case "shell":
return new(requestShell), nil
default:
return nil, fmt.Errorf("request %q not supported", t)
}
return r, ssh.Unmarshal(b, r)
}