summaryrefslogtreecommitdiffstats
path: root/internal/nntp/client_test.go
blob: 26354edf34869bc43d7d79b2baad1622c8061577 (plain) (blame)
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
package nntp

import (
	"bufio"
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/binary"
	"fmt"
	"io"
	"math/big"
	"net"
	"strings"
	"sync"
	"testing"
	"time"
)

type fakeServer struct {
	listener net.Listener
	posted   string
	mu       sync.Mutex
}

func startFakeServer(t *testing.T) *fakeServer {
	t.Helper()
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	return startFakeServerOn(t, listener)
}

func startFakeTLSServer(t *testing.T) (*fakeServer, *tls.Config) {
	t.Helper()
	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	now := time.Now()
	template := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject:      pkix.Name{CommonName: "Aegis NNTP test"},
		NotBefore:    now.Add(-time.Minute),
		NotAfter:     now.Add(time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		IPAddresses:  []net.IP{net.ParseIP("127.0.0.1")},
	}
	der, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
	if err != nil {
		t.Fatal(err)
	}
	certificate := tls.Certificate{Certificate: [][]byte{der}, PrivateKey: privateKey}
	listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{
		Certificates: []tls.Certificate{certificate},
		MinVersion:   tls.VersionTLS12,
	})
	if err != nil {
		t.Fatal(err)
	}
	parsed, err := x509.ParseCertificate(der)
	if err != nil {
		t.Fatal(err)
	}
	roots := x509.NewCertPool()
	roots.AddCert(parsed)
	return startFakeServerOn(t, listener), &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}
}

func startFakeServerOn(t *testing.T, listener net.Listener) *fakeServer {
	t.Helper()
	server := &fakeServer{listener: listener}
	go server.serve(t)
	t.Cleanup(func() { listener.Close() })
	return server
}

func (s *fakeServer) address() (string, string) {
	host, port, _ := net.SplitHostPort(s.listener.Addr().String())
	return host, port
}

func (s *fakeServer) serve(t *testing.T) {
	conn, err := s.listener.Accept()
	if err != nil {
		return
	}
	defer conn.Close()
	reader := bufio.NewReader(conn)
	writer := bufio.NewWriter(conn)
	write := func(value string) {
		_, _ = writer.WriteString(value)
		_ = writer.Flush()
	}
	write("200 fake server ready\r\n")
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			return
		}
		line = strings.TrimSpace(line)
		switch {
		case line == "AUTHINFO USER reader":
			write("381 password required\r\n")
		case line == "AUTHINFO PASS secret":
			write("281 authentication accepted\r\n")
		case line == "MODE READER":
			write("200 reader mode\r\n")
		case line == "CAPABILITIES":
			write("101 capabilities follow\r\nVERSION 2\r\nOVER\r\nPOST\r\n.\r\n")
		case line == "LIST ACTIVE":
			write("215 list follows\r\ncomp.lang.go 120 101 y\r\nempty.group 0 1 n\r\n.\r\n")
		case line == "GROUP comp.lang.go":
			write("211 19 101 120 comp.lang.go\r\n")
		case line == "OVER 119-120":
			write("224 overview follows\r\n119\tFirst\tAlice <a@example.org>\tMon, 1 Jan 2024 00:00:00 +0000\t<119@example>\t\t100\t5\r\n120\tSecond\tBob <b@example.org>\tMon, 1 Jan 2024 01:00:00 +0000\t<120@example>\t<119@example>\t120\t6\r\n.\r\n")
		case line == "ARTICLE 120":
			write("220 120 <120@example> article follows\r\nSubject: Second\r\n\r\nHello\r\n..dot line\r\n.\r\n")
		case line == "POST":
			write("340 send article\r\n")
			var article strings.Builder
			for {
				postedLine, readErr := reader.ReadString('\n')
				if readErr != nil {
					return
				}
				if postedLine == ".\r\n" {
					break
				}
				article.WriteString(postedLine)
			}
			s.mu.Lock()
			s.posted = article.String()
			s.mu.Unlock()
			write("240 article received\r\n")
		case line == "QUIT":
			write("205 closing connection\r\n")
			return
		default:
			write(fmt.Sprintf("500 unsupported: %s\r\n", line))
		}
	}
}

func startSOCKSProxy(t *testing.T, upstreamAddress string) string {
	t.Helper()
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { listener.Close() })
	go func() {
		connection, acceptErr := listener.Accept()
		if acceptErr != nil {
			return
		}
		defer connection.Close()
		hello := make([]byte, 3)
		if _, err := io.ReadFull(connection, hello); err != nil || hello[0] != 5 {
			return
		}
		if _, err := connection.Write([]byte{5, 0}); err != nil {
			return
		}
		header := make([]byte, 4)
		if _, err := io.ReadFull(connection, header); err != nil || header[0] != 5 || header[1] != 1 {
			return
		}
		switch header[3] {
		case 1:
			_, err = io.ReadFull(connection, make([]byte, 4))
		case 3:
			length := make([]byte, 1)
			if _, err = io.ReadFull(connection, length); err == nil {
				_, err = io.ReadFull(connection, make([]byte, int(length[0])))
			}
		case 4:
			_, err = io.ReadFull(connection, make([]byte, 16))
		default:
			return
		}
		if err != nil {
			return
		}
		port := make([]byte, 2)
		if _, err := io.ReadFull(connection, port); err != nil || binary.BigEndian.Uint16(port) == 0 {
			return
		}
		upstream, err := net.DialTimeout("tcp", upstreamAddress, 2*time.Second)
		if err != nil {
			_, _ = connection.Write([]byte{5, 1, 0, 1, 0, 0, 0, 0, 0, 0})
			return
		}
		defer upstream.Close()
		if _, err := connection.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 1}); err != nil {
			return
		}
		done := make(chan struct{})
		go func() {
			_, _ = io.Copy(upstream, connection)
			_ = upstream.Close()
			close(done)
		}()
		_, _ = io.Copy(connection, upstream)
		<-done
	}()
	return listener.Addr().String()
}

