-
Notifications
You must be signed in to change notification settings - Fork 3
/
s_auth.c
2198 lines (1971 loc) · 68.3 KB
/
s_auth.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
/************************************************************************
* IRC - Internet Relay Chat, src/s_auth.c
* Copyright (C) 1992 Darren Reed
*
* 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 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Changes:
* July 6, 1999 - Rewrote most of the code here. When a client connects
* to the server and passes initial socket validation checks, it
* is owned by this module (auth) which returns it to the rest of the
* server when dns and auth queries are finished. Until the client is
* released, the server does not know it exists and does not process
* any messages from it.
* --Bleep Thomas Helvey <tomh@inxpress.net>
*
* December 26, 2005 - Rewrite the flag handling and integrate that with
* an IRCnet-style IAuth protocol.
* -- Michael Poole
*/
/** @file
* @brief Implementation of DNS and ident lookups.
* @version $Id: s_auth.c,v 1.37.2.25 2007/08/09 03:46:20 entrope Exp $
*/
#include "config.h"
#include "s_auth.h"
#include "class.h"
#include "client.h"
#include "IPcheck.h"
#include "ircd.h"
#include "ircd_alloc.h"
#include "ircd_chattr.h"
#include "ircd_events.h"
#include "ircd_features.h"
#include "ircd_log.h"
#include "ircd_osdep.h"
#include "ircd_reply.h"
#include "ircd_snprintf.h"
#include "ircd_string.h"
#include "list.h"
#include "msg.h" /* for MAXPARA */
#include "numeric.h"
#include "querycmds.h"
#include "random.h"
#include "res.h"
#include "s_bsd.h"
#include "s_conf.h"
#include "s_debug.h"
#include "s_misc.h"
#include "s_user.h"
#include "send.h"
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
/** Pending operations during registration. */
enum AuthRequestFlag {
AR_AUTH_PENDING, /**< ident connecting or waiting for response */
AR_DNS_PENDING, /**< dns request sent, waiting for response */
AR_CAP_PENDING, /**< in middle of CAP negotiations */
AR_NEEDS_PONG, /**< user has not PONGed */
AR_NEEDS_USER, /**< user must send USER command */
AR_NEEDS_NICK, /**< user must send NICK command */
AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
AR_IAUTH_HURRY, /**< we told iauth to hurry up */
AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
AR_PASSWORD_CHECKED, /**< client password already checked */
AR_NUM_FLAGS
};
DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
/** Stores registration state of a client. */
struct AuthRequest {
struct AuthRequest* next; /**< linked list node ptr */
struct AuthRequest* prev; /**< linked list node ptr */
struct Client* client; /**< pointer to client struct for request */
struct irc_sockaddr local; /**< local endpoint address */
struct irc_in_addr original; /**< original client IP address */
struct Socket socket; /**< socket descriptor for auth queries */
struct Timer timeout; /**< timeout timer for ident and dns queries */
struct AuthRequestFlags flags; /**< current state of request */
unsigned int cookie; /**< cookie the user must PONG */
unsigned short port; /**< client's remote port number */
};
/** Array of message text (with length) pairs for AUTH status
* messages. Indexed using #ReportType.
*/
static struct {
const char* message;
unsigned int length;
} HeaderMessages [] = {
#define MSG(STR) { STR, sizeof(STR) - 1 }
MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
MSG("NOTICE AUTH :*** Found your hostname\r\n"),
MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
MSG("NOTICE AUTH :*** Checking Ident\r\n"),
MSG("NOTICE AUTH :*** Got ident response\r\n"),
MSG("NOTICE AUTH :*** No ident response\r\n"),
MSG("NOTICE AUTH :*** \r\n"),
MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
"ignoring hostname.\r\n"),
MSG("NOTICE AUTH :*** Invalid hostname\r\n")
#undef MSG
};
/** Enum used to index messages in the HeaderMessages[] array. */
typedef enum {
REPORT_DO_DNS,
REPORT_FIN_DNS,
REPORT_FAIL_DNS,
REPORT_DO_ID,
REPORT_FIN_ID,
REPORT_FAIL_ID,
REPORT_FAIL_IAUTH,
REPORT_IP_MISMATCH,
REPORT_INVAL_DNS
} ReportType;
/** Sends response \a r (from #ReportType) to client \a c. */
#define sendheader(c, r) \
send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
/** Enumeration of IAuth connection flags. */
enum IAuthFlag
{
IAUTH_BLOCKED, /**< socket buffer full */
IAUTH_CLOSING, /**< candidate to be disposed */
/* The following flags are controlled by iauth's "O" options command. */
IAUTH_ADDLINFO, /**< Send additional info
* (password and username). */
IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
IAUTH_REQUIRED, /**< IAuth completion required for registration. */
IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
IAUTH_UNDERNET, /**< Enable Undernet extensions. */
IAUTH_LAST_FLAG /**< total number of flags */
};
/** Declare a bitset structure indexed by IAuthFlag. */
DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
/** Describes state of an IAuth connection. */
struct IAuth {
struct MsgQ i_sendQ; /**< messages queued to send */
struct Socket i_socket; /**< main socket to iauth */
struct Socket i_stderr; /**< error socket for iauth */
struct IAuthFlags i_flags; /**< connection state/status/flags */
uint64_t i_recvB; /**< bytes received */
uint64_t i_sendB; /**< bytes sent */
time_t started; /**< time that this instance was started */
unsigned int i_recvM; /**< messages received */
unsigned int i_sendM; /**< messages sent */
unsigned int i_count; /**< characters used in i_buffer */
unsigned int i_errcount; /**< characters used in i_errbuf */
int i_debug; /**< debug level */
char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
char *i_version; /**< iauth version string */
struct SLink *i_config; /**< configuration string list */
struct SLink *i_stats; /**< statistics string list */
char **i_argv; /**< argument list */
};
/** Return whether flag \a flag is set on \a iauth. */
#define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
/** Set flag \a flag on \a iauth. */
#define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
/** Clear flag \a flag from \a iauth. */
#define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
/** Get connected flag for \a iauth. */
#define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
/** Return socket event generator for \a iauth. */
#define i_socket(iauth) (&(iauth)->i_socket)
/** Return stderr socket for \a iauth. */
#define i_stderr(iauth) (&(iauth)->i_stderr)
/** Return outbound message queue for \a iauth. */
#define i_sendQ(iauth) (&(iauth)->i_sendQ)
/** Return debug level for \a iauth. */
#define i_debug(iauth) ((iauth)->i_debug)
/** Active instance of IAuth. */
static struct IAuth *iauth;
/** Freelist of AuthRequest structures. */
static struct AuthRequest *auth_freelist;
static void iauth_sock_callback(struct Event *ev);
static void iauth_stderr_callback(struct Event *ev);
static int sendto_iauth(struct Client *cptr, const char *format, ...);
static int preregister_user(struct Client *cptr);
typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
int parc, char **params);
/** Set username for user associated with \a auth.
* @param[in] auth Client authorization request to work on.
* @return Zero if client is kept, CPTR_KILLED if client rejected.
*/
static int auth_set_username(struct AuthRequest *auth)
{
struct Client *sptr = auth->client;
struct User *user = cli_user(sptr);
char *d;
char *s;
int rlen = USERLEN;
int killreason;
short character = 0;
short pos = 0;
short other = 0;
short digits = 0;
char ch;
char last;
if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
{
ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
}
else
{
/* Copy username from source to destination. Since they may be the
* same, and we may prefix with a '~', use a buffer character (ch)
* to hold the next character to copy.
*/
s = IsIdented(sptr) ? cli_username(sptr) : user->username;
last = *s++;
d = user->username;
if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
{
*d++ = '~';
--rlen;
}
while (last && !IsCntrl(last) && rlen--)
{
ch = *s++;
*d++ = IsUserChar(last) ? last : '_';
last = (ch != '~') ? ch : '_';
}
*d = 0;
}
/* If username is empty or just ~, reject. */
if ((user->username[0] == '\0')
|| ((user->username[0] == '~') && (user->username[1] == '\0')))
return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
/* Have to set up "realusername" before doing the gline check below */
ircd_strncpy(user->realusername, user->username, USERLEN);
/* Check for K- or G-line. */
killreason = find_kill(sptr, 1);
if (killreason) {
ServerStats->is_ref++;
return exit_client(sptr, sptr, &me,
(killreason == -1 ? "K-lined" : "G-lined"));
}
if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
{
/* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
* Explanations of rules moved to where it is checked Entrope 2-06
*/
s = d = user->username + (user->username[0] == '~');
for (last = '\0';
(ch = *d++) != '\0';
pos++, last = ch)
{
if (IsLower(ch) || IsUpper(ch))
{
character++;
}
else if (IsDigit(ch))
{
digits++;
}
else if (ch == '-' || ch == '_' || ch == '.')
{
other++;
/* If -_. exist at start, consecutively, or more than twice, reject. */
if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
goto badid;
}
else /* All other punctuation is rejected. */
goto badid;
}
/* Must have at least one letter. */
if (!character)
goto badid;
}
return 0;
badid:
/* If we confirmed their username, and it is what they claimed,
* accept it. */
if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
return 0;
ServerStats->is_ref++;
send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
":Your username is invalid.");
send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
":Connect with your real username, in lowercase.");
send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
":If your mail address were foo@bar.com, your username "
"would be foo.");
return exit_client(sptr, sptr, &me, "USER: Bad username");
}
/** Check whether an authorization request is complete.
* This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
* If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
* 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
* destroy \a auth, clear the password, set the username, and register
* the client.
* @param[in] auth Authorization request to check.
* @return Zero if client is kept, CPTR_KILLED if client rejected.
*/
static int check_auth_finished(struct AuthRequest *auth)
{
enum AuthRequestFlag flag;
int res;
/* Check non-iauth registration blocking flags. */
for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
if (FlagHas(&auth->flags, flag))
{
Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
cli_fd(auth->client), flag));
return 0;
}
/* If appropriate, do preliminary assignment to connection class. */
if (IsUserPort(auth->client)
&& !FlagHas(&auth->flags, AR_IAUTH_HURRY)
&& preregister_user(auth->client))
return CPTR_KILLED;
/* If we have not done so, check client password. Do this as soon
* as possible so that iauth's challenge/response (which uses PASS
* for responses) is not confused with the client's password.
*/
if (IsUserPort(auth->client)
&& !FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
{
struct ConfItem *aconf;
aconf = cli_confs(auth->client)->value.aconf;
if (aconf
&& !EmptyString(aconf->passwd)
&& strcmp(cli_passwd(auth->client), aconf->passwd))
{
ServerStats->is_ref++;
send_reply(auth->client, ERR_PASSWDMISMATCH);
return exit_client(auth->client, auth->client, &me, "Bad Password");
}
FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
}
/* Check if iauth is done. */
if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
{
/* Switch auth request to hurry-up state. */
if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
{
/* Set "hurry" flag in auth request. */
FlagSet(&auth->flags, AR_IAUTH_HURRY);
/* If iauth wants it, send notification. */
if (IAuthHas(iauth, IAUTH_UNDERNET))
sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
/* If iauth wants it, give client more time. */
if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
cli_firsttime(auth->client) = CurrentTime;
}
Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
cli_fd(auth->client), AR_IAUTH_PENDING));
return 0;
}
else
FlagSet(&auth->flags, AR_IAUTH_HURRY);
if (IsUserPort(auth->client))
{
memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
res = auth_set_username(auth);
if (res == 0)
res = register_user(auth->client, auth->client);
}
else
res = 0;
if (res == 0)
destroy_auth_request(auth);
return res;
}
/** Verify that a hostname is valid, i.e., only contains characters
* valid for a hostname and that a hostname is not too long.
* @param host Hostname to check.
* @param maxlen Maximum length of hostname, not including NUL terminator.
* @return Non-zero if the hostname is valid.
*/
static int
auth_verify_hostname(const char *host, int maxlen)
{
int i;
/* Walk through the host name */
for (i = 0; host[i]; i++)
/* If it's not a hostname character or if it's too long, return false */
if (!IsHostChar(host[i]) || i >= maxlen)
return 0;
return 1; /* it's a valid hostname */
}
/** Assign a client to a connection class.
* @param[in] cptr Client to assign to a class.
* @return Zero if client is kept, CPTR_KILLED if rejected.
*/
static int preregister_user(struct Client *cptr)
{
static time_t last_too_many1;
static time_t last_too_many2;
ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
switch (conf_check_client(cptr))
{
case ACR_OK:
break;
case ACR_NO_AUTHORIZATION:
sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
get_client_name(cptr, HIDE_IP));
++ServerStats->is_ref;
return exit_client(cptr, cptr, &me,
"No Authorization - use another server");
case ACR_TOO_MANY_IN_CLASS:
sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
"Too many connections in class %s for %s.",
get_client_class(cptr),
get_client_name(cptr, SHOW_IP));
++ServerStats->is_ref;
return exit_client(cptr, cptr, &me,
"Sorry, your connection class is full - try "
"again later or try another server");
case ACR_TOO_MANY_FROM_IP:
sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
"Too many connections from same IP for %s.",
get_client_name(cptr, SHOW_IP));
++ServerStats->is_ref;
return exit_client(cptr, cptr, &me,
"Too many connections from your host");
case ACR_ALREADY_AUTHORIZED:
/* Can this ever happen? */
case ACR_BAD_SOCKET:
++ServerStats->is_ref;
IPcheck_connect_fail(cptr);
return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
}
return 0;
}
/** Send the ident server a query giving "theirport , ourport". The
* write is only attempted *once* so it is deemed to be a fail if the
* entire write doesn't write all the data given. This shouldn't be a
* problem since the socket should have a write buffer far greater
* than this message to store it in should problems arise. -avalon
* @param[in] auth The request to send.
*/
static void send_auth_query(struct AuthRequest* auth)
{
char authbuf[32];
unsigned int count;
assert(0 != auth);
ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
auth->port, auth->local.port);
if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
close(s_fd(&auth->socket));
socket_del(&auth->socket);
s_fd(&auth->socket) = -1;
++ServerStats->is_abad;
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
FlagClr(&auth->flags, AR_AUTH_PENDING);
check_auth_finished(auth);
}
}
/** Enum used to index ident reply fields in a human-readable way. */
enum IdentReplyFields {
IDENT_PORT_NUMBERS,
IDENT_REPLY_TYPE,
IDENT_OS_TYPE,
IDENT_INFO,
USERID_TOKEN_COUNT
};
/** Parse an ident reply line and extract the userid from it.
* @param[in] reply The ident reply line.
* @return The userid, or NULL on parse failure.
*/
static char* check_ident_reply(char* reply)
{
char* token;
char* end;
char* vector[USERID_TOKEN_COUNT];
int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
if (USERID_TOKEN_COUNT != count)
return 0;
/*
* second token is the reply type
*/
token = vector[IDENT_REPLY_TYPE];
if (EmptyString(token))
return 0;
while (IsSpace(*token))
++token;
if (0 != strncmp(token, "USERID", 6))
return 0;
/*
* third token is the os type
*/
token = vector[IDENT_OS_TYPE];
if (EmptyString(token))
return 0;
while (IsSpace(*token))
++token;
/*
* Unless "OTHER" is specified as the operating system
* type, the server is expected to return the "normal"
* user identification of the owner of this connection.
* "Normal" in this context may be taken to mean a string
* of characters which uniquely identifies the connection
* owner such as a user identifier assigned by the system
* administrator and used by such user as a mail
* identifier, or as the "user" part of a user/password
* pair used to gain access to system resources. When an
* operating system is specified (e.g., anything but
* "OTHER"), the user identifier is expected to be in a
* more or less immediately useful form - e.g., something
* that could be used as an argument to "finger" or as a
* mail address.
*/
if (0 == strncmp(token, "OTHER", 5))
return 0;
/*
* fourth token is the username
*/
token = vector[IDENT_INFO];
if (EmptyString(token))
return 0;
while (IsSpace(*token))
++token;
/*
* look for the end of the username, terminators are '\0, @, <SPACE>, :'
*/
for (end = token; *end; ++end) {
if (IsSpace(*end) || '@' == *end || ':' == *end)
break;
}
*end = '\0';
return token;
}
/** Read the reply (if any) from the ident server we connected to. We
* only give it one shot, if the reply isn't good the first time fail
* the authentication entirely. --Bleep
* @param[in] auth The request to read.
*/
static void read_auth_reply(struct AuthRequest* auth)
{
char* username = 0;
unsigned int len;
/*
* rfc1453 sez we MUST accept 512 bytes
*/
char buf[BUFSIZE + 1];
assert(0 != auth);
assert(0 != auth->client);
assert(auth == cli_auth(auth->client));
if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
buf[len] = '\0';
Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
username = check_ident_reply(buf);
Debug((DEBUG_INFO, "Username: %s", username));
}
Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
close(s_fd(&auth->socket));
socket_del(&auth->socket);
s_fd(&auth->socket) = -1;
if (EmptyString(username)) {
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
++ServerStats->is_abad;
} else {
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FIN_ID);
++ServerStats->is_asuc;
if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
ircd_strncpy(cli_username(auth->client), username, USERLEN);
SetGotId(auth->client);
}
if (IAuthHas(iauth, IAUTH_UNDERNET))
sendto_iauth(auth->client, "u %s", username);
}
FlagClr(&auth->flags, AR_AUTH_PENDING);
check_auth_finished(auth);
}
/** Handle socket I/O activity.
* @param[in] ev A socket event whos associated data is the active
* struct AuthRequest.
*/
static void auth_sock_callback(struct Event* ev)
{
struct AuthRequest* auth;
assert(0 != ev_socket(ev));
assert(0 != s_data(ev_socket(ev)));
auth = (struct AuthRequest*) s_data(ev_socket(ev));
switch (ev_type(ev)) {
case ET_DESTROY: /* being destroyed */
break;
case ET_CONNECT: /* socket connection completed */
Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
auth, cli_fd(auth->client)));
socket_state(&auth->socket, SS_CONNECTED);
send_auth_query(auth);
break;
case ET_READ: /* socket is readable */
case ET_EOF: /* end of file on socket */
case ET_ERROR: /* error on socket */
Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
read_auth_reply(auth);
break;
default:
assert(0 && "Unrecognized event in auth_socket_callback().");
break;
}
}
/** Stop an auth request completely.
* @param[in] auth The struct AuthRequest to cancel.
*/
void destroy_auth_request(struct AuthRequest* auth)
{
Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
delete_resolver_queries(auth);
}
if (-1 < s_fd(&auth->socket)) {
close(s_fd(&auth->socket));
socket_del(&auth->socket);
s_fd(&auth->socket) = -1;
}
if (t_active(&auth->timeout))
timer_del(&auth->timeout);
cli_auth(auth->client) = NULL;
auth->next = auth_freelist;
auth_freelist = auth;
}
/** Handle a 'ping' (authorization) timeout for a client.
* @param[in] cptr The client whose session authorization has timed out.
* @return Zero if client is kept, CPTR_KILLED if client rejected.
*/
int auth_ping_timeout(struct Client *cptr)
{
struct AuthRequest *auth;
enum AuthRequestFlag flag;
auth = cli_auth(cptr);
/* Check whether the auth request is gone (more likely, it never
* existed, as in an outbound server connection). */
if (!auth)
return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
/* Check for a user-controlled timeout. */
for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
if (FlagHas(&auth->flags, flag)) {
/* Display message if they have sent a NICK and a USER but no
* nospoof PONG.
*/
if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
":Your client may not be compatible with this server.");
send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
":Compatible clients are available at %s",
feature_str(FEAT_URL_CLIENTS));
}
return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
}
}
/* Check for iauth timeout. */
if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
sendto_iauth(cptr, "T");
if (IAuthHas(iauth, IAUTH_REQUIRED)) {
sendheader(cptr, REPORT_FAIL_IAUTH);
return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
}
FlagClr(&auth->flags, AR_IAUTH_PENDING);
return check_auth_finished(auth);
}
assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
return 0;
}
/** Timeout a given auth request.
* @param[in] ev A timer event whose associated data is the expired
* struct AuthRequest.
*/
static void auth_timeout_callback(struct Event* ev)
{
struct AuthRequest* auth;
assert(0 != ev_timer(ev));
assert(0 != t_data(ev_timer(ev)));
auth = (struct AuthRequest*) t_data(ev_timer(ev));
if (ev_type(ev) == ET_EXPIRE) {
/* Report the timeout in the log. */
log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
get_client_name(auth->client, HIDE_IP));
/* Notify client if ident lookup failed. */
if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
FlagClr(&auth->flags, AR_AUTH_PENDING);
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
}
/* Likewise if dns lookup failed. */
if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
FlagClr(&auth->flags, AR_DNS_PENDING);
delete_resolver_queries(auth);
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_DNS);
}
/* Try to register the client. */
check_auth_finished(auth);
}
}
/** Handle a complete DNS lookup. Send the client on it's way to a
* connection completion, regardless of success or failure -- unless
* there was a mismatch and KILL_IPMISMATCH is set.
* @param[in] vptr The pending struct AuthRequest.
* @param[in] addr IP address being resolved.
* @param[in] h_name Resolved name, or NULL if lookup failed.
*/
static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
{
struct AuthRequest* auth = (struct AuthRequest*) vptr;
assert(0 != auth);
FlagClr(&auth->flags, AR_DNS_PENDING);
if (!addr) {
/* DNS entry was missing for the IP. */
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_DNS);
sendto_iauth(auth->client, "d");
} else if (!irc_in_addr_valid(addr)
|| (irc_in_addr_cmp(&cli_ip(auth->client), addr)
&& irc_in_addr_cmp(&auth->original, addr))) {
/* IP for hostname did not match client's IP. */
sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
cli_sock_ip(auth->client), h_name,
ircd_ntoa(addr));
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_IP_MISMATCH);
if (feature_bool(FEAT_KILL_IPMISMATCH)) {
exit_client(auth->client, auth->client, &me, "IP mismatch");
return;
}
} else if (!auth_verify_hostname(h_name, HOSTLEN)) {
/* Hostname did not look valid. */
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_INVAL_DNS);
sendto_iauth(auth->client, "d");
} else {
/* Hostname and mappings checked out. */
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FIN_DNS);
ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
sendto_iauth(auth->client, "N %s", h_name);
}
check_auth_finished(auth);
}
/** Flag the client to show an attempt to contact the ident server on
* the client's host. Should the connect or any later phase of the
* identifying process fail, it is aborted and the user is given a
* username of "unknown".
* @param[in] auth The request for which to start the ident lookup.
*/
static void start_auth_query(struct AuthRequest* auth)
{
struct irc_sockaddr remote_addr;
struct irc_sockaddr local_addr;
int fd;
IOResult result;
assert(0 != auth);
assert(0 != auth->client);
/*
* get the local address of the client and bind to that to
* make the auth request. This used to be done only for
* ifdef VIRTUAL_HOST, but needs to be done for all clients
* since the ident request must originate from that same address--
* and machines with multiple IP addresses are common now
*/
memcpy(&local_addr, &auth->local, sizeof(local_addr));
local_addr.port = 0;
memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
remote_addr.port = 113;
fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
if (fd < 0) {
++ServerStats->is_abad;
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
return;
}
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_DO_ID);
if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
!socket_add(&auth->socket, auth_sock_callback, (void*) auth,
result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
SOCK_EVENT_READABLE, fd)) {
++ServerStats->is_abad;
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
close(fd);
return;
}
FlagSet(&auth->flags, AR_AUTH_PENDING);
if (result == IO_SUCCESS)
send_auth_query(auth);
}
/** Initiate DNS lookup for a client.
* @param[in] auth The auth request for which to start the DNS lookup.
*/
static void start_dns_query(struct AuthRequest *auth)
{
if (feature_bool(FEAT_NODNS)) {
sendto_iauth(auth->client, "d");
return;
}
if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
strcpy(cli_sockhost(auth->client), cli_name(&me));
sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
return;
}
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_DO_DNS);
FlagSet(&auth->flags, AR_DNS_PENDING);
gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
}
/** Initiate IAuth check for a client.
* @param[in] auth The auth request for which to star the IAuth check.
*/
static void start_iauth_query(struct AuthRequest *auth)
{
FlagSet(&auth->flags, AR_IAUTH_PENDING);
if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
cli_sock_ip(auth->client), auth->port,
ircd_ntoa(&auth->local.addr), auth->local.port))
FlagClr(&auth->flags, AR_IAUTH_PENDING);
}
/** Starts auth (identd) and dns queries for a client.
* @param[in] client The client for which to start queries.
*/
void start_auth(struct Client* client)
{
struct irc_sockaddr remote;
struct AuthRequest* auth;
assert(0 != client);
Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
/* Register with event handlers. */
cli_lasttime(client) = CurrentTime;
cli_since(client) = CurrentTime;
if (cli_fd(client) > HighestFd)
HighestFd = cli_fd(client);
LocalClientArray[cli_fd(client)] = client;
socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
/* Allocate the AuthRequest. */
auth = auth_freelist;
if (auth)
auth_freelist = auth->next;
else
auth = MyMalloc(sizeof(*auth));
assert(0 != auth);
memset(auth, 0, sizeof(*auth));
auth->client = client;
cli_auth(client) = auth;
s_fd(&auth->socket) = -1;
timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
/* Try to get socket endpoint addresses. */
if (!os_get_sockname(cli_fd(client), &auth->local)
|| !os_get_peername(cli_fd(client), &remote)) {
++ServerStats->is_abad;
if (IsUserPort(auth->client))
sendheader(auth->client, REPORT_FAIL_ID);
exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
return;
}
auth->port = remote.port;
/* Try to start DNS lookup. */
start_dns_query(auth);
/* Try to start ident lookup. */
start_auth_query(auth);
/* Set required client inputs for users. */
if (IsUserPort(client)) {
cli_user(client) = make_user(client);
cli_user(client)->server = &me;
FlagSet(&auth->flags, AR_NEEDS_USER);
FlagSet(&auth->flags, AR_NEEDS_NICK);
/* Try to start iauth lookup. */
start_iauth_query(auth);
}
/* Add client to GlobalClientList. */
add_client_to_list(client);
/* Check which auth events remain pending. */
check_auth_finished(auth);
}
/** Mark that a user has PONGed while unregistered.
* @param[in] auth Authorization request for client.
* @param[in] cookie PONG cookie value sent by client.
* @return Zero if client should be kept, CPTR_KILLED if rejected.
*/