-
Notifications
You must be signed in to change notification settings - Fork 2
/
listener.go
127 lines (108 loc) · 2.13 KB
/
listener.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
package main
import (
"fmt"
"net"
"os"
"os/user"
"strconv"
"golang.org/x/crypto/ssh/agent"
)
var ErrListenerSocketPathIsNotAUnixSocket = fmt.Errorf("listener socket path is not unix socket")
type Listener struct {
cfg *Config
fd net.Listener
kr agent.Agent
}
func connPeerCredentials(conn *net.UnixConn) (uint32, uint32, error) {
f, err := conn.File()
if err != nil {
return 0, 0, err
}
uid, gid, err := listenerGetSocketUidGid(int(f.Fd()))
f.Close()
if err != nil {
return 0, 0, err
}
return uid, gid, nil
}
func userInGroup(uid uint32, gid uint32) (exists bool) {
u, err := user.LookupId(strconv.FormatUint(uint64(uid), 10))
if err != nil {
return
}
g, err := u.GroupIds()
if err != nil {
return
}
for _, element := range g {
if element == strconv.FormatUint(uint64(gid), 10) {
exists = true
return
}
}
exists = false
return
}
func NewListener(cfg *Config) (*Listener, error) {
fi, err := os.Stat(cfg.SocketPath)
if !os.IsNotExist(err) {
switch mode := fi.Mode(); {
case mode&os.ModeSocket != 0:
err = os.Remove(cfg.SocketPath)
if err != nil {
return nil, err
}
default:
return nil, ErrListenerSocketPathIsNotAUnixSocket
}
}
fd, err := net.Listen("unix", cfg.SocketPath)
if err != nil {
return nil, err
}
err = os.Chown(cfg.SocketPath, int(cfg.TrustedUserId), int(cfg.AllowedGroupId))
if err != nil {
fd.Close()
return nil, err
}
err = os.Chmod(cfg.SocketPath, 0660)
if err != nil {
fd.Close()
return nil, err
}
l := &Listener{
cfg: cfg,
fd: fd,
kr: agent.NewKeyring(),
}
return l, nil
}
func (l *Listener) Serve() error {
for {
fd, err := l.fd.Accept()
if err != nil {
return err
}
go func() {
l.serveClient(fd)
fd.Close()
}()
}
}
func (l *Listener) serveClient(c net.Conn) {
uc, ok := c.(*net.UnixConn)
if !ok {
return
}
uid, _, err := connPeerCredentials(uc)
if err != nil {
return
}
if uid == l.cfg.TrustedUserId {
agent.ServeAgent(&TrustedKeyring{Agent: l.kr}, c)
} else if userInGroup(uid, l.cfg.AllowedGroupId) {
agent.ServeAgent(&SignOnlyKeyring{Agent: l.kr}, c)
} else {
agent.ServeAgent(&NoopKeyring{}, c)
}
}