Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
333 lines (302 loc) · 8.75 KB
/
Copy pathmain.go
File metadata and controls
333 lines (302 loc) · 8.75 KB
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 goversioninfo -platform-specific -icon=assets/icon.ico
import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"sync"
"time"
"github.com/buptczq/WinCryptSSHAgent/capi"
"github.com/Microsoft/go-winio"
"github.com/buptczq/WinCryptSSHAgent/app"
"github.com/buptczq/WinCryptSSHAgent/sshagent"
"github.com/buptczq/WinCryptSSHAgent/utils"
notify "github.com/hattya/go.notify"
notification "github.com/hattya/go.notify/windows"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
const agentTitle = "WinCrypt SSH Agent"
// variables for buildtime inject
var (
agentVersion = "v1.1.9"
agentBuildTime = ""
agentBuildHash = ""
)
var applications = []app.Application{
new(app.PubKeyView),
new(app.WSL),
new(app.VSock),
new(app.Cygwin),
new(app.NamedPipe),
new(app.Pageant),
new(app.XShell),
}
var installHVService = flag.Bool("i", false, "Install Hyper-V Guest Communication Services")
var disableCapi = flag.Bool("disable-capi", false, "Disable Windows Crypto API")
var disablePINCache = flag.Bool("disable-pin-cache", false, "Clear the Smart Card PIN Cache after each operation")
var confirmRequired = flag.Bool("confirm", false, "Require user confirmation before signing (or set WCSA_CONFIRM=1)")
func installService() {
if !utils.IsAdmin() {
err := utils.RunMeElevated()
if err != nil {
utils.MessageBox("Install Service Error:", err.Error(), utils.MB_ICONERROR)
}
return
}
err := winio.RunWithPrivilege(winio.SeRestorePrivilege, func() error {
gcs, err := registry.OpenKey(registry.LOCAL_MACHINE, utils.HyperVServiceRegPath, registry.ALL_ACCESS)
if err != nil {
return err
}
defer gcs.Close()
agentSrv, _, err := registry.CreateKey(gcs, utils.HyperVServiceGUID.String(), registry.ALL_ACCESS)
if err != nil {
return err
}
err = agentSrv.SetStringValue("ElementName", "WinCryptSSHAgent")
if err != nil {
return err
}
return nil
})
if err != nil {
utils.MessageBox("Install Service Error:", err.Error(), utils.MB_ICONERROR)
} else {
utils.MessageBox("Install Service Success:", "Please reboot your computer to take effect!", utils.MB_ICONINFORMATION)
}
return
}
func initDebugLog() {
if os.Getenv("WCSA_DEBUG") == "1" {
home, err := os.UserHomeDir()
if err != nil {
return
}
f, err := os.OpenFile(filepath.Join(home, "WCSA_DEBUG.log"), os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0664)
if err != nil {
return
}
err = windows.SetStdHandle(windows.STD_OUTPUT_HANDLE, windows.Handle(f.Fd()))
if err != nil {
return
}
err = windows.SetStdHandle(windows.STD_ERROR_HANDLE, windows.Handle(f.Fd()))
if err != nil {
return
}
os.Stdout = f
os.Stderr = f
log.SetOutput(f)
}
}
func main() {
flag.Parse()
utils.SetProcessSystemDpiAware()
initDebugLog()
if *installHVService {
installService()
return
}
// 单实例保护
// 注意:-i 安装模式已在上面提前返回,不受单例限制,
// 否则托盘常驻时提权子进程会被误判为第二实例而拦截。
mutex, err := windows.CreateMutex(nil, false, windows.StringToUTF16Ptr("WinCryptSSHAgent_SingleInstance"))
if err != nil {
utils.MessageBox("Warning:", "WinCryptSSHAgent is already running!: "+err.Error(), utils.MB_ICONWARNING)
return
}
defer windows.CloseHandle(mutex)
// 检查是否已有实例运行
result, err := windows.WaitForSingleObject(mutex, 0)
if err != nil || result != windows.WAIT_OBJECT_0 {
utils.MessageBox("Warning:", "WinCryptSSHAgent is already running!", utils.MB_ICONWARNING)
return
}
// Confirm mode resolution: explicit flag/env wins; otherwise fall back to the
// persisted registry state; otherwise default to Auto Confirm.
manualConfirm := *confirmRequired || os.Getenv("WCSA_CONFIRM") == "1"
if manualConfirm {
utils.ConfirmRequired = true
utils.SaveConfirmToRegistry(true)
} else if regVal, ok := utils.LoadConfirmFromRegistry(); ok {
utils.ConfirmRequired = regVal
} else {
utils.ConfirmRequired = false
}
// hyper-v
hvClient := false
hvCtx, hvCancel := context.WithTimeout(context.Background(), 5*time.Second)
hvConn, err := utils.ConnectHyperV(hvCtx)
hvCancel()
if err == nil {
hvConn.Close()
hvClient = true
}
// systray
notifier, err := initSystray(hvClient)
if err != nil {
utils.MessageBox("Error:", err.Error(), utils.MB_ICONERROR)
return
}
sysTray := notifier.Sys().(*notification.NotifyIcon)
menu := NewMenu(sysTray)
// context
ctx, cancel := context.WithCancel(context.Background())
capi.SetDisablePINCache(*disablePINCache)
// agent
var ag agent.Agent
var keyring *sshagent.KeyRingAgent
if hvClient {
ag = sshagent.NewHVAgent()
} else if *disableCapi {
keyring = sshagent.NewKeyRingAgent()
ag = keyring
} else {
cag := new(sshagent.CAPIAgent)
defer cag.Close()
keyring = sshagent.NewKeyRingAgent()
ag = sshagent.NewWrappedAgent(keyring, []agent.Agent{agent.Agent(cag)})
}
ctx = context.WithValue(ctx, "agent", ag)
ctx = context.WithValue(ctx, "hv", hvClient)
server := &sshagent.Server{
Agent: ag,
}
// application
wg := new(sync.WaitGroup)
for _, v := range applications {
wg.Add(1)
go func(application app.Application) {
handler := server.SSHAgentHandlerWithSource(application.AppId().FullName())
err := application.Run(ctx, handler)
if err != nil {
utils.MessageBox(application.AppId().String()+" Error:", err.Error(), utils.MB_ICONWARNING)
}
wg.Done()
}(v)
}
// interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
// buildMenu (re)builds the tray menu so the "•" marker always reflects the
// current confirm mode. CreateMenu replaces the notifier's item list, which
// the library turns into a fresh native popup on every right-click.
buildMenu := func() {
menu.menu = sysTray.CreateMenu()
for _, v := range applications {
v.Menu(menu.Register)
}
menu.menu.Sep()
mark := func(checked bool) string {
if checked {
return "• "
}
return " "
}
menu.menu.Item(mark(utils.ConfirmRequired)+"Manual Confirm", app.MENU_CONFIRM_MANUAL)
menu.menu.Item(mark(!utils.ConfirmRequired)+"Auto Confirm", app.MENU_CONFIRM_AUTO)
menu.menu.Sep()
menu.menu.Item("Quit", app.MENU_QUIT)
}
// show systray
buildMenu()
err = sysTray.Add()
if err != nil {
log.Printf("systray: Add failed: %v", err)
utils.MessageBox("Error:", err.Error(), utils.MB_ICONERROR)
goto cleanup
}
// AutoLoad after the tray icon exists: key import toasts require the
// icon to be added first, otherwise Notify triggers an early NIM_ADD
// and the Add above fails with "Unspecified error". Runs in background
// so passphrase helpers never block the tray menu.
if keyring != nil {
go sshagent.AutoLoadKeys(keyring)
}
// event
for {
select {
case clicked := <-sysTray.Menu:
if clicked.ID == app.MENU_QUIT {
goto cleanup
}
if clicked.ID == app.MENU_CONFIRM_MANUAL {
utils.ConfirmRequired = true
utils.SaveConfirmToRegistry(true)
buildMenu()
} else if clicked.ID == app.MENU_CONFIRM_AUTO {
utils.ConfirmRequired = false
utils.SaveConfirmToRegistry(false)
buildMenu()
} else {
menu.Handle(app.AppId(clicked.ID))
}
case <-sysTray.Balloon:
continue
case <-quit:
goto cleanup
}
}
cleanup:
sysTray.Close()
cancel()
done := make(chan struct{})
go func() {
wg.Wait()
done <- struct{}{}
}()
select {
case <-time.After(time.Second * 5):
case <-done:
}
}
func initSystray(hv bool) (notify.Notifier, error) {
// 2 is the app icon resource.
icon, err := notification.LoadIcon(2)
if err != nil {
icon, err = notification.LoadIcon(1)
if err != nil {
return nil, err
}
}
title := fmt.Sprintf("%s %s _ %s", agentTitle, agentVersion, agentBuildTime)
if hv {
title += " (Hyper-V)"
}
n, err := notification.NewNotifier(title, icon)
if err != nil {
return nil, err
}
// "auth" event: Authenticated (keeps original icon.ico)
err = n.Register("auth", icon, map[string]interface{}{
"windows:fallback-icon": notification.IconInfo,
"windows:sound": false,
})
if err != nil {
_ = n.Register("auth", notification.IconInfo, map[string]interface{}{
"windows:sound": false,
})
}
// "info" / "add" event: Key added (IconInfo / NIIF_INFO)
_ = n.Register("info", notification.IconInfo, map[string]interface{}{
"windows:sound": false,
})
_ = n.Register("add", notification.IconInfo, map[string]interface{}{
"windows:sound": false,
})
// "warn" / "remove" event: Key removed (IconWarn / NIIF_WARNING)
_ = n.Register("warn", notification.IconWarn, map[string]interface{}{
"windows:sound": false,
})
_ = n.Register("remove", notification.IconWarn, map[string]interface{}{
"windows:sound": false,
})
utils.RegisterNotifier(n)
return n, nil
}