-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.go
169 lines (149 loc) · 4.22 KB
/
server.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
/*This file is part of kuberpult.
Kuberpult is free software: you can redistribute it and/or modify
it under the terms of the Expat(MIT) License as published by
the Free Software Foundation.
Kuberpult is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
MIT License for more details.
You should have received a copy of the MIT License
along with kuberpult. If not, see <https://directory.fsf.org/wiki/License:Expat>.
Copyright 2023 freiheit.com*/
package testssh
import (
"crypto/ed25519"
"encoding/pem"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/mattn/go-shellwords"
"github.com/mikesmitty/edkey"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
type TestServer struct {
Port int
KnownHosts string
ClientKey string
Url string
l net.Listener
execDelay time.Duration
}
type envReq struct {
Env string
Value string
}
type execReq struct {
Command string
}
type exitReq struct {
Status uint32
}
func New(workdir string) *TestServer {
ts := TestServer{}
// Allocate a new listening port
ts.l, _ = net.ListenTCP("tcp", &net.TCPAddr{})
ts.Port = ts.l.Addr().(*net.TCPAddr).Port
// Setup a private key for the server and write a known hosts file
_, servPriv, _ := ed25519.GenerateKey(nil)
ps, _ := ssh.NewSignerFromSigner(servPriv)
kh := knownhosts.Line([]string{fmt.Sprintf("127.0.0.1")}, ps.PublicKey())
ts.KnownHosts = filepath.Join(workdir, "known_hosts")
os.WriteFile(ts.KnownHosts, []byte(kh), 0644)
sc := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
return &ssh.Permissions{}, nil
},
}
sc.AddHostKey(ps)
// Setup a private key for the client and write it to an openssh compatible file
_, clientPriv, _ := ed25519.GenerateKey(nil)
ts.ClientKey = filepath.Join(workdir, "id_ed25519")
key := pem.EncodeToMemory(&pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: edkey.MarshalED25519PrivateKey(clientPriv),
})
os.WriteFile(ts.ClientKey, key, 0600)
ts.Url = fmt.Sprintf("ssh://git@127.0.0.1:%d/.", ts.Port)
go func() {
for {
con, err := ts.l.Accept()
if err != nil {
fmt.Printf("testssh: err %q\n", err)
return
}
go ts.handleConn(con, workdir, sc)
}
}()
return &ts
}
func (ts *TestServer) handleConn(con net.Conn, workdir string, sc *ssh.ServerConfig) {
defer con.Close()
sCon, chans, reqs, err := ssh.NewServerConn(con, sc)
if err != nil {
fmt.Printf("testssh: err %q\n", err)
return
}
defer sCon.Close()
go ssh.DiscardRequests(reqs)
for newch := range chans {
if newch.ChannelType() != "session" {
newch.Reject(ssh.UnknownChannelType, "only channel type session is allowed")
}
ch, reqs, err := newch.Accept()
if err != nil {
fmt.Printf("testssh: accept err %q\n", err)
return
}
env := []string{}
for req := range reqs {
switch req.Type {
case "env":
var payload envReq
ssh.Unmarshal(req.Payload, &payload)
env = append(env, fmt.Sprintf("%s=%s", payload.Env, payload.Value))
case "exec":
var payload execReq
ssh.Unmarshal(req.Payload, &payload)
args, _ := shellwords.Parse(payload.Command)
if args[0] != "git-upload-pack" && args[0] != "git-receive-pack" {
fmt.Printf("testssh: illegal command: %q\n", args[0])
req.Reply(false, nil)
ch.Close()
return
}
args[1] = filepath.Join(workdir, args[1])
cmd := exec.Command(args[0], args[1:len(args)]...)
cmd.Env = env
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
go io.Copy(stdin, ch)
time.Sleep(ts.execDelay)
cmd.Start()
req.Reply(true, nil)
_, _ = io.Copy(ch, stdout)
_, _ = io.Copy(ch.Stderr(), stderr)
err = cmd.Wait()
if err != nil {
fmt.Printf("testssh: run err %q\n", err)
}
ch.SendRequest("exit-status", false, ssh.Marshal(&exitReq{Status: uint32(cmd.ProcessState.ExitCode())}))
ch.Close()
default:
fmt.Printf("testssh: illegal req: %q\n", req.Type)
ch.Close()
}
}
}
}
func (ts *TestServer) DelayExecs(dr time.Duration) {
ts.execDelay = dr
}
func (ts *TestServer) Close() {
ts.l.Close()
}