func TestClientWorkflow(t *testing.T) {
	server, tlsConfig := startFakeTLSServer(t)
	host, port := server.address()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	client, err := Dial(ctx, DialConfig{
		Host:      host,
		Port:      port,
		UseTLS:    true,
		Username:  "reader",
		Password:  "secret",
		ProxyType: "DIRECT",
		tlsConfig: tlsConfig,
	})
	if err != nil {
		t.Fatalf("Dial() error = %v", err)
	}
	defer client.Close()

	capabilities, err := client.Capabilities()
	if err != nil || len(capabilities) != 3 {
		t.Fatalf("Capabilities() = %v, %v", capabilities, err)
	}
	groups, err := client.ListActive()
	if err != nil {
		t.Fatal(err)
	}
	if len(groups) != 2 || groups[0].EstimatedPost != 20 || groups[1].EstimatedPost != 0 {
		t.Fatalf("ListActive() = %#v", groups)
	}
	status, headers, err := client.LatestOverview("comp.lang.go", 2)
	if err != nil || status.Count != 19 || status.High != 120 {
		t.Fatalf("LatestOverview() status = %#v, error = %v", status, err)
	}
	if err != nil || len(headers) != 2 || headers[1].Subject != "Second" {
		t.Fatalf("LatestOverview() headers = %#v, error = %v", headers, err)
	}
	article, err := client.ArticleInGroup("comp.lang.go", 120)
	if err != nil || !strings.Contains(article, "\n.dot line") {
		t.Fatalf("Article() = %q, %v", article, err)
	}
	if err := client.Post("From: reader@example.org\nNewsgroups: comp.lang.go\nSubject: Test\n\n.line"); err != nil {
		t.Fatal(err)
	}
	server.mu.Lock()
	posted := server.posted
	server.mu.Unlock()
	if !strings.Contains(posted, "\r\n..line\r\n") {
		t.Fatalf("posted article was not dot-stuffed: %q", posted)
	}
}

func TestTLSCertificateVerificationCannotBeSkipped(t *testing.T) {
	server, _ := startFakeTLSServer(t)
	host, port := server.address()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	client, err := Dial(ctx, DialConfig{Host: host, Port: port, UseTLS: true, ProxyType: "DIRECT"})
	if client != nil {
		client.Close()
	}
	if err == nil {
		t.Fatal("Dial() trusted an unknown TLS certificate")
	}
}

func TestRejectsCommandInjection(t *testing.T) {
	if _, err := Dial(context.Background(), DialConfig{Host: "example.org\r\nQUIT", Port: "119"}); err == nil {
		t.Fatal("Dial() accepted command injection in host")
	}
	client := &Client{}
	if _, err := client.SelectGroup("comp.lang.go\r\nPOST"); err == nil {
		t.Fatal("SelectGroup() accepted command injection")
	}
}

func TestValidateArticleTextConstraints(t *testing.T) {
	tests := []struct {
		name    string
		article string
		wantErr bool
	}{
		{name: "valid UTF-8 and CRLF", article: "Subject: café\r\n\r\ncorps UTF-8\r\n"},
		{name: "valid LF normalized by Post", article: "Subject: test\n\nbody"},
		{name: "998 octets", article: "Subject: " + strings.Repeat("a", 989)},
		{name: "oversized line", article: strings.Repeat("a", maxPostLineBytes+1), wantErr: true},
		{name: "dot-stuffed oversized line", article: "." + strings.Repeat("a", maxPostLineBytes-1), wantErr: true},
		{name: "NUL", article: "Subject: test\x00", wantErr: true},
		{name: "invalid UTF-8", article: string([]byte{'a', 0xff}), wantErr: true},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			err := ValidateArticle(test.article)
			if (err != nil) != test.wantErr {
				t.Fatalf("ValidateArticle() error = %v, wantErr %t", err, test.wantErr)
			}
		})
	}
}

func TestRejectsAuthenticationWithoutTLS(t *testing.T) {
	if _, err := Dial(context.Background(), DialConfig{
		Host: "127.0.0.1", Port: "119", Username: "reader", Password: "secret",
	}); err == nil {
		t.Fatal("Dial() accepted authentication without TLS")
	}
}

func TestSOCKS5Connection(t *testing.T) {
	server := startFakeServer(t)
	proxyAddress := startSOCKSProxy(t, server.listener.Addr().String())
	host, port := server.address()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	client, err := Dial(ctx, DialConfig{
		Host: host, Port: port, ProxyType: "SOCKS5", ProxyAddress: proxyAddress,
	})
	if err != nil {
		t.Fatalf("Dial() through SOCKS5 error = %v", err)
	}
	defer client.Close()
	groups, err := client.ListActive()
	if err != nil || len(groups) != 2 {
		t.Fatalf("ListActive() through SOCKS5 = %#v, %v", groups, err)
	}
}

func TestPopulationEstimate(t *testing.T) {
	tests := []struct {
		low, high int64
		want      int64
	}{
		{101, 120, 20},
		{1, 1, 1},
		{1, 0, 0},
		{0, 0, 0},
	}
	for _, test := range tests {
		if got := estimatePopulation(test.low, test.high); got != test.want {
			t.Errorf("estimatePopulation(%d, %d) = %d, want %d", test.low, test.high, got, test.want)
		}
	}
}