-
Notifications
You must be signed in to change notification settings - Fork 41
/
main.go
333 lines (270 loc) · 7.23 KB
/
main.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
package main
//go:generate go run github.com/go-bindata/go-bindata/go-bindata -pkg $GOPACKAGE -o assets.go assets/
import (
"bufio"
"encoding/binary"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"os/user"
"reflect"
"sync"
"syscall"
"unsafe"
"github.com/Microsoft/go-winio"
"github.com/apenwarr/fixconsole"
"github.com/getlantern/systray"
"github.com/lxn/win"
"golang.org/x/sys/windows"
)
var (
unixSocket = flag.String("wsl", "", "Path to Unix socket for passthrough to WSL")
namedPipe = flag.String("winssh", "", "Named pipe for use with Win32 OpenSSH")
verbose = flag.Bool("verbose", false, "Enable verbose logging")
systrayFlag = flag.Bool("systray", false, "Enable systray integration")
force = flag.Bool("force", false, "Force socket usage (unlink existing socket)")
)
const (
// Windows constats
invalidHandleValue = ^windows.Handle(0)
pageReadWrite = 0x4
fileMapWrite = 0x2
// ssh-agent/Pageant constants
agentMaxMessageLength = 8192
agentCopyDataID = 0x804e50ba
)
// copyDataStruct is used to pass data in the WM_COPYDATA message.
// We directly pass a pointer to our copyDataStruct type, we need to be
// careful that it matches the Windows type exactly
type copyDataStruct struct {
dwData uintptr
cbData uint32
lpData uintptr
}
type SecurityAttributes struct {
Length uint32
SecurityDescriptor uintptr
InheritHandle uint32
}
var queryPageantMutex sync.Mutex
func makeInheritSaWithSid() *windows.SecurityAttributes {
var sa windows.SecurityAttributes
u, err := user.Current()
if err == nil {
sd, err := windows.SecurityDescriptorFromString("O:" + u.Uid)
if err == nil {
sa.SecurityDescriptor = sd
}
}
sa.Length = uint32(unsafe.Sizeof(sa))
sa.InheritHandle = 1
return &sa
}
func queryPageant(buf []byte) (result []byte, err error) {
if len(buf) > agentMaxMessageLength {
err = errors.New("Message too long")
return
}
hwnd := win.FindWindow(syscall.StringToUTF16Ptr("Pageant"), syscall.StringToUTF16Ptr("Pageant"))
if hwnd == 0 {
err = errors.New("Could not find Pageant window")
return
}
// Typically you'd add thread ID here but thread ID isn't useful in Go
// We would need goroutine ID but Go hides this and provides no good way of
// accessing it, instead we serialise calls to queryPageant and treat it
// as not being goroutine safe
mapName := fmt.Sprintf("WSLPageantRequest")
queryPageantMutex.Lock()
var sa = makeInheritSaWithSid()
fileMap, err := windows.CreateFileMapping(invalidHandleValue, sa, pageReadWrite, 0, agentMaxMessageLength, syscall.StringToUTF16Ptr(mapName))
if err != nil {
queryPageantMutex.Unlock()
return
}
defer func() {
windows.CloseHandle(fileMap)
queryPageantMutex.Unlock()
}()
sharedMemory, err := windows.MapViewOfFile(fileMap, fileMapWrite, 0, 0, 0)
if err != nil {
return
}
defer windows.UnmapViewOfFile(sharedMemory)
sharedMemoryArray := (*[agentMaxMessageLength]byte)(unsafe.Pointer(sharedMemory))
copy(sharedMemoryArray[:], buf)
mapNameWithNul := mapName + "\000"
// We use our knowledge of Go strings to get the length and pointer to the
// data and the length directly
cds := copyDataStruct{
dwData: agentCopyDataID,
cbData: uint32(((*reflect.StringHeader)(unsafe.Pointer(&mapNameWithNul))).Len),
lpData: ((*reflect.StringHeader)(unsafe.Pointer(&mapNameWithNul))).Data,
}
ret := win.SendMessage(hwnd, win.WM_COPYDATA, 0, uintptr(unsafe.Pointer(&cds)))
if ret == 0 {
err = errors.New("WM_COPYDATA failed")
return
}
len := binary.BigEndian.Uint32(sharedMemoryArray[:4])
len += 4
if len > agentMaxMessageLength {
err = errors.New("Return message too long")
return
}
result = make([]byte, len)
copy(result, sharedMemoryArray[:len])
return
}
var failureMessage = [...]byte{0, 0, 0, 1, 5}
func handleConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
lenBuf := make([]byte, 4)
_, err := io.ReadFull(reader, lenBuf)
if err != nil {
if *verbose {
log.Printf("io.ReadFull error '%s'", err)
}
return
}
len := binary.BigEndian.Uint32(lenBuf)
buf := make([]byte, len)
_, err = io.ReadFull(reader, buf)
if err != nil {
if *verbose {
log.Printf("io.ReadFull error '%s'", err)
}
return
}
result, err := queryPageant(append(lenBuf, buf...))
if err != nil {
// If for some reason talking to Pageant fails we fall back to
// sending an agent error to the client
if *verbose {
log.Printf("Pageant query error '%s'", err)
}
result = failureMessage[:]
}
_, err = conn.Write(result)
if err != nil {
if *verbose {
log.Printf("net.Conn.Write error '%s'", err)
}
return
}
}
}
func listenLoop(ln net.Listener) {
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("net.Listener.Accept error '%s'", err)
return
}
if *verbose {
log.Printf("New connection: %v\n", conn)
}
go handleConnection(conn)
}
}
func main() {
fixconsole.FixConsoleIfNeeded()
flag.Parse()
var unix, pipe net.Listener
var err error
done := make(chan bool, 1)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
go func() {
sig := <-sigs
switch sig {
case os.Interrupt:
log.Printf("Caught signal")
done <- true
}
}()
if *unixSocket != "" {
_, err := os.Stat(*unixSocket)
if err == nil || !os.IsNotExist(err) {
if *force {
// If the socket file already exists then unlink it
err = syscall.Unlink(*unixSocket)
if err != nil {
log.Fatalf("Failed to unlink socket %s, error '%s'\n", *unixSocket, err)
}
} else {
log.Fatalf("Error: the SSH_AUTH_SOCK file already exists. Please delete it manually or use --force option.")
}
}
unix, err = net.Listen("unix", *unixSocket)
if err != nil {
log.Fatalf("Could not open socket %s, error '%s'\n", *unixSocket, err)
}
defer unix.Close()
log.Printf("Listening on Unix socket: %s\n", *unixSocket)
go func() {
listenLoop(unix)
// If for some reason our listener breaks, kill the program
done <- true
}()
}
if *namedPipe != "" {
namedPipeFullName := "\\\\.\\pipe\\" + *namedPipe
var cfg = &winio.PipeConfig{}
pipe, err = winio.ListenPipe(namedPipeFullName, cfg)
if err != nil {
log.Fatalf("Could not open named pipe %s, error '%s'\n", namedPipeFullName, err)
}
defer pipe.Close()
log.Printf("Listening on named pipe: %s\n", namedPipeFullName)
go func() {
listenLoop(pipe)
// If for some reason our listener breaks, kill the program
done <- true
}()
}
if *namedPipe == "" && *unixSocket == "" {
flag.PrintDefaults()
os.Exit(1)
}
if *systrayFlag {
go func() {
// Wait until we are signalled as finished
<-done
// If for some reason our listener breaks, kill the program
systray.Quit()
}()
systray.Run(onSystrayReady, nil)
log.Print("Exiting...")
} else {
// Wait until we are signalled as finished
<-done
log.Print("Exiting...")
}
}
func onSystrayReady() {
systray.SetTitle("WSL-SSH-Pageant")
systray.SetTooltip("WSL-SSH-Pageant")
data, err := Asset("assets/icon.ico")
if err == nil {
systray.SetIcon(data)
}
quit := systray.AddMenuItem("Quit", "Quits this app")
go func() {
for {
select {
case <-quit.ClickedCh:
systray.Quit()
return
}
}
}()
}