-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
378 lines (322 loc) · 9.1 KB
/
main.go
File metadata and controls
378 lines (322 loc) · 9.1 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
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
package main
import (
"crypto/rand"
"encoding/hex"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// UnionAgent combines multiple upstream SSH agents, forwarding requests in order.
type UnionAgent struct {
upstreamSockets []string
}
// NewUnionAgent creates a new UnionAgent with the given upstream socket paths.
func NewUnionAgent(sockets []string) *UnionAgent {
return &UnionAgent{upstreamSockets: sockets}
}
// connectToUpstream connects to an upstream agent socket.
func (u *UnionAgent) connectToUpstream(socketPath string) (agent.ExtendedAgent, net.Conn, error) {
conn, err := net.Dial("unix", socketPath)
if err != nil {
return nil, nil, err
}
return agent.NewClient(conn), conn, nil
}
// List returns the union of all keys from all upstream agents.
func (u *UnionAgent) List() ([]*agent.Key, error) {
var allKeys []*agent.Key
seen := make(map[string]bool)
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
log.Printf("Warning: failed to connect to upstream %s: %v", socketPath, err)
continue
}
defer conn.Close()
keys, err := upstream.List()
if err != nil {
log.Printf("Warning: failed to list keys from %s: %v", socketPath, err)
continue
}
for _, key := range keys {
keyID := string(key.Blob)
if !seen[keyID] {
seen[keyID] = true
allKeys = append(allKeys, key)
}
}
}
return allKeys, nil
}
// Sign tries to sign with each upstream agent in order until one succeeds.
func (u *UnionAgent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
return u.SignWithFlags(key, data, 0)
}
// SignWithFlags tries to sign with flags using each upstream agent in order.
func (u *UnionAgent) SignWithFlags(key ssh.PublicKey, data []byte, flags agent.SignatureFlags) (*ssh.Signature, error) {
keyBlob := key.Marshal()
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
log.Printf("Warning: failed to connect to upstream %s: %v", socketPath, err)
continue
}
sig, err := upstream.SignWithFlags(key, data, flags)
conn.Close()
if err == nil {
return sig, nil
}
// Check if this agent has the key
keys, listErr := upstream.List()
if listErr != nil {
continue
}
hasKey := false
for _, k := range keys {
if string(k.Blob) == string(keyBlob) {
hasKey = true
break
}
}
if hasKey {
// Agent has the key but signing failed
log.Printf("Warning: signing failed with upstream %s: %v", socketPath, err)
}
}
return nil, fmt.Errorf("no upstream agent could sign with the requested key")
}
// Add forwards add requests to the first upstream agent.
func (u *UnionAgent) Add(key agent.AddedKey) error {
if len(u.upstreamSockets) == 0 {
return fmt.Errorf("no upstream agents configured")
}
upstream, conn, err := u.connectToUpstream(u.upstreamSockets[0])
if err != nil {
return err
}
defer conn.Close()
return upstream.Add(key)
}
// Remove forwards remove requests to all upstream agents.
func (u *UnionAgent) Remove(key ssh.PublicKey) error {
var lastErr error
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
lastErr = err
continue
}
err = upstream.Remove(key)
conn.Close()
if err != nil {
lastErr = err
}
}
return lastErr
}
// RemoveAll forwards remove-all requests to all upstream agents.
func (u *UnionAgent) RemoveAll() error {
var lastErr error
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
lastErr = err
continue
}
err = upstream.RemoveAll()
conn.Close()
if err != nil {
lastErr = err
}
}
return lastErr
}
// Lock forwards lock requests to all upstream agents.
func (u *UnionAgent) Lock(passphrase []byte) error {
var lastErr error
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
lastErr = err
continue
}
err = upstream.Lock(passphrase)
conn.Close()
if err != nil {
lastErr = err
}
}
return lastErr
}
// Unlock forwards unlock requests to all upstream agents.
func (u *UnionAgent) Unlock(passphrase []byte) error {
var lastErr error
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
lastErr = err
continue
}
err = upstream.Unlock(passphrase)
conn.Close()
if err != nil {
lastErr = err
}
}
return lastErr
}
// Signers returns signers for all keys from all upstream agents.
func (u *UnionAgent) Signers() ([]ssh.Signer, error) {
var allSigners []ssh.Signer
seen := make(map[string]bool)
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
log.Printf("Warning: failed to connect to upstream %s: %v", socketPath, err)
continue
}
defer conn.Close()
signers, err := upstream.Signers()
if err != nil {
log.Printf("Warning: failed to get signers from %s: %v", socketPath, err)
continue
}
for _, signer := range signers {
keyID := string(signer.PublicKey().Marshal())
if !seen[keyID] {
seen[keyID] = true
allSigners = append(allSigners, signer)
}
}
}
return allSigners, nil
}
// Extension forwards extension requests to each upstream agent until one succeeds.
func (u *UnionAgent) Extension(extensionType string, contents []byte) ([]byte, error) {
for _, socketPath := range u.upstreamSockets {
upstream, conn, err := u.connectToUpstream(socketPath)
if err != nil {
continue
}
result, err := upstream.Extension(extensionType, contents)
conn.Close()
if err == nil {
return result, nil
}
}
return nil, agent.ErrExtensionUnsupported
}
// generateSocketPath creates a socket path following the ssh-agent convention:
// $TMPDIR/ssh-XXXXXXXXXX/agent.<ppid>
func generateSocketPath() (string, error) {
tmpdir := os.TempDir()
// Generate 10 random hex characters (5 bytes = 10 hex chars)
randBytes := make([]byte, 5)
if _, err := rand.Read(randBytes); err != nil {
return "", fmt.Errorf("failed to generate random bytes: %w", err)
}
randStr := hex.EncodeToString(randBytes)
// Create directory: $TMPDIR/ssh-XXXXXXXXXX
dirName := fmt.Sprintf("ssh-%s", randStr)
dirPath := filepath.Join(tmpdir, dirName)
if err := os.MkdirAll(dirPath, 0700); err != nil {
return "", fmt.Errorf("failed to create socket directory: %w", err)
}
// Socket name: agent.<ppid>
socketName := fmt.Sprintf("agent.%d", os.Getppid())
return filepath.Join(dirPath, socketName), nil
}
func usage() {
fmt.Fprintf(os.Stderr, `Usage: %s [-socket <path>] <upstream-socket>...
Options:
`, os.Args[0])
flag.PrintDefaults()
fmt.Fprint(os.Stderr, `
Arguments:
upstream-socket One or more paths to upstream SSH agent sockets
`)
}
func main() {
socketPath := flag.String("socket", "", "Path for the union agent's socket (auto-generated if not specified)")
flag.Usage = usage
flag.Parse()
upstreamSockets := flag.Args()
if len(upstreamSockets) == 0 {
usage()
os.Exit(1)
}
// Generate socket path if not specified
actualSocketPath := *socketPath
var socketDir string
if actualSocketPath == "" {
var err error
actualSocketPath, err = generateSocketPath()
if err != nil {
log.Fatalf("Failed to generate socket path: %v", err)
}
socketDir = filepath.Dir(actualSocketPath)
}
// Remove existing socket if present
if err := os.RemoveAll(actualSocketPath); err != nil {
log.Fatalf("Failed to remove existing socket: %v", err)
}
listener, err := net.Listen("unix", actualSocketPath)
if err != nil {
log.Fatalf("Failed to listen on socket %s: %v", actualSocketPath, err)
}
defer listener.Close()
// Set socket permissions
if err := os.Chmod(actualSocketPath, 0600); err != nil {
log.Fatalf("Failed to set socket permissions: %v", err)
}
unionAgent := NewUnionAgent(upstreamSockets)
// Print in ssh-agent compatible format for eval
fmt.Printf("SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;\n", actualSocketPath)
fmt.Printf("SSH_AGENT_PID=%d; export SSH_AGENT_PID;\n", os.Getpid())
fmt.Printf("echo Agent pid %d;\n", os.Getpid())
log.Printf("Union SSH agent listening on %s", actualSocketPath)
log.Printf("Forwarding to upstream agents: %v", upstreamSockets)
// Handle graceful shutdown
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
shutdownCh := make(chan bool, 1)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
select {
case clean := <-shutdownCh:
if clean {
// Clean shutdown requested, exit quietly
return
}
default:
}
log.Printf("Accept error: %v", err)
return
}
go func(c net.Conn) {
defer c.Close()
if err := agent.ServeAgent(unionAgent, c); err != nil && err != io.EOF {
log.Printf("Agent serve error: %v", err)
}
}(conn)
}
}()
<-sigCh
log.Println("Shutting down...")
shutdownCh <- true
listener.Close()
os.Remove(actualSocketPath)
if socketDir != "" {
os.Remove(socketDir) // Clean up the directory we created
}
}