-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
281 lines (271 loc) · 7.45 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
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
package ldapserver
import (
"crypto/tls"
"errors"
"log"
"net"
"strings"
"syscall"
)
// The LDAP server object
type LDAPServer struct {
// Listener for new connections
listener net.Listener
// Signal for shutdown complete
done chan struct{}
// Handler for LDAP requests
Handler Handler
// TLS config for StartTLS and LDAPS connections
TLSConfig *tls.Config
}
// Create a new LDAP server with the specified handler.
func NewLDAPServer(handler Handler) *LDAPServer {
s := &LDAPServer{
Handler: handler,
done: make(chan struct{}),
}
return s
}
// Load the certificate and key to enable TLS connections.
func (s *LDAPServer) SetupTLS(certFile string, keyFile string) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
s.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
}
return nil
}
// Listen for (initially) non-TLS connections on the specified address.
// Clients may still send StartTLS requests which are accepted if s.TLSConfig is not nil
func (s *LDAPServer) ListenAndServe(address string) error {
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
s.Serve(listener)
return nil
}
// Listen for TLS connections on the specified address.
func (s *LDAPServer) ListenAndServeTLS(address string) error {
if s.TLSConfig == nil {
panic("ListenAndServeTLS called with nil TLSConfig")
}
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
listener = tls.NewListener(listener, s.TLSConfig)
s.Serve(listener)
return nil
}
// Run a LDAP server using the specified listener.
// Should not be called more than once on the same server object.
func (s *LDAPServer) Serve(listener net.Listener) {
if listener == nil {
panic("nil listener")
}
if s.Handler == nil {
s.Handler = &BaseHandler{}
}
if s.done == nil {
// Shutdown() was called
listener.Close()
return
}
s.listener = listener
defer func() {
s.done <- struct{}{}
}()
for {
conn, err := s.listener.Accept()
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == "use of closed network connection" {
break
}
log.Println("Accept error:", err.Error())
continue
}
go s.handleConnection(conn)
}
}
// Signal the server to shut down and wait for it to stop.
func (s *LDAPServer) Shutdown() {
if s.listener == nil {
return
}
s.listener.Close()
<-s.done
close(s.done)
s.done = nil
}
// Handle a connection received from the listener.
func (s *LDAPServer) handleConnection(c net.Conn) {
defer c.Close()
ldapConn := Conn{
conn: c,
TLSConfig: s.TLSConfig,
MessageCache: make(map[MessageID]any),
}
if tlsConn, isTLS := c.(*tls.Conn); isTLS {
ldapConn.isTLS = true
err := tlsConn.Handshake()
if err != nil {
log.Println("TLS handshake error:", err)
return
}
}
for {
if ldapConn.closed {
// Close() called
return
}
ldapConn.tlsStarting.RLock()
msg, err := ldapConn.ReadMessage()
ldapConn.tlsStarting.RUnlock()
if err != nil {
if errors.Is(err, syscall.Errno(0x2746)) || // Windows: An existing connection was forcibly closed by the client
strings.HasSuffix(err.Error(), "connection reset by peer") {
log.Println("Connection was reset.")
ldapConn.Close()
return
} else {
log.Println("Error reading LDAPMessage, closing connection:", err)
// Might fail if it is a transport problem, but we're closing anyway
ldapConn.NotifyDisconnect(ResultProtocolError, "error reading LDAP message")
ldapConn.Close()
return
}
}
s.handleMessage(&ldapConn, msg)
}
}
// Process a LDAP Message received from the connection.
func (s *LDAPServer) handleMessage(conn *Conn, msg *Message) {
if msg.ProtocolOp.Type != TypeBindRequestOp {
conn.asyncOperations.Add(1)
defer conn.asyncOperations.Done()
}
switch msg.ProtocolOp.Type {
case TypeAbandonRequestOp:
messageID, err := BerGetInteger(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Abandon request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Abandon request received")
conn.Close()
return
}
if messageID < 0 || messageID > 2147483647 {
log.Println("Invalid Abandon message ID:", messageID)
return
}
s.Handler.Abandon(conn, msg, MessageID(messageID))
case TypeAddRequestOp:
req, err := GetAddRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Add request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Add request received")
conn.Close()
return
}
conn.asyncOperations.Add(1)
go func() {
defer conn.asyncOperations.Done()
s.Handler.Add(conn, msg, req)
}()
case TypeBindRequestOp:
req, err := GetBindRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Bind request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Bind request received")
conn.Close()
return
}
// Handle this so that implementations don't have to
if req.Version != 3 {
log.Println("Unsupported LDAP version in Bind request:", req.Version)
conn.SendResult(msg.MessageID, nil, TypeBindResponseOp,
ResultProtocolError.AsResult("unsupported LDAP version specified in Bind request"))
return
}
conn.asyncOperations.Wait()
s.Handler.Bind(conn, msg, req)
case TypeCompareRequestOp:
req, err := GetCompareRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Compare request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Compare request received")
conn.Close()
return
}
conn.asyncOperations.Add(1)
go func() {
defer conn.asyncOperations.Done()
s.Handler.Compare(conn, msg, req)
}()
case TypeDeleteRequestOp:
dn := BerGetOctetString(msg.ProtocolOp.Data)
conn.asyncOperations.Add(1)
go func() {
defer conn.asyncOperations.Done()
s.Handler.Delete(conn, msg, dn)
}()
case TypeExtendedRequestOp:
req, err := GetExtendedRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Extended request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Extended request received")
conn.Close()
return
}
// This is not concurrent in case it is a StartTLS request
s.Handler.Extended(conn, msg, req)
case TypeModifyRequestOp:
req, err := GetModifyRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Modify request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Modify request received")
conn.Close()
return
}
conn.asyncOperations.Add(1)
defer func() {
defer conn.asyncOperations.Done()
s.Handler.Modify(conn, msg, req)
}()
case TypeModifyDNRequestOp:
req, err := GetModifyDNRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing ModifyDN request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid ModifyDN request received")
conn.Close()
return
}
conn.asyncOperations.Add(1)
defer func() {
defer conn.asyncOperations.Done()
s.Handler.ModifyDN(conn, msg, req)
}()
case TypeSearchRequestOp:
req, err := GetSearchRequest(msg.ProtocolOp.Data)
if err != nil {
log.Println("Error parsing Search request:", err)
conn.NotifyDisconnect(ResultProtocolError, "invalid Search request received")
conn.Close()
return
}
conn.asyncOperations.Add(1)
go func() {
defer conn.asyncOperations.Done()
s.Handler.Search(conn, msg, req)
}()
case TypeUnbindRequestOp:
// Unbind has no result
// Simply close the connection
conn.Close()
default:
// Let the handler deal with it if it knows how
s.Handler.Other(conn, msg)
}
}