-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathnntp-proxy.c
1103 lines (920 loc) · 32 KB
/
nntp-proxy.c
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the nntp proxy project
* Copyright (C) 2012 Julien Perrot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* See the file "COPYING" for the exact licensing terms.
*/
#define _GNU_SOURCE
#include <signal.h>
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#ifdef __APPLE__
#include <unistd.h>
#else
#include <crypt.h>
#endif
#include <sys/time.h>
#include <time.h>
#include <libconfig.h>
#include <event2/dns.h>
#include <event2/bufferevent_ssl.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/engine.h>
struct server_info {
const char *server;
int port;
const char *username;
const char *password;
int max_conns;
};
struct user_info {
const char *username;
const char *password;
int max_conns;
};
struct proxy_info {
const char *bind_ip;
int port;
int prohibit_post;
const char *ssl_key;
const char *ssl_cert;
};
int user_count = 0;
struct user_info *users;
struct config_t cfg;
/** Configuration part **/
struct server_info nntp_server;
struct proxy_info proxy_server;
/** end of configuration **/
#define NNTP_SERVICE_READY 200
#define NNTP_SERVICE_READY_PROHIBIT_POSTING 201
#define NNTP_AUTH_ACCEPTED 281
#define NNTP_MORE_AUTH 381
#define NNTP_POSTING_PROHIBITED 440
#define NNTP_AUTH_REQUIRED 480
#define NNTP_AUTH_REJECTED 482
#define NNTP_NO_PERM 502
#define NNTP_BANNER "NNTP Proxy service ready."
#define ERROR_LEVEL 0
#define WARNING_LEVEL 1
#define NOTICE_LEVEL 2
#define INFO_LEVEL 3
#define DEBUG_LEVEL 4
#define PRINT_MSG(level, fmt, ...) print_msg(level, "[%s:%d] " fmt, __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__)
#define ERROR(fmt, ...) PRINT_MSG(ERROR_LEVEL, fmt, ## __VA_ARGS__)
#define WARNING(fmt, ...) PRINT_MSG(WARNING_LEVEL, fmt, ## __VA_ARGS__)
#define NOTICE(fmt, ...) PRINT_MSG(NOTICE_LEVEL, fmt, ## __VA_ARGS__)
#define INFO(fmt, ...) PRINT_MSG(INFO_LEVEL, fmt, ## __VA_ARGS__)
#define DEBUG(fmt, ...) PRINT_MSG(DEBUG_LEVEL, fmt, ## __VA_ARGS__)
#define MAX_CMD_ARGS 32
#define PARTNER_BEV(bev, conn) (bev == conn->server_bev) ? conn->client_bev : conn->server_bev
#define IS_SERVER(bev, conn) bev == conn->server_bev
enum conn_status {
CLIENT_CONNECTING,
CLIENT_CONNECTED,
CLIENT_AUTHENTICATED,
SERVER_CONNECTING,
SERVER_CONNECTED,
SERVER_AUTHENTICATED,
CLIENT_CLOSING,
CLIENT_CLOSED,
SERVER_CLOSING,
SERVER_CLOSED
};
struct conn_desc {
/* connection from the proxy to the server */
struct bufferevent *server_bev;
/* connection from the client to the proxy */
struct bufferevent *client_bev;
int status;
/* username from the client */
char *client_username;
/* number of the connection */
int n;
struct timeval last_cmd;
size_t bytes;
};
static struct conn_desc *connections;
static int verbose_level = ERROR_LEVEL;
static struct event_base *base;
static struct evdns_base *dns_base;
static struct sockaddr_storage listen_on_addr;
/* proxy server-side */
static SSL_CTX *ssl_server_ctx = NULL;
/* proxy client-side */
static SSL_CTX *ssl_client_ctx = NULL;
static int use_padlock_engine = 0;
#define MAX_OUTPUT (256*1024)
/* forward declarations */
static void common_readcb(struct bufferevent *bev, void *arg);
static void server_auth_readcb(struct bufferevent *bev, void *arg);
static void client_auth_readcb(struct bufferevent *bev, void *arg);
static void drained_writecb(struct bufferevent *bev, void *arg);
static void close_on_finished_writecb(struct bufferevent *bev, void *arg);
static void eventcb(struct bufferevent *bev, short what, void *arg);
static char str_inet[INET_ADDRSTRLEN];
static char str_inet6[INET6_ADDRSTRLEN];
static void print_msg(int level, const char *fmt, ...)
{
char outstr[200];
time_t t;
struct tm *tmp;
va_list ap;
if (verbose_level < level)
return;
t = time(NULL);
tmp = localtime(&t);
strftime(outstr, sizeof(outstr), "%d/%m/%y %T", tmp);
fprintf(stderr, "%s ", outstr);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
static struct conn_desc * get_next_conn(void)
{
struct conn_desc *ret;
int i;
ret = connections;
for (i = 0; i < nntp_server.max_conns; i++) {
if (!ret->server_bev && !ret->client_bev) {
ret->n = i;
ret->bytes = 0;
INFO("Connection %d is available\n", ret->n);
return ret;
} else {
DEBUG("conn %d not available, ret->server_bev = %p, ret->clien_bev = %p\n", i,
ret->server_bev, ret->client_bev);
}
ret++;
}
WARNING("No more connections available\n");
return NULL;
}
static int allow_connection(const char *username)
{
struct conn_desc *conn;
struct user_info *user;
int i, n = 0;
user = users;
while (user->username != NULL) {
if (!strcmp(user->username, username)) {
break;
}
user++;
}
if (user->username == NULL) {
WARNING("user info not found for username %s\n", username);
return -1;
}
conn = connections;
for (i = 0; i < nntp_server.max_conns; i++) {
if (conn->client_username &&
!strcmp(conn->client_username, username)) {
DEBUG("connection %d is used by user %s\n", conn->n, username);
n++;
}
conn++;
}
DEBUG("found %d existing connections for user %s\n", n, username);
if (n < user->max_conns)
return 0;
else
return -1;
}
static char * parse_nntp_response(char *str, int *code)
{
char *tok;
tok = strtok(str, " \t");
if (!tok) {
WARNING("invalid response\n");
return NULL;
}
*code = atoi(tok);
if (*code == 0) {
WARNING("invalid code in response\n");
return NULL;
}
tok = strtok(NULL, "");
return tok;
}
static void parse_nntp_cmd(char *str, char **args, int *n)
{
char *tok;
tok = strtok(str, " ");
if (!tok) {
WARNING("invalid cmd\n");
*n = 0;
return;
}
*n = 0;
while (tok != NULL && *n < MAX_CMD_ARGS) {
args[*n] = tok;
*n += 1;
tok = strtok(NULL, " ");
}
}
static char *ip_str_from_sa(const struct sockaddr *sa)
{
char *ret;
switch(sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
str_inet, INET_ADDRSTRLEN);
ret = str_inet;
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
str_inet6, INET6_ADDRSTRLEN);
ret = str_inet6;
break;
default:
ret =NULL;
}
return ret;
}
static void syntax(const char *binpath)
{
fprintf(stderr, "Syntax:\n");
fprintf(stderr, "\t%s [<config file>]\n", binpath);
fprintf(stderr, "Example:\n");
fprintf(stderr, "\t%s nntp-proxy.conf\n", binpath);
exit(EXIT_FAILURE);
}
static SSL_CTX * ssl_server_init(const char *keypath, const char *certpath)
{
SSL_CTX *ctx;
ENGINE *e;
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
e = ENGINE_by_id("padlock");
if (e) {
fprintf(stderr, "[*] Using padlock engine for default ciphers\n");
ENGINE_set_default_ciphers(ENGINE_by_id("padlock"));
use_padlock_engine = 1;
} else {
fprintf(stderr, "[*] Padlock engine not available\n");
use_padlock_engine = 0;
}
SSL_load_error_strings();
SSL_library_init();
if (!RAND_poll())
return NULL;
ctx = SSL_CTX_new(SSLv23_server_method());
if (!SSL_CTX_use_certificate_chain_file(ctx, certpath) ||
!SSL_CTX_use_PrivateKey_file(ctx, keypath, SSL_FILETYPE_PEM)) {
fprintf(stderr, "Could not read %s or %s file\n", keypath, certpath);
fprintf(stderr, "To generate a key and self-signed certificate, run:\n");
fprintf(stderr, "\topenssl genrsa -out key.pem 2048\n");
fprintf(stderr, "\topenssl req -new -key key.pem -out cert.req\n");
fprintf(stderr, "\topenssl x509 -req -days 365 -in cert.req -signkey key.pem -out cert.pem\n");
return NULL;
}
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
if (use_padlock_engine == 1) {
if (SSL_CTX_set_cipher_list(ctx, "AES+SHA") != 1) {
fprintf(stderr, "Error setting client cipher list\n");
return NULL;
}
}
return ctx;
}
static SSL_CTX * ssl_client_init(void)
{
SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
if (use_padlock_engine == 1) {
if (SSL_CTX_set_cipher_list(ctx, "AES+SHA") != 1) {
fprintf(stderr, "Error setting client cipher list\n");
return NULL;
}
}
return ctx;
}
static void close_client(struct conn_desc *conn)
{
//SSL *ssl;
DEBUG("closing client connection %d\n", conn->n);
assert(conn->client_bev);
assert(conn->status != CLIENT_CLOSED);
// FIXME
//ssl = bufferevent_openssl_get_ssl(conn->client_bev);
//SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
//SSL_shutdown(ssl);
bufferevent_free(conn->client_bev);
conn->client_bev = NULL;
conn->status = CLIENT_CLOSED;
if (conn->client_username) {
free(conn->client_username);
conn->client_username = NULL;
}
}
static void close_server(struct conn_desc *conn)
{
//SSL *ssl;
DEBUG("closing server connection %d\n", conn->n);
assert(conn->server_bev);
assert(conn->status != SERVER_CLOSED);
//FIXME
//ssl = bufferevent_openssl_get_ssl(conn->server_bev);
//SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
//SSL_shutdown(ssl);
bufferevent_free(conn->server_bev);
conn->server_bev = NULL;
conn->status = SERVER_CLOSED;
if (conn->client_username) {
free(conn->client_username);
conn->client_username = NULL;
}
}
static void close_connection(struct conn_desc *conn)
{
close_client(conn);
close_server(conn);
}
static void close_bev(struct bufferevent *bev, struct conn_desc *conn)
{
if (IS_SERVER(bev, conn))
close_server(conn);
else
close_client(conn);
}
static void drained_writecb(struct bufferevent *bev, void *arg)
{
struct conn_desc *conn = arg;
struct bufferevent *partner = PARTNER_BEV(bev, conn);
assert(conn->status == SERVER_AUTHENTICATED);
//DEBUG("write buffer is drained\n");
/* We were choking the other side until we drained our outbuf a bit.
* Now it seems drained. */
bufferevent_setcb(bev, common_readcb, NULL, eventcb, conn);
bufferevent_setwatermark(bev, EV_WRITE, 0, 0);
if (partner) {
//DEBUG("enabling read events on partner\n");
bufferevent_enable(partner, EV_READ);
}
}
static void close_on_finished_writecb(struct bufferevent *bev, void *arg)
{
struct conn_desc *conn = arg;
struct evbuffer *b = bufferevent_get_output(bev);
if (evbuffer_get_length(b) == 0)
close_bev(bev, conn);
}
static int timeval_subtract (result, x, y)
struct timeval *result, *x, *y;
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
static void common_readcb(struct bufferevent *bev, void *arg)
{
struct conn_desc *conn = arg;
struct bufferevent *partner;
struct evbuffer *src, *dst;
size_t len;
char *cmd;
/* the two parts of the connection must be authenticated */
assert(conn->status == SERVER_AUTHENTICATED);
src = bufferevent_get_input(bev);
len = evbuffer_get_length(src);
partner = PARTNER_BEV(bev, conn);
dst = bufferevent_get_output(partner);
if (conn->client_bev == bev) {
DEBUG("client -> proxy: got %d bytes to read\n", len);
if (conn->bytes != 0) {
struct timeval now;
struct timeval tdiff;
float sec_diff;
gettimeofday(&now, NULL);
timeval_subtract(&tdiff, &now, &conn->last_cmd);
sec_diff = tdiff.tv_sec + (tdiff.tv_usec / 1000000.0);
DEBUG("[%d] command finished, %d bytes transferred in %.2f seconds (%.2f kb/s)\n", conn->n, conn->bytes,
sec_diff, (conn->bytes * 1.0 / 1024 ) / sec_diff);
}
cmd = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF);
if (cmd != NULL) {
DEBUG("[%d] command from client: %s\n", conn->n, cmd);
if (strcasestr(cmd, "AUTHINFO USER")) {
evbuffer_add_printf(dst, "AUTHINFO USER %s\r\n", nntp_server.username);
} else if (strcasestr(cmd, "AUTHINFO PASS")) {
evbuffer_add_printf(dst, "AUTHINFO PASS %s\r\n", nntp_server.password);
} else if (proxy_server.prohibit_post && strcasestr(cmd, "POST")==cmd) {
DEBUG("[%d] command send to client: %d Posting not permitted\n", conn->n, NNTP_POSTING_PROHIBITED);
dst = bufferevent_get_output(bev);
evbuffer_add_printf(dst, "%d Posting not permitted\r\n", NNTP_POSTING_PROHIBITED);
} else if (strcasestr(cmd, "MODE READER")) {
dst = bufferevent_get_output(bev);
if (proxy_server.prohibit_post)
evbuffer_add_printf(dst, "%d %s %s\r\n", NNTP_SERVICE_READY_PROHIBIT_POSTING, NNTP_BANNER, "(posting prohibited)");
else
evbuffer_add_printf(dst, "%d %s %s\r\n", NNTP_SERVICE_READY, NNTP_BANNER, "(posting ok)");
} else {
DEBUG("[%d] command send to server: %s\n", conn->n, cmd);
evbuffer_add_printf(dst, "%s\r\n", cmd);
}
free(cmd);
conn->bytes = 0;
gettimeofday(&conn->last_cmd, NULL);
} else {
DEBUG("[%d] command from client is empty??\n", conn->n);
}
} else {
conn->bytes += len;
evbuffer_add_buffer(dst, src);
}
len = evbuffer_get_length(dst);
if (len >= MAX_OUTPUT) {
/* We're giving the other side data faster than it can
* pass it on. Stop reading here until we have drained the
* other side to MAX_OUTPUT/2 bytes. */
//WARNING("[%d] Client not fast enough (%d bytes in write buffer of %p), disabling read callbacks\n",
// conn->n, len, partner);
bufferevent_setcb(partner, common_readcb, drained_writecb, eventcb, conn);
bufferevent_setwatermark(partner, EV_WRITE, MAX_OUTPUT/2, MAX_OUTPUT);
bufferevent_disable(bev, EV_READ);
}
}
static int load_config(char *file)
{
/* Initialize the configuration */
config_init(&cfg);
if(!config_read_file(&cfg, file))
{
ERROR("Failed to read config file: %s\tIs it well formed?\n", file);
exit(1);
}
else
{
config_setting_t *setting_max_connections, *setting_username, *setting_password, *setting_server, *setting_port = NULL;
config_setting_t *setting_proxy_bind_ip, *setting_proxy_port, *setting_proxy_users, *setting_proxy_ssl_key, *setting_proxy_prohibit_post, *setting_proxy_ssl_cert, *setting_proxy_verbose = NULL;
setting_max_connections = config_lookup(&cfg, "nntp_server.max_connections");
setting_username = config_lookup(&cfg, "nntp_server.username");
setting_password = config_lookup(&cfg, "nntp_server.password");
setting_server = config_lookup(&cfg, "nntp_server.server");
setting_port = config_lookup(&cfg, "nntp_server.port");
setting_proxy_verbose = config_lookup(&cfg, "proxy.verbose");
setting_proxy_bind_ip = config_lookup(&cfg, "proxy.bind_ip");
setting_proxy_port = config_lookup(&cfg, "proxy.bind_port");
setting_proxy_prohibit_post = config_lookup(&cfg, "proxy.prohibit_posting");
setting_proxy_ssl_key = config_lookup(&cfg, "proxy.ssl_key");
setting_proxy_ssl_cert = config_lookup(&cfg, "proxy.ssl_cert");
setting_proxy_users = config_lookup(&cfg, "proxy.users");
if(!setting_max_connections || !setting_username || !setting_password || !setting_server || !setting_port || !setting_proxy_prohibit_post ||
!setting_proxy_bind_ip || !setting_proxy_port || !setting_proxy_ssl_key || !setting_proxy_ssl_cert || !setting_proxy_users) {
ERROR("Something went wrong while reading the config file! Are all required fields available?\n");
exit(EXIT_FAILURE);
} else {
if (setting_proxy_verbose) {
const char* level = config_setting_get_string(setting_proxy_verbose);
int invalidLevel = 0;
if (!strcmp(level, "ERROR")) {
verbose_level = ERROR_LEVEL;
} else if (!strcmp(level, "WARNING")) {
verbose_level = WARNING_LEVEL;
} else if (!strcmp(level, "NOTICE")) {
verbose_level = NOTICE_LEVEL;
} else if (!strcmp(level, "INFO")) {
verbose_level = INFO_LEVEL;
} else if (!strcmp(level, "DEBUG")) {
verbose_level = DEBUG_LEVEL;
} else {
ERROR("Invalid verbose level: %s\n", level);
invalidLevel = 1;
}
if (!invalidLevel)
DEBUG("Verbose level: %s\n", level);
}
nntp_server.server = strdup(config_setting_get_string(setting_server));
nntp_server.port = config_setting_get_int(setting_port);
nntp_server.max_conns = config_setting_get_int(setting_max_connections);
nntp_server.username = strdup(config_setting_get_string(setting_username));
nntp_server.password = strdup(config_setting_get_string(setting_password));
proxy_server.bind_ip = strdup(config_setting_get_string(setting_proxy_bind_ip));
proxy_server.port = config_setting_get_int(setting_proxy_port);
proxy_server.prohibit_post = config_setting_get_bool(setting_proxy_prohibit_post);
proxy_server.ssl_key = strdup(config_setting_get_string(setting_proxy_ssl_key));
proxy_server.ssl_cert = strdup(config_setting_get_string(setting_proxy_ssl_cert));
DEBUG("loaded settings from file...\nNNTP server: %s:%i\nmax_conns: %i\nusername: %s\npassword: %s\nProxy server: %s:%i\nSSL key: %s\nSSL cert: %s\nProhibit posting: %s\n",
nntp_server.server, nntp_server.port,
nntp_server.max_conns, nntp_server.username, nntp_server.password,
proxy_server.bind_ip, proxy_server.port,
proxy_server.ssl_key, proxy_server.ssl_cert, proxy_server.prohibit_post ? "true" : "false");
user_count = config_setting_length(setting_proxy_users);
DEBUG("Users: %i\n", user_count);
users = (struct user_info *) malloc(sizeof(struct user_info) * (user_count + 1));
int i;
for(i = 0; i < user_count; i++) {
config_setting_t *user = config_setting_get_elem(setting_proxy_users, i);
const char *username, *password;
#if (((LIBCONFIG_VER_MAJOR == 1) && (LIBCONFIG_VER_MINOR >= 4)) \
|| (LIBCONFIG_VER_MAJOR > 1))
//DAHH libconfig changed from long int to int type in 1.4+
int max_conns;
#else
long int max_conns;
#endif
if(!(config_setting_lookup_string(user, "username", &username)
&& config_setting_lookup_string(user, "password", &password)
&& config_setting_lookup_int(user, "max_connections", &max_conns)))
continue;
DEBUG("Username: %s\tpassword: %s\tmax connections: %i\n", username, password, max_conns);
users[i].username = strdup(username);
users[i].password = strdup(password);
users[i].max_conns = max_conns;
}
users[i].username = NULL;
users[i].password = NULL;
users[i].max_conns = 0;
}
}
/* Free the configuration */
config_destroy(&cfg);
return 0;
}
static int authenticate(const char *username, const char *password)
{
struct user_info *user;
char *ret;
user = users;
while (user->username != NULL) {
if (!strcmp(user->username, username)) {
ret = crypt(password, user->password);
if (!strcmp(ret, user->password)) {
return 0;
}
}
user++;
}
return -1;
}
static int connect_to_server(struct conn_desc *conn)
{
SSL *ssl;
conn->status = SERVER_CONNECTING;
ssl = SSL_new(ssl_client_ctx);
assert(ssl);
conn->server_bev = bufferevent_openssl_socket_new(base, -1, ssl,
BUFFEREVENT_SSL_CONNECTING,
BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
if (!conn->server_bev) {
perror("bufferevent_openssl_socket_new");
return -1;
}
INFO("Connecting to %s port %d\n", nntp_server.server, nntp_server.port);
if (bufferevent_socket_connect_hostname(conn->server_bev,
dns_base, AF_UNSPEC, nntp_server.server, nntp_server.port)) {
perror("bufferevent_socket_connect_hostname");
return -1;
}
bufferevent_setcb(conn->server_bev, server_auth_readcb, NULL, eventcb, conn);
bufferevent_enable(conn->server_bev, EV_READ|EV_WRITE);
bufferevent_disable(conn->client_bev, EV_READ);
return 0;
}
/* handles read event from client during the authentication process */
static void client_auth_readcb(struct bufferevent *bev, void *arg)
{
struct conn_desc *conn = arg;
struct evbuffer *src, *dst;
size_t len;
char *cmd;
char *cmd_args[MAX_CMD_ARGS];
int nargs;
assert(conn->client_bev == bev);
assert(conn->status == CLIENT_CONNECTED);
src = bufferevent_get_input(bev);
dst = bufferevent_get_output(bev);
len = evbuffer_get_length(src);
DEBUG("client -> proxy: got %d bytes to read\n", len);
cmd = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF);
if (!cmd) {
WARNING("invalid command\n");
goto exit;
}
assert(cmd);
DEBUG("cmd = %s\n", cmd);
if (!strcasestr(cmd, "AUTHINFO")) {
DEBUG("sending 480 Authentication required for command\n");
evbuffer_add_printf(dst, "%d Authentication required for command\r\n",
NNTP_AUTH_REQUIRED);
goto exit;
}
parse_nntp_cmd(cmd, cmd_args, &nargs);
if (nargs < 2) {
WARNING("invalid command\n");
goto exit;
}
DEBUG("cmd_args = %s %s\n", cmd_args[1], cmd_args[2]);
if (!strcasecmp("USER", cmd_args[1])) {
char *username = cmd_args[2];
if (allow_connection(username) == -1) {
WARNING("Too many connections for username %s\n", username);
evbuffer_add_printf(dst, "%d Too many connections\r\n",
NNTP_NO_PERM);
close_client(conn);
goto exit;
}
conn->client_username = strdup(username);
DEBUG("username = %s\n", username);
evbuffer_add_printf(dst, "%d PASS required\r\n", NNTP_MORE_AUTH);
} else if (!strcasecmp("PASS", cmd_args[1])) {
if (!conn->client_username) {
evbuffer_add_printf(dst, "%d Authentication required for command\r\n",
NNTP_AUTH_REQUIRED);
goto exit;
}
if (authenticate(conn->client_username, cmd_args[2]) == -1) {
WARNING("Authentication failed for username %s\n", conn->client_username);
evbuffer_add_printf(dst, "%d Wrong username or password\r\n",
NNTP_AUTH_REJECTED);
goto exit;
}
DEBUG("client is authenticated\n");
conn->status = CLIENT_AUTHENTICATED;
evbuffer_add_printf(dst, "%d OK\r\n", NNTP_AUTH_ACCEPTED);
if (connect_to_server(conn) == -1) {
ERROR("cannot connect to server, closing connection ...\n");
close_connection(conn);
}
} else {
WARNING("invalid AUTHINFO command\n");
evbuffer_add_printf(dst, "%d Authentication required for command\r\n",
NNTP_AUTH_REQUIRED);
}
exit:
if (cmd != NULL) free(cmd);
}
/* handles read event from server during the authentication process */
static void server_auth_readcb(struct bufferevent *bev, void *arg)
{
struct conn_desc *conn = arg;
struct evbuffer *src, *dst;
size_t len;
char *resp, *msg;
int code;
assert(conn->server_bev == bev);
assert(conn->status == SERVER_CONNECTED);
src = bufferevent_get_input(bev);
dst = bufferevent_get_output(bev);
len = evbuffer_get_length(src);
DEBUG("server -> proxy: got %d bytes to read\n", len);
resp = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF);
assert(resp);
msg = parse_nntp_response(resp, &code);
if (!msg) {
WARNING("invalid response\n");
return;
}
DEBUG("code = %d, msg = %s\n", code, msg);
if (code == NNTP_AUTH_REQUIRED) {
evbuffer_add_printf(dst, "AUTHINFO USER %s\r\n", nntp_server.username);
} else if (code == NNTP_MORE_AUTH) {
evbuffer_add_printf(dst, "AUTHINFO PASS %s\r\n", nntp_server.password);
} else if (code == NNTP_AUTH_ACCEPTED) {
DEBUG("got authentication from server\n");
conn->status = SERVER_AUTHENTICATED;
bufferevent_setcb(conn->server_bev, common_readcb, NULL, eventcb, conn);
bufferevent_setcb(conn->client_bev, common_readcb, NULL, eventcb, conn);
bufferevent_enable(conn->client_bev, EV_READ);
} else if (code == NNTP_SERVICE_READY || code == NNTP_SERVICE_READY_PROHIBIT_POSTING) {
/* Banner from server */
evbuffer_add_printf(dst, "AUTHINFO USER %s\r\n", nntp_server.username);
}
free(resp);
}
static void print_openssl_err(struct bufferevent *bev)
{
unsigned long err;
while ((err = (bufferevent_get_openssl_error(bev)))) {
const char *msg = (const char*)
ERR_reason_error_string(err);
const char *lib = (const char*)
ERR_lib_error_string(err);
const char *func = (const char*)
ERR_func_error_string(err);
fprintf(stderr,
"%s in %s %s\n", msg, lib, func);
}
}
static void eventcb(struct bufferevent *bev, short what, void *ctx)
{
struct conn_desc *conn = ctx;
struct bufferevent *partner;
struct evbuffer *dst;
int err;
if (IS_SERVER(bev, conn)) {
DEBUG("event received for server connection\n");
} else {
DEBUG("event received for client connection\n");
}
partner = PARTNER_BEV(bev, conn);
if (what & BEV_EVENT_READING)
DEBUG("BEV_EVENT_READING\n");
if (what & BEV_EVENT_WRITING)
DEBUG("BEV_EVENT_WRITING\n");
if (what & BEV_EVENT_ERROR)
DEBUG("BEV_EVENT_ERROR\n");
if (what & BEV_EVENT_TIMEOUT)
DEBUG("BEV_EVENT_TIMEOUT\n");
if (what & BEV_EVENT_EOF)
DEBUG("BEV_EVENT_EOF\n");
if (what & BEV_EVENT_CONNECTED)
DEBUG("BEV_EVENT_CONNECTED\n");
/* TODO : clean this */
if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
print_openssl_err(bev);
ERROR("Error: %s\n", evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
err = bufferevent_socket_get_dns_error(bev);
if (err)
ERROR("DNS error: %s\n", evutil_gai_strerror(err));
}
if (partner) {
size_t len;
/* Flush all pending data */
len = evbuffer_get_length(bufferevent_get_input(bev));
if (len) {
DEBUG("Flushing pending data: %d\n", len);
common_readcb(bev, ctx);
}
len = evbuffer_get_length(bufferevent_get_output(partner));
if (len) {
/* We still have to flush data from the other
* side, but when that's done, close the other
* side. */
bufferevent_setcb(partner, NULL, close_on_finished_writecb,
eventcb, conn);
bufferevent_disable(partner, EV_READ);
} else {
/* We have nothing left to say to the other
* side; close it. */
close_bev(partner, conn);
}
}
close_bev(bev, conn);
} else if (what & BEV_EVENT_CONNECTED) {
if (bev == conn->client_bev) {
DEBUG("client connected, sending banner to client\n");
conn->status = CLIENT_CONNECTED;
dst = bufferevent_get_output(bev);
if (proxy_server.prohibit_post)
evbuffer_add_printf(dst, "%d %s %s\r\n", NNTP_SERVICE_READY_PROHIBIT_POSTING, NNTP_BANNER, "(posting prohibited)");
else
evbuffer_add_printf(dst, "%d %s %s\r\n", NNTP_SERVICE_READY, NNTP_BANNER, "(posting ok)");
//bufferevent_setcb(bev, client_auth_readcb, NULL, eventcb, conn);
//bufferevent_enable(bev, EV_READ);
} else {
DEBUG("connected to server, waiting for banner\n");
conn->status = SERVER_CONNECTED;
}
}
}
static void ssl_accept_cb(struct evconnlistener *listener, evutil_socket_t sock,
struct sockaddr *sa, int sa_len, void *arg)
{
SSL *ssl;
struct conn_desc *conn;
INFO("new connection from %s\n", ip_str_from_sa(sa));
conn = get_next_conn();
if (!conn) {
ERROR("no more available connections\n");
goto err;
}
conn->status = CLIENT_CONNECTING;
assert(conn->client_username == NULL);
ssl = SSL_new(ssl_server_ctx);
if (!ssl) {
fprintf(stderr, "Error creating SSL server side\n");
goto err;
}
conn->client_bev = bufferevent_openssl_socket_new(base, sock, ssl,
BUFFEREVENT_SSL_ACCEPTING,
BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
if (!conn->client_bev) {
perror("bufferevent_openssl_socket_new");
goto err;
}
conn->server_bev = NULL;
bufferevent_setcb(conn->client_bev, client_auth_readcb, NULL, eventcb, conn);
bufferevent_enable(conn->client_bev, EV_READ|EV_WRITE);
return;
err:
if (conn && conn->client_bev) {
bufferevent_free(conn->client_bev);
conn->client_bev = NULL;
}
evutil_closesocket(sock);
}
static void ignore_sigpipe(void)
{
// ignore SIGPIPE (or else it will bring our program down if the client