-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.go
228 lines (193 loc) · 4.58 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
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
package main
import (
"bytes"
"context"
"encoding/binary"
"io"
"log"
"net"
"sync"
"time"
)
type server struct {
listener net.Listener
powershellPath string
pipeName string
}
func newServer(socketPath string, powershellPath string, pipeName string) *server {
listener, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatal(err)
}
log.Printf("start listening on %s", socketPath)
return &server{listener, powershellPath, pipeName}
}
type request struct {
data []byte
resultChannel chan response
}
type response []byte
func (s *server) run(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
go func() {
<-ctx.Done()
log.Println("shutdown")
s.listener.Close()
}()
// invoke gorountine for ssh-agent.exe
done := make(chan struct{}, 1)
requestQueue := make(chan request)
go func() {
s.server(ctx, cancel, requestQueue, done)
}()
wg := &sync.WaitGroup{}
for {
// wait for connection
sshClient, err := s.listener.Accept()
if err != nil {
log.Printf("failed to accept: %s", err)
cancel()
break
}
// invoke goroutine for ssh client
log.Printf("ssh: connected")
wg.Add(1)
go s.client(wg, ctx, sshClient, requestQueue)
}
// wait for all ssh clients to disconnect
wg.Wait()
// wait for ssh-agent.exe to exit
close(requestQueue)
<-done
}
func (s *server) server(ctx context.Context, cancel func(), requestQueue chan request, done chan struct{}) {
defer close(done)
var pendingRequest *request
retryCount := 0
defer func() {
// abort all pending requests
cancel()
if pendingRequest != nil {
close(pendingRequest.resultChannel)
}
for req := range requestQueue {
close(req.resultChannel)
}
}()
for {
// invoke PowerShell.exe
rep, err := newRepeater(ctx, s.powershellPath, s.pipeName)
if err != nil {
return
}
defer rep.terminate()
// process a pending request if any
if pendingRequest != nil && handleRequest(rep, pendingRequest) != nil {
// fail
retryCount += 1
log.Printf("failed to process request (%d/3)", retryCount)
if retryCount == 3 {
log.Printf("give up")
break
}
} else {
// process requests sequentially
for req := range requestQueue {
retryCount = 0
pendingRequest = &req
if handleRequest(rep, pendingRequest) != nil {
break
}
}
}
select {
case <-ctx.Done():
log.Printf("[W] terminated")
return
default:
log.Printf("[W] terminated; retry")
}
}
}
type deadliner interface {
SetReadDeadline(time.Time) error
}
var readTimeLimit = 10 * time.Second
func handleRequest(rep *repeater, req *request) error {
_, err := rep.in.Write(req.data)
if err != nil {
log.Printf("failed to write to [W]: %s", err)
return err
}
log.Printf("[L] -> [W] (%d B)", len(req.data))
if out, ok := rep.out.(deadliner); ok {
err = out.SetReadDeadline(time.Now().Add(readTimeLimit))
if err != nil {
log.Printf("failed to set timeout: %s", err)
}
}
resp, err := readMessage(rep.out)
if err != nil {
log.Printf("failed to read from [W]: %s", err)
return err
}
log.Printf("[L] <- [W] (%d B)", len(resp))
if out, ok := rep.out.(deadliner); ok {
err = out.SetReadDeadline(time.Time{})
if err != nil {
log.Printf("failed to set timeout: %s", err)
}
}
req.resultChannel <- resp
return nil
}
func (s *server) client(wg *sync.WaitGroup, ctx context.Context, sshClient net.Conn, requestQueue chan request) {
defer wg.Done()
defer sshClient.Close()
resChan := make(chan response)
for {
req, err := readMessage(sshClient)
if err != nil {
break
}
log.Printf("ssh -> [L] (%d B)", len(req))
requestQueue <- request{data: req, resultChannel: resChan}
resp, ok := <-resChan
if !ok {
log.Printf("failed to get result")
break
}
_, err = sshClient.Write(resp)
if err != nil {
log.Printf("failed to write to ssh: %s", err)
break
}
log.Printf("ssh <- [L] (%d B)", len(resp))
}
log.Printf("ssh: closed")
}
func readMessage(from io.Reader) ([]byte, error) {
// In ssh-agent protocol, any message consists of:
//
// uint32 message length (network order)
// byte message type
// byte[message length - 1] message contents
//
// ref: https://tools.ietf.org/html/draft-miller-ssh-agent-04
header := make([]byte, 4)
_, err := io.ReadFull(from, header)
if err != nil {
return nil, err
}
var n uint32
err = binary.Read(bytes.NewReader(header), binary.BigEndian, &n)
if err != nil {
log.Fatal("unreachable")
}
body := make([]byte, n)
_, err = io.ReadFull(from, body)
if err != nil {
return nil, err
}
return append(header, body...), nil
}