-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsmtpd_test.go
583 lines (539 loc) · 14.4 KB
/
smtpd_test.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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//
// Let's see if I can write Go tests
package smtpd
import (
"bufio"
"bytes"
"io"
"net"
"strings"
"testing"
"time"
)
// This should contain only things that are actually valid. Do not test
// error handling here.
var smtpValidTests = []struct {
line string // Input line
cmd Command // Output SMTP command
arg string // Output argument
params string // Output params
}{
{"HELO localhost", HELO, "localhost", ""},
{"HELO", HELO, "", ""},
{"EHLO fred", EHLO, "fred", ""},
{"EHLO", EHLO, "", ""},
{"MAIL FROM:<>", MAILFROM, "", ""},
{"MAIL FROM:<[email protected]>", MAILFROM, "[email protected]", ""},
{"RCPT TO:<[email protected]>", RCPTTO, "[email protected]", ""},
{"DATA", DATA, "", ""},
{"QUIT", QUIT, "", ""},
{"RSET", RSET, "", ""},
{"NOOP", NOOP, "", ""},
{"VRFY [email protected]", VRFY, "[email protected]", ""},
{"EXPN [email protected]", EXPN, "[email protected]", ""},
{"HELP barney", HELP, "barney", ""},
{"HELP", HELP, "", ""},
{"STARTTLS", STARTTLS, "", ""},
{"AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ=", AUTH, "PLAIN", "dGVzdAB0ZXN0ADEyMzQ="},
// Torture cases.
{"RCPT TO:<a>", RCPTTO, "a", ""}, // Minimal address
{"HELO ", HELO, "", ""}, // all blank optional argument
{"HELO a ", HELO, "a", ""}, // whitespace in argument
{"RSET ", RSET, "", ""}, // space after no-arg command
// Accepted as valid by ParseCmd even if they're wrong by the views
// of higher layers.
{"RCPT TO:<>", RCPTTO, "", ""},
{"MAIL FROM:<<>>", MAILFROM, "<>", ""},
{"MAIL FROM:<barney>", MAILFROM, "barney", ""},
// Extended MAIL FROM and RCPT TO with additional arguments.
{"MAIL FROM:<[email protected]> SIZE=10000", MAILFROM, "[email protected]", "SIZE=10000"},
{"RCPT TO:<[email protected]> SIZE=100", RCPTTO, "[email protected]", "SIZE=100"},
// commands in lower case and mixed case, preserving argument case
{"mail from:<FreD@Barney>", MAILFROM, "FreD@Barney", ""},
{"Rcpt To:<joe@joe>", RCPTTO, "joe@joe", ""},
// Space after MAIL FROM:
{"MAIL FROM: <fred@barney>", MAILFROM, "fred@barney", ""},
}
func TestGoodParses(t *testing.T) {
var s ParsedLine
for _, inp := range smtpValidTests {
s = ParseCmd(inp.line)
if s.Cmd != inp.cmd {
t.Fatalf("mismatched CMD result on '%s': got %v wanted %v", inp.line, s.Cmd, inp.cmd)
}
if len(s.Err) > 0 {
t.Fatalf("command failed on '%s': error '%s'", inp.line, s.Err)
}
if inp.arg != s.Arg {
t.Fatalf("mismatched arg results on '%s': got %v expected %v", inp.line, s.Arg, inp.arg)
}
}
}
// We mostly don't match on the exact error text.
var smtpInvalidTests = []struct {
line string // Input line
cmd Command // Output SMTP command
err string // Output err to check if non-empty
}{
{"argble", BadCmd, ""},
// UTF-8, and I want to test that this is specifically recognized
// in an otherwise valid command
{"MAIL FROM:<Å@fred.com>", BadCmd, "command contains non 7-bit ASCII"},
// prefix validation
{"VRFYFred", BadCmd, ""},
{"MAIL FROMFred", BadCmd, ""},
// malformed or missing addresses
{"MAIL FROM <fred>", MAILFROM, ""},
{"RCPT TO: <fred> ", RCPTTO, ""},
{"MAIL FROM:", MAILFROM, ""},
{"MAIL FROM:<", MAILFROM, ""},
{"MAIL FROM:<fred@barney", MAILFROM, ""},
// alleged 'argument' is all white space
{"MAIL FROM: ", MAILFROM, ""},
// no space between > and param
{"MAIL FROM:<fred@barney>SIZE=100", MAILFROM, ""},
// No arguments
{"VRFY", VRFY, ""},
{"EXPN", EXPN, ""},
{"AUTH", AUTH, ""},
// Extra arguments on commands that don't take them.
{"RSET fred", RSET, ""},
{"NOOP fred", NOOP, ""},
{"DATA fred", DATA, ""},
{"QUIT fred", QUIT, ""},
}
func TestBadParses(t *testing.T) {
var s ParsedLine
for _, inp := range smtpInvalidTests {
s = ParseCmd(inp.line)
if len(s.Err) == 0 {
t.Fatalf("'%s' not detected as error: cmd %v arg '%v'", inp.line, s.Cmd, s.Arg)
}
if inp.cmd != s.Cmd {
t.Fatalf("mismatched CMD on '%s': got %v expected %v", inp.line, s.Cmd, inp.cmd)
}
if len(inp.err) > 0 && inp.err != s.Err {
t.Fatalf("wrong error string on '%s': got '%s' expected '%s'", inp.line, s.Err, inp.err)
}
}
}
// This is a very quick test for basic functionality.
func TestParam(t *testing.T) {
s := ParseCmd("MAIL FROM:<[email protected]> SIZE=1000")
// We assume that basic parsing works and don't check.
if s.Params != "SIZE=1000" {
t.Fatalf("MAIL FROM params failed: expected 'SIZE=1000', got '%s'", s.Params)
}
s = ParseCmd("MAIL FROM:<[email protected]>")
if len(s.Params) > 0 {
t.Fatalf("MAIL FROM w/o params got a parms value of: '%s'", s.Params)
}
}
//
// -------
// Current tests are crude because Server() API is not exactly settled.
// We're really testing the sequencing logic, both for accepting a good
// transaction and rejecting out of sequence things.
//
// TODO
// Testing literal text output is a losing approach. What we should do
// is mostly test that the response codes are what we expect. Possibly
// we should connect an instance of the Go SMTP client to the server and
// verify that that works and sees the right EHLO things, once we support
// EHLO things that is.
//
// faker implements the net.Conn() interface.
type faker struct {
io.ReadWriter
}
func (f faker) Close() error { return nil }
func (f faker) LocalAddr() net.Addr { return nil }
func (f faker) SetDeadline(time.Time) error { return nil }
func (f faker) SetReadDeadline(time.Time) error { return nil }
func (f faker) SetWriteDeadline(time.Time) error { return nil }
func (f faker) RemoteAddr() net.Addr {
a, _ := net.ResolveTCPAddr("tcp", "127.10.10.100:56789")
return a
}
// returns expected server output \r\n'd, and the actual output.
// current approach cribbed from the net/smtp tests.
func runSMTPTest(
serverStr, clientStr string,
config Config,
loop func(*Conn),
) (string, string) {
server := strings.Join(strings.Split(serverStr, "\n"), "\r\n")
client := strings.Join(strings.Split(clientStr, "\n"), "\r\n")
var outbuf bytes.Buffer
writer := bufio.NewWriter(&outbuf)
reader := bufio.NewReader(strings.NewReader(client))
cxn := &faker{ReadWriter: bufio.NewReadWriter(reader, writer)}
// Server(reader, writer)
conn := NewConn(cxn, config, nil)
loop(conn)
writer.Flush()
return server, outbuf.String()
}
func runSimpleSMTPTest(serverStr, clientStr string) (string, string) {
return runSMTPTest(serverStr, clientStr, Config{}, func(c *Conn) {
for {
evt := c.Next()
if evt.What == DONE || evt.What == ABORT {
break
}
}
})
}
func TestBasicSmtpd(t *testing.T) {
server, actualout := runSimpleSMTPTest(basicServer, basicClient)
if actualout != server {
t.Fatalf("Got:\n%s\nExpected:\n%s", actualout, server)
}
}
// EHLO, send email, send email again, try what should be an out of
// sequence RCPT TO.
var basicClient = `EHLO localhost
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
Subject: A test
Done.
.
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
Subject: A test 2
Done. 2.
.
RCPT TO:<[email protected]>
HELO
QUIT
`
var basicServer = `220 localhost go-smtpd
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250 HELP
250 Okay, I'll believe you for now
250 Okay, I'll believe you for now
354 Send away
250 I've put it in a can
250 Okay, I'll believe you for now
250 Okay, I'll believe you for now
354 Send away
250 I've put it in a can
503 Out of sequence command
250 localhost Hello 127.10.10.100:56789
221 Goodbye
`
func TestSequenceErrors(t *testing.T) {
server, actualout := runSimpleSMTPTest(sequenceServer, sequenceClient)
if actualout != server {
t.Fatalf("Got:\n%s\nExpected:\n%s", actualout, server)
}
}
// A whole series of out of sequence commands, and finally an unrecognized
// one. We try a RSET to validate that it doesn't allow us to MAIL FROM
// without an EHLO.
var sequenceClient = `MAIL FROM:<[email protected]>
RSET
MAIL FROM:<[email protected]>
EHLO localhost
NOOP
RCPT TO:<[email protected]>
MAIL FROM:<[email protected]>
DATA
Subject: yadda yadda
RSET
MAIL FROM:<[email protected]>
RCPT TO:<>
RCPT TO:<abc@def>
RCPT TO:<abc@ghi> SIZE=9999
`
var sequenceServer = `220 localhost go-smtpd
503 Out of sequence command
250 Okay
503 Out of sequence command
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250 HELP
250 Okay
503 Out of sequence command
250 Okay, I'll believe you for now
503 Out of sequence command
501 Bad: unrecognized command
250 Okay
250 Okay, I'll believe you for now
550 Bad address
250 Okay, I'll believe you for now
504 Command parameter not implemented
`
// Test the stream of events emitted from Next(), as opposed to the output
// that the server produces.
var testStream = []struct {
what Event
cmd Command
}{
{COMMAND, EHLO}, {COMMAND, MAILFROM}, {COMMAND, RCPTTO},
{COMMAND, RCPTTO}, {COMMAND, DATA}, {GOTDATA, noCmd},
{COMMAND, MAILFROM}, {COMMAND, MAILFROM}, {DONE, noCmd},
}
var testClient = `EHLO fred
NOOP
RSET
RCPT TO:<barney@jim>
MAIL FROM:<fred@fred>
MAIL FROM:<[email protected]>
RCPT TO:<>
RCPT TO:<[email protected]>
RCPT TO:<[email protected]>
DATA
Subject: A test.
.
RSET
MAIL FROM:<[email protected]>
RSET
MAIL FROM:<[email protected]>
QUIT
`
func TestSequence(t *testing.T) {
client := strings.Join(strings.Split(testClient, "\n"), "\r\n")
var outbuf bytes.Buffer
writer := bufio.NewWriter(&outbuf)
reader := bufio.NewReader(strings.NewReader(client))
cxn := &faker{ReadWriter: bufio.NewReadWriter(reader, writer)}
// Server(reader, writer)
var evt EventInfo
conn := NewConn(cxn, Config{}, nil)
pos := 0
for {
evt = conn.Next()
ts := testStream[pos]
if evt.What != ts.what || evt.Cmd != ts.cmd {
t.Fatalf("Sequence mismatch at step %d: expected %v %v got %v %v\n",
pos, ts.what, ts.cmd, evt.What, evt.Cmd)
}
pos++
if evt.What == DONE {
break
}
}
}
var authClient1 = `EHLO localhost
MAIL FROM:<[email protected]>
AUTH NOT-ADVERTISED
AUTH TEST initial-auth-resp
*
MAIL FROM:<[email protected]>
QUIT
`
var authServer1 = `220 localhost go-smtpd
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250-AUTH PLAIN LOGIN TEST
250 HELP
530 Authentication required
504 Command parameter not implemented
334 Y2hhbGxlbmdl
501 Authentication aborted
530 Authentication required
221 Goodbye
`
func TestAuthEvents(t *testing.T) {
cfg := Config{
Auth: &AuthConfig{Mechanisms: []string{"PLAIN", "LOGIN", "TEST"}},
}
server, actualout := runSMTPTest(authServer1, authClient1, cfg, func(c *Conn) {
var lastevt EventInfo
for {
evt := c.Next()
switch evt.What {
case DONE:
return
case AUTHRESP:
if evt.Arg != "initial-auth-resp" {
t.Errorf("event arg mismatch, got %q, want %q", evt.Arg, "initial-auth-resp")
}
if !(lastevt.What == COMMAND && lastevt.Cmd == AUTH) {
t.Error("Next returned out-of-order AUTHRESP, previous event", lastevt)
}
c.AuthChallenge([]byte("challenge"))
case AUTHABORT:
if lastevt.What != AUTHRESP {
t.Error("Next returned out-of-order AUTHABORT, previous event", lastevt)
}
case COMMAND:
if evt.Cmd == AUTH {
if evt.Arg != "TEST" {
t.Fatalf("event arg mismatch, got %q, want %q", evt.Arg, "TEST")
}
} else {
c.Accept()
}
default:
t.Fatalf("unexpected event: %+v", evt)
}
lastevt = evt
}
})
if actualout != server {
t.Errorf("Server log mismatch, Got:\n%s\nExpected:\n%s", actualout, server)
}
}
var authClient2 = `EHLO localhost
AUTH TEST
AUTH TEST
QUIT
`
var authServer2 = `220 localhost go-smtpd
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250-AUTH TEST
250 HELP
235 Authentication successful
503 Out of sequence command
221 Goodbye
`
func TestAuthOnce(t *testing.T) {
cfg := Config{
Auth: &AuthConfig{Mechanisms: []string{"TEST"}},
}
server, actualout := runSMTPTest(authServer2, authClient2, cfg, func(c *Conn) {
for {
evt := c.Next()
if evt.What == DONE || evt.What == ABORT {
return
}
c.Accept()
}
})
if actualout != server {
t.Errorf("Server log mismatch, Got:\n%s\nExpected:\n%s", actualout, server)
}
}
var authClient3 = `EHLO localhost
AUTH TEST =
aW5pdGlhbC1yZXNwb25zZQ==
c3Vic2VxdWVudC1yZXNwb25zZQ==
ZmluYWwtcmVzcG9uc2U=
QUIT
`
var authServer3 = `220 localhost go-smtpd
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250-AUTH TEST
250 HELP
334 YzA=
334 ` + `
334 ` + `
235 Authentication successful
221 Goodbye
`
func TestAuthenticateSuccess(t *testing.T) {
cfg := Config{
Auth: &AuthConfig{Mechanisms: []string{"TEST"}},
}
server, actualout := runSMTPTest(authServer3, authClient3, cfg, func(c *Conn) {
for {
switch evt := c.Next(); evt.What {
case DONE:
return
case COMMAND:
if evt.Cmd == AUTH {
wantInput := [][]byte{
{},
[]byte("initial-response"),
[]byte("subsequent-response"),
[]byte("final-response"),
}
challenges := [][]byte{
[]byte("c0"),
{},
nil,
}
i := 0
success := c.Authenticate(func(c *Conn, input []byte) {
if i >= len(wantInput) {
t.Fatalf("AuthFunc called %d times, expected %d calls", i+1, len(wantInput))
}
if !bytes.Equal(input, wantInput[i]) {
t.Errorf("invalid input: got %q, expected %q", input, wantInput[i])
}
if i == len(wantInput)-1 {
c.Accept()
} else {
c.AuthChallenge(challenges[i])
}
i++
})
if !success {
t.Errorf("Authenticate returned false, should've returned true to indicate success.")
}
} else {
c.Accept()
}
default:
t.Fatalf("unexpected event: %+v", evt)
}
}
})
if actualout != server {
t.Errorf("Server log mismatch, Got:\n%s\nExpected:\n%s", actualout, server)
}
}
var authClient4 = `EHLO localhost
AUTH TEST initial-resp
AUTH TEST
*
AUTH TEST =
*
QUIT
`
var authServer4 = `220 localhost go-smtpd
250-localhost Hello 127.10.10.100:56789
250-8BITMIME
250-PIPELINING
250-AUTH TEST
250 HELP
501 Invalid authentication response
334 ` + `
501 Authentication aborted
334 ` + `
501 Authentication aborted
221 Goodbye
`
func TestAuthenticateAborts(t *testing.T) {
cfg := Config{
Auth: &AuthConfig{Mechanisms: []string{"TEST"}},
}
server, actualout := runSMTPTest(authServer4, authClient4, cfg, func(c *Conn) {
for {
switch evt := c.Next(); evt.What {
case DONE:
return
case COMMAND:
if evt.Cmd == AUTH {
success := c.Authenticate(func(c *Conn, input []byte) {
if len(input) > 0 {
t.Errorf("unexpected non-empty AuthFunc input: %q", input)
}
})
if success {
t.Errorf("Authenticate returned true, should've returned false to indicate abort.")
}
} else {
c.Accept()
}
default:
t.Fatalf("unexpected event: %+v", evt)
}
}
})
if actualout != server {
t.Errorf("Server log mismatch, Got:\n%s\nExpected:\n%s", actualout, server)
}
}