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 */
89 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
91 /** Stores registration state of a client. */
93 struct AuthRequest* next; /**< linked list node ptr */
94 struct AuthRequest* prev; /**< linked list node ptr */
95 struct Client* client; /**< pointer to client struct for request */
96 struct irc_sockaddr local; /**< local endpoint address */
97 struct irc_in_addr original; /**< original client IP address */
98 struct Socket socket; /**< socket descriptor for auth queries */
99 struct Timer timeout; /**< timeout timer for ident and dns queries */
100 struct AuthRequestFlags flags; /**< current state of request */
101 unsigned int cookie; /**< cookie the user must PONG */
102 unsigned short port; /**< client's remote port number */
105 /** Array of message text (with length) pairs for AUTH status
106 * messages. Indexed using #ReportType.
111 } HeaderMessages [] = {
112 #define MSG(STR) { STR, sizeof(STR) - 1 }
113 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
114 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
115 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
116 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
117 MSG("NOTICE AUTH :*** Got ident response\r\n"),
118 MSG("NOTICE AUTH :*** No ident response\r\n"),
119 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
120 "ignoring hostname.\r\n"),
121 MSG("NOTICE AUTH :*** Invalid hostname\r\n")
125 /** Enum used to index messages in the HeaderMessages[] array. */
137 /** Sends response \a r (from #ReportType) to client \a c. */
138 #define sendheader(c, r) \
139 send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
141 /** Enumeration of IAuth connection flags. */
144 IAUTH_BLOCKED, /**< socket buffer full */
145 IAUTH_CLOSING, /**< candidate to be disposed */
146 /* The following flags are controlled by iauth's "O" options command. */
147 IAUTH_ADDLINFO, /**< Send additional info
148 * (password and username). */
149 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
150 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
151 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
152 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
153 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
154 IAUTH_LAST_FLAG /**< total number of flags */
156 /** Declare a bitset structure indexed by IAuthFlag. */
157 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
159 /** Describes state of an IAuth connection. */
161 struct MsgQ i_sendQ; /**< messages queued to send */
162 struct Socket i_socket; /**< main socket to iauth */
163 struct Socket i_stderr; /**< error socket for iauth */
164 struct IAuthFlags i_flags; /**< connection state/status/flags */
165 uint64_t i_recvB; /**< bytes received */
166 uint64_t i_sendB; /**< bytes sent */
167 time_t started; /**< time that this instance was started */
168 unsigned int i_recvM; /**< messages received */
169 unsigned int i_sendM; /**< messages sent */
170 unsigned int i_count; /**< characters used in i_buffer */
171 unsigned int i_errcount; /**< characters used in i_errbuf */
172 int i_debug; /**< debug level */
173 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
174 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
175 char *i_version; /**< iauth version string */
176 struct SLink *i_config; /**< configuration string list */
177 struct SLink *i_stats; /**< statistics string list */
178 char **i_argv; /**< argument list */
181 /** Return whether flag \a flag is set on \a iauth. */
182 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
183 /** Set flag \a flag on \a iauth. */
184 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
185 /** Clear flag \a flag from \a iauth. */
186 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
187 /** Get connected flag for \a iauth. */
188 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
190 /** Return socket event generator for \a iauth. */
191 #define i_socket(iauth) (&(iauth)->i_socket)
192 /** Return stderr socket for \a iauth. */
193 #define i_stderr(iauth) (&(iauth)->i_stderr)
194 /** Return outbound message queue for \a iauth. */
195 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
196 /** Return debug level for \a iauth. */
197 #define i_debug(iauth) ((iauth)->i_debug)
199 /** Active instance of IAuth. */
202 static void iauth_sock_callback(struct Event *ev);
203 static void iauth_stderr_callback(struct Event *ev);
204 static int sendto_iauth(struct Client *cptr, const char *format, ...);
205 static int preregister_user(struct Client *cptr);
206 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
207 int parc, char **params);
209 /** Set username for user associated with \a auth.
210 * @param[in] auth Client authorization request to work on.
211 * @return Zero if client is kept, CPTR_KILLED if client rejected.
213 static int auth_set_username(struct AuthRequest *auth)
215 struct Client *sptr = auth->client;
216 struct User *user = cli_user(sptr);
227 short digitgroups = 0;
231 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
233 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
237 /* Copy username from source to destination. Since they may be the
238 * same, and we may prefix with a '~', use a buffer character (ch)
239 * to hold the next character to copy.
241 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
244 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
249 while (last && !IsCntrl(last) && rlen--)
252 *d++ = IsUserChar(last) ? last : '_';
253 last = (ch != '~') ? ch : '_';
258 /* If username is empty or just ~, reject. */
259 if ((user->username[0] == '\0')
260 || ((user->username[0] == '~') && (user->username[1] == '\0')))
261 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
263 /* Check for K- or G-line. */
264 killreason = find_kill(sptr);
266 ServerStats->is_ref++;
267 return exit_client(sptr, sptr, &me,
268 (killreason == -1 ? "K-lined" : "G-lined"));
271 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
273 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
274 * Explanations of rules moved to where it is checked Entrope 2-06
276 s = d = user->username + (user->username[0] == '~');
285 else if (IsUpper(ch))
288 /* Accept caps as leading if we haven't seen lower case or digits yet. */
289 if ((leadcaps || pos == 0) && !lower && !digits)
292 else if (IsDigit(ch))
295 if (pos == 0 || !IsDigit(last))
298 /* If more than two groups of digits, reject. */
303 else if (ch == '-' || ch == '_' || ch == '.')
306 /* If -_. exist at start, consecutively, or more than twice, reject. */
307 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
310 else /* All other punctuation is rejected. */
314 /* If mixed case, first must be capital, but no more than three;
315 * but if three capitals, they must all be leading. */
316 if (lower && upper && (!leadcaps || leadcaps > 3 ||
317 (upper > 2 && upper > leadcaps)))
319 /* If two different groups of digits, one must be either at the
321 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
323 /* Must have at least one letter. */
324 if (!lower && !upper)
326 /* Final character must not be punctuation. */
334 /* If we confirmed their username, and it is what they claimed,
336 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
339 ServerStats->is_ref++;
340 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
341 ":Your username is invalid.");
342 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
343 ":Connect with your real username, in lowercase.");
344 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
345 ":If your mail address were foo@bar.com, your username "
347 return exit_client(sptr, sptr, &me, "USER: Bad username");
350 /** Check whether an authorization request is complete.
351 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
352 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
353 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
354 * destroy \a auth, clear the password, set the username, and register
356 * @param[in] auth Authorization request to check.
357 * @param[in] send_reports Passed to destroy_auth_request() if \a auth
359 * @return Zero if client is kept, CPTR_KILLED if client rejected.
361 static int check_auth_finished(struct AuthRequest *auth, int send_reports)
363 enum AuthRequestFlag flag;
366 /* Check non-iauth registration blocking flags. */
367 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
368 if (FlagHas(&auth->flags, flag))
370 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
371 cli_fd(auth->client), flag));
375 /* If appropriate, do preliminary assignment to connection class. */
376 if (IsUserPort(auth->client)
377 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
378 && preregister_user(auth->client))
381 /* Check if iauth is done. */
382 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
384 /* Switch auth request to hurry-up state. */
385 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
387 struct ConfItem* aconf;
389 /* Set "hurry" flag in auth request. */
390 FlagSet(&auth->flags, AR_IAUTH_HURRY);
392 /* Check password now (to avoid challenge/response conflicts). */
393 aconf = cli_confs(auth->client)->value.aconf;
394 if (!EmptyString(aconf->passwd)
395 && strcmp(cli_passwd(auth->client), aconf->passwd))
397 ServerStats->is_ref++;
398 send_reply(auth->client, ERR_PASSWDMISMATCH);
399 return exit_client(auth->client, auth->client, &me, "Bad Password");
402 /* If iauth wants it, send notification. */
403 if (IAuthHas(iauth, IAUTH_UNDERNET))
404 sendto_iauth(auth->client, "H %s", ConfClass(aconf));
406 /* If iauth wants it, give client more time. */
407 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
408 cli_firsttime(auth->client) = CurrentTime;
411 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
412 cli_fd(auth->client), AR_IAUTH_PENDING));
416 FlagSet(&auth->flags, AR_IAUTH_HURRY);
418 destroy_auth_request(auth, send_reports);
419 if (!IsUserPort(auth->client))
421 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
422 res = auth_set_username(auth);
424 res = register_user(auth->client, auth->client);
428 /** Verify that a hostname is valid, i.e., only contains characters
429 * valid for a hostname and that a hostname is not too long.
430 * @param host Hostname to check.
431 * @param maxlen Maximum length of hostname, not including NUL terminator.
432 * @return Non-zero if the hostname is valid.
435 auth_verify_hostname(const char *host, int maxlen)
439 /* Walk through the host name */
440 for (i = 0; host[i]; i++)
441 /* If it's not a hostname character or if it's too long, return false */
442 if (!IsHostChar(host[i]) || i >= maxlen)
445 return 1; /* it's a valid hostname */
448 /** Assign a client to a connection class.
449 * @param[in] cptr Client to assign to a class.
450 * @return Zero if client is kept, CPTR_KILLED if rejected.
452 static int preregister_user(struct Client *cptr)
454 static time_t last_too_many1;
455 static time_t last_too_many2;
457 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
458 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
460 switch (conf_check_client(cptr))
464 case ACR_NO_AUTHORIZATION:
465 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
466 get_client_name(cptr, HIDE_IP));
467 ++ServerStats->is_ref;
468 return exit_client(cptr, cptr, &me,
469 "No Authorization - use another server");
470 case ACR_TOO_MANY_IN_CLASS:
471 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
472 "Too many connections in class %s for %s.",
473 get_client_class(cptr),
474 get_client_name(cptr, SHOW_IP));
475 ++ServerStats->is_ref;
476 return exit_client(cptr, cptr, &me,
477 "Sorry, your connection class is full - try "
478 "again later or try another server");
479 case ACR_TOO_MANY_FROM_IP:
480 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
481 "Too many connections from same IP for %s.",
482 get_client_name(cptr, SHOW_IP));
483 ++ServerStats->is_ref;
484 return exit_client(cptr, cptr, &me,
485 "Too many connections from your host");
486 case ACR_ALREADY_AUTHORIZED:
487 /* Can this ever happen? */
489 ++ServerStats->is_ref;
490 IPcheck_connect_fail(cptr);
491 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
496 /** Send the ident server a query giving "theirport , ourport". The
497 * write is only attempted *once* so it is deemed to be a fail if the
498 * entire write doesn't write all the data given. This shouldn't be a
499 * problem since the socket should have a write buffer far greater
500 * than this message to store it in should problems arise. -avalon
501 * @param[in] auth The request to send.
503 static void send_auth_query(struct AuthRequest* auth)
510 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
511 auth->port, auth->local.port);
513 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
514 close(s_fd(&auth->socket));
515 socket_del(&auth->socket);
516 s_fd(&auth->socket) = -1;
517 ++ServerStats->is_abad;
518 if (IsUserPort(auth->client))
519 sendheader(auth->client, REPORT_FAIL_ID);
520 FlagClr(&auth->flags, AR_AUTH_PENDING);
521 check_auth_finished(auth, 0);
525 /** Enum used to index ident reply fields in a human-readable way. */
526 enum IdentReplyFields {
534 /** Parse an ident reply line and extract the userid from it.
535 * @param[in] reply The ident reply line.
536 * @return The userid, or NULL on parse failure.
538 static char* check_ident_reply(char* reply)
542 char* vector[USERID_TOKEN_COUNT];
543 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
545 if (USERID_TOKEN_COUNT != count)
548 * second token is the reply type
550 token = vector[IDENT_REPLY_TYPE];
551 if (EmptyString(token))
554 while (IsSpace(*token))
557 if (0 != strncmp(token, "USERID", 6))
561 * third token is the os type
563 token = vector[IDENT_OS_TYPE];
564 if (EmptyString(token))
566 while (IsSpace(*token))
570 * Unless "OTHER" is specified as the operating system
571 * type, the server is expected to return the "normal"
572 * user identification of the owner of this connection.
573 * "Normal" in this context may be taken to mean a string
574 * of characters which uniquely identifies the connection
575 * owner such as a user identifier assigned by the system
576 * administrator and used by such user as a mail
577 * identifier, or as the "user" part of a user/password
578 * pair used to gain access to system resources. When an
579 * operating system is specified (e.g., anything but
580 * "OTHER"), the user identifier is expected to be in a
581 * more or less immediately useful form - e.g., something
582 * that could be used as an argument to "finger" or as a
585 if (0 == strncmp(token, "OTHER", 5))
588 * fourth token is the username
590 token = vector[IDENT_INFO];
591 if (EmptyString(token))
593 while (IsSpace(*token))
596 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
598 for (end = token; *end; ++end) {
599 if (IsSpace(*end) || '@' == *end || ':' == *end)
606 /** Read the reply (if any) from the ident server we connected to. We
607 * only give it one shot, if the reply isn't good the first time fail
608 * the authentication entirely. --Bleep
609 * @param[in] auth The request to read.
611 static void read_auth_reply(struct AuthRequest* auth)
616 * rfc1453 sez we MUST accept 512 bytes
618 char buf[BUFSIZE + 1];
621 assert(0 != auth->client);
622 assert(auth == cli_auth(auth->client));
624 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
626 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
627 username = check_ident_reply(buf);
628 Debug((DEBUG_INFO, "Username: %s", username));
631 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
632 close(s_fd(&auth->socket));
633 socket_del(&auth->socket);
634 s_fd(&auth->socket) = -1;
636 if (EmptyString(username)) {
637 if (IsUserPort(auth->client))
638 sendheader(auth->client, REPORT_FAIL_ID);
639 ++ServerStats->is_abad;
641 if (IsUserPort(auth->client))
642 sendheader(auth->client, REPORT_FIN_ID);
643 ++ServerStats->is_asuc;
644 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
645 ircd_strncpy(cli_username(auth->client), username, USERLEN);
646 SetGotId(auth->client);
648 if (IAuthHas(iauth, IAUTH_UNDERNET))
649 sendto_iauth(auth->client, "u %s", username);
652 FlagClr(&auth->flags, AR_AUTH_PENDING);
653 check_auth_finished(auth, 0);
656 /** Handle socket I/O activity.
657 * @param[in] ev A socket event whos associated data is the active
658 * struct AuthRequest.
660 static void auth_sock_callback(struct Event* ev)
662 struct AuthRequest* auth;
664 assert(0 != ev_socket(ev));
665 assert(0 != s_data(ev_socket(ev)));
667 auth = (struct AuthRequest*) s_data(ev_socket(ev));
669 switch (ev_type(ev)) {
670 case ET_DESTROY: /* being destroyed */
673 case ET_CONNECT: /* socket connection completed */
674 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
675 auth, cli_fd(auth->client)));
676 socket_state(&auth->socket, SS_CONNECTED);
677 send_auth_query(auth);
680 case ET_READ: /* socket is readable */
681 case ET_EOF: /* end of file on socket */
682 case ET_ERROR: /* error on socket */
683 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
684 read_auth_reply(auth);
688 assert(0 && "Unrecognized event in auth_socket_callback().");
693 /** Stop an auth request completely.
694 * @param[in] auth The struct AuthRequest to cancel.
695 * @param[in] send_reports If non-zero, report the failure to the user.
697 void destroy_auth_request(struct AuthRequest* auth, int send_reports)
699 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
701 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
702 if (send_reports && IsUserPort(auth->client))
703 sendheader(auth->client, REPORT_FAIL_ID);
706 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
707 delete_resolver_queries(auth);
708 if (send_reports && IsUserPort(auth->client))
709 sendheader(auth->client, REPORT_FAIL_DNS);
712 if (-1 < s_fd(&auth->socket)) {
713 close(s_fd(&auth->socket));
714 socket_del(&auth->socket);
715 s_fd(&auth->socket) = -1;
718 if (t_active(&auth->timeout))
719 timer_del(&auth->timeout);
720 cli_auth(auth->client) = NULL;
723 /** Timeout a given auth request.
724 * @param[in] ev A timer event whose associated data is the expired
725 * struct AuthRequest.
727 static void auth_timeout_callback(struct Event* ev)
729 struct AuthRequest* auth;
731 assert(0 != ev_timer(ev));
732 assert(0 != t_data(ev_timer(ev)));
734 auth = (struct AuthRequest*) t_data(ev_timer(ev));
736 if (ev_type(ev) == ET_EXPIRE) {
737 /* Report the timeout in the log. */
738 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
739 get_client_name(auth->client, HIDE_IP));
740 /* Tell iauth if we will let the client on. */
741 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)
742 && !IAuthHas(iauth, IAUTH_REQUIRED))
744 sendto_iauth(auth->client, "T");
745 FlagClr(&auth->flags , AR_IAUTH_PENDING);
747 /* Try to register the client. */
748 check_auth_finished(auth, 1);
752 /** Handle a complete DNS lookup. Send the client on it's way to a
753 * connection completion, regardless of success or failure -- unless
754 * there was a mismatch and KILL_IPMISMATCH is set.
755 * @param[in] vptr The pending struct AuthRequest.
756 * @param[in] addr IP address being resolved.
757 * @param[in] h_name Resolved name, or NULL if lookup failed.
759 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
761 struct AuthRequest* auth = (struct AuthRequest*) vptr;
764 FlagClr(&auth->flags, AR_DNS_PENDING);
766 /* DNS entry was missing for the IP. */
767 if (IsUserPort(auth->client))
768 sendheader(auth->client, REPORT_FAIL_DNS);
769 sendto_iauth(auth->client, "d");
770 } else if (irc_in_addr_cmp(addr, &cli_ip(auth->client))
771 && irc_in_addr_cmp(addr, &auth->original)) {
772 /* IP for hostname did not match client's IP. */
773 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
774 cli_sock_ip(auth->client), h_name,
776 if (IsUserPort(auth->client))
777 sendheader(auth->client, REPORT_IP_MISMATCH);
778 /* Clear DNS pending flag so free_client doesn't ask the resolver
779 * to delete the query that just finished.
781 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
782 IPcheck_disconnect(auth->client);
783 Count_unknowndisconnects(UserStats);
784 free_client(auth->client);
786 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
787 /* Hostname did not look valid. */
788 if (IsUserPort(auth->client))
789 sendheader(auth->client, REPORT_INVAL_DNS);
790 sendto_iauth(auth->client, "d");
792 /* Hostname and mappings checked out. */
793 if (IsUserPort(auth->client))
794 sendheader(auth->client, REPORT_FIN_DNS);
795 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
796 sendto_iauth(auth->client, "N %s", h_name);
798 check_auth_finished(auth, 0);
801 /** Flag the client to show an attempt to contact the ident server on
802 * the client's host. Should the connect or any later phase of the
803 * identifying process fail, it is aborted and the user is given a
804 * username of "unknown".
805 * @param[in] auth The request for which to start the ident lookup.
807 static void start_auth_query(struct AuthRequest* auth)
809 struct irc_sockaddr remote_addr;
810 struct irc_sockaddr local_addr;
815 assert(0 != auth->client);
818 * get the local address of the client and bind to that to
819 * make the auth request. This used to be done only for
820 * ifdef VIRTUAL_HOST, but needs to be done for all clients
821 * since the ident request must originate from that same address--
822 * and machines with multiple IP addresses are common now
824 memcpy(&local_addr, &auth->local, sizeof(local_addr));
826 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
827 remote_addr.port = 113;
828 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
830 ++ServerStats->is_abad;
831 if (IsUserPort(auth->client))
832 sendheader(auth->client, REPORT_FAIL_ID);
835 if (IsUserPort(auth->client))
836 sendheader(auth->client, REPORT_DO_ID);
838 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
839 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
840 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
841 SOCK_EVENT_READABLE, fd)) {
842 ++ServerStats->is_abad;
843 if (IsUserPort(auth->client))
844 sendheader(auth->client, REPORT_FAIL_ID);
849 FlagSet(&auth->flags, AR_AUTH_PENDING);
850 if (result == IO_SUCCESS)
851 send_auth_query(auth);
854 /** Initiate DNS lookup for a client.
855 * @param[in] auth The auth request for which to start the DNS lookup.
857 static void start_dns_query(struct AuthRequest *auth)
859 if (feature_bool(FEAT_NODNS)) {
860 sendto_iauth(auth->client, "d");
864 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
865 strcpy(cli_sockhost(auth->client), cli_name(&me));
866 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
870 if (IsUserPort(auth->client))
871 sendheader(auth->client, REPORT_DO_DNS);
873 FlagSet(&auth->flags, AR_DNS_PENDING);
874 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
877 /** Initiate IAuth check for a client.
878 * @param[in] auth The auth request for which to star the IAuth check.
880 static void start_iauth_query(struct AuthRequest *auth)
882 FlagSet(&auth->flags, AR_IAUTH_PENDING);
883 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
884 cli_sock_ip(auth->client), auth->port,
885 ircd_ntoa(&auth->local.addr), auth->local.port))
886 FlagClr(&auth->flags, AR_IAUTH_PENDING);
889 /** Starts auth (identd) and dns queries for a client.
890 * @param[in] client The client for which to start queries.
892 void start_auth(struct Client* client)
894 struct irc_sockaddr remote;
895 struct AuthRequest* auth;
898 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
900 /* Register with event handlers. */
901 cli_lasttime(client) = CurrentTime;
902 cli_since(client) = CurrentTime;
903 if (cli_fd(client) > HighestFd)
904 HighestFd = cli_fd(client);
905 LocalClientArray[cli_fd(client)] = client;
906 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
908 /* Allocate the AuthRequest. */
909 auth = MyCalloc(1, sizeof(*auth));
911 auth->client = client;
912 cli_auth(client) = auth;
913 s_fd(&auth->socket) = -1;
914 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
915 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
917 /* Try to get socket endpoint addresses. */
918 if (!os_get_sockname(cli_fd(client), &auth->local)
919 || !os_get_peername(cli_fd(client), &remote)) {
920 ++ServerStats->is_abad;
921 if (IsUserPort(auth->client))
922 sendheader(auth->client, REPORT_FAIL_ID);
923 IPcheck_disconnect(auth->client);
924 Count_unknowndisconnects(UserStats);
925 free_client(auth->client);
928 auth->port = remote.port;
930 /* Try to start DNS lookup. */
931 start_dns_query(auth);
933 /* Try to start ident lookup. */
934 start_auth_query(auth);
936 /* Set required client inputs for users. */
937 if (IsUserPort(client)) {
938 cli_user(client) = make_user(client);
939 cli_user(client)->server = &me;
940 FlagSet(&auth->flags, AR_NEEDS_USER);
941 FlagSet(&auth->flags, AR_NEEDS_NICK);
943 /* Try to start iauth lookup. */
944 start_iauth_query(auth);
947 /* Add client to GlobalClientList. */
948 add_client_to_list(client);
950 /* Check which auth events remain pending. */
951 check_auth_finished(auth, 0);
954 /** Mark that a user has PONGed while unregistered.
955 * @param[in] auth Authorization request for client.
956 * @param[in] cookie PONG cookie value sent by client.
957 * @return Zero if client should be kept, CPTR_KILLED if rejected.
959 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
961 assert(auth != NULL);
962 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
964 if (cookie != auth->cookie)
966 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
967 ":To connect, type /QUOTE PONG %u", auth->cookie);
970 FlagClr(&auth->flags, AR_NEEDS_PONG);
971 return check_auth_finished(auth, 0);
974 /** Record a user's claimed username and userinfo.
975 * @param[in] auth Authorization request for client.
976 * @param[in] username Client's asserted username.
977 * @param[in] userinfo Client's asserted self-description.
978 * @return Zero if client should be kept, CPTR_KILLED if rejected.
980 int auth_set_user(struct AuthRequest *auth, const char *username, const char *userinfo)
984 assert(auth != NULL);
985 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
987 FlagClr(&auth->flags, AR_NEEDS_USER);
989 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
990 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
991 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
992 if (IAuthHas(iauth, IAUTH_UNDERNET))
993 sendto_iauth(cptr, "U %s :%s", username, userinfo);
994 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
995 sendto_iauth(cptr, "U %s", username);
996 return check_auth_finished(auth, 0);
999 /** Handle authorization-related aspects of initial nickname selection.
1000 * This is called after verifying that the nickname is available.
1001 * @param[in] auth Authorization request for client.
1002 * @param[in] nickname Client's requested nickname.
1003 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1005 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1007 assert(auth != NULL);
1008 FlagClr(&auth->flags, AR_NEEDS_NICK);
1010 * If the client hasn't gotten a cookie-ping yet,
1011 * choose a cookie and send it. -record!jegelhof@cloud9.net
1013 if (!auth->cookie) {
1015 auth->cookie = ircrandom();
1016 } while (!auth->cookie);
1017 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1018 FlagSet(&auth->flags, AR_NEEDS_PONG);
1020 if (IAuthHas(iauth, IAUTH_UNDERNET))
1021 sendto_iauth(auth->client, "n %s", nickname);
1022 return check_auth_finished(auth, 0);
1025 /** Record a user's password.
1026 * @param[in] auth Authorization request for client.
1027 * @param[in] password Client's password.
1028 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1030 int auth_set_password(struct AuthRequest *auth, const char *password)
1032 assert(auth != NULL);
1033 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1034 sendto_iauth(auth->client, "P :%s", password);
1038 /** Send exit notification for \a cptr to iauth.
1039 * @param[in] cptr Client who is exiting.
1041 void auth_send_exit(struct Client *cptr)
1043 sendto_iauth(cptr, "D");
1046 /** Mark that a user has started capabilities negotiation.
1047 * This blocks authorization until auth_cap_done() is called.
1048 * @param[in] auth Authorization request for client.
1049 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1051 int auth_cap_start(struct AuthRequest *auth)
1053 assert(auth != NULL);
1054 FlagSet(&auth->flags, AR_CAP_PENDING);
1058 /** Mark that a user has completed capabilities negotiation.
1059 * This unblocks authorization if auth_cap_start() was called.
1060 * @param[in] auth Authorization request for client.
1061 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1063 int auth_cap_done(struct AuthRequest *auth)
1065 assert(auth != NULL);
1066 FlagClr(&auth->flags, AR_CAP_PENDING);
1067 return check_auth_finished(auth, 0);
1070 /** Attempt to spawn the process for an IAuth instance.
1071 * @param[in] iauth IAuth descriptor.
1072 * @param[in] automatic If non-zero, apply sanity checks against
1073 * excessive automatic restarts.
1074 * @return 0 on success, non-zero on failure.
1076 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1083 if (automatic && CurrentTime - iauth->started < 5)
1085 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1089 /* Record time we tried to spawn the iauth process. */
1090 iauth->started = CurrentTime;
1092 /* Attempt to allocate a pair of sockets. */
1093 res = os_socketpair(s_io);
1097 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1098 res = os_set_nonblocking(s_io[0]);
1106 /* Initialize the socket structure to talk to the child. */
1107 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1108 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1116 /* Allocate another pair for stderr. */
1117 res = os_socketpair(s_err);
1120 socket_del(i_socket(iauth));
1126 /* Mark parent side of this pair non-blocking, too. */
1127 res = os_set_nonblocking(s_err[0]);
1132 socket_del(i_socket(iauth));
1138 /* And set up i_stderr(iauth). */
1139 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1140 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1145 socket_del(i_socket(iauth));
1151 /* Attempt to fork a child process. */
1154 /* Error forking the child, still in parent. */
1156 socket_del(i_stderr(iauth));
1159 socket_del(i_socket(iauth));
1166 /* We are the parent process. Close the child's sockets. */
1169 /* Send our server name (supposedly for proxy checking purposes)
1170 * and maximum number of connections (for allocation hints).
1171 * Need to use conf_get_local() since &me may not be fully
1172 * initialized the first time we run.
1174 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1175 /* Indicate success (until the child dies). */
1179 /* We are the child process.
1180 * Duplicate our end of the socket to stdin, stdout and stderr.
1181 * Then close all the higher-numbered FDs and exec the process.
1183 if (dup2(s_io[1], 0) == 0
1184 && dup2(s_io[1], 1) == 1
1185 && dup2(s_err[1], 2) == 2) {
1186 close_connections(0);
1187 execvp(iauth->i_argv[0], iauth->i_argv);
1190 /* If we got here, something was seriously wrong. */
1194 /** See if an %IAuth program must be spawned.
1195 * If a process is already running with the specified options, keep it.
1196 * Otherwise spawn a new child process to perform the %IAuth function.
1197 * @param[in] argc Number of parameters to use when starting process.
1198 * @param[in] argv Array of parameters to start process.
1199 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1201 int auth_spawn(int argc, char *argv[])
1208 /* Check that incoming arguments all match pre-existing arguments. */
1209 for (ii = 0; same && (ii < argc); ++ii) {
1210 if (NULL == iauth->i_argv[ii]
1211 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1214 /* Check that we have no more pre-existing arguments. */
1215 if (iauth->i_argv[ii])
1217 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1218 if (same && i_GetConnected(iauth)) {
1219 IAuthClr(iauth, IAUTH_CLOSING);
1222 /* Deallocate old argv elements. */
1223 for (ii = 0; iauth->i_argv[ii]; ++ii)
1224 MyFree(iauth->i_argv[ii]);
1225 MyFree(iauth->i_argv);
1228 /* Need to initialize a new connection. */
1229 iauth = MyCalloc(1, sizeof(*iauth));
1230 msgq_init(i_sendQ(iauth));
1231 /* Populate iauth's argv array. */
1232 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1233 for (ii = 0; ii < argc; ++ii)
1234 DupString(iauth->i_argv[ii], argv[ii]);
1235 iauth->i_argv[ii] = NULL;
1236 /* Try to spawn it, and handle the results. */
1237 if (iauth_do_spawn(iauth, 0))
1239 IAuthClr(iauth, IAUTH_CLOSING);
1243 /** Mark all %IAuth connections as closing. */
1244 void auth_mark_closing(void)
1247 IAuthSet(iauth, IAUTH_CLOSING);
1250 /** Complete disconnection of an %IAuth connection.
1251 * @param[in] iauth %Connection to fully close.
1253 static void iauth_disconnect(struct IAuth *iauth)
1255 if (!i_GetConnected(iauth))
1258 /* Close main socket. */
1259 close(s_fd(i_socket(iauth)));
1260 socket_del(i_socket(iauth));
1261 s_fd(i_socket(iauth)) = -1;
1263 /* Close error socket. */
1264 close(s_fd(i_stderr(iauth)));
1265 socket_del(i_stderr(iauth));
1266 s_fd(i_stderr(iauth)) = -1;
1269 /** Close all %IAuth connections marked as closing. */
1270 void auth_close_unused(void)
1272 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1274 iauth_disconnect(iauth);
1275 if (iauth->i_argv) {
1276 for (ii = 0; iauth->i_argv[ii]; ++ii)
1277 MyFree(iauth->i_argv[ii]);
1278 MyFree(iauth->i_argv);
1284 /** Send queued output to \a iauth.
1285 * @param[in] iauth Writable connection with queued data.
1287 static void iauth_write(struct IAuth *iauth)
1289 unsigned int bytes_tried, bytes_sent;
1292 if (IAuthHas(iauth, IAUTH_BLOCKED))
1294 while (MsgQLength(i_sendQ(iauth)) > 0) {
1295 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1298 msgq_delete(i_sendQ(iauth), bytes_sent);
1299 iauth->i_sendB += bytes_sent;
1300 if (bytes_tried == bytes_sent)
1302 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1304 IAuthSet(iauth, IAUTH_BLOCKED);
1305 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1308 iauth_disconnect(iauth);
1312 /* We were able to flush all events, so remove notification. */
1313 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1316 /** Send a message to iauth.
1317 * @param[in] cptr Optional client context for message.
1318 * @param[in] format Format string for message.
1319 * @return Non-zero on successful send or buffering, zero on failure.
1321 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1326 /* Do not send requests when we have no iauth. */
1327 if (!i_GetConnected(iauth))
1329 /* Do not send for clients in the NORMAL state. */
1331 && (format[0] != 'D')
1332 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1335 /* Build the message buffer. */
1336 vd.vd_format = format;
1337 va_start(vd.vd_args, format);
1339 mb = msgq_make(NULL, "-1 %v", &vd);
1341 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1344 /* Tack it onto the iauth sendq and try to write it. */
1346 msgq_add(i_sendQ(iauth), mb, 0);
1351 /** Send text to interested operators (SNO_AUTH server notice).
1352 * @param[in] iauth Active IAuth session.
1353 * @param[in] cli Client referenced by command.
1354 * @param[in] parc Number of parameters (1).
1355 * @param[in] params Text to send.
1358 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1359 int parc, char **params)
1361 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1365 /** Set the debug level for the session.
1366 * @param[in] iauth Active IAuth session.
1367 * @param[in] cli Client referenced by command.
1368 * @param[in] parc Number of parameters (1).
1369 * @param[in] params String starting with an integer.
1372 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1373 int parc, char **params)
1377 new_level = parc > 0 ? atoi(params[0]) : 0;
1378 if (i_debug(iauth) > 0 || new_level > 0) {
1379 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1380 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1382 i_debug(iauth) = new_level;
1386 /** Set policy options for the session.
1387 * Old policy is forgotten, and any of the following characters in \a
1388 * params enable the corresponding policy:
1389 * \li A IAUTH_ADDLINFO
1390 * \li R IAUTH_REQUIRED
1391 * \li T IAUTH_TIMEOUT
1392 * \li W IAUTH_EXTRAWAIT
1393 * \li U IAUTH_UNDERNET
1395 * @param[in] iauth Active IAuth session.
1396 * @param[in] cli Client referenced by command.
1397 * @param[in] parc Number of parameters (1).
1398 * @param[in] params Zero or more policy options.
1401 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1402 int parc, char **params)
1404 enum IAuthFlag flag;
1407 /* Erase old policy first. */
1408 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1409 IAuthClr(iauth, flag);
1411 if (parc > 0) /* only try to parse if we were given a policy string */
1412 /* Parse new policy set. */
1413 for (p = params[0]; *p; p++) switch (*p) {
1414 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1415 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1416 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1417 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1418 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1421 /* Optionally notify operators. */
1422 if (i_debug(iauth) > 0)
1423 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1427 /** Set the iauth program version number.
1428 * @param[in] iauth Active IAuth session.
1429 * @param[in] cli Client referenced by command.
1430 * @param[in] parc Number of parameters (1).
1431 * @param[in] params Version number or name.
1434 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1435 int parc, char **params)
1437 MyFree(iauth->i_version);
1438 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1439 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1444 /** Paste a parameter list together into a single string.
1445 * @param[in] parc Number of parameters.
1446 * @param[in] params Parameter list to paste together.
1447 * @return Pasted parameter list.
1449 static char *paste_params(int parc, char **params)
1452 int len = 0, lengths[MAXPARA], i;
1454 /* Compute the length... */
1455 for (i = 0; i < parc; i++)
1456 len += lengths[i] = strlen(params[i]);
1458 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1459 * sentinel, and the trailing \0
1461 str = MyMalloc(len + parc + 1);
1463 /* Build the pasted string */
1464 for (tmp = str, i = 0; i < parc; i++) {
1465 if (i) /* add space separator... */
1467 if (i == parc - 1) /* add colon sentinel */
1470 /* Copy string component... */
1471 memcpy(tmp, params[i], lengths[i]);
1472 tmp += lengths[i]; /* move to end of string */
1475 /* terminate the string... */
1478 return str; /* return the pasted string */
1481 /** Clear cached iauth configuration information.
1482 * @param[in] iauth Active IAuth session.
1483 * @param[in] cli Client referenced by command.
1484 * @param[in] parc Number of parameters (0).
1485 * @param[in] params Parameter list (ignored).
1488 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1489 int parc, char **params)
1494 head = iauth->i_config;
1495 iauth->i_config = NULL;
1496 for (; head; head = next) {
1498 MyFree(head->value.cp);
1501 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1505 /** Append iauth configuration information.
1506 * @param[in] iauth Active IAuth session.
1507 * @param[in] cli Client referenced by command.
1508 * @param[in] parc Number of parameters.
1509 * @param[in] params Description of configuration element.
1512 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1513 int parc, char **params)
1517 if (iauth->i_config) {
1518 for (node = iauth->i_config; node->next; node = node->next) ;
1519 node = node->next = make_link();
1521 node = iauth->i_config = make_link();
1523 node->value.cp = paste_params(parc, params);
1524 node->next = 0; /* must be explicitly cleared */
1528 /** Clear cached iauth configuration information.
1529 * @param[in] iauth Active IAuth session.
1530 * @param[in] cli Client referenced by command.
1531 * @param[in] parc Number of parameters (0).
1532 * @param[in] params Parameter list (ignored).
1535 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1536 int parc, char **params)
1541 head = iauth->i_stats;
1542 iauth->i_stats = NULL;
1543 for (; head; head = next) {
1545 MyFree(head->value.cp);
1548 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1552 /** Append iauth statistics information.
1553 * @param[in] iauth Active IAuth session.
1554 * @param[in] cli Client referenced by command.
1555 * @param[in] parc Number of parameters.
1556 * @param[in] params Statistics element.
1559 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1560 int parc, char **params)
1563 if (iauth->i_stats) {
1564 for (node = iauth->i_stats; node->next; node = node->next) ;
1565 node = node->next = make_link();
1567 node = iauth->i_stats = make_link();
1569 node->value.cp = paste_params(parc, params);
1570 node->next = 0; /* must be explicitly cleared */
1574 /** Set client's username to a trusted string even if it breaks the rules.
1575 * @param[in] iauth Active IAuth session.
1576 * @param[in] cli Client referenced by command.
1577 * @param[in] parc Number of parameters (1).
1578 * @param[in] params Forced username.
1581 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1582 int parc, char **params)
1584 assert(cli_auth(cli) != NULL);
1585 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1586 if (!EmptyString(params[0])) {
1587 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1589 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1590 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1595 /** Set client's username to a trusted string.
1596 * @param[in] iauth Active IAuth session.
1597 * @param[in] cli Client referenced by command.
1598 * @param[in] parc Number of parameters (1).
1599 * @param[in] params Trusted username.
1602 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1603 int parc, char **params)
1605 assert(cli_auth(cli) != NULL);
1606 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1607 if (!EmptyString(params[0])) {
1608 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1610 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1615 /** Set client's username to an untrusted string.
1616 * @param[in] iauth Active IAuth session.
1617 * @param[in] cli Client referenced by command.
1618 * @param[in] parc Number of parameters (1).
1619 * @param[in] params Untrusted username.
1622 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1623 int parc, char **params)
1625 assert(cli_auth(cli) != NULL);
1626 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1627 if (!EmptyString(params[0]))
1628 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1632 /** Set client's hostname.
1633 * @param[in] iauth Active IAuth session.
1634 * @param[in] cli Client referenced by command.
1635 * @param[in] parc Number of parameters (1).
1636 * @param[in] params New hostname for client.
1637 * @return Non-zero if \a cli authorization should be checked for completion.
1639 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1640 int parc, char **params)
1642 struct AuthRequest *auth;
1644 if (EmptyString(params[0])) {
1645 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1649 auth = cli_auth(cli);
1650 assert(auth != NULL);
1652 /* If a DNS request is pending, abort it. */
1653 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1654 FlagClr(&auth->flags, AR_DNS_PENDING);
1655 delete_resolver_queries(auth);
1656 if (IsUserPort(cli))
1657 sendheader(cli, REPORT_FIN_DNS);
1659 /* Set hostname from params. */
1660 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1664 /** Set client's IP address.
1665 * @param[in] iauth Active IAuth session.
1666 * @param[in] cli Client referenced by command.
1667 * @param[in] parc Number of parameters (1).
1668 * @param[in] params New IP address for client in dotted quad or
1669 * standard IPv6 format.
1672 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1673 int parc, char **params)
1675 struct irc_in_addr addr;
1676 struct AuthRequest *auth;
1678 if (EmptyString(params[0])) {
1679 sendto_iauth(cli, "E Missing :Missing IP address parameter");
1683 /* Get AuthRequest for client. */
1684 auth = cli_auth(cli);
1685 assert(auth != NULL);
1687 /* Parse the client's new IP address. */
1688 if (!ircd_aton(&addr, params[0])) {
1689 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1693 /* If this is the first IP override, save the client's original
1694 * address in case we get a DNS response later.
1696 if (!irc_in_addr_valid(&auth->original))
1697 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1699 /* Undo original IP connection in IPcheck. */
1700 IPcheck_connect_fail(cli);
1701 ClearIPChecked(cli);
1703 /* Update the IP and charge them as a remote connect. */
1704 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1705 IPcheck_remote_connect(cli, 0);
1710 /** Find a ConfItem structure for a named connection class.
1711 * @param[in] class_name Name of configuration class to find.
1712 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1714 static struct ConfItem *auth_find_class_conf(const char *class_name)
1716 static struct ConfItem *aconf_list;
1717 struct ConnectionClass *class;
1718 struct ConfItem *aconf;
1720 /* Make sure the configuration class is valid. */
1721 class = find_class(class_name);
1725 /* Look for an existing ConfItem for the class. */
1726 for (aconf = aconf_list; aconf; aconf = aconf->next)
1727 if (aconf->conn_class == class)
1730 /* If no ConfItem, create one. */
1732 aconf = make_conf(CONF_CLIENT);
1734 sendto_opmask_butone(NULL, SNO_AUTH,
1735 "Unable to allocate ConfItem for class %s!",
1739 aconf->conn_class = class;
1740 aconf->next = aconf_list;
1747 /** Accept a client in IAuth.
1748 * @param[in] iauth Active IAuth session.
1749 * @param[in] cli Client referenced by command.
1750 * @param[in] parc Number of parameters.
1751 * @param[in] params Optional class name for client.
1754 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1755 int parc, char **params)
1757 static time_t warn_time;
1759 /* Clear iauth pending flag. */
1760 assert(cli_auth(cli) != NULL);
1761 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1763 /* If a connection class was specified (and usable), assign the client to it. */
1764 if (!EmptyString(params[0])) {
1765 struct ConfItem *aconf;
1767 aconf = auth_find_class_conf(params[0]);
1769 attach_conf(cli, aconf);
1771 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1772 "iauth tried to use undefined class [%s]",
1779 /** Accept a client in IAuth and assign them to an account.
1780 * @param[in] iauth Active IAuth session.
1781 * @param[in] cli Client referenced by command.
1782 * @param[in] parc Number of parameters.
1783 * @param[in] params Account name and optional class name for client.
1784 * @return Non-zero if \a cli authorization should be checked for completion.
1786 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1787 int parc, char **params)
1792 if (EmptyString(params[0])) {
1793 sendto_iauth(cli, "E Missing :Missing account parameter");
1796 /* Check length of account name. */
1797 len = strcspn(params[0], ": ");
1798 if (len > ACCOUNTLEN) {
1799 sendto_iauth(cli, "E Invalid :Account parameter too long");
1802 /* If account has a creation timestamp, use it. */
1803 assert(cli_user(cli) != NULL);
1804 if (params[0][len] == ':')
1805 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1807 /* Copy account name to User structure. */
1808 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1811 /* Fall through to the normal "done" handler. */
1812 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1815 /** Reject a client's connection.
1816 * @param[in] iauth Active IAuth session.
1817 * @param[in] cli Client referenced by command.
1818 * @param[in] parc Number of parameters (1).
1819 * @param[in] params Optional kill message.
1822 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1823 int parc, char **params)
1826 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1827 if (EmptyString(params[0]))
1828 params[0] = "Access denied";
1829 exit_client(cli, cli, &me, params[0]);
1833 /** Send a challenge string to the client.
1834 * @param[in] iauth Active IAuth session.
1835 * @param[in] cli Client referenced by command.
1836 * @param[in] parc Number of parameters (1).
1837 * @param[in] params Challenge message for client.
1840 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
1841 int parc, char **params)
1843 if (!EmptyString(params[0]))
1844 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
1848 /** Parse a \a message from \a iauth.
1849 * @param[in] iauth Active IAuth session.
1850 * @param[in] message Message to be parsed.
1852 static void iauth_parse(struct IAuth *iauth, char *message)
1854 char *params[MAXPARA + 1]; /* leave space for NULL */
1856 iauth_cmd_handler handler;
1857 struct AuthRequest *auth;
1862 /* Find command handler... */
1863 switch (*(message++)) {
1864 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1865 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1866 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1867 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1868 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1869 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1870 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1871 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1872 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1873 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1874 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1875 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1876 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1877 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1878 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1879 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1880 case 'k': /* The 'k' command indicates the user should be booted
1881 * off without telling opers. There is no way to
1882 * signal that to exit_client(), so we fall through to
1883 * the case that we do implement.
1885 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1886 case 'r': /* we handle termination directly */ return;
1887 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
1890 while (parc < MAXPARA) {
1891 while (IsSpace(*message)) /* skip leading whitespace */
1894 if (!*message) /* hit the end of the string, break out */
1897 if (*message == ':') { /* found sentinel... */
1898 params[parc++] = message + 1;
1899 break; /* it's the last parameter anyway */
1902 params[parc++] = message; /* save the parameter */
1903 while (*message && !IsSpace(*message))
1904 message++; /* find the end of the parameter */
1906 if (*message) /* terminate the parameter */
1907 *(message++) = '\0';
1910 params[parc] = NULL; /* terminate the parameter list */
1912 /* Check to see if the command specifies a client... */
1914 /* Handler does not need a client. */
1915 handler(iauth, NULL, parc, params);
1917 /* Try to find the client associated with the request. */
1918 id = strtol(params[0], NULL, 10);
1919 if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
1920 /* Client no longer exists (or never existed). */
1921 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
1923 else if ((!(auth = cli_auth(cli)) ||
1924 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
1926 /* Client is done with IAuth checks. */
1927 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
1929 struct irc_sockaddr addr;
1932 /* Parse IP address and port number from parameters */
1933 res = ipmask_parse(params[1], &addr.addr, NULL);
1934 addr.port = strtol(params[2], NULL, 10);
1936 /* Check IP address and port number against expected. */
1938 irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
1939 (auth && addr.port != auth->port))
1940 /* Report mismatch to iauth. */
1941 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
1942 ircd_ntoa(&cli_ip(cli)));
1943 else if (handler(iauth, cli, parc - 3, params + 3))
1944 /* Handler indicated a possible state change. */
1945 check_auth_finished(auth, 0);
1950 /** Read input from \a iauth.
1951 * Reads up to SERVER_TCP_WINDOW bytes per pass.
1952 * @param[in] iauth Readable connection.
1954 static void iauth_read(struct IAuth *iauth)
1956 static char readbuf[SERVER_TCP_WINDOW];
1957 unsigned int length, count;
1961 /* Copy partial data to readbuf, append new data. */
1962 length = iauth->i_count;
1963 memcpy(readbuf, iauth->i_buffer, length);
1964 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
1966 sizeof(readbuf) - length - 1,
1969 readbuf[length += count] = '\0';
1971 /* Parse each complete line. */
1972 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
1974 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
1977 /* If spammy debug, send the message to opers. */
1978 if (i_debug(iauth) > 1)
1979 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
1981 /* Parse the line... */
1982 iauth_parse(iauth, sol);
1985 /* Put unused data back into connection's buffer. */
1986 iauth->i_count = strlen(sol);
1987 if (iauth->i_count > BUFSIZE)
1988 iauth->i_count = BUFSIZE;
1989 memcpy(iauth->i_buffer, sol, iauth->i_count);
1992 /** Handle socket activity for an %IAuth connection.
1993 * @param[in] ev &Socket event; the IAuth connection is the user data
1994 * pointer for the socket.
1996 static void iauth_sock_callback(struct Event *ev)
1998 struct IAuth *iauth;
2000 assert(0 != ev_socket(ev));
2001 iauth = (struct IAuth*) s_data(ev_socket(ev));
2004 switch (ev_type(ev)) {
2006 /* Hm, what happened here? */
2007 if (!IAuthHas(iauth, IAUTH_CLOSING))
2008 iauth_do_spawn(iauth, 1);
2014 IAuthClr(iauth, IAUTH_BLOCKED);
2018 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2019 /* and fall through to the ET_EOF case */
2021 iauth_disconnect(iauth);
2024 assert(0 && "Unrecognized event type");
2029 /** Read error input from \a iauth.
2030 * @param[in] iauth Readable connection.
2032 static void iauth_read_stderr(struct IAuth *iauth)
2034 static char readbuf[SERVER_TCP_WINDOW];
2035 unsigned int length, count;
2039 /* Copy partial data to readbuf, append new data. */
2040 length = iauth->i_errcount;
2041 memcpy(readbuf, iauth->i_errbuf, length);
2042 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2044 sizeof(readbuf) - length - 1,
2047 readbuf[length += count] = '\0';
2049 /* Send each complete line to SNO_AUTH. */
2050 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2052 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2054 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2055 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2056 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2059 /* Put unused data back into connection's buffer. */
2060 iauth->i_errcount = strlen(sol);
2061 if (iauth->i_errcount > BUFSIZE)
2062 iauth->i_errcount = BUFSIZE;
2063 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2066 /** Handle error socket activity for an %IAuth connection.
2067 * @param[in] ev &Socket event; the IAuth connection is the user data
2068 * pointer for the socket.
2070 static void iauth_stderr_callback(struct Event *ev)
2072 struct IAuth *iauth;
2074 assert(0 != ev_socket(ev));
2075 iauth = (struct IAuth*) s_data(ev_socket(ev));
2078 switch (ev_type(ev)) {
2080 iauth_read_stderr(iauth);
2083 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2084 /* and fall through to the ET_EOF/ET_DESTROY case */
2089 assert(0 && "Unrecognized event type");
2094 /** Report active iauth's configuration to \a cptr.
2095 * @param[in] cptr Client requesting statistics.
2096 * @param[in] sd Stats descriptor for request.
2097 * @param[in] param Extra parameter from user (may be NULL).
2099 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2103 if (iauth) for (link = iauth->i_config; link; link = link->next)
2105 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2108 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth configuration.");
2111 /** Report active iauth's statistics to \a cptr.
2112 * @param[in] cptr Client requesting statistics.
2113 * @param[in] sd Stats descriptor for request.
2114 * @param[in] param Extra parameter from user (may be NULL).
2116 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2120 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2122 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2125 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth statistics.");