Author: Ghostwolf <foxxe@wtfs.net>
[ircu2.10.12-pk.git] / ircd / s_auth.c
1 /************************************************************************
2  *   IRC - Internet Relay Chat, src/s_auth.c
3  *   Copyright (C) 1992 Darren Reed
4  *
5  *   This program is free software; you can redistribute it and/or modify
6  *   it under the terms of the GNU General Public License as published by
7  *   the Free Software Foundation; either version 1, or (at your option)
8  *   any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  *   $Id$
20  *
21  * Changes:
22  *   July 6, 1999 - Rewrote most of the code here. When a client connects
23  *     to the server and passes initial socket validation checks, it
24  *     is owned by this module (auth) which returns it to the rest of the
25  *     server when dns and auth queries are finished. Until the client is
26  *     released, the server does not know it exists and does not process
27  *     any messages from it.
28  *     --Bleep  Thomas Helvey <tomh@inxpress.net>
29  */
30 #include "config.h"
31
32 #include "s_auth.h"
33 #include "client.h"
34 #include "IPcheck.h"
35 #include "ircd.h"
36 #include "ircd_alloc.h"
37 #include "ircd_chattr.h"
38 #include "ircd_events.h"
39 #include "ircd_features.h"
40 #include "ircd_log.h"
41 #include "ircd_osdep.h"
42 #include "ircd_snprintf.h"
43 #include "ircd_string.h"
44 #include "list.h"
45 #include "numeric.h"
46 #include "querycmds.h"
47 #include "res.h"
48 #include "s_bsd.h"
49 #include "s_debug.h"
50 #include "s_misc.h"
51 #include "send.h"
52 #include "struct.h"
53 #include "sys.h"               /* TRUE bleah */
54
55 #include <arpa/inet.h>         /* inet_netof */
56 #include <netdb.h>             /* struct hostent */
57 #include <string.h>
58 #include <stdlib.h>
59 #include <unistd.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <assert.h>
63 #include <sys/socket.h>
64 #include <sys/file.h>
65 #include <sys/ioctl.h>
66
67 /*
68  * a bit different approach
69  * this replaces the original sendheader macros
70  */
71 static struct {
72   const char*  message;
73   unsigned int length;
74 } HeaderMessages [] = {
75   /* 123456789012345678901234567890123456789012345678901234567890 */
76   { "NOTICE AUTH :*** Looking up your hostname\r\n",       43 },
77   { "NOTICE AUTH :*** Found your hostname\r\n",            38 },
78   { "NOTICE AUTH :*** Found your hostname, cached\r\n",    46 },
79   { "NOTICE AUTH :*** Couldn't look up your hostname\r\n", 49 },
80   { "NOTICE AUTH :*** Checking Ident\r\n",                 33 },
81   { "NOTICE AUTH :*** Got ident response\r\n",             37 },
82   { "NOTICE AUTH :*** No ident response\r\n",              36 },
83   { "NOTICE AUTH :*** Your forward and reverse DNS do not match, " \
84     "ignoring hostname.\r\n",                              80 }
85 };
86
87 typedef enum {
88   REPORT_DO_DNS,
89   REPORT_FIN_DNS,
90   REPORT_FIN_DNSC,
91   REPORT_FAIL_DNS,
92   REPORT_DO_ID,
93   REPORT_FIN_ID,
94   REPORT_FAIL_ID,
95   REPORT_IP_MISMATCH
96 } ReportType;
97
98 #define sendheader(c, r) \
99    send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
100
101 struct AuthRequest* AuthPollList = 0; /* GLOBAL - auth queries pending io */
102 static struct AuthRequest* AuthIncompleteList = 0;
103
104 enum { AUTH_TIMEOUT = 60 };
105
106 static void release_auth_client(struct Client* client);
107 static void unlink_auth_request(struct AuthRequest* request,
108                                 struct AuthRequest** list);
109 void free_auth_request(struct AuthRequest* auth);
110
111 /*
112  * auth_timeout - timeout a given auth request
113  */
114 static void auth_timeout_callback(struct Event* ev)
115 {
116   struct AuthRequest* auth;
117
118   assert(0 != ev_timer(ev));
119   assert(0 != t_data(ev_timer(ev)));
120
121   auth = t_data(ev_timer(ev));
122
123   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
124     auth->flags &= ~AM_TIMEOUT;
125
126     if (!(auth->flags & AM_FREE_MASK)) {
127       Debug((DEBUG_LIST, "Freeing auth from timeout callback; %p [%p]", auth,
128              ev_timer(ev)));
129       MyFree(auth); /* done with it, finally */
130     }
131   } else {
132     assert(ev_type(ev) == ET_EXPIRE);
133
134     destroy_auth_request(auth, 1);
135   }
136 }
137
138 /*
139  * auth_sock_callback - called when an event occurs on the socket
140  */
141 static void auth_sock_callback(struct Event* ev)
142 {
143   struct AuthRequest* auth;
144
145   assert(0 != ev_socket(ev));
146   assert(0 != s_data(ev_socket(ev)));
147
148   auth = s_data(ev_socket(ev));
149
150   switch (ev_type(ev)) {
151   case ET_DESTROY: /* being destroyed */
152     auth->flags &= ~AM_SOCKET;
153
154     if (!(auth->flags & AM_FREE_MASK)) {
155       Debug((DEBUG_LIST, "Freeing auth from sock callback; %p [%p]", auth,
156              ev_socket(ev)));
157       MyFree(auth); /* done with it finally */
158     }
159     break;
160
161   case ET_CONNECT: /* socket connection completed */
162     Debug((DEBUG_LIST, "Connection completed for auth %p [%p]; sending query",
163            auth, ev_socket(ev)));
164     socket_state(&auth->socket, SS_CONNECTED);
165     send_auth_query(auth);
166     break;
167
168   case ET_READ: /* socket is readable */
169   case ET_EOF: /* end of file on socket */
170   case ET_ERROR: /* error on socket */
171     Debug((DEBUG_LIST, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
172     read_auth_reply(auth);
173     break;
174
175   default:
176 #ifndef NDEBUG
177     abort(); /* unrecognized event */
178 #endif
179     break;
180   }
181 }
182
183 /*
184  * destroy_auth_request - stop an auth request completely
185  */
186 void destroy_auth_request(struct AuthRequest* auth, int send_reports)
187 {
188   struct AuthRequest** authList;
189
190   if (IsDoingAuth(auth)) {
191     authList = &AuthPollList;
192     if (-1 < auth->fd) {
193       close(auth->fd);
194       auth->fd = -1;
195       socket_del(&auth->socket);
196     }
197
198     if (send_reports && IsUserPort(auth->client))
199       sendheader(auth->client, REPORT_FAIL_ID);
200   } else
201     authList = &AuthIncompleteList;
202
203   if (IsDNSPending(auth)) {
204     delete_resolver_queries(auth);
205     if (send_reports && IsUserPort(auth->client))
206       sendheader(auth->client, REPORT_FAIL_DNS);
207   }
208
209   if (send_reports) {
210     log_write(LS_RESOLVER, L_INFO, 0, "DNS/AUTH timeout %s",
211               get_client_name(auth->client, HIDE_IP));
212     release_auth_client(auth->client);
213   }
214
215   unlink_auth_request(auth, authList);
216   free_auth_request(auth);
217 }
218
219 /*
220  * make_auth_request - allocate a new auth request
221  */
222 static struct AuthRequest* make_auth_request(struct Client* client)
223 {
224   struct AuthRequest* auth = 
225                (struct AuthRequest*) MyMalloc(sizeof(struct AuthRequest));
226   assert(0 != auth);
227   memset(auth, 0, sizeof(struct AuthRequest));
228   auth->flags   = AM_TIMEOUT;
229   auth->fd      = -1;
230   auth->client  = client;
231   cli_auth(client) = auth;
232   timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
233             TT_RELATIVE, AUTH_TIMEOUT);
234   return auth;
235 }
236
237 /*
238  * free_auth_request - cleanup auth request allocations
239  */
240 void free_auth_request(struct AuthRequest* auth)
241 {
242   if (-1 < auth->fd) {
243     close(auth->fd);
244     Debug((DEBUG_LIST, "Deleting auth socket for %p", auth->client));
245     socket_del(&auth->socket);
246   }
247   Debug((DEBUG_LIST, "Deleting auth timeout timer for %p", auth->client));
248   timer_del(&auth->timeout);
249 }
250
251 /*
252  * unlink_auth_request - remove auth request from a list
253  */
254 static void unlink_auth_request(struct AuthRequest* request,
255                                 struct AuthRequest** list)
256 {
257   if (request->next)
258     request->next->prev = request->prev;
259   if (request->prev)
260     request->prev->next = request->next;
261   else
262     *list = request->next;
263 }
264
265 /*
266  * link_auth_request - add auth request to a list
267  */
268 static void link_auth_request(struct AuthRequest* request,
269                               struct AuthRequest** list)
270 {
271   request->prev = 0;
272   request->next = *list;
273   if (*list)
274     (*list)->prev = request;
275   *list = request;
276 }
277
278 /*
279  * release_auth_client - release auth client from auth system
280  * this adds the client into the local client lists so it can be read by
281  * the main io processing loop
282  */
283 static void release_auth_client(struct Client* client)
284 {
285   assert(0 != client);
286   cli_auth(client) = 0;
287   cli_lasttime(client) = cli_since(client) = CurrentTime;
288   if (cli_fd(client) > HighestFd)
289     HighestFd = cli_fd(client);
290   LocalClientArray[cli_fd(client)] = client;
291
292   add_client_to_list(client);
293   socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
294   Debug((DEBUG_INFO, "Auth: release_auth_client %s@%s[%s]",
295          cli_username(client), cli_sockhost(client), cli_sock_ip(client)));
296 }
297  
298 static void auth_kill_client(struct AuthRequest* auth)
299 {
300   assert(0 != auth);
301
302   unlink_auth_request(auth, (IsDoingAuth(auth)) ? &AuthPollList : &AuthIncompleteList);
303
304   if (IsDNSPending(auth))
305     delete_resolver_queries(auth);
306   IPcheck_disconnect(auth->client);
307   Count_unknowndisconnects(UserStats);
308   cli_auth(auth->client) = 0;
309   free_client(auth->client);
310   free_auth_request(auth);
311 }
312
313 /*
314  * auth_dns_callback - called when resolver query finishes
315  * if the query resulted in a successful search, hp will contain
316  * a non-null pointer, otherwise hp will be null.
317  * set the client on it's way to a connection completion, regardless
318  * of success of failure
319  */
320 static void auth_dns_callback(void* vptr, struct DNSReply* reply)
321 {
322   struct AuthRequest* auth = (struct AuthRequest*) vptr;
323
324   assert(0 != auth);
325   /*
326    * need to do this here so auth_kill_client doesn't
327    * try have the resolver delete the query it's about
328    * to delete anyways. --Bleep
329    */
330   ClearDNSPending(auth);
331
332   if (reply) {
333     const struct hostent* hp = reply->hp;
334     int i;
335     assert(0 != hp);
336     /*
337      * Verify that the host to ip mapping is correct both ways and that
338      * the ip#(s) for the socket is listed for the host.
339      */
340     for (i = 0; hp->h_addr_list[i]; ++i) {
341       if (0 == memcmp(hp->h_addr_list[i], &(cli_ip(auth->client)),
342                       sizeof(struct in_addr)))
343          break;
344     }
345     if (!hp->h_addr_list[i]) {
346       if (IsUserPort(auth->client))
347         sendheader(auth->client, REPORT_IP_MISMATCH);
348       sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
349                            cli_sock_ip(auth->client), hp->h_name, 
350                            ircd_ntoa(hp->h_addr_list[0]));
351       if (feature_bool(FEAT_KILL_IPMISMATCH)) {
352         auth_kill_client(auth);
353         return;
354       }
355     }
356     else {
357       ++reply->ref_count;
358       cli_dns_reply(auth->client) = reply;
359       ircd_strncpy(cli_sockhost(auth->client), hp->h_name, HOSTLEN);
360       if (IsUserPort(auth->client))
361         sendheader(auth->client, REPORT_FIN_DNS);
362     }
363   }
364   else {
365     /*
366      * this should have already been done by s_bsd.c in add_connection
367      *
368      * strcpy(auth->client->sockhost, auth->client->sock_ip);
369      */
370     if (IsUserPort(auth->client))
371       sendheader(auth->client, REPORT_FAIL_DNS);
372   }
373   if (!IsDoingAuth(auth)) {
374     release_auth_client(auth->client);
375     unlink_auth_request(auth, &AuthIncompleteList);
376     free_auth_request(auth);
377   }
378 }
379
380 /*
381  * authsenderr - handle auth send errors
382  */
383 static void auth_error(struct AuthRequest* auth, int kill)
384 {
385   ++ServerStats->is_abad;
386
387   assert(0 != auth);
388   close(auth->fd);
389   auth->fd = -1;
390   socket_del(&auth->socket);
391
392   if (IsUserPort(auth->client))
393     sendheader(auth->client, REPORT_FAIL_ID);
394
395   if (kill) {
396     /*
397      * we can't read the client info from the client socket,
398      * close the client connection and free the client
399      * Need to do this before we ClearAuth(auth) so we know
400      * which list to remove the query from. --Bleep
401      */
402     auth_kill_client(auth);
403     return;
404   }
405
406   ClearAuth(auth);
407   unlink_auth_request(auth, &AuthPollList);
408
409   if (IsDNSPending(auth))
410     link_auth_request(auth, &AuthIncompleteList);
411   else {
412     release_auth_client(auth->client);
413     free_auth_request(auth);
414   }
415 }
416
417 /*
418  * start_auth_query - Flag the client to show that an attempt to 
419  * contact the ident server on the client's host.  The connect and
420  * subsequently the socket are all put into 'non-blocking' mode.  
421  * Should the connect or any later phase of the identifing process fail,
422  * it is aborted and the user is given a username of "unknown".
423  */
424 static int start_auth_query(struct AuthRequest* auth)
425 {
426   struct sockaddr_in remote_addr;
427   struct sockaddr_in local_addr;
428   int                fd;
429   IOResult           result;
430
431   assert(0 != auth);
432   assert(0 != auth->client);
433
434   if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
435     ++ServerStats->is_abad;
436     return 0;
437   }
438   if ((MAXCONNECTIONS - 10) < fd) {
439     close(fd);
440     return 0;
441   }
442   if (!os_set_nonblocking(fd)) {
443     close(fd);
444     return 0;
445   }
446   if (IsUserPort(auth->client))
447     sendheader(auth->client, REPORT_DO_ID);
448   /* 
449    * get the local address of the client and bind to that to
450    * make the auth request.  This used to be done only for
451    * ifdef VIRTTUAL_HOST, but needs to be done for all clients
452    * since the ident request must originate from that same address--
453    * and machines with multiple IP addresses are common now
454    */
455   memset(&local_addr, 0, sizeof(struct sockaddr_in));
456   os_get_sockname(cli_fd(auth->client), &local_addr);
457   local_addr.sin_port = htons(0);
458
459   if (bind(fd, (struct sockaddr*) &local_addr, sizeof(struct sockaddr_in))) {
460     close(fd);
461     return 0;
462   }
463
464   remote_addr.sin_addr.s_addr = (cli_ip(auth->client)).s_addr;
465   remote_addr.sin_port = htons(113);
466   remote_addr.sin_family = AF_INET;
467
468   if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
469       !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
470                   result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
471                   SOCK_EVENT_READABLE, fd)) {
472     ServerStats->is_abad++;
473     /*
474      * No error report from this...
475      */
476     close(fd);
477     if (IsUserPort(auth->client))
478       sendheader(auth->client, REPORT_FAIL_ID);
479     return 0;
480   }
481
482   auth->flags |= AM_SOCKET;
483   auth->fd = fd;
484
485   SetAuthConnect(auth);
486   if (result == IO_SUCCESS)
487     send_auth_query(auth); /* this does a SetAuthPending(auth) for us */
488
489   return 1;
490 }
491
492
493 enum IdentReplyFields {
494   IDENT_PORT_NUMBERS,
495   IDENT_REPLY_TYPE,
496   IDENT_OS_TYPE,
497   IDENT_INFO,
498   USERID_TOKEN_COUNT
499 };
500
501 static char* check_ident_reply(char* reply)
502 {
503   char* token;
504   char* end;
505   char* vector[USERID_TOKEN_COUNT];
506   int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
507
508   if (USERID_TOKEN_COUNT != count)
509     return 0;
510   /*
511    * second token is the reply type
512    */
513   token = vector[IDENT_REPLY_TYPE];
514   if (EmptyString(token))
515     return 0;
516
517   while (IsSpace(*token))
518     ++token;
519
520   if (0 != strncmp(token, "USERID", 6))
521     return 0;
522
523   /*
524    * third token is the os type
525    */
526   token = vector[IDENT_OS_TYPE];
527   if (EmptyString(token))
528     return 0;
529   while (IsSpace(*token))
530    ++token;
531
532   /*
533    * Unless "OTHER" is specified as the operating system
534    * type, the server is expected to return the "normal"
535    * user identification of the owner of this connection.
536    * "Normal" in this context may be taken to mean a string
537    * of characters which uniquely identifies the connection
538    * owner such as a user identifier assigned by the system
539    * administrator and used by such user as a mail
540    * identifier, or as the "user" part of a user/password
541    * pair used to gain access to system resources.  When an
542    * operating system is specified (e.g., anything but
543    * "OTHER"), the user identifier is expected to be in a
544    * more or less immediately useful form - e.g., something
545    * that could be used as an argument to "finger" or as a
546    * mail address.
547    */
548   if (0 == strncmp(token, "OTHER", 5))
549     return 0;
550   /*
551    * fourth token is the username
552    */
553   token = vector[IDENT_INFO];
554   if (EmptyString(token))
555     return 0;
556   while (IsSpace(*token))
557     ++token;
558   /*
559    * look for the end of the username, terminators are '\0, @, <SPACE>, :'
560    */
561   for (end = token; *end; ++end) {
562     if (IsSpace(*end) || '@' == *end || ':' == *end)
563       break;
564   }
565   *end = '\0'; 
566   return token;
567 }
568
569 /*
570  * start_auth - starts auth (identd) and dns queries for a client
571  */
572 enum { LOOPBACK = 127 };
573
574 void start_auth(struct Client* client)
575 {
576   struct AuthRequest* auth = 0;
577
578   assert(0 != client);
579
580   auth = make_auth_request(client);
581   assert(0 != auth);
582
583   Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
584
585   if (!feature_bool(FEAT_NODNS)) {
586     if (LOOPBACK == inet_netof(cli_ip(client)))
587       strcpy(cli_sockhost(client), cli_name(&me));
588     else {
589       struct DNSQuery query;
590
591       query.vptr     = auth;
592       query.callback = auth_dns_callback;
593
594       if (IsUserPort(auth->client))
595         sendheader(client, REPORT_DO_DNS);
596
597       cli_dns_reply(client) = gethost_byaddr((const char*) &(cli_ip(client)),
598                                              &query);
599
600       if (cli_dns_reply(client)) {
601         ++(cli_dns_reply(client))->ref_count;
602         ircd_strncpy(cli_sockhost(client), cli_dns_reply(client)->hp->h_name,
603                      HOSTLEN);
604         if (IsUserPort(auth->client))
605           sendheader(client, REPORT_FIN_DNSC);
606         Debug((DEBUG_LIST, "DNS entry for %p was cached", auth->client));
607       } else
608         SetDNSPending(auth);
609     }
610   }
611
612   if (start_auth_query(auth)) {
613     Debug((DEBUG_LIST, "identd query for %p initiated successfully",
614            auth->client));
615     link_auth_request(auth, &AuthPollList);
616   } else if (IsDNSPending(auth)) {
617     Debug((DEBUG_LIST, "identd query for %p not initiated successfully; "
618            "waiting on DNS", auth->client));
619     link_auth_request(auth, &AuthIncompleteList);
620   } else {
621     Debug((DEBUG_LIST, "identd query for %p not initiated successfully; "
622            "no DNS pending; releasing immediately", auth->client));
623     free_auth_request(auth);
624     release_auth_client(client);
625   }
626 }
627
628 /*
629  * send_auth_query - send the ident server a query giving "theirport , ourport"
630  * The write is only attempted *once* so it is deemed to be a fail if the
631  * entire write doesn't write all the data given.  This shouldnt be a
632  * problem since the socket should have a write buffer far greater than
633  * this message to store it in should problems arise. -avalon
634  */
635 void send_auth_query(struct AuthRequest* auth)
636 {
637   struct sockaddr_in us;
638   struct sockaddr_in them;
639   char               authbuf[32];
640   unsigned int       count;
641
642   assert(0 != auth);
643   assert(0 != auth->client);
644
645   if (!os_get_sockname(cli_fd(auth->client), &us) ||
646       !os_get_peername(cli_fd(auth->client), &them)) {
647     auth_error(auth, 1);
648     return;
649   }
650   ircd_snprintf(0, authbuf, sizeof(authbuf), "%u , %u\r\n",
651                 (unsigned int) ntohs(them.sin_port),
652                 (unsigned int) ntohs(us.sin_port));
653
654   if (IO_SUCCESS == os_send_nonb(auth->fd, authbuf, strlen(authbuf), &count)) {
655     ClearAuthConnect(auth);
656     SetAuthPending(auth);
657   }
658   else
659     auth_error(auth, 0);
660 }
661
662
663 /*
664  * read_auth_reply - read the reply (if any) from the ident server 
665  * we connected to.
666  * We only give it one shot, if the reply isn't good the first time
667  * fail the authentication entirely. --Bleep
668  */
669 void read_auth_reply(struct AuthRequest* auth)
670 {
671   char*        username = 0;
672   unsigned int len;
673   /*
674    * rfc1453 sez we MUST accept 512 bytes
675    */
676   char   buf[BUFSIZE + 1];
677
678   assert(0 != auth);
679   assert(0 != auth->client);
680   assert(auth == cli_auth(auth->client));
681
682   if (IO_SUCCESS == os_recv_nonb(auth->fd, buf, BUFSIZE, &len)) {
683     buf[len] = '\0';
684     Debug((DEBUG_LIST, "Auth %p [%p] reply: %s", auth, &auth->socket, buf));
685     username = check_ident_reply(buf);
686     Debug((DEBUG_LIST, "Username: %s", username));
687   }
688
689   close(auth->fd);
690   auth->fd = -1;
691   Debug((DEBUG_LIST, "Deleting auth [%p] socket %p", auth, &auth->socket));
692   socket_del(&auth->socket);
693   ClearAuth(auth);
694   
695   if (!EmptyString(username)) {
696     ircd_strncpy(cli_username(auth->client), username, USERLEN);
697     /*
698      * Not needed, struct is zeroed by memset
699      * auth->client->username[USERLEN] = '\0';
700      */
701     SetGotId(auth->client);
702     ++ServerStats->is_asuc;
703     if (IsUserPort(auth->client))
704       sendheader(auth->client, REPORT_FIN_ID);
705   }
706   else {
707     ++ServerStats->is_abad;
708   }
709   unlink_auth_request(auth, &AuthPollList);
710
711   if (IsDNSPending(auth))
712     link_auth_request(auth, &AuthIncompleteList);
713   else {
714     release_auth_client(auth->client);
715     free_auth_request(auth);
716   }
717 }