1 /************************************************************************
2 * IRC - Internet Relay Chat, src/s_auth.c
3 * Copyright (C) 1992 Darren Reed
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)
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.
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.
20 * July 6, 1999 - Rewrote most of the code here. When a client connects
21 * to the server and passes initial socket validation checks, it
22 * is owned by this module (auth) which returns it to the rest of the
23 * server when dns and auth queries are finished. Until the client is
24 * released, the server does not know it exists and does not process
25 * any messages from it.
26 * --Bleep Thomas Helvey <tomh@inxpress.net>
28 * December 26, 2005 - Rewrite the flag handling and integrate that with
29 * an IRCnet-style IAuth protocol.
33 * @brief Implementation of DNS and ident lookups.
43 #include "ircd_alloc.h"
44 #include "ircd_chattr.h"
45 #include "ircd_events.h"
46 #include "ircd_features.h"
48 #include "ircd_osdep.h"
49 #include "ircd_reply.h"
50 #include "ircd_snprintf.h"
51 #include "ircd_string.h"
53 #include "msg.h" /* for MAXPARA */
55 #include "querycmds.h"
70 #include <sys/socket.h>
71 #include <sys/ioctl.h>
73 /** Pending operations during registration. */
74 enum AuthRequestFlag {
75 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
76 AR_DNS_PENDING, /**< dns request sent, waiting for response */
77 AR_CAP_PENDING, /**< in middle of CAP negotiations */
78 AR_NEEDS_PONG, /**< user has not PONGed */
79 AR_NEEDS_USER, /**< user must send USER command */
80 AR_NEEDS_NICK, /**< user must send NICK command */
81 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
82 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
83 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
84 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
85 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
86 AR_PASSWORD_CHECKED, /**< client password already checked */
90 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
92 /** Stores registration state of a client. */
94 struct AuthRequest* next; /**< linked list node ptr */
95 struct AuthRequest* prev; /**< linked list node ptr */
96 struct Client* client; /**< pointer to client struct for request */
97 struct irc_sockaddr local; /**< local endpoint address */
98 struct irc_in_addr original; /**< original client IP address */
99 struct Socket socket; /**< socket descriptor for auth queries */
100 struct Timer timeout; /**< timeout timer for ident and dns queries */
101 struct AuthRequestFlags flags; /**< current state of request */
102 unsigned int cookie; /**< cookie the user must PONG */
103 unsigned short port; /**< client's remote port number */
106 /** Array of message text (with length) pairs for AUTH status
107 * messages. Indexed using #ReportType.
112 } HeaderMessages [] = {
113 #define MSG(STR) { STR, sizeof(STR) - 1 }
114 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
115 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
116 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
117 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
118 MSG("NOTICE AUTH :*** Got ident response\r\n"),
119 MSG("NOTICE AUTH :*** No ident response\r\n"),
120 MSG("NOTICE AUTH :*** \r\n"),
121 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
122 "ignoring hostname.\r\n"),
123 MSG("NOTICE AUTH :*** Invalid hostname\r\n")
127 /** Enum used to index messages in the HeaderMessages[] array. */
140 /** Sends response \a r (from #ReportType) to client \a c. */
141 #define sendheader(c, r) \
142 send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
144 /** Enumeration of IAuth connection flags. */
147 IAUTH_BLOCKED, /**< socket buffer full */
148 IAUTH_CLOSING, /**< candidate to be disposed */
149 /* The following flags are controlled by iauth's "O" options command. */
150 IAUTH_ADDLINFO, /**< Send additional info
151 * (password and username). */
152 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
153 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
154 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
155 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
156 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
157 IAUTH_LAST_FLAG /**< total number of flags */
159 /** Declare a bitset structure indexed by IAuthFlag. */
160 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
162 /** Describes state of an IAuth connection. */
164 struct MsgQ i_sendQ; /**< messages queued to send */
165 struct Socket i_socket; /**< main socket to iauth */
166 struct Socket i_stderr; /**< error socket for iauth */
167 struct IAuthFlags i_flags; /**< connection state/status/flags */
168 uint64_t i_recvB; /**< bytes received */
169 uint64_t i_sendB; /**< bytes sent */
170 time_t started; /**< time that this instance was started */
171 unsigned int i_recvM; /**< messages received */
172 unsigned int i_sendM; /**< messages sent */
173 unsigned int i_count; /**< characters used in i_buffer */
174 unsigned int i_errcount; /**< characters used in i_errbuf */
175 int i_debug; /**< debug level */
176 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
177 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
178 char *i_version; /**< iauth version string */
179 struct SLink *i_config; /**< configuration string list */
180 struct SLink *i_stats; /**< statistics string list */
181 char **i_argv; /**< argument list */
184 /** Return whether flag \a flag is set on \a iauth. */
185 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
186 /** Set flag \a flag on \a iauth. */
187 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
188 /** Clear flag \a flag from \a iauth. */
189 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
190 /** Get connected flag for \a iauth. */
191 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
193 /** Return socket event generator for \a iauth. */
194 #define i_socket(iauth) (&(iauth)->i_socket)
195 /** Return stderr socket for \a iauth. */
196 #define i_stderr(iauth) (&(iauth)->i_stderr)
197 /** Return outbound message queue for \a iauth. */
198 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
199 /** Return debug level for \a iauth. */
200 #define i_debug(iauth) ((iauth)->i_debug)
202 /** Active instance of IAuth. */
203 static struct IAuth *iauth;
204 /** Freelist of AuthRequest structures. */
205 static struct AuthRequest *auth_freelist;
207 static void iauth_sock_callback(struct Event *ev);
208 static void iauth_stderr_callback(struct Event *ev);
209 static int sendto_iauth(struct Client *cptr, const char *format, ...);
210 static int preregister_user(struct Client *cptr);
211 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
212 int parc, char **params);
214 /** Set username for user associated with \a auth.
215 * @param[in] auth Client authorization request to work on.
216 * @return Zero if client is kept, CPTR_KILLED if client rejected.
218 static int auth_set_username(struct AuthRequest *auth)
220 struct Client *sptr = auth->client;
221 struct User *user = cli_user(sptr);
232 short digitgroups = 0;
236 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
238 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
242 /* Copy username from source to destination. Since they may be the
243 * same, and we may prefix with a '~', use a buffer character (ch)
244 * to hold the next character to copy.
246 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
249 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
254 while (last && !IsCntrl(last) && rlen--)
257 *d++ = IsUserChar(last) ? last : '_';
258 last = (ch != '~') ? ch : '_';
263 /* If username is empty or just ~, reject. */
264 if ((user->username[0] == '\0')
265 || ((user->username[0] == '~') && (user->username[1] == '\0')))
266 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
268 /* Check for K- or G-line. */
269 killreason = find_kill(sptr);
271 ServerStats->is_ref++;
272 return exit_client(sptr, sptr, &me,
273 (killreason == -1 ? "K-lined" : "G-lined"));
276 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
278 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
279 * Explanations of rules moved to where it is checked Entrope 2-06
281 s = d = user->username + (user->username[0] == '~');
290 else if (IsUpper(ch))
293 /* Accept caps as leading if we haven't seen lower case or digits yet. */
294 if ((leadcaps || pos == 0) && !lower && !digits)
297 else if (IsDigit(ch))
300 if (pos == 0 || !IsDigit(last))
303 /* If more than two groups of digits, reject. */
308 else if (ch == '-' || ch == '_' || ch == '.')
311 /* If -_. exist at start, consecutively, or more than twice, reject. */
312 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
315 else /* All other punctuation is rejected. */
319 /* If mixed case, first must be capital, but no more than three;
320 * but if three capitals, they must all be leading. */
321 if (lower && upper && (!leadcaps || leadcaps > 3 ||
322 (upper > 2 && upper > leadcaps)))
324 /* If two different groups of digits, one must be either at the
326 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
328 /* Must have at least one letter. */
329 if (!lower && !upper)
331 /* Final character must not be punctuation. */
339 /* If we confirmed their username, and it is what they claimed,
341 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
344 ServerStats->is_ref++;
345 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
346 ":Your username is invalid.");
347 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
348 ":Connect with your real username, in lowercase.");
349 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
350 ":If your mail address were foo@bar.com, your username "
352 return exit_client(sptr, sptr, &me, "USER: Bad username");
355 /** Check whether an authorization request is complete.
356 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
357 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
358 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
359 * destroy \a auth, clear the password, set the username, and register
361 * @param[in] auth Authorization request to check.
362 * @return Zero if client is kept, CPTR_KILLED if client rejected.
364 static int check_auth_finished(struct AuthRequest *auth)
366 enum AuthRequestFlag flag;
369 /* Check non-iauth registration blocking flags. */
370 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
371 if (FlagHas(&auth->flags, flag))
373 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
374 cli_fd(auth->client), flag));
378 /* If appropriate, do preliminary assignment to connection class. */
379 if (IsUserPort(auth->client)
380 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
381 && preregister_user(auth->client))
384 /* If we have not done so, check client password. Do this as soon
385 * as possible so that iauth's challenge/response (which uses PASS
386 * for responses) is not confused with the client's password.
388 if (IsUserPort(auth->client)
389 && !FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
391 struct ConfItem *aconf;
393 aconf = cli_confs(auth->client)->value.aconf;
395 && !EmptyString(aconf->passwd)
396 && strcmp(cli_passwd(auth->client), aconf->passwd))
398 ServerStats->is_ref++;
399 send_reply(auth->client, ERR_PASSWDMISMATCH);
400 return exit_client(auth->client, auth->client, &me, "Bad Password");
402 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
405 /* Check if iauth is done. */
406 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
408 /* Switch auth request to hurry-up state. */
409 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
411 /* Set "hurry" flag in auth request. */
412 FlagSet(&auth->flags, AR_IAUTH_HURRY);
414 /* If iauth wants it, send notification. */
415 if (IAuthHas(iauth, IAUTH_UNDERNET))
416 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
418 /* If iauth wants it, give client more time. */
419 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
420 cli_firsttime(auth->client) = CurrentTime;
423 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
424 cli_fd(auth->client), AR_IAUTH_PENDING));
428 FlagSet(&auth->flags, AR_IAUTH_HURRY);
430 if (IsUserPort(auth->client))
432 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
433 res = auth_set_username(auth);
435 res = register_user(auth->client, auth->client);
440 destroy_auth_request(auth);
444 /** Verify that a hostname is valid, i.e., only contains characters
445 * valid for a hostname and that a hostname is not too long.
446 * @param host Hostname to check.
447 * @param maxlen Maximum length of hostname, not including NUL terminator.
448 * @return Non-zero if the hostname is valid.
451 auth_verify_hostname(const char *host, int maxlen)
455 /* Walk through the host name */
456 for (i = 0; host[i]; i++)
457 /* If it's not a hostname character or if it's too long, return false */
458 if (!IsHostChar(host[i]) || i >= maxlen)
461 return 1; /* it's a valid hostname */
464 /** Assign a client to a connection class.
465 * @param[in] cptr Client to assign to a class.
466 * @return Zero if client is kept, CPTR_KILLED if rejected.
468 static int preregister_user(struct Client *cptr)
470 static time_t last_too_many1;
471 static time_t last_too_many2;
473 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
474 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
476 switch (conf_check_client(cptr))
480 case ACR_NO_AUTHORIZATION:
481 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
482 get_client_name(cptr, HIDE_IP));
483 ++ServerStats->is_ref;
484 return exit_client(cptr, cptr, &me,
485 "No Authorization - use another server");
486 case ACR_TOO_MANY_IN_CLASS:
487 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
488 "Too many connections in class %s for %s.",
489 get_client_class(cptr),
490 get_client_name(cptr, SHOW_IP));
491 ++ServerStats->is_ref;
492 return exit_client(cptr, cptr, &me,
493 "Sorry, your connection class is full - try "
494 "again later or try another server");
495 case ACR_TOO_MANY_FROM_IP:
496 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
497 "Too many connections from same IP for %s.",
498 get_client_name(cptr, SHOW_IP));
499 ++ServerStats->is_ref;
500 return exit_client(cptr, cptr, &me,
501 "Too many connections from your host");
502 case ACR_ALREADY_AUTHORIZED:
503 /* Can this ever happen? */
505 ++ServerStats->is_ref;
506 IPcheck_connect_fail(cptr);
507 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
512 /** Send the ident server a query giving "theirport , ourport". The
513 * write is only attempted *once* so it is deemed to be a fail if the
514 * entire write doesn't write all the data given. This shouldn't be a
515 * problem since the socket should have a write buffer far greater
516 * than this message to store it in should problems arise. -avalon
517 * @param[in] auth The request to send.
519 static void send_auth_query(struct AuthRequest* auth)
526 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
527 auth->port, auth->local.port);
529 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
530 close(s_fd(&auth->socket));
531 socket_del(&auth->socket);
532 s_fd(&auth->socket) = -1;
533 ++ServerStats->is_abad;
534 if (IsUserPort(auth->client))
535 sendheader(auth->client, REPORT_FAIL_ID);
536 FlagClr(&auth->flags, AR_AUTH_PENDING);
537 check_auth_finished(auth);
541 /** Enum used to index ident reply fields in a human-readable way. */
542 enum IdentReplyFields {
550 /** Parse an ident reply line and extract the userid from it.
551 * @param[in] reply The ident reply line.
552 * @return The userid, or NULL on parse failure.
554 static char* check_ident_reply(char* reply)
558 char* vector[USERID_TOKEN_COUNT];
559 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
561 if (USERID_TOKEN_COUNT != count)
564 * second token is the reply type
566 token = vector[IDENT_REPLY_TYPE];
567 if (EmptyString(token))
570 while (IsSpace(*token))
573 if (0 != strncmp(token, "USERID", 6))
577 * third token is the os type
579 token = vector[IDENT_OS_TYPE];
580 if (EmptyString(token))
582 while (IsSpace(*token))
586 * Unless "OTHER" is specified as the operating system
587 * type, the server is expected to return the "normal"
588 * user identification of the owner of this connection.
589 * "Normal" in this context may be taken to mean a string
590 * of characters which uniquely identifies the connection
591 * owner such as a user identifier assigned by the system
592 * administrator and used by such user as a mail
593 * identifier, or as the "user" part of a user/password
594 * pair used to gain access to system resources. When an
595 * operating system is specified (e.g., anything but
596 * "OTHER"), the user identifier is expected to be in a
597 * more or less immediately useful form - e.g., something
598 * that could be used as an argument to "finger" or as a
601 if (0 == strncmp(token, "OTHER", 5))
604 * fourth token is the username
606 token = vector[IDENT_INFO];
607 if (EmptyString(token))
609 while (IsSpace(*token))
612 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
614 for (end = token; *end; ++end) {
615 if (IsSpace(*end) || '@' == *end || ':' == *end)
622 /** Read the reply (if any) from the ident server we connected to. We
623 * only give it one shot, if the reply isn't good the first time fail
624 * the authentication entirely. --Bleep
625 * @param[in] auth The request to read.
627 static void read_auth_reply(struct AuthRequest* auth)
632 * rfc1453 sez we MUST accept 512 bytes
634 char buf[BUFSIZE + 1];
637 assert(0 != auth->client);
638 assert(auth == cli_auth(auth->client));
640 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
642 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
643 username = check_ident_reply(buf);
644 Debug((DEBUG_INFO, "Username: %s", username));
647 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
648 close(s_fd(&auth->socket));
649 socket_del(&auth->socket);
650 s_fd(&auth->socket) = -1;
652 if (EmptyString(username)) {
653 if (IsUserPort(auth->client))
654 sendheader(auth->client, REPORT_FAIL_ID);
655 ++ServerStats->is_abad;
657 if (IsUserPort(auth->client))
658 sendheader(auth->client, REPORT_FIN_ID);
659 ++ServerStats->is_asuc;
660 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
661 ircd_strncpy(cli_username(auth->client), username, USERLEN);
662 SetGotId(auth->client);
664 if (IAuthHas(iauth, IAUTH_UNDERNET))
665 sendto_iauth(auth->client, "u %s", username);
668 FlagClr(&auth->flags, AR_AUTH_PENDING);
669 check_auth_finished(auth);
672 /** Handle socket I/O activity.
673 * @param[in] ev A socket event whos associated data is the active
674 * struct AuthRequest.
676 static void auth_sock_callback(struct Event* ev)
678 struct AuthRequest* auth;
680 assert(0 != ev_socket(ev));
681 assert(0 != s_data(ev_socket(ev)));
683 auth = (struct AuthRequest*) s_data(ev_socket(ev));
685 switch (ev_type(ev)) {
686 case ET_DESTROY: /* being destroyed */
689 case ET_CONNECT: /* socket connection completed */
690 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
691 auth, cli_fd(auth->client)));
692 socket_state(&auth->socket, SS_CONNECTED);
693 send_auth_query(auth);
696 case ET_READ: /* socket is readable */
697 case ET_EOF: /* end of file on socket */
698 case ET_ERROR: /* error on socket */
699 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
700 read_auth_reply(auth);
704 assert(0 && "Unrecognized event in auth_socket_callback().");
709 /** Stop an auth request completely.
710 * @param[in] auth The struct AuthRequest to cancel.
712 void destroy_auth_request(struct AuthRequest* auth)
714 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
716 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
717 delete_resolver_queries(auth);
720 if (-1 < s_fd(&auth->socket)) {
721 close(s_fd(&auth->socket));
722 socket_del(&auth->socket);
723 s_fd(&auth->socket) = -1;
726 if (t_active(&auth->timeout))
727 timer_del(&auth->timeout);
729 cli_auth(auth->client) = NULL;
730 auth->next = auth_freelist;
731 auth_freelist = auth;
734 /** Handle a 'ping' (authorization) timeout for a client.
735 * @param[in] cptr The client whose session authorization has timed out.
736 * @return Zero if client is kept, CPTR_KILLED if client rejected.
738 int auth_ping_timeout(struct Client *cptr)
740 struct AuthRequest *auth;
741 enum AuthRequestFlag flag;
743 auth = cli_auth(cptr);
745 /* Check whether the auth request is gone (more likely, it never
746 * existed, as in an outbound server connection). */
748 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
750 /* Check for a user-controlled timeout. */
751 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
752 if (FlagHas(&auth->flags, flag)) {
753 /* Display message if they have sent a NICK and a USER but no
756 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
757 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
758 ":Your client may not be compatible with this server.");
759 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
760 ":Compatible clients are available at %s",
761 feature_str(FEAT_URL_CLIENTS));
763 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
767 /* Check for iauth timeout. */
768 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
769 sendto_iauth(cptr, "T");
770 if (IAuthHas(iauth, IAUTH_REQUIRED)) {
771 sendheader(cptr, REPORT_FAIL_IAUTH);
772 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
774 FlagClr(&auth->flags, AR_IAUTH_PENDING);
775 return check_auth_finished(auth);
778 assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
782 /** Timeout a given auth request.
783 * @param[in] ev A timer event whose associated data is the expired
784 * struct AuthRequest.
786 static void auth_timeout_callback(struct Event* ev)
788 struct AuthRequest* auth;
790 assert(0 != ev_timer(ev));
791 assert(0 != t_data(ev_timer(ev)));
793 auth = (struct AuthRequest*) t_data(ev_timer(ev));
795 if (ev_type(ev) == ET_EXPIRE) {
796 /* Report the timeout in the log. */
797 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
798 get_client_name(auth->client, HIDE_IP));
800 /* Notify client if ident lookup failed. */
801 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
802 FlagClr(&auth->flags, AR_AUTH_PENDING);
803 if (IsUserPort(auth->client))
804 sendheader(auth->client, REPORT_FAIL_ID);
807 /* Likewise if dns lookup failed. */
808 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
809 FlagClr(&auth->flags, AR_DNS_PENDING);
810 delete_resolver_queries(auth);
811 if (IsUserPort(auth->client))
812 sendheader(auth->client, REPORT_FAIL_DNS);
815 /* Try to register the client. */
816 check_auth_finished(auth);
820 /** Handle a complete DNS lookup. Send the client on it's way to a
821 * connection completion, regardless of success or failure -- unless
822 * there was a mismatch and KILL_IPMISMATCH is set.
823 * @param[in] vptr The pending struct AuthRequest.
824 * @param[in] addr IP address being resolved.
825 * @param[in] h_name Resolved name, or NULL if lookup failed.
827 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
829 struct AuthRequest* auth = (struct AuthRequest*) vptr;
832 FlagClr(&auth->flags, AR_DNS_PENDING);
834 /* DNS entry was missing for the IP. */
835 if (IsUserPort(auth->client))
836 sendheader(auth->client, REPORT_FAIL_DNS);
837 sendto_iauth(auth->client, "d");
838 } else if (!irc_in_addr_valid(addr)
839 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
840 && irc_in_addr_cmp(&auth->original, addr))) {
841 /* IP for hostname did not match client's IP. */
842 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
843 cli_sock_ip(auth->client), h_name,
845 if (IsUserPort(auth->client))
846 sendheader(auth->client, REPORT_IP_MISMATCH);
847 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
848 exit_client(auth->client, auth->client, &me, "IP mismatch");
851 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
852 /* Hostname did not look valid. */
853 if (IsUserPort(auth->client))
854 sendheader(auth->client, REPORT_INVAL_DNS);
855 sendto_iauth(auth->client, "d");
857 /* Hostname and mappings checked out. */
858 if (IsUserPort(auth->client))
859 sendheader(auth->client, REPORT_FIN_DNS);
860 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
861 sendto_iauth(auth->client, "N %s", h_name);
863 check_auth_finished(auth);
866 /** Flag the client to show an attempt to contact the ident server on
867 * the client's host. Should the connect or any later phase of the
868 * identifying process fail, it is aborted and the user is given a
869 * username of "unknown".
870 * @param[in] auth The request for which to start the ident lookup.
872 static void start_auth_query(struct AuthRequest* auth)
874 struct irc_sockaddr remote_addr;
875 struct irc_sockaddr local_addr;
880 assert(0 != auth->client);
883 * get the local address of the client and bind to that to
884 * make the auth request. This used to be done only for
885 * ifdef VIRTUAL_HOST, but needs to be done for all clients
886 * since the ident request must originate from that same address--
887 * and machines with multiple IP addresses are common now
889 memcpy(&local_addr, &auth->local, sizeof(local_addr));
891 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
892 remote_addr.port = 113;
893 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
895 ++ServerStats->is_abad;
896 if (IsUserPort(auth->client))
897 sendheader(auth->client, REPORT_FAIL_ID);
900 if (IsUserPort(auth->client))
901 sendheader(auth->client, REPORT_DO_ID);
903 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
904 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
905 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
906 SOCK_EVENT_READABLE, fd)) {
907 ++ServerStats->is_abad;
908 if (IsUserPort(auth->client))
909 sendheader(auth->client, REPORT_FAIL_ID);
914 FlagSet(&auth->flags, AR_AUTH_PENDING);
915 if (result == IO_SUCCESS)
916 send_auth_query(auth);
919 /** Initiate DNS lookup for a client.
920 * @param[in] auth The auth request for which to start the DNS lookup.
922 static void start_dns_query(struct AuthRequest *auth)
924 if (feature_bool(FEAT_NODNS)) {
925 sendto_iauth(auth->client, "d");
929 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
930 strcpy(cli_sockhost(auth->client), cli_name(&me));
931 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
935 if (IsUserPort(auth->client))
936 sendheader(auth->client, REPORT_DO_DNS);
938 FlagSet(&auth->flags, AR_DNS_PENDING);
939 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
942 /** Initiate IAuth check for a client.
943 * @param[in] auth The auth request for which to star the IAuth check.
945 static void start_iauth_query(struct AuthRequest *auth)
947 FlagSet(&auth->flags, AR_IAUTH_PENDING);
948 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
949 cli_sock_ip(auth->client), auth->port,
950 ircd_ntoa(&auth->local.addr), auth->local.port))
951 FlagClr(&auth->flags, AR_IAUTH_PENDING);
954 /** Starts auth (identd) and dns queries for a client.
955 * @param[in] client The client for which to start queries.
957 void start_auth(struct Client* client)
959 struct irc_sockaddr remote;
960 struct AuthRequest* auth;
963 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
965 /* Register with event handlers. */
966 cli_lasttime(client) = CurrentTime;
967 cli_since(client) = CurrentTime;
968 if (cli_fd(client) > HighestFd)
969 HighestFd = cli_fd(client);
970 LocalClientArray[cli_fd(client)] = client;
971 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
973 /* Allocate the AuthRequest. */
974 auth = auth_freelist;
976 auth_freelist = auth->next;
978 auth = MyMalloc(sizeof(*auth));
980 memset(auth, 0, sizeof(*auth));
981 auth->client = client;
982 cli_auth(client) = auth;
983 s_fd(&auth->socket) = -1;
984 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
985 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
987 /* Try to get socket endpoint addresses. */
988 if (!os_get_sockname(cli_fd(client), &auth->local)
989 || !os_get_peername(cli_fd(client), &remote)) {
990 ++ServerStats->is_abad;
991 if (IsUserPort(auth->client))
992 sendheader(auth->client, REPORT_FAIL_ID);
993 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
996 auth->port = remote.port;
998 /* Try to start DNS lookup. */
999 start_dns_query(auth);
1001 /* Try to start ident lookup. */
1002 start_auth_query(auth);
1004 /* Set required client inputs for users. */
1005 if (IsUserPort(client)) {
1006 cli_user(client) = make_user(client);
1007 cli_user(client)->server = &me;
1008 FlagSet(&auth->flags, AR_NEEDS_USER);
1009 FlagSet(&auth->flags, AR_NEEDS_NICK);
1011 /* Try to start iauth lookup. */
1012 start_iauth_query(auth);
1015 /* Add client to GlobalClientList. */
1016 add_client_to_list(client);
1018 /* Check which auth events remain pending. */
1019 check_auth_finished(auth);
1022 /** Mark that a user has PONGed while unregistered.
1023 * @param[in] auth Authorization request for client.
1024 * @param[in] cookie PONG cookie value sent by client.
1025 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1027 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1029 assert(auth != NULL);
1030 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1032 if (cookie != auth->cookie)
1034 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1035 ":To connect, type /QUOTE PONG %u", auth->cookie);
1038 cli_lasttime(auth->client) = CurrentTime;
1039 FlagClr(&auth->flags, AR_NEEDS_PONG);
1040 return check_auth_finished(auth);
1043 /** Record a user's claimed username and userinfo.
1044 * @param[in] auth Authorization request for client.
1045 * @param[in] username Client's asserted username.
1046 * @param[in] hostname Third argument of USER command (client's
1047 * hostname, per RFC 1459).
1048 * @param[in] servername Fourth argument of USER command (server's
1049 * name, per RFC 1459).
1050 * @param[in] userinfo Client's asserted self-description.
1051 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1053 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1055 struct Client *cptr;
1057 assert(auth != NULL);
1058 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1060 FlagClr(&auth->flags, AR_NEEDS_USER);
1061 cptr = auth->client;
1062 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1063 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1064 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1065 if (IAuthHas(iauth, IAUTH_UNDERNET))
1066 sendto_iauth(cptr, "U %s %s %s :%s", username, hostname, servername, userinfo);
1067 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1068 sendto_iauth(cptr, "U %s", username);
1069 return check_auth_finished(auth);
1072 /** Handle authorization-related aspects of initial nickname selection.
1073 * This is called after verifying that the nickname is available.
1074 * @param[in] auth Authorization request for client.
1075 * @param[in] nickname Client's requested nickname.
1076 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1078 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1080 assert(auth != NULL);
1081 FlagClr(&auth->flags, AR_NEEDS_NICK);
1083 * If the client hasn't gotten a cookie-ping yet,
1084 * choose a cookie and send it. -record!jegelhof@cloud9.net
1086 if (!auth->cookie) {
1088 auth->cookie = ircrandom();
1089 } while (!auth->cookie);
1090 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1091 FlagSet(&auth->flags, AR_NEEDS_PONG);
1093 if (IAuthHas(iauth, IAUTH_UNDERNET))
1094 sendto_iauth(auth->client, "n %s", nickname);
1095 return check_auth_finished(auth);
1098 /** Record a user's password.
1099 * @param[in] auth Authorization request for client.
1100 * @param[in] password Client's password.
1101 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1103 int auth_set_password(struct AuthRequest *auth, const char *password)
1105 assert(auth != NULL);
1106 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1107 sendto_iauth(auth->client, "P :%s", password);
1111 /** Send exit notification for \a cptr to iauth.
1112 * @param[in] cptr Client who is exiting.
1114 void auth_send_exit(struct Client *cptr)
1116 sendto_iauth(cptr, "D");
1119 /** Mark that a user has started capabilities negotiation.
1120 * This blocks authorization until auth_cap_done() is called.
1121 * @param[in] auth Authorization request for client.
1122 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1124 int auth_cap_start(struct AuthRequest *auth)
1126 assert(auth != NULL);
1127 FlagSet(&auth->flags, AR_CAP_PENDING);
1131 /** Mark that a user has completed capabilities negotiation.
1132 * This unblocks authorization if auth_cap_start() was called.
1133 * @param[in] auth Authorization request for client.
1134 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1136 int auth_cap_done(struct AuthRequest *auth)
1138 assert(auth != NULL);
1139 FlagClr(&auth->flags, AR_CAP_PENDING);
1140 return check_auth_finished(auth);
1143 /** Attempt to spawn the process for an IAuth instance.
1144 * @param[in] iauth IAuth descriptor.
1145 * @param[in] automatic If non-zero, apply sanity checks against
1146 * excessive automatic restarts.
1147 * @return 0 on success, non-zero on failure.
1149 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1156 if (automatic && CurrentTime - iauth->started < 5)
1158 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1162 /* Record time we tried to spawn the iauth process. */
1163 iauth->started = CurrentTime;
1165 /* Attempt to allocate a pair of sockets. */
1166 res = os_socketpair(s_io);
1170 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1171 res = os_set_nonblocking(s_io[0]);
1179 /* Initialize the socket structure to talk to the child. */
1180 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1181 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1189 /* Allocate another pair for stderr. */
1190 res = os_socketpair(s_err);
1193 socket_del(i_socket(iauth));
1199 /* Mark parent side of this pair non-blocking, too. */
1200 res = os_set_nonblocking(s_err[0]);
1205 socket_del(i_socket(iauth));
1211 /* And set up i_stderr(iauth). */
1212 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1213 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1218 socket_del(i_socket(iauth));
1224 /* Attempt to fork a child process. */
1227 /* Error forking the child, still in parent. */
1229 socket_del(i_stderr(iauth));
1232 socket_del(i_socket(iauth));
1239 /* We are the parent process. Close the child's sockets. */
1242 /* Send our server name (supposedly for proxy checking purposes)
1243 * and maximum number of connections (for allocation hints).
1244 * Need to use conf_get_local() since &me may not be fully
1245 * initialized the first time we run.
1247 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1248 /* Indicate success (until the child dies). */
1252 /* We are the child process.
1253 * Duplicate our end of the socket to stdin, stdout and stderr.
1254 * Then close all the higher-numbered FDs and exec the process.
1256 if (dup2(s_io[1], 0) == 0
1257 && dup2(s_io[1], 1) == 1
1258 && dup2(s_err[1], 2) == 2) {
1259 close_connections(0);
1260 execvp(iauth->i_argv[0], iauth->i_argv);
1263 /* If we got here, something was seriously wrong. */
1267 /** See if an %IAuth program must be spawned.
1268 * If a process is already running with the specified options, keep it.
1269 * Otherwise spawn a new child process to perform the %IAuth function.
1270 * @param[in] argc Number of parameters to use when starting process.
1271 * @param[in] argv Array of parameters to start process.
1272 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1274 int auth_spawn(int argc, char *argv[])
1281 /* Check that incoming arguments all match pre-existing arguments. */
1282 for (ii = 0; same && (ii < argc); ++ii) {
1283 if (NULL == iauth->i_argv[ii]
1284 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1287 /* Check that we have no more pre-existing arguments. */
1288 if (iauth->i_argv[ii])
1290 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1291 if (same && i_GetConnected(iauth)) {
1292 IAuthClr(iauth, IAUTH_CLOSING);
1295 /* Deallocate old argv elements. */
1296 for (ii = 0; iauth->i_argv[ii]; ++ii)
1297 MyFree(iauth->i_argv[ii]);
1298 MyFree(iauth->i_argv);
1301 /* Need to initialize a new connection. */
1302 iauth = MyCalloc(1, sizeof(*iauth));
1303 msgq_init(i_sendQ(iauth));
1304 /* Populate iauth's argv array. */
1305 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1306 for (ii = 0; ii < argc; ++ii)
1307 DupString(iauth->i_argv[ii], argv[ii]);
1308 iauth->i_argv[ii] = NULL;
1309 /* Try to spawn it, and handle the results. */
1310 if (iauth_do_spawn(iauth, 0))
1312 IAuthClr(iauth, IAUTH_CLOSING);
1316 /** Mark all %IAuth connections as closing. */
1317 void auth_mark_closing(void)
1320 IAuthSet(iauth, IAUTH_CLOSING);
1323 /** Complete disconnection of an %IAuth connection.
1324 * @param[in] iauth %Connection to fully close.
1326 static void iauth_disconnect(struct IAuth *iauth)
1331 /* Close main socket. */
1332 if (s_fd(i_socket(iauth)) != -1) {
1333 close(s_fd(i_socket(iauth)));
1334 socket_del(i_socket(iauth));
1335 s_fd(i_socket(iauth)) = -1;
1338 /* Close error socket. */
1339 if (s_fd(i_stderr(iauth)) != -1) {
1340 close(s_fd(i_stderr(iauth)));
1341 socket_del(i_stderr(iauth));
1342 s_fd(i_stderr(iauth)) = -1;
1346 /** Close all %IAuth connections marked as closing. */
1347 void auth_close_unused(void)
1349 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1351 iauth_disconnect(iauth);
1352 if (iauth->i_argv) {
1353 for (ii = 0; iauth->i_argv[ii]; ++ii)
1354 MyFree(iauth->i_argv[ii]);
1355 MyFree(iauth->i_argv);
1361 /** Send queued output to \a iauth.
1362 * @param[in] iauth Writable connection with queued data.
1364 static void iauth_write(struct IAuth *iauth)
1366 unsigned int bytes_tried, bytes_sent;
1369 if (IAuthHas(iauth, IAUTH_BLOCKED))
1371 while (MsgQLength(i_sendQ(iauth)) > 0) {
1372 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1375 msgq_delete(i_sendQ(iauth), bytes_sent);
1376 iauth->i_sendB += bytes_sent;
1377 if (bytes_tried == bytes_sent)
1379 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1381 IAuthSet(iauth, IAUTH_BLOCKED);
1382 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1385 iauth_disconnect(iauth);
1389 /* We were able to flush all events, so remove notification. */
1390 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1393 /** Send a message to iauth.
1394 * @param[in] cptr Optional client context for message.
1395 * @param[in] format Format string for message.
1396 * @return Non-zero on successful send or buffering, zero on failure.
1398 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1403 /* Do not send requests when we have no iauth. */
1404 if (!i_GetConnected(iauth))
1406 /* Do not send for clients in the NORMAL state. */
1408 && (format[0] != 'D')
1409 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1412 /* Build the message buffer. */
1413 vd.vd_format = format;
1414 va_start(vd.vd_args, format);
1416 mb = msgq_make(NULL, "-1 %v", &vd);
1418 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1421 /* Tack it onto the iauth sendq and try to write it. */
1423 msgq_add(i_sendQ(iauth), mb, 0);
1429 /** Send text to interested operators (SNO_AUTH server notice).
1430 * @param[in] iauth Active IAuth session.
1431 * @param[in] cli Client referenced by command.
1432 * @param[in] parc Number of parameters (1).
1433 * @param[in] params Text to send.
1436 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1437 int parc, char **params)
1439 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1443 /** Set the debug level for the session.
1444 * @param[in] iauth Active IAuth session.
1445 * @param[in] cli Client referenced by command.
1446 * @param[in] parc Number of parameters (1).
1447 * @param[in] params String starting with an integer.
1450 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1451 int parc, char **params)
1455 new_level = parc > 0 ? atoi(params[0]) : 0;
1456 if (i_debug(iauth) > 0 || new_level > 0) {
1457 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1458 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1460 i_debug(iauth) = new_level;
1464 /** Set policy options for the session.
1465 * Old policy is forgotten, and any of the following characters in \a
1466 * params enable the corresponding policy:
1467 * \li A IAUTH_ADDLINFO
1468 * \li R IAUTH_REQUIRED
1469 * \li T IAUTH_TIMEOUT
1470 * \li W IAUTH_EXTRAWAIT
1471 * \li U IAUTH_UNDERNET
1473 * @param[in] iauth Active IAuth session.
1474 * @param[in] cli Client referenced by command.
1475 * @param[in] parc Number of parameters (1).
1476 * @param[in] params Zero or more policy options.
1479 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1480 int parc, char **params)
1482 enum IAuthFlag flag;
1485 /* Erase old policy first. */
1486 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1487 IAuthClr(iauth, flag);
1489 if (parc > 0) /* only try to parse if we were given a policy string */
1490 /* Parse new policy set. */
1491 for (p = params[0]; *p; p++) switch (*p) {
1492 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1493 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1494 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1495 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1496 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1499 /* Optionally notify operators. */
1500 if (i_debug(iauth) > 0)
1501 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1505 /** Set the iauth program version number.
1506 * @param[in] iauth Active IAuth session.
1507 * @param[in] cli Client referenced by command.
1508 * @param[in] parc Number of parameters (1).
1509 * @param[in] params Version number or name.
1512 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1513 int parc, char **params)
1515 MyFree(iauth->i_version);
1516 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1517 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1522 /** Paste a parameter list together into a single string.
1523 * @param[in] parc Number of parameters.
1524 * @param[in] params Parameter list to paste together.
1525 * @return Pasted parameter list.
1527 static char *paste_params(int parc, char **params)
1530 int len = 0, lengths[MAXPARA], i;
1532 /* Compute the length... */
1533 for (i = 0; i < parc; i++)
1534 len += lengths[i] = strlen(params[i]);
1536 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1537 * sentinel, and the trailing \0
1539 str = MyMalloc(len + parc + 1);
1541 /* Build the pasted string */
1542 for (tmp = str, i = 0; i < parc; i++) {
1543 if (i) /* add space separator... */
1545 if (i == parc - 1) /* add colon sentinel */
1548 /* Copy string component... */
1549 memcpy(tmp, params[i], lengths[i]);
1550 tmp += lengths[i]; /* move to end of string */
1553 /* terminate the string... */
1556 return str; /* return the pasted string */
1559 /** Clear cached iauth configuration information.
1560 * @param[in] iauth Active IAuth session.
1561 * @param[in] cli Client referenced by command.
1562 * @param[in] parc Number of parameters (0).
1563 * @param[in] params Parameter list (ignored).
1566 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1567 int parc, char **params)
1572 head = iauth->i_config;
1573 iauth->i_config = NULL;
1574 for (; head; head = next) {
1576 MyFree(head->value.cp);
1579 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1583 /** Append iauth configuration information.
1584 * @param[in] iauth Active IAuth session.
1585 * @param[in] cli Client referenced by command.
1586 * @param[in] parc Number of parameters.
1587 * @param[in] params Description of configuration element.
1590 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1591 int parc, char **params)
1595 if (iauth->i_config) {
1596 for (node = iauth->i_config; node->next; node = node->next) ;
1597 node = node->next = make_link();
1599 node = iauth->i_config = make_link();
1601 node->value.cp = paste_params(parc, params);
1602 node->next = 0; /* must be explicitly cleared */
1606 /** Clear cached iauth configuration information.
1607 * @param[in] iauth Active IAuth session.
1608 * @param[in] cli Client referenced by command.
1609 * @param[in] parc Number of parameters (0).
1610 * @param[in] params Parameter list (ignored).
1613 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1614 int parc, char **params)
1619 head = iauth->i_stats;
1620 iauth->i_stats = NULL;
1621 for (; head; head = next) {
1623 MyFree(head->value.cp);
1626 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1630 /** Append iauth statistics information.
1631 * @param[in] iauth Active IAuth session.
1632 * @param[in] cli Client referenced by command.
1633 * @param[in] parc Number of parameters.
1634 * @param[in] params Statistics element.
1637 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1638 int parc, char **params)
1641 if (iauth->i_stats) {
1642 for (node = iauth->i_stats; node->next; node = node->next) ;
1643 node = node->next = make_link();
1645 node = iauth->i_stats = make_link();
1647 node->value.cp = paste_params(parc, params);
1648 node->next = 0; /* must be explicitly cleared */
1652 /** Set client's username to a trusted string even if it breaks the rules.
1653 * @param[in] iauth Active IAuth session.
1654 * @param[in] cli Client referenced by command.
1655 * @param[in] parc Number of parameters (1).
1656 * @param[in] params Forced username.
1659 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1660 int parc, char **params)
1662 assert(cli_auth(cli) != NULL);
1663 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1664 if (!EmptyString(params[0])) {
1665 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1667 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1668 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1673 /** Set client's username to a trusted string.
1674 * @param[in] iauth Active IAuth session.
1675 * @param[in] cli Client referenced by command.
1676 * @param[in] parc Number of parameters (1).
1677 * @param[in] params Trusted username.
1680 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1681 int parc, char **params)
1683 assert(cli_auth(cli) != NULL);
1684 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1685 if (!EmptyString(params[0])) {
1686 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1688 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1693 /** Set client's username to an untrusted string.
1694 * @param[in] iauth Active IAuth session.
1695 * @param[in] cli Client referenced by command.
1696 * @param[in] parc Number of parameters (1).
1697 * @param[in] params Untrusted username.
1700 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1701 int parc, char **params)
1703 assert(cli_auth(cli) != NULL);
1704 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1705 if (!EmptyString(params[0]))
1706 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1710 /** Set client's hostname.
1711 * @param[in] iauth Active IAuth session.
1712 * @param[in] cli Client referenced by command.
1713 * @param[in] parc Number of parameters (1).
1714 * @param[in] params New hostname for client.
1715 * @return Non-zero if \a cli authorization should be checked for completion.
1717 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1718 int parc, char **params)
1720 struct AuthRequest *auth;
1722 if (EmptyString(params[0])) {
1723 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1727 auth = cli_auth(cli);
1728 assert(auth != NULL);
1730 /* If a DNS request is pending, abort it. */
1731 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1732 FlagClr(&auth->flags, AR_DNS_PENDING);
1733 delete_resolver_queries(auth);
1734 if (IsUserPort(cli))
1735 sendheader(cli, REPORT_FIN_DNS);
1737 /* Set hostname from params. */
1738 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1742 /** Set client's IP address.
1743 * @param[in] iauth Active IAuth session.
1744 * @param[in] cli Client referenced by command.
1745 * @param[in] parc Number of parameters (1).
1746 * @param[in] params New IP address for client in dotted quad or
1747 * standard IPv6 format.
1750 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1751 int parc, char **params)
1753 struct irc_in_addr addr;
1754 struct AuthRequest *auth;
1756 if (EmptyString(params[0])) {
1757 sendto_iauth(cli, "E Missing :Missing IP address parameter");
1761 /* Get AuthRequest for client. */
1762 auth = cli_auth(cli);
1763 assert(auth != NULL);
1765 /* Parse the client's new IP address. */
1766 if (!ircd_aton(&addr, params[0])) {
1767 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1771 /* If this is the first IP override, save the client's original
1772 * address in case we get a DNS response later.
1774 if (!irc_in_addr_valid(&auth->original))
1775 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1777 /* Undo original IP connection in IPcheck. */
1778 IPcheck_connect_fail(cli);
1779 ClearIPChecked(cli);
1781 /* Update the IP and charge them as a remote connect. */
1782 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1783 IPcheck_remote_connect(cli, 0);
1788 /** Find a ConfItem structure for a named connection class.
1789 * @param[in] class_name Name of configuration class to find.
1790 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1792 static struct ConfItem *auth_find_class_conf(const char *class_name)
1794 static struct ConfItem *aconf_list;
1795 struct ConnectionClass *class;
1796 struct ConfItem *aconf;
1798 /* Make sure the configuration class is valid. */
1799 class = find_class(class_name);
1803 /* Look for an existing ConfItem for the class. */
1804 for (aconf = aconf_list; aconf; aconf = aconf->next)
1805 if (aconf->conn_class == class)
1808 /* If no ConfItem, create one. */
1810 aconf = make_conf(CONF_CLIENT);
1812 sendto_opmask_butone(NULL, SNO_AUTH,
1813 "Unable to allocate ConfItem for class %s!",
1817 aconf->conn_class = class;
1818 aconf->next = aconf_list;
1825 /** Accept a client in IAuth.
1826 * @param[in] iauth Active IAuth session.
1827 * @param[in] cli Client referenced by command.
1828 * @param[in] parc Number of parameters.
1829 * @param[in] params Optional class name for client.
1832 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1833 int parc, char **params)
1835 static time_t warn_time;
1837 /* Clear iauth pending flag. */
1838 assert(cli_auth(cli) != NULL);
1839 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1841 /* If a connection class was specified (and usable), assign the client to it. */
1842 if (!EmptyString(params[0])) {
1843 struct ConfItem *aconf;
1845 aconf = auth_find_class_conf(params[0]);
1847 attach_conf(cli, aconf);
1849 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1850 "iauth tried to use undefined class [%s]",
1857 /** Accept a client in IAuth and assign them to an account.
1858 * @param[in] iauth Active IAuth session.
1859 * @param[in] cli Client referenced by command.
1860 * @param[in] parc Number of parameters.
1861 * @param[in] params Account name and optional class name for client.
1862 * @return Non-zero if \a cli authorization should be checked for completion.
1864 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1865 int parc, char **params)
1870 if (EmptyString(params[0])) {
1871 sendto_iauth(cli, "E Missing :Missing account parameter");
1874 /* Check length of account name. */
1875 len = strcspn(params[0], ": ");
1876 if (len > ACCOUNTLEN) {
1877 sendto_iauth(cli, "E Invalid :Account parameter too long");
1880 /* If account has a creation timestamp, use it. */
1881 assert(cli_user(cli) != NULL);
1882 if (params[0][len] == ':')
1883 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1885 /* Copy account name to User structure. */
1886 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1889 /* Fall through to the normal "done" handler. */
1890 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1893 /** Reject a client's connection.
1894 * @param[in] iauth Active IAuth session.
1895 * @param[in] cli Client referenced by command.
1896 * @param[in] parc Number of parameters (1).
1897 * @param[in] params Optional kill message.
1900 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1901 int parc, char **params)
1904 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1905 if (EmptyString(params[0]))
1906 params[0] = "Access denied";
1907 exit_client(cli, cli, &me, params[0]);
1911 /** Change a client's usermode.
1912 * @param[in] iauth Active IAuth session.
1913 * @param[in] cli Client referenced by command.
1914 * @param[in] parc Number of parameters (at least one).
1915 * @param[in] params Usermode arguments for client (with the first
1916 * starting with '+').
1919 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
1920 int parc, char **params)
1922 if (params[0][0] == '+')
1924 set_user_mode(cli, cli, parc + 2, params - 2, ALLOWMODES_ANY);
1930 /** Send a challenge string to the client.
1931 * @param[in] iauth Active IAuth session.
1932 * @param[in] cli Client referenced by command.
1933 * @param[in] parc Number of parameters (1).
1934 * @param[in] params Challenge message for client.
1937 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
1938 int parc, char **params)
1940 if (!EmptyString(params[0]))
1941 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
1945 /** Parse a \a message from \a iauth.
1946 * @param[in] iauth Active IAuth session.
1947 * @param[in] message Message to be parsed.
1949 static void iauth_parse(struct IAuth *iauth, char *message)
1951 char *params[MAXPARA + 1]; /* leave space for NULL */
1953 iauth_cmd_handler handler;
1954 struct AuthRequest *auth;
1959 /* Find command handler... */
1960 switch (*(message++)) {
1961 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1962 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1963 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1964 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1965 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1966 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1967 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1968 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1969 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1970 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1971 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1972 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1973 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1974 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
1975 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1976 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1977 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1978 case 'k': /* The 'k' command indicates the user should be booted
1979 * off without telling opers. There is no way to
1980 * signal that to exit_client(), so we fall through to
1981 * the case that we do implement.
1983 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1984 case 'r': /* we handle termination directly */ return;
1985 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
1988 while (parc < MAXPARA) {
1989 while (IsSpace(*message)) /* skip leading whitespace */
1992 if (!*message) /* hit the end of the string, break out */
1995 if (*message == ':') { /* found sentinel... */
1996 params[parc++] = message + 1;
1997 break; /* it's the last parameter anyway */
2000 params[parc++] = message; /* save the parameter */
2001 while (*message && !IsSpace(*message))
2002 message++; /* find the end of the parameter */
2004 if (*message) /* terminate the parameter */
2005 *(message++) = '\0';
2008 params[parc] = NULL; /* terminate the parameter list */
2010 /* Check to see if the command specifies a client... */
2012 /* Handler does not need a client. */
2013 handler(iauth, NULL, parc, params);
2015 /* Try to find the client associated with the request. */
2016 id = strtol(params[0], NULL, 10);
2018 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2019 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2020 /* Client no longer exists (or never existed). */
2021 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2023 else if ((!(auth = cli_auth(cli)) ||
2024 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2026 /* Client is done with IAuth checks. */
2027 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2029 struct irc_sockaddr addr;
2032 /* Parse IP address and port number from parameters */
2033 res = ipmask_parse(params[1], &addr.addr, NULL);
2034 addr.port = strtol(params[2], NULL, 10);
2036 /* Check IP address and port number against expected. */
2038 irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
2039 (auth && addr.port != auth->port))
2040 /* Report mismatch to iauth. */
2041 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2042 ircd_ntoa(&cli_ip(cli)));
2043 else if (handler(iauth, cli, parc - 3, params + 3))
2044 /* Handler indicated a possible state change. */
2045 check_auth_finished(auth);
2050 /** Read input from \a iauth.
2051 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2052 * @param[in] iauth Readable connection.
2054 static void iauth_read(struct IAuth *iauth)
2056 static char readbuf[SERVER_TCP_WINDOW];
2057 unsigned int length, count;
2061 /* Copy partial data to readbuf, append new data. */
2062 length = iauth->i_count;
2063 memcpy(readbuf, iauth->i_buffer, length);
2064 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2066 sizeof(readbuf) - length - 1,
2069 readbuf[length += count] = '\0';
2071 /* Parse each complete line. */
2072 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2074 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2077 /* If spammy debug, send the message to opers. */
2078 if (i_debug(iauth) > 1)
2079 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2081 /* Parse the line... */
2082 iauth_parse(iauth, sol);
2085 /* Put unused data back into connection's buffer. */
2086 iauth->i_count = strlen(sol);
2087 if (iauth->i_count > BUFSIZE)
2088 iauth->i_count = BUFSIZE;
2089 memcpy(iauth->i_buffer, sol, iauth->i_count);
2092 /** Handle socket activity for an %IAuth connection.
2093 * @param[in] ev &Socket event; the IAuth connection is the user data
2094 * pointer for the socket.
2096 static void iauth_sock_callback(struct Event *ev)
2098 struct IAuth *iauth;
2100 assert(0 != ev_socket(ev));
2101 iauth = (struct IAuth*) s_data(ev_socket(ev));
2104 switch (ev_type(ev)) {
2106 /* Hm, what happened here? */
2107 if (!IAuthHas(iauth, IAUTH_CLOSING))
2108 iauth_do_spawn(iauth, 1);
2114 IAuthClr(iauth, IAUTH_BLOCKED);
2118 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2119 /* and fall through to the ET_EOF case */
2121 iauth_disconnect(iauth);
2124 assert(0 && "Unrecognized event type");
2129 /** Read error input from \a iauth.
2130 * @param[in] iauth Readable connection.
2132 static void iauth_read_stderr(struct IAuth *iauth)
2134 static char readbuf[SERVER_TCP_WINDOW];
2135 unsigned int length, count;
2139 /* Copy partial data to readbuf, append new data. */
2140 length = iauth->i_errcount;
2141 memcpy(readbuf, iauth->i_errbuf, length);
2142 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2144 sizeof(readbuf) - length - 1,
2147 readbuf[length += count] = '\0';
2149 /* Send each complete line to SNO_AUTH. */
2150 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2152 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2154 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2155 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2156 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2159 /* Put unused data back into connection's buffer. */
2160 iauth->i_errcount = strlen(sol);
2161 if (iauth->i_errcount > BUFSIZE)
2162 iauth->i_errcount = BUFSIZE;
2163 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2166 /** Handle error socket activity for an %IAuth connection.
2167 * @param[in] ev &Socket event; the IAuth connection is the user data
2168 * pointer for the socket.
2170 static void iauth_stderr_callback(struct Event *ev)
2172 struct IAuth *iauth;
2174 assert(0 != ev_socket(ev));
2175 iauth = (struct IAuth*) s_data(ev_socket(ev));
2178 switch (ev_type(ev)) {
2180 /* We do not restart iauth here: the stdout handler does that for us. */
2183 iauth_read_stderr(iauth);
2186 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2187 /* and fall through to the ET_EOF case */
2189 iauth_disconnect(iauth);
2192 assert(0 && "Unrecognized event type");
2197 /** Report active iauth's configuration to \a cptr.
2198 * @param[in] cptr Client requesting statistics.
2199 * @param[in] sd Stats descriptor for request.
2200 * @param[in] param Extra parameter from user (may be NULL).
2202 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2206 if (iauth) for (link = iauth->i_config; link; link = link->next)
2208 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2213 /** Report active iauth's statistics to \a cptr.
2214 * @param[in] cptr Client requesting statistics.
2215 * @param[in] sd Stats descriptor for request.
2216 * @param[in] param Extra parameter from user (may be NULL).
2218 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2222 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2224 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",