-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsasl.go
More file actions
381 lines (326 loc) · 11.4 KB
/
sasl.go
File metadata and controls
381 lines (326 loc) · 11.4 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
379
380
381
package main
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
)
// saslIdleTimeout bounds how long the AUTH loop waits for the next request
// on a persistent connection. Postfix' xsasl_dovecot client caches the
// auth socket per smtpd worker up to smtpd_timeout (default 300s); closing
// earlier leaves Postfix with a half-open socket and produces
// `454 Connection lost to authentication server` on the next AUTH instead
// of a clean FAIL. It is a var (not const) so tests can shorten it.
var saslIdleTimeout = 360 * time.Second
// SASLServer implements the Dovecot SASL authentication protocol.
// It acts as a Dovecot auth server so Postfix can authenticate SMTP
// clients via smtpd_sasl_type=dovecot without requiring Dovecot itself.
type SASLServer struct {
client UserliService
logger *zap.Logger
connID atomic.Uint64
}
// NewSASLServer creates a new SASLServer with the given UserliService.
func NewSASLServer(client UserliService, logger *zap.Logger) *SASLServer {
return &SASLServer{client: client, logger: logger}
}
// StartSASLServer starts the SASL auth server on the given address.
func StartSASLServer(ctx context.Context, wg *sync.WaitGroup, addr string, server *SASLServer) {
config := TCPServerConfig{
Name: "sasl",
Addr: addr,
Logger: server.logger,
OnConnectionAcquired: func() {
saslActiveConnections.Inc()
},
OnConnectionReleased: func() {
saslActiveConnections.Dec()
},
OnConnectionPoolFull: func() {
saslConnectionPoolFullTotal.Inc()
},
}
StartTCPServer(ctx, wg, config, server)
}
// HandleConnection implements the ConnectionHandler interface.
// It performs the Dovecot auth protocol handshake and then handles
// AUTH requests in a loop (persistent connections).
func (s *SASLServer) HandleConnection(ctx context.Context, conn net.Conn) {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
cuid := s.connID.Add(1)
// Send server handshake
_ = conn.SetWriteDeadline(time.Now().Add(WriteTimeout))
if err := s.sendHandshake(writer, cuid); err != nil {
s.logger.Error("failed to send handshake", zap.Error(err))
return
}
// Read client handshake
if err := s.readClientHandshake(conn, reader); err != nil {
s.logger.Error("failed to read client handshake", zap.Error(err))
return
}
// Handle AUTH requests in a loop (persistent connection). Use the
// longer saslIdleTimeout here so Postfix' xsasl_dovecot client can
// reuse the cached auth socket across smtpd sessions without us
// closing it mid-cache (which produces 454 Connection lost on the
// next AUTH instead of a clean FAIL).
for {
if ctx.Err() != nil {
return
}
_ = conn.SetReadDeadline(time.Now().Add(saslIdleTimeout))
line, err := reader.ReadString('\n')
if err != nil {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
return
}
s.logger.Debug("failed to read AUTH request", zap.Error(err))
return
}
line = strings.TrimRight(line, "\r\n")
parts := strings.Split(line, "\t")
if len(parts) == 0 {
continue
}
switch parts[0] {
case "AUTH":
s.handleAuth(ctx, conn, reader, writer, parts)
default:
s.logger.Debug("ignoring unknown command", zap.String("command", parts[0]))
}
}
}
// sendHandshake sends the Dovecot auth server handshake.
func (s *SASLServer) sendHandshake(writer *bufio.Writer, cuid uint64) error {
cookie := make([]byte, 16)
if _, err := rand.Read(cookie); err != nil {
return fmt.Errorf("failed to generate cookie: %w", err)
}
// MECH lines must precede SPID: Postfix uses SPID-before-MECH as the
// signal that it has connected to an auth-master socket and aborts.
lines := []string{
"VERSION\t1\t2",
"MECH\tPLAIN\tplaintext",
"MECH\tLOGIN\tplaintext",
fmt.Sprintf("SPID\t%d", os.Getpid()),
fmt.Sprintf("CUID\t%d", cuid),
fmt.Sprintf("COOKIE\t%032x", cookie),
"DONE",
}
for _, line := range lines {
if _, err := writer.WriteString(line + "\n"); err != nil {
return err
}
}
return writer.Flush()
}
// readClientHandshake reads and validates the client (Postfix) handshake.
func (s *SASLServer) readClientHandshake(conn net.Conn, reader *bufio.Reader) error {
gotVersion := false
gotCPID := false
for {
_ = conn.SetReadDeadline(time.Now().Add(ReadTimeout))
line, err := reader.ReadString('\n')
if err != nil {
return fmt.Errorf("failed to read client handshake: %w", err)
}
line = strings.TrimRight(line, "\r\n")
parts := strings.Split(line, "\t")
if len(parts) == 0 {
continue
}
switch parts[0] {
case "VERSION":
if len(parts) < 3 {
return fmt.Errorf("invalid VERSION line: %s", line)
}
if parts[1] != "1" {
return fmt.Errorf("unsupported major version: %s", parts[1])
}
gotVersion = true
case "CPID":
gotCPID = true
}
// Postfix sends VERSION then CPID, and CPID terminates the handshake
if gotVersion && gotCPID {
return nil
}
}
}
// handleAuth processes an AUTH request and sends OK or FAIL.
func (s *SASLServer) handleAuth(ctx context.Context, conn net.Conn, reader *bufio.Reader, writer *bufio.Writer, parts []string) {
// AUTH\t<id>\t<mechanism>\t[params...]
if len(parts) < 3 {
s.writeResponse(conn, writer, "FAIL\t0\treason=Invalid AUTH request")
return
}
id := parts[1]
mechanism := strings.ToUpper(parts[2])
startTime := time.Now()
var email, password string
var err error
switch mechanism {
case "PLAIN":
email, password, err = s.parsePlainAuth(parts)
case "LOGIN":
email, password, err = s.handleLoginAuth(id, conn, reader, writer)
default:
s.recordAuthResult(mechanism, "error", startTime)
s.writeResponse(conn, writer, fmt.Sprintf("FAIL\t%s\treason=Unsupported mechanism", id))
return
}
if err != nil {
s.logger.Info("auth parsing failed", zap.String("mechanism", mechanism), zap.Error(err))
s.recordAuthResult(mechanism, "error", startTime)
s.writeResponse(conn, writer, fmt.Sprintf("FAIL\t%s\treason=%s", id, sanitizeField(err.Error())))
return
}
s.authenticateAndRespond(ctx, conn, writer, id, mechanism, email, password, startTime)
}
// parsePlainAuth extracts email and password from a PLAIN AUTH request.
// The resp= parameter contains base64-encoded "\x00user\x00password".
func (s *SASLServer) parsePlainAuth(parts []string) (string, string, error) {
var respB64 string
for _, p := range parts[3:] {
if strings.HasPrefix(p, "resp=") {
respB64 = strings.TrimPrefix(p, "resp=")
break
}
}
if respB64 == "" {
return "", "", fmt.Errorf("missing resp= parameter")
}
decoded, err := base64.StdEncoding.DecodeString(respB64)
if err != nil {
return "", "", fmt.Errorf("invalid base64 in resp=")
}
// RFC 4616: authzid \x00 authcid \x00 passwd
// authzid is typically empty, so: \x00user\x00password
nullParts := strings.SplitN(string(decoded), "\x00", 3)
if len(nullParts) != 3 {
return "", "", fmt.Errorf("invalid PLAIN payload format")
}
email := nullParts[1]
password := nullParts[2]
if email == "" || password == "" {
return "", "", fmt.Errorf("empty username or password")
}
return email, password, nil
}
// handleLoginAuth handles the LOGIN mechanism using CONT roundtrips.
//
// Flow:
//
// S: CONT\t<id>\t<base64("Username:")>
// C: CONT\t<id>\t<base64(username)>
// S: CONT\t<id>\t<base64("Password:")>
// C: CONT\t<id>\t<base64(password)>
func (s *SASLServer) handleLoginAuth(id string, conn net.Conn, reader *bufio.Reader, writer *bufio.Writer) (string, string, error) {
// Send Username challenge
usernameChallenge := base64.StdEncoding.EncodeToString([]byte("Username:"))
s.writeResponse(conn, writer, fmt.Sprintf("CONT\t%s\t%s", id, usernameChallenge))
// Read username response
_ = conn.SetReadDeadline(time.Now().Add(ReadTimeout))
line, err := reader.ReadString('\n')
if err != nil {
return "", "", fmt.Errorf("failed to read LOGIN username: %w", err)
}
line = strings.TrimRight(line, "\r\n")
contParts := strings.SplitN(line, "\t", 3)
if len(contParts) < 3 || contParts[0] != "CONT" {
return "", "", fmt.Errorf("expected CONT response for username")
}
usernameBytes, err := base64.StdEncoding.DecodeString(contParts[2])
if err != nil {
return "", "", fmt.Errorf("invalid base64 in LOGIN username")
}
email := string(usernameBytes)
// Send Password challenge
passwordChallenge := base64.StdEncoding.EncodeToString([]byte("Password:"))
s.writeResponse(conn, writer, fmt.Sprintf("CONT\t%s\t%s", id, passwordChallenge))
// Read password response
_ = conn.SetReadDeadline(time.Now().Add(ReadTimeout))
line, err = reader.ReadString('\n')
if err != nil {
return "", "", fmt.Errorf("failed to read LOGIN password: %w", err)
}
line = strings.TrimRight(line, "\r\n")
contParts = strings.SplitN(line, "\t", 3)
if len(contParts) < 3 || contParts[0] != "CONT" {
return "", "", fmt.Errorf("expected CONT response for password")
}
passwordBytes, err := base64.StdEncoding.DecodeString(contParts[2])
if err != nil {
return "", "", fmt.Errorf("invalid base64 in LOGIN password")
}
password := string(passwordBytes)
if email == "" || password == "" {
return "", "", fmt.Errorf("empty username or password")
}
return email, password, nil
}
// authenticateAndRespond calls the Userli API and writes the auth result.
func (s *SASLServer) authenticateAndRespond(ctx context.Context, conn net.Conn, writer *bufio.Writer, id, mechanism, email, password string, startTime time.Time) {
ok, message, err := s.client.Authenticate(ctx, email, password)
if err != nil {
// Fail-closed: API errors reject authentication
s.logger.Error("authentication API error",
zap.String("email", email), zap.Error(err))
s.recordAuthResult(mechanism, "error", startTime)
s.writeResponse(conn, writer, fmt.Sprintf("FAIL\t%s\tuser=%s\treason=Internal error", id, sanitizeField(email)))
return
}
if ok {
s.logger.Info("authentication successful", zap.String("email", email))
s.recordAuthResult(mechanism, "success", startTime)
s.writeResponse(conn, writer, fmt.Sprintf("OK\t%s\tuser=%s", id, sanitizeField(email)))
} else {
reason := message
if reason == "" {
reason = "authentication failed"
}
s.logger.Info("authentication failed", zap.String("email", email), zap.String("reason", reason))
s.recordAuthResult(mechanism, "invalid_credentials", startTime)
s.writeResponse(conn, writer, fmt.Sprintf("FAIL\t%s\tuser=%s\treason=%s", id, sanitizeField(email), sanitizeField(reason)))
}
}
// writeResponse writes a line to the writer and flushes.
func (s *SASLServer) writeResponse(conn net.Conn, writer *bufio.Writer, line string) {
_ = conn.SetWriteDeadline(time.Now().Add(WriteTimeout))
if _, err := writer.WriteString(line + "\n"); err != nil {
s.logger.Error("failed to write response", zap.Error(err))
}
if err := writer.Flush(); err != nil {
s.logger.Error("failed to flush response", zap.Error(err))
}
}
// sanitizeField removes characters that would break the Dovecot auth
// protocol's tab/newline framing. Postfix treats reason/user as opaque
// text up to the next field separator.
func sanitizeField(s string) string {
return strings.Map(func(r rune) rune {
switch r {
case '\t', '\n', '\r':
return ' '
default:
return r
}
}, s)
}
// recordAuthResult records metrics for an authentication attempt.
func (s *SASLServer) recordAuthResult(mechanism, result string, startTime time.Time) {
duration := time.Since(startTime).Seconds()
saslAuthTotal.WithLabelValues(mechanism, result).Inc()
saslAuthDuration.WithLabelValues(mechanism, result).Observe(duration)
}