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"
54 #include "querycmds.h"
69 #include <sys/socket.h>
70 #include <sys/ioctl.h>
72 /** Pending operations during registration. */
73 enum AuthRequestFlag {
74 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
75 AR_DNS_PENDING, /**< dns request sent, waiting for response */
76 AR_CAP_PENDING, /**< in middle of CAP negotiations */
77 AR_NEEDS_PONG, /**< user has not PONGed */
78 AR_NEEDS_USER, /**< user must send USER command */
79 AR_NEEDS_NICK, /**< user must send NICK command */
80 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
81 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
82 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
83 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
84 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
88 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
90 /** Stores registration state of a client. */
92 struct AuthRequest* next; /**< linked list node ptr */
93 struct AuthRequest* prev; /**< linked list node ptr */
94 struct Client* client; /**< pointer to client struct for request */
95 struct irc_sockaddr local; /**< local endpoint address */
96 struct irc_in_addr original; /**< original client IP address */
97 struct Socket socket; /**< socket descriptor for auth queries */
98 struct Timer timeout; /**< timeout timer for auth queries */
99 struct AuthRequestFlags flags; /**< current state of request */
100 unsigned int cookie; /**< cookie the user must PONG */
101 unsigned short port; /**< client's remote port number */
104 /** Array of message text (with length) pairs for AUTH status
105 * messages. Indexed using #ReportType.
110 } HeaderMessages [] = {
111 #define MSG(STR) { STR, sizeof(STR) - 1 }
112 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
113 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
114 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
115 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
116 MSG("NOTICE AUTH :*** Got ident response\r\n"),
117 MSG("NOTICE AUTH :*** No ident response\r\n"),
118 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
119 "ignoring hostname.\r\n"),
120 MSG("NOTICE AUTH :*** Invalid hostname\r\n")
124 /** Enum used to index messages in the HeaderMessages[] array. */
136 /** Sends response \a r (from #ReportType) to client \a c. */
137 #define sendheader(c, r) \
138 send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
140 /** Enumeration of IAuth connection flags. */
143 IAUTH_BLOCKED, /**< socket buffer full */
144 IAUTH_CLOSING, /**< candidate to be disposed */
145 /* The following flags are controlled by iauth's "O" options command. */
146 IAUTH_ADDLINFO, /**< Send additional info
147 * (password and username). */
148 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
149 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
150 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
151 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
152 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
153 IAUTH_LAST_FLAG /**< total number of flags */
155 /** Declare a bitset structure indexed by IAuthFlag. */
156 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
158 /** Describes state of an IAuth connection. */
160 struct MsgQ i_sendQ; /**< messages queued to send */
161 struct Socket i_socket; /**< main socket to iauth */
162 struct Socket i_stderr; /**< error socket for iauth */
163 struct IAuthFlags i_flags; /**< connection state/status/flags */
164 uint64_t i_recvB; /**< bytes received */
165 uint64_t i_sendB; /**< bytes sent */
166 time_t started; /**< time that this instance was started */
167 unsigned int i_recvM; /**< messages received */
168 unsigned int i_sendM; /**< messages sent */
169 unsigned int i_count; /**< characters used in i_buffer */
170 unsigned int i_errcount; /**< characters used in i_errbuf */
171 int i_debug; /**< debug level */
172 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
173 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
174 char *i_version; /**< iauth version string */
175 struct SLink *i_config; /**< configuration string list */
176 struct SLink *i_stats; /**< statistics string list */
177 char **i_argv; /**< argument list */
180 /** Return whether flag \a flag is set on \a iauth. */
181 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
182 /** Set flag \a flag on \a iauth. */
183 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
184 /** Clear flag \a flag from \a iauth. */
185 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
186 /** Get connected flag for \a iauth. */
187 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
189 /** Return socket event generator for \a iauth. */
190 #define i_socket(iauth) (&(iauth)->i_socket)
191 /** Return stderr socket for \a iauth. */
192 #define i_stderr(iauth) (&(iauth)->i_stderr)
193 /** Return outbound message queue for \a iauth. */
194 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
195 /** Return debug level for \a iauth. */
196 #define i_debug(iauth) ((iauth)->i_debug)
198 /** Active instance of IAuth. */
201 static void iauth_sock_callback(struct Event *ev);
202 static void iauth_stderr_callback(struct Event *ev);
203 static int sendto_iauth(struct Client *cptr, const char *format, ...);
204 static int preregister_user(struct Client *cptr);
205 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli, char *params);
207 /** Set username for user associated with \a auth.
208 * @param[in] auth Client authorization request to work on.
209 * @return Zero if client is kept, CPTR_KILLED if client rejected.
211 static int auth_set_username(struct AuthRequest *auth)
213 struct Client *sptr = auth->client;
214 struct User *user = cli_user(sptr);
225 short digitgroups = 0;
229 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
231 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
235 /* Copy username from source to destination. Since they may be the
236 * same, and we may prefix with a '~', use a buffer character (ch)
237 * to hold the next character to copy.
239 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
242 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
247 while (last && !IsCntrl(last) && rlen--)
250 *d++ = IsUserChar(last) ? last : '_';
251 last = (ch != '~') ? ch : '_';
256 /* If username is empty or just ~, reject. */
257 if ((user->username[0] == '\0')
258 || ((user->username[0] == '~') && (user->username[1] == '\0')))
259 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
261 /* Check for K- or G-line. */
262 killreason = find_kill(sptr);
264 ServerStats->is_ref++;
265 return exit_client(sptr, sptr, &me,
266 (killreason == -1 ? "K-lined" : "G-lined"));
269 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
271 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
272 * Explanations of rules moved to where it is checked Entrope 2-06
274 s = d = user->username + (user->username[0] == '~');
283 else if (IsUpper(ch))
286 /* Accept caps as leading if we haven't seen lower case or digits yet. */
287 if ((leadcaps || pos == 0) && !lower && !digits)
290 else if (IsDigit(ch))
293 if (pos == 0 || !IsDigit(last))
296 /* If more than two groups of digits, reject. */
301 else if (ch == '-' || ch == '_' || ch == '.')
304 /* If -_. exist at start, consecutively, or more than twice, reject. */
305 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
308 else /* All other punctuation is rejected. */
312 /* If mixed case, first must be capital, but no more than three;
313 * but if three capitals, they must all be leading. */
314 if (lower && upper && (!leadcaps || leadcaps > 3 ||
315 (upper > 2 && upper > leadcaps)))
317 /* If two different groups of digits, one must be either at the
319 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
321 /* Must have at least one letter. */
322 if (!lower && !upper)
324 /* Final character must not be punctuation. */
332 /* If we confirmed their username, and it is what they claimed,
334 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
337 ServerStats->is_ref++;
338 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
339 ":Your username is invalid.");
340 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
341 ":Connect with your real username, in lowercase.");
342 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
343 ":If your mail address were foo@bar.com, your username "
345 return exit_client(sptr, sptr, &me, "USER: Bad username");
348 /** Check whether an authorization request is complete.
349 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
350 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
351 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
352 * destroy \a auth, clear the password, set the username, and register
354 * @param[in] auth Authorization request to check.
355 * @param[in] send_reports Passed to destroy_auth_request() if \a auth
357 * @return Zero if client is kept, CPTR_KILLED if client rejected.
359 static int check_auth_finished(struct AuthRequest *auth, int send_reports)
361 enum AuthRequestFlag flag;
364 /* Check non-iauth registration blocking flags. */
365 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
366 if (FlagHas(&auth->flags, flag))
368 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
369 cli_fd(auth->client), flag));
373 /* If appropriate, do preliminary assignment to connection class. */
374 if (IsUserPort(auth->client)
375 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
376 && preregister_user(auth->client))
379 /* Check if iauth is done. */
380 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
382 /* Switch auth request to hurry-up state. */
383 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
385 struct ConfItem* aconf;
387 /* Set "hurry" flag in auth request. */
388 FlagSet(&auth->flags, AR_IAUTH_HURRY);
390 /* Check password now (to avoid challenge/response conflicts). */
391 aconf = cli_confs(auth->client)->value.aconf;
392 if (!EmptyString(aconf->passwd)
393 && strcmp(cli_passwd(auth->client), aconf->passwd))
395 ServerStats->is_ref++;
396 send_reply(auth->client, ERR_PASSWDMISMATCH);
397 return exit_client(auth->client, auth->client, &me, "Bad Password");
400 /* If iauth wants it, send notification. */
401 if (IAuthHas(iauth, IAUTH_UNDERNET))
402 sendto_iauth(auth->client, "H %s", ConfClass(aconf));
404 /* If iauth wants it, give client more time. */
405 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
406 timer_chg(&auth->timeout, TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
409 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
410 cli_fd(auth->client), AR_IAUTH_PENDING));
414 FlagSet(&auth->flags, AR_IAUTH_HURRY);
417 destroy_auth_request(auth, send_reports);
418 if (!IsUserPort(auth->client))
420 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
421 res = auth_set_username(auth);
423 res = register_user(auth->client, auth->client);
427 /** Verify that a hostname is valid, i.e., only contains characters
428 * valid for a hostname and that a hostname is not too long.
429 * @param host Hostname to check.
430 * @param maxlen Maximum length of hostname, not including NUL terminator.
431 * @return Non-zero if the hostname is valid.
434 auth_verify_hostname(const char *host, int maxlen)
438 /* Walk through the host name */
439 for (i = 0; host[i]; i++)
440 /* If it's not a hostname character or if it's too long, return false */
441 if (!IsHostChar(host[i]) || i >= maxlen)
444 return 1; /* it's a valid hostname */
447 /** Assign a client to a connection class.
448 * @param[in] cptr Client to assign to a class.
449 * @return Zero if client is kept, CPTR_KILLED if rejected.
451 static int preregister_user(struct Client *cptr)
453 static time_t last_too_many1;
454 static time_t last_too_many2;
456 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
457 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
459 switch (conf_check_client(cptr))
463 case ACR_NO_AUTHORIZATION:
464 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
465 get_client_name(cptr, HIDE_IP));
466 ++ServerStats->is_ref;
467 return exit_client(cptr, cptr, &me,
468 "No Authorization - use another server");
469 case ACR_TOO_MANY_IN_CLASS:
470 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
471 "Too many connections in class %s for %s.",
472 get_client_class(cptr),
473 get_client_name(cptr, SHOW_IP));
474 ++ServerStats->is_ref;
475 return exit_client(cptr, cptr, &me,
476 "Sorry, your connection class is full - try "
477 "again later or try another server");
478 case ACR_TOO_MANY_FROM_IP:
479 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
480 "Too many connections from same IP for %s.",
481 get_client_name(cptr, SHOW_IP));
482 ++ServerStats->is_ref;
483 return exit_client(cptr, cptr, &me,
484 "Too many connections from your host");
485 case ACR_ALREADY_AUTHORIZED:
486 /* Can this ever happen? */
488 ++ServerStats->is_ref;
489 IPcheck_connect_fail(cptr);
490 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
495 /** Send the ident server a query giving "theirport , ourport". The
496 * write is only attempted *once* so it is deemed to be a fail if the
497 * entire write doesn't write all the data given. This shouldn't be a
498 * problem since the socket should have a write buffer far greater
499 * than this message to store it in should problems arise. -avalon
500 * @param[in] auth The request to send.
502 static void send_auth_query(struct AuthRequest* auth)
509 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
510 auth->port, auth->local.port);
512 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
513 close(s_fd(&auth->socket));
514 socket_del(&auth->socket);
515 s_fd(&auth->socket) = -1;
516 ++ServerStats->is_abad;
517 if (IsUserPort(auth->client))
518 sendheader(auth->client, REPORT_FAIL_ID);
519 FlagClr(&auth->flags, AR_AUTH_PENDING);
520 check_auth_finished(auth, 0);
524 /** Enum used to index ident reply fields in a human-readable way. */
525 enum IdentReplyFields {
533 /** Parse an ident reply line and extract the userid from it.
534 * @param[in] reply The ident reply line.
535 * @return The userid, or NULL on parse failure.
537 static char* check_ident_reply(char* reply)
541 char* vector[USERID_TOKEN_COUNT];
542 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
544 if (USERID_TOKEN_COUNT != count)
547 * second token is the reply type
549 token = vector[IDENT_REPLY_TYPE];
550 if (EmptyString(token))
553 while (IsSpace(*token))
556 if (0 != strncmp(token, "USERID", 6))
560 * third token is the os type
562 token = vector[IDENT_OS_TYPE];
563 if (EmptyString(token))
565 while (IsSpace(*token))
569 * Unless "OTHER" is specified as the operating system
570 * type, the server is expected to return the "normal"
571 * user identification of the owner of this connection.
572 * "Normal" in this context may be taken to mean a string
573 * of characters which uniquely identifies the connection
574 * owner such as a user identifier assigned by the system
575 * administrator and used by such user as a mail
576 * identifier, or as the "user" part of a user/password
577 * pair used to gain access to system resources. When an
578 * operating system is specified (e.g., anything but
579 * "OTHER"), the user identifier is expected to be in a
580 * more or less immediately useful form - e.g., something
581 * that could be used as an argument to "finger" or as a
584 if (0 == strncmp(token, "OTHER", 5))
587 * fourth token is the username
589 token = vector[IDENT_INFO];
590 if (EmptyString(token))
592 while (IsSpace(*token))
595 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
597 for (end = token; *end; ++end) {
598 if (IsSpace(*end) || '@' == *end || ':' == *end)
605 /** Read the reply (if any) from the ident server we connected to. We
606 * only give it one shot, if the reply isn't good the first time fail
607 * the authentication entirely. --Bleep
608 * @param[in] auth The request to read.
610 static void read_auth_reply(struct AuthRequest* auth)
615 * rfc1453 sez we MUST accept 512 bytes
617 char buf[BUFSIZE + 1];
620 assert(0 != auth->client);
621 assert(auth == cli_auth(auth->client));
623 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
625 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
626 username = check_ident_reply(buf);
627 Debug((DEBUG_INFO, "Username: %s", username));
630 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
631 close(s_fd(&auth->socket));
632 socket_del(&auth->socket);
633 s_fd(&auth->socket) = -1;
635 if (EmptyString(username)) {
636 if (IsUserPort(auth->client))
637 sendheader(auth->client, REPORT_FAIL_ID);
638 ++ServerStats->is_abad;
640 if (IsUserPort(auth->client))
641 sendheader(auth->client, REPORT_FIN_ID);
642 ++ServerStats->is_asuc;
643 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
644 ircd_strncpy(cli_username(auth->client), username, USERLEN);
645 SetGotId(auth->client);
647 if (IAuthHas(iauth, IAUTH_UNDERNET))
648 sendto_iauth(auth->client, "u %s", username);
651 FlagClr(&auth->flags, AR_AUTH_PENDING);
652 check_auth_finished(auth, 0);
655 /** Handle socket I/O activity.
656 * @param[in] ev A socket event whos associated data is the active
657 * struct AuthRequest.
659 static void auth_sock_callback(struct Event* ev)
661 struct AuthRequest* auth;
663 assert(0 != ev_socket(ev));
664 assert(0 != s_data(ev_socket(ev)));
666 auth = (struct AuthRequest*) s_data(ev_socket(ev));
668 switch (ev_type(ev)) {
669 case ET_DESTROY: /* being destroyed */
672 case ET_CONNECT: /* socket connection completed */
673 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
674 auth, cli_fd(auth->client)));
675 socket_state(&auth->socket, SS_CONNECTED);
676 send_auth_query(auth);
679 case ET_READ: /* socket is readable */
680 case ET_EOF: /* end of file on socket */
681 case ET_ERROR: /* error on socket */
682 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
683 read_auth_reply(auth);
687 assert(0 && "Unrecognized event in auth_socket_callback().");
692 /** Stop an auth request completely.
693 * @param[in] auth The struct AuthRequest to cancel.
694 * @param[in] send_reports If non-zero, report the failure to the user.
696 void destroy_auth_request(struct AuthRequest* auth, int send_reports)
698 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
700 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
701 if (send_reports && IsUserPort(auth->client))
702 sendheader(auth->client, REPORT_FAIL_ID);
705 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
706 delete_resolver_queries(auth);
707 if (send_reports && IsUserPort(auth->client))
708 sendheader(auth->client, REPORT_FAIL_DNS);
711 if (-1 < s_fd(&auth->socket)) {
712 close(s_fd(&auth->socket));
713 socket_del(&auth->socket);
714 s_fd(&auth->socket) = -1;
717 timer_del(&auth->timeout);
718 cli_auth(auth->client) = NULL;
721 /** Timeout a given auth request.
722 * @param[in] ev A timer event whose associated data is the expired
723 * struct AuthRequest.
725 static void auth_timeout_callback(struct Event* ev)
727 struct AuthRequest* auth;
729 assert(0 != ev_timer(ev));
730 assert(0 != t_data(ev_timer(ev)));
732 auth = (struct AuthRequest*) t_data(ev_timer(ev));
734 if (ev_type(ev) == ET_EXPIRE) {
735 /* Report the timeout in the log. */
736 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
737 get_client_name(auth->client, HIDE_IP));
738 /* Tell iauth if we will let the client on. */
739 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)
740 && !IAuthHas(iauth, IAUTH_REQUIRED))
742 sendto_iauth(auth->client, "T");
743 FlagClr(&auth->flags , AR_IAUTH_PENDING);
745 /* Try to register the client. */
746 check_auth_finished(auth, 1);
747 /* If that failed, kick them off. */
748 if (!IsUser(auth->client))
749 exit_client(auth->client, auth->client, &me, "Authorization timed out");
753 /** Handle a complete DNS lookup. Send the client on it's way to a
754 * connection completion, regardless of success or failure -- unless
755 * there was a mismatch and KILL_IPMISMATCH is set.
756 * @param[in] vptr The pending struct AuthRequest.
757 * @param[in] addr IP address being resolved.
758 * @param[in] h_name Resolved name, or NULL if lookup failed.
760 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
762 struct AuthRequest* auth = (struct AuthRequest*) vptr;
765 FlagClr(&auth->flags, AR_DNS_PENDING);
767 /* DNS entry was missing for the IP. */
768 if (IsUserPort(auth->client))
769 sendheader(auth->client, REPORT_FAIL_DNS);
770 sendto_iauth(auth->client, "d");
771 } else if (irc_in_addr_cmp(addr, &cli_ip(auth->client))
772 && irc_in_addr_cmp(addr, &auth->original)) {
773 /* IP for hostname did not match client's IP. */
774 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
775 cli_sock_ip(auth->client), h_name,
777 if (IsUserPort(auth->client))
778 sendheader(auth->client, REPORT_IP_MISMATCH);
779 /* Clear DNS pending flag so free_client doesn't ask the resolver
780 * to delete the query that just finished.
782 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
783 IPcheck_disconnect(auth->client);
784 Count_unknowndisconnects(UserStats);
785 free_client(auth->client);
787 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
788 /* Hostname did not look valid. */
789 if (IsUserPort(auth->client))
790 sendheader(auth->client, REPORT_INVAL_DNS);
791 sendto_iauth(auth->client, "d");
793 /* Hostname and mappings checked out. */
794 if (IsUserPort(auth->client))
795 sendheader(auth->client, REPORT_FIN_DNS);
796 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
797 sendto_iauth(auth->client, "N %s", h_name);
799 check_auth_finished(auth, 0);
802 /** Flag the client to show an attempt to contact the ident server on
803 * the client's host. Should the connect or any later phase of the
804 * identifying process fail, it is aborted and the user is given a
805 * username of "unknown".
806 * @param[in] auth The request for which to start the ident lookup.
808 static void start_auth_query(struct AuthRequest* auth)
810 struct irc_sockaddr remote_addr;
811 struct irc_sockaddr local_addr;
816 assert(0 != auth->client);
819 * get the local address of the client and bind to that to
820 * make the auth request. This used to be done only for
821 * ifdef VIRTUAL_HOST, but needs to be done for all clients
822 * since the ident request must originate from that same address--
823 * and machines with multiple IP addresses are common now
825 memcpy(&local_addr, &auth->local, sizeof(local_addr));
827 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
828 remote_addr.port = 113;
829 fd = os_socket(&local_addr, SOCK_STREAM, "auth query");
831 ++ServerStats->is_abad;
832 if (IsUserPort(auth->client))
833 sendheader(auth->client, REPORT_FAIL_ID);
836 if (IsUserPort(auth->client))
837 sendheader(auth->client, REPORT_DO_ID);
839 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
840 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
841 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
842 SOCK_EVENT_READABLE, fd)) {
843 ++ServerStats->is_abad;
844 if (IsUserPort(auth->client))
845 sendheader(auth->client, REPORT_FAIL_ID);
850 FlagSet(&auth->flags, AR_AUTH_PENDING);
851 if (result == IO_SUCCESS)
852 send_auth_query(auth);
855 /** Initiate DNS lookup for a client.
856 * @param[in] auth The auth request for which to start the DNS lookup.
858 static void start_dns_query(struct AuthRequest *auth)
860 if (feature_bool(FEAT_NODNS)) {
861 sendto_iauth(auth->client, "d");
865 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
866 strcpy(cli_sockhost(auth->client), cli_name(&me));
867 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
871 if (IsUserPort(auth->client))
872 sendheader(auth->client, REPORT_DO_DNS);
874 FlagSet(&auth->flags, AR_DNS_PENDING);
875 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
878 /** Initiate IAuth check for a client.
879 * @param[in] auth The auth request for which to star the IAuth check.
881 static void start_iauth_query(struct AuthRequest *auth)
883 FlagSet(&auth->flags, AR_IAUTH_PENDING);
884 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
885 cli_sock_ip(auth->client), auth->port,
886 ircd_ntoa(&auth->local.addr), auth->local.port))
887 FlagClr(&auth->flags, AR_IAUTH_PENDING);
890 /** Starts auth (identd) and dns queries for a client.
891 * @param[in] client The client for which to start queries.
893 void start_auth(struct Client* client)
895 struct irc_sockaddr remote;
896 struct AuthRequest* auth;
899 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
901 /* Register with event handlers. */
902 cli_lasttime(client) = CurrentTime;
903 cli_since(client) = CurrentTime;
904 if (cli_fd(client) > HighestFd)
905 HighestFd = cli_fd(client);
906 LocalClientArray[cli_fd(client)] = client;
907 add_client_to_list(client);
908 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
910 /* Allocate the AuthRequest. */
911 auth = MyCalloc(1, sizeof(*auth));
913 auth->client = client;
914 cli_auth(client) = auth;
915 s_fd(&auth->socket) = -1;
916 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
917 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
919 /* Try to get socket endpoint addresses. */
920 if (!os_get_sockname(cli_fd(client), &auth->local)
921 || !os_get_peername(cli_fd(client), &remote)) {
922 ++ServerStats->is_abad;
923 if (IsUserPort(auth->client))
924 sendheader(auth->client, REPORT_FAIL_ID);
925 IPcheck_disconnect(auth->client);
926 Count_unknowndisconnects(UserStats);
927 free_client(auth->client);
930 auth->port = remote.port;
932 /* Try to start DNS lookup. */
933 start_dns_query(auth);
935 /* Try to start ident lookup. */
936 start_auth_query(auth);
938 /* Set required client inputs for users. */
939 if (IsUserPort(client)) {
940 cli_user(client) = make_user(client);
941 cli_user(client)->server = &me;
942 FlagSet(&auth->flags, AR_NEEDS_USER);
943 FlagSet(&auth->flags, AR_NEEDS_NICK);
945 /* Try to start iauth lookup. */
946 start_iauth_query(auth);
949 /* Check which auth events remain pending. */
950 check_auth_finished(auth, 0);
953 /** Mark that a user has PONGed while unregistered.
954 * @param[in] auth Authorization request for client.
955 * @param[in] cookie PONG cookie value sent by client.
956 * @return Zero if client should be kept, CPTR_KILLED if rejected.
958 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
960 assert(auth != NULL);
961 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
963 if (cookie != auth->cookie)
965 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
966 ":To connect, type /QUOTE PONG %u", auth->cookie);
969 FlagClr(&auth->flags, AR_NEEDS_PONG);
970 return check_auth_finished(auth, 0);
973 /** Record a user's claimed username and userinfo.
974 * @param[in] auth Authorization request for client.
975 * @param[in] username Client's asserted username.
976 * @param[in] userinfo Client's asserted self-description.
977 * @return Zero if client should be kept, CPTR_KILLED if rejected.
979 int auth_set_user(struct AuthRequest *auth, const char *username, const char *userinfo)
983 assert(auth != NULL);
984 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
986 FlagClr(&auth->flags, AR_NEEDS_USER);
988 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
989 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
990 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
991 if (IAuthHas(iauth, IAUTH_UNDERNET))
992 sendto_iauth(cptr, "U %s %s", username, userinfo);
993 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
994 sendto_iauth(cptr, "U %s", username);
995 return check_auth_finished(auth, 0);
998 /** Handle authorization-related aspects of initial nickname selection.
999 * This is called after verifying that the nickname is available.
1000 * @param[in] auth Authorization request for client.
1001 * @param[in] nickname Client's requested nickname.
1002 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1004 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1006 assert(auth != NULL);
1007 FlagClr(&auth->flags, AR_NEEDS_NICK);
1009 * If the client hasn't gotten a cookie-ping yet,
1010 * choose a cookie and send it. -record!jegelhof@cloud9.net
1012 if (!auth->cookie) {
1014 auth->cookie = ircrandom();
1015 } while (!auth->cookie);
1016 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1017 FlagSet(&auth->flags, AR_NEEDS_PONG);
1019 if (IAuthHas(iauth, IAUTH_UNDERNET))
1020 sendto_iauth(auth->client, "n %s", nickname);
1021 return check_auth_finished(auth, 0);
1024 /** Record a user's password.
1025 * @param[in] auth Authorization request for client.
1026 * @param[in] password Client's password.
1027 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1029 int auth_set_password(struct AuthRequest *auth, const char *password)
1031 assert(auth != NULL);
1032 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1033 sendto_iauth(auth->client, "P %s", password);
1037 /** Send exit notification for \a cptr to iauth.
1038 * @param[in] cptr Client who is exiting.
1040 void auth_send_exit(struct Client *cptr)
1042 sendto_iauth(cptr, "D");
1045 /** Mark that a user has started capabilities negotiation.
1046 * This blocks authorization until auth_cap_done() is called.
1047 * @param[in] auth Authorization request for client.
1048 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1050 int auth_cap_start(struct AuthRequest *auth)
1052 assert(auth != NULL);
1053 FlagSet(&auth->flags, AR_CAP_PENDING);
1057 /** Mark that a user has completed capabilities negotiation.
1058 * This unblocks authorization if auth_cap_start() was called.
1059 * @param[in] auth Authorization request for client.
1060 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1062 int auth_cap_done(struct AuthRequest *auth)
1064 assert(auth != NULL);
1065 FlagClr(&auth->flags, AR_CAP_PENDING);
1066 return check_auth_finished(auth, 0);
1069 /** Attempt to spawn the process for an IAuth instance.
1070 * @param[in] iauth IAuth descriptor.
1071 * @param[in] automatic If non-zero, apply sanity checks against
1072 * excessive automatic restarts.
1073 * @return 0 on success, non-zero on failure.
1075 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1082 if (automatic && CurrentTime - iauth->started < 5)
1084 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1088 /* Record time we tried to spawn the iauth process. */
1089 iauth->started = CurrentTime;
1091 /* Attempt to allocate a pair of sockets. */
1092 res = os_socketpair(s_io);
1096 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1097 res = os_set_nonblocking(s_io[0]);
1105 /* Initialize the socket structure to talk to the child. */
1106 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1107 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1115 /* Allocate another pair for stderr. */
1116 res = os_socketpair(s_err);
1119 socket_del(i_socket(iauth));
1125 /* Mark parent side of this pair non-blocking, too. */
1126 res = os_set_nonblocking(s_err[0]);
1131 socket_del(i_socket(iauth));
1137 /* And set up i_stderr(iauth). */
1138 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1139 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1144 socket_del(i_socket(iauth));
1150 /* Attempt to fork a child process. */
1153 /* Error forking the child, still in parent. */
1155 socket_del(i_stderr(iauth));
1158 socket_del(i_socket(iauth));
1165 /* We are the parent process. Close the child's sockets. */
1168 /* Send our server name (supposedly for proxy checking purposes)
1169 * and maximum number of connections (for allocation hints).
1170 * Need to use conf_get_local() since &me may not be fully
1171 * initialized the first time we run.
1173 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1174 /* Indicate success (until the child dies). */
1178 /* We are the child process.
1179 * Duplicate our end of the socket to stdin, stdout and stderr.
1180 * Then close all the higher-numbered FDs and exec the process.
1182 if (dup2(s_io[1], 0) == 0
1183 && dup2(s_io[1], 1) == 1
1184 && dup2(s_err[1], 2) == 2) {
1185 close_connections(0);
1186 execvp(iauth->i_argv[0], iauth->i_argv);
1189 /* If we got here, something was seriously wrong. */
1193 /** See if an %IAuth program must be spawned.
1194 * If a process is already running with the specified options, keep it.
1195 * Otherwise spawn a new child process to perform the %IAuth function.
1196 * @param[in] argc Number of parameters to use when starting process.
1197 * @param[in] argv Array of parameters to start process.
1198 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1200 int auth_spawn(int argc, char *argv[])
1207 /* Check that incoming arguments all match pre-existing arguments. */
1208 for (ii = 0; same && (ii < argc); ++ii) {
1209 if (NULL == iauth->i_argv[ii]
1210 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1213 /* Check that we have no more pre-existing arguments. */
1214 if (iauth->i_argv[ii])
1216 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1217 if (same && i_GetConnected(iauth)) {
1218 IAuthClr(iauth, IAUTH_CLOSING);
1221 /* Deallocate old argv elements. */
1222 for (ii = 0; iauth->i_argv[ii]; ++ii)
1223 MyFree(iauth->i_argv[ii]);
1224 MyFree(iauth->i_argv);
1227 /* Need to initialize a new connection. */
1228 iauth = MyCalloc(1, sizeof(*iauth));
1229 msgq_init(i_sendQ(iauth));
1230 /* Populate iauth's argv array. */
1231 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1232 for (ii = 0; ii < argc; ++ii)
1233 DupString(iauth->i_argv[ii], argv[ii]);
1234 iauth->i_argv[ii] = NULL;
1235 /* Try to spawn it, and handle the results. */
1236 if (iauth_do_spawn(iauth, 0))
1238 IAuthClr(iauth, IAUTH_CLOSING);
1242 /** Mark all %IAuth connections as closing. */
1243 void auth_mark_closing(void)
1246 IAuthSet(iauth, IAUTH_CLOSING);
1249 /** Complete disconnection of an %IAuth connection.
1250 * @param[in] iauth %Connection to fully close.
1252 static void iauth_disconnect(struct IAuth *iauth)
1254 if (!i_GetConnected(iauth))
1257 /* Close main socket. */
1258 close(s_fd(i_socket(iauth)));
1259 socket_del(i_socket(iauth));
1260 s_fd(i_socket(iauth)) = -1;
1262 /* Close error socket. */
1263 close(s_fd(i_stderr(iauth)));
1264 socket_del(i_stderr(iauth));
1265 s_fd(i_stderr(iauth)) = -1;
1268 /** Close all %IAuth connections marked as closing. */
1269 void auth_close_unused(void)
1271 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1273 iauth_disconnect(iauth);
1274 if (iauth->i_argv) {
1275 for (ii = 0; iauth->i_argv[ii]; ++ii)
1276 MyFree(iauth->i_argv[ii]);
1277 MyFree(iauth->i_argv);
1283 /** Send queued output to \a iauth.
1284 * @param[in] iauth Writable connection with queued data.
1286 static void iauth_write(struct IAuth *iauth)
1288 unsigned int bytes_tried, bytes_sent;
1291 if (IAuthHas(iauth, IAUTH_BLOCKED))
1293 while (MsgQLength(i_sendQ(iauth)) > 0) {
1294 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1297 msgq_delete(i_sendQ(iauth), bytes_sent);
1298 iauth->i_sendB += bytes_sent;
1299 if (bytes_tried == bytes_sent)
1301 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1303 IAuthSet(iauth, IAUTH_BLOCKED);
1304 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1307 iauth_disconnect(iauth);
1311 /* We were able to flush all events, so remove notification. */
1312 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1315 /** Send a message to iauth.
1316 * @param[in] cptr Optional client context for message.
1317 * @param[in] format Format string for message.
1318 * @return Non-zero on successful send or buffering, zero on failure.
1320 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1325 /* Do not send requests when we have no iauth. */
1326 if (!i_GetConnected(iauth))
1328 /* Do not send for clients in the NORMAL state. */
1330 && (format[0] != 'D')
1331 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1334 /* Build the message buffer. */
1335 vd.vd_format = format;
1336 va_start(vd.vd_args, format);
1338 mb = msgq_make(NULL, "-1 %v", &vd);
1340 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1343 /* Tack it onto the iauth sendq and try to write it. */
1345 msgq_add(i_sendQ(iauth), mb, 0);
1350 /** Send text to interested operators (SNO_AUTH server notice).
1351 * @param[in] iauth Active IAuth session.
1352 * @param[in] cli Client referenced by command.
1353 * @param[in] params Text to send.
1356 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli, char *params)
1358 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params);
1362 /** Set the debug level for the session.
1363 * @param[in] iauth Active IAuth session.
1364 * @param[in] cli Client referenced by command.
1365 * @param[in] params String starting with an integer.
1368 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli, char *params)
1372 new_level = atoi(params);
1373 if (i_debug(iauth) > 0 || new_level > 0) {
1374 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1375 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1377 i_debug(iauth) = new_level;
1381 /** Set policy options for the session.
1382 * Old policy is forgotten, and any of the following characters in \a
1383 * params enable the corresponding policy:
1384 * \li A IAUTH_ADDLINFO
1385 * \li R IAUTH_REQUIRED
1386 * \li T IAUTH_TIMEOUT
1387 * \li W IAUTH_EXTRAWAIT
1388 * \li U IAUTH_UNDERNET
1390 * @param[in] iauth Active IAuth session.
1391 * @param[in] cli Client referenced by command.
1392 * @param[in] params Zero or more policy options.
1395 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli, char *params)
1397 enum IAuthFlag flag;
1400 /* Erase old policy first. */
1401 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1402 IAuthClr(iauth, flag);
1404 /* Parse new policy set. */
1405 for (p = params; *p; p++) switch (*p) {
1406 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1407 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1408 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1409 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1410 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1413 /* Optionally notify operators. */
1414 if (i_debug(iauth) > 0)
1415 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params);
1419 /** Set the iauth program version number.
1420 * @param[in] iauth Active IAuth session.
1421 * @param[in] cli Client referenced by command.
1422 * @param[in] params Version number or name.
1425 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli, char *params)
1427 MyFree(iauth->i_version);
1428 while (IsSpace(*params))
1430 DupString(iauth->i_version, params);
1431 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.", iauth->i_version);
1435 /** Clear cached iauth configuration information.
1436 * @param[in] iauth Active IAuth session.
1437 * @param[in] cli Client referenced by command.
1438 * @param[in] params Parameter list (ignored).
1441 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli, char *params)
1446 head = iauth->i_config;
1447 iauth->i_config = NULL;
1448 for (; head; head = next) {
1450 MyFree(head->value.cp);
1453 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1457 /** Append iauth configuration information.
1458 * @param[in] iauth Active IAuth session.
1459 * @param[in] cli Client referenced by command.
1460 * @param[in] params Description of configuration element.
1463 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli, char *params)
1467 if (iauth->i_config) {
1468 for (node = iauth->i_config; node->next; node = node->next) ;
1469 node = node->next = make_link();
1471 node = iauth->i_config = make_link();
1473 while (IsSpace(*params))
1475 DupString(node->value.cp, params);
1479 /** Clear cached iauth configuration information.
1480 * @param[in] iauth Active IAuth session.
1481 * @param[in] cli Client referenced by command.
1482 * @param[in] params Parameter list (ignored).
1485 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli, char *params)
1490 head = iauth->i_stats;
1491 iauth->i_stats = NULL;
1492 for (; head; head = next) {
1494 MyFree(head->value.cp);
1497 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1501 /** Append iauth statistics information.
1502 * @param[in] iauth Active IAuth session.
1503 * @param[in] cli Client referenced by command.
1504 * @param[in] params Statistics element.
1507 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli, char *params)
1510 if (iauth->i_stats) {
1511 for (node = iauth->i_stats; node->next; node = node->next) ;
1512 node = node->next = make_link();
1514 node = iauth->i_stats = make_link();
1516 while (IsSpace(*params))
1518 DupString(node->value.cp, params);
1522 /** Set client's username to a trusted string even if it breaks the rules.
1523 * @param[in] iauth Active IAuth session.
1524 * @param[in] cli Client referenced by command.
1525 * @param[in] params Forced username.
1528 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli, char *params)
1530 assert(cli_auth(cli) != NULL);
1531 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1532 if (!EmptyString(params)) {
1533 ircd_strncpy(cli_username(cli), params, USERLEN);
1535 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1536 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1541 /** Set client's username to a trusted string.
1542 * @param[in] iauth Active IAuth session.
1543 * @param[in] cli Client referenced by command.
1544 * @param[in] params Trusted username.
1547 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli, char *params)
1549 assert(cli_auth(cli) != NULL);
1550 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1551 if (!EmptyString(params)) {
1552 ircd_strncpy(cli_username(cli), params, USERLEN);
1554 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1559 /** Set client's username to an untrusted string.
1560 * @param[in] iauth Active IAuth session.
1561 * @param[in] cli Client referenced by command.
1562 * @param[in] params Untrusted username.
1565 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli, char *params)
1567 assert(cli_auth(cli) != NULL);
1568 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1569 if (!EmptyString(params))
1570 ircd_strncpy(cli_user(cli)->username, params, USERLEN);
1574 /** Set client's hostname.
1575 * @param[in] iauth Active IAuth session.
1576 * @param[in] cli Client referenced by command.
1577 * @param[in] params New hostname for client.
1578 * @return Non-zero if \a cli authorization should be checked for completion.
1580 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli, char *params)
1582 struct AuthRequest *auth;
1584 if (EmptyString(params)) {
1585 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1589 auth = cli_auth(cli);
1590 assert(auth != NULL);
1592 /* If a DNS request is pending, abort it. */
1593 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1594 FlagClr(&auth->flags, AR_DNS_PENDING);
1595 delete_resolver_queries(auth);
1596 if (IsUserPort(cli))
1597 sendheader(cli, REPORT_FIN_DNS);
1599 /* Set hostname from params. */
1600 ircd_strncpy(cli_sockhost(cli), params, HOSTLEN);
1604 /** Set client's IP address.
1605 * @param[in] iauth Active IAuth session.
1606 * @param[in] cli Client referenced by command.
1607 * @param[in] params New IP address for client in dotted quad or
1608 * standard IPv6 format.
1611 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli, char *params)
1613 struct irc_in_addr addr;
1614 struct AuthRequest *auth;
1616 /* Get AuthRequest for client. */
1617 auth = cli_auth(cli);
1618 assert(auth != NULL);
1620 /* Parse the client's new IP address. */
1621 if (!ircd_aton(&addr, params)) {
1622 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params);
1626 /* If this is the first IP override, save the client's original
1627 * address in case we get a DNS response later.
1629 if (!irc_in_addr_valid(&auth->original))
1630 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1632 /* Undo original IP connection in IPcheck. */
1633 IPcheck_connect_fail(cli);
1634 ClearIPChecked(cli);
1636 /* Update the IP and charge them as a remote connect. */
1637 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1638 IPcheck_remote_connect(cli, 0);
1643 /** Find a ConfItem structure for a named connection class.
1644 * @param[in] class_name Name of configuration class to find.
1645 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1647 static struct ConfItem *auth_find_class_conf(const char *class_name)
1649 static struct ConfItem *aconf_list;
1650 struct ConnectionClass *class;
1651 struct ConfItem *aconf;
1653 /* Make sure the configuration class is valid. */
1654 class = find_class(class_name);
1658 /* Look for an existing ConfItem for the class. */
1659 for (aconf = aconf_list; aconf; aconf = aconf->next)
1660 if (aconf->conn_class == class)
1663 /* If no ConfItem, create one. */
1665 aconf = make_conf(CONF_CLIENT);
1667 sendto_opmask_butone(NULL, SNO_AUTH,
1668 "Unable to allocate ConfItem for class %s!",
1672 aconf->conn_class = class;
1673 aconf->next = aconf_list;
1680 /** Accept a client in IAuth.
1681 * @param[in] iauth Active IAuth session.
1682 * @param[in] cli Client referenced by command.
1683 * @param[in] params Optional class name for client.
1686 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli, char *params)
1688 static time_t warn_time;
1690 /* Clear iauth pending flag. */
1691 assert(cli_auth(cli) != NULL);
1692 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1694 /* If a connection class was specified (and usable), assign the client to it. */
1695 if (!EmptyString(params)) {
1696 struct ConfItem *aconf;
1698 aconf = auth_find_class_conf(params);
1700 attach_conf(cli, aconf);
1702 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1703 "iauth tried to use undefined class [%s]",
1710 /** Accept a client in IAuth and assign them to an account.
1711 * @param[in] iauth Active IAuth session.
1712 * @param[in] cli Client referenced by command.
1713 * @param[in] params Account name and optional class name for client.
1714 * @return Non-zero if \a cli authorization should be checked for completion.
1716 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli, char *params)
1722 if (EmptyString(params)) {
1723 sendto_iauth(cli, "E Missing :Missing account parameter");
1726 /* Check length of account name. */
1727 len = strcspn(params, ": ");
1728 if (len > ACCOUNTLEN) {
1729 sendto_iauth(cli, "E Invalid :Account parameter too long");
1732 /* If account has a creation timestamp, use it. */
1733 assert(cli_user(cli) != NULL);
1734 if (params[len] == ':')
1735 cli_user(cli)->acc_create = strtoul(params + len + 1, &end, 10);
1738 /* Copy account name to User structure. */
1739 ircd_strncpy(cli_user(cli)->account, params, ACCOUNTLEN);
1741 /* Skip whitespace before next argument. */
1742 while (IsSpace(*end))
1744 /* Fall through to the normal "done" handler. */
1745 return iauth_cmd_done_client(iauth, cli, end);
1748 /** Reject a client's connection.
1749 * @param[in] iauth Active IAuth session.
1750 * @param[in] cli Client referenced by command.
1751 * @param[in] params Optional kill message.
1754 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli, char *params)
1757 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1758 if (EmptyString(params))
1759 params = "Access denied";
1760 exit_client(cli, cli, &me, params);
1764 /** Send a challenge string to the client.
1765 * @param[in] iauth Active IAuth session.
1766 * @param[in] cli Client referenced by command.
1767 * @param[in] params Challenge message for client.
1770 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli, char *params)
1772 sendrawto_one(cli, "NOTICE AUTH :*** %s", params);
1776 /** Read input from \a iauth.
1777 * Reads up to SERVER_TCP_WINDOW bytes per pass.
1778 * @param[in] iauth Readable connection.
1780 static void iauth_read(struct IAuth *iauth)
1782 static char readbuf[SERVER_TCP_WINDOW];
1783 iauth_cmd_handler handler;
1784 struct AuthRequest *auth;
1790 unsigned int length;
1795 switch (os_recv_nonb(s_fd(i_socket(iauth)), readbuf, sizeof(readbuf), &length))
1797 case IO_SUCCESS: break;
1798 case IO_FAILURE: iauth_disconnect(iauth);
1799 case IO_BLOCKED: return;
1801 iauth->i_recvB += length;
1802 old_buffer = iauth->i_buffer;
1803 endp = old_buffer + iauth->i_count;
1804 for (src = readbuf; length > 0; --length) {
1807 /* Terminate line, reset buffer and update statistics. */
1812 /* If spammy debug, send the message to opers. */
1813 if (i_debug(iauth) > 1)
1814 sendto_opmask_butone(NULL, SNO_AUTH, "%s", endp);
1816 /* Find command handler. A lot of the handlers would be simpler
1817 * with an argument splitter like in parse.c, but some commands
1818 * (notably '>') do not use delimiters that way.
1820 switch (*(endp = old_buffer)) {
1821 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1822 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1823 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1824 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1825 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1826 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1827 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1828 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1829 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1830 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1831 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1832 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1833 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1834 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1835 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1836 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1837 case 'k': /* The 'k' command indicates the user should be booted
1838 * off without telling opers. There is no way to
1839 * signal that to exit_client(), so we fall through to
1840 * the case that we do implement.
1842 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1843 case 'r': /* we handle termination directly */ continue;
1844 default: sendto_iauth(NULL, "E Garbage :[%s]", endp); continue;
1847 /* Skip whitespace at start of arguments. */
1848 while (IsSpace(*++endp)) ;
1850 /* At this point, has_cli has one of three values:
1851 * 0 - no client is identified
1852 * 1 - a client is identified and must still be registering
1853 * 2 - a client is identified but may be fully registered
1856 /* Figure out how to handle the command. */
1858 /* Handler does not need a client. */
1859 handler(iauth, NULL, endp);
1861 /* Try to find the client associated with the request. */
1862 id = strtol(endp, ¶ms, 10);
1863 while (IsSpace(*params))
1865 if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id])) {
1866 /* Client no longer exists (or never existed). */
1867 sendto_iauth(NULL, "E Gone :[%s]", params);
1868 } else if ((!(auth = cli_auth(cli))
1869 || !FlagHas(&auth->flags, AR_IAUTH_PENDING))
1870 && (has_cli == 1)) {
1871 /* Client is done with IAuth checks. */
1872 sendto_iauth(cli, "E Done :[%s]", params);
1874 struct irc_sockaddr addr;
1877 /* Skip whitespace before IP address. */
1878 while (IsSpace(*params))
1880 /* Record start of IP address, then null terminate it. */
1882 while (!IsSpace(*params) && *params != '\0')
1884 if (IsSpace(*params))
1886 /* Parse out client IP address and port number. */
1887 res = ipmask_parse(orig_ip, &addr.addr, NULL);
1888 addr.port = strtol(params, ¶ms, 10);
1889 /* Skip whitespace and optional sentinel after port number. */
1890 while (IsSpace(*params))
1894 /* Check IP address and port number against expected. */
1896 || irc_in_addr_cmp(&addr.addr, &cli_ip(cli))
1897 || (auth && addr.port != auth->port)) {
1898 /* Report mismatch to iauth. */
1899 sendto_iauth(cli, "E Mismatch :[%s] != [%s]",
1900 orig_ip, ircd_ntoa(&cli_ip(cli)));
1901 } else if (handler(iauth, cli, params)) {
1902 /* Handler indicated a possible state change. */
1903 check_auth_finished(auth, 0);
1908 /* Reset buffer pointer to read next line. */
1911 else if (endp < old_buffer + BUFSIZE)
1914 iauth->i_count = endp - old_buffer;
1917 /** Handle socket activity for an %IAuth connection.
1918 * @param[in] ev &Socket event; the IAuth connection is the user data
1919 * pointer for the socket.
1921 static void iauth_sock_callback(struct Event *ev)
1923 struct IAuth *iauth;
1925 assert(0 != ev_socket(ev));
1926 iauth = (struct IAuth*) s_data(ev_socket(ev));
1929 switch (ev_type(ev)) {
1931 /* Hm, what happened here? */
1932 if (!IAuthHas(iauth, IAUTH_CLOSING))
1933 iauth_do_spawn(iauth, 1);
1939 IAuthClr(iauth, IAUTH_BLOCKED);
1943 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
1944 /* and fall through to the ET_EOF case */
1946 iauth_disconnect(iauth);
1949 assert(0 && "Unrecognized event type");
1954 /** Read error input from \a iauth.
1955 * @param[in] iauth Readable connection.
1957 static void iauth_read_stderr(struct IAuth *iauth)
1959 static char readbuf[SERVER_TCP_WINDOW];
1960 unsigned int length;
1964 /* Copy partial data to readbuf, append new data. */
1965 length = iauth->i_errcount;
1966 memcpy(readbuf, iauth->i_errbuf, length);
1967 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
1969 sizeof(readbuf) - length - 1,
1972 readbuf[length] = '\0';
1974 /* Send each complete line to SNO_AUTH. */
1975 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
1977 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
1978 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
1979 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
1982 /* Put unused data back into connection's buffer. */
1983 iauth->i_errcount = strlen(sol);
1984 if (iauth->i_errcount > BUFSIZE)
1985 iauth->i_errcount = BUFSIZE;
1986 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
1989 /** Handle error socket activity for an %IAuth connection.
1990 * @param[in] ev &Socket event; the IAuth connection is the user data
1991 * pointer for the socket.
1993 static void iauth_stderr_callback(struct Event *ev)
1995 struct IAuth *iauth;
1997 assert(0 != ev_socket(ev));
1998 iauth = (struct IAuth*) s_data(ev_socket(ev));
2001 switch (ev_type(ev)) {
2003 iauth_read_stderr(iauth);
2006 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2007 /* and fall through to the ET_EOF/ET_DESTROY case */
2012 assert(0 && "Unrecognized event type");
2017 /** Report active iauth's configuration to \a cptr.
2018 * @param[in] cptr Client requesting statistics.
2019 * @param[in] sd Stats descriptor for request.
2020 * @param[in] param Extra parameter from user (may be NULL).
2022 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2026 if (iauth) for (link = iauth->i_config; link; link = link->next)
2028 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2031 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth configuration.");
2034 /** Report active iauth's statistics to \a cptr.
2035 * @param[in] cptr Client requesting statistics.
2036 * @param[in] sd Stats descriptor for request.
2037 * @param[in] param Extra parameter from user (may be NULL).
2039 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2043 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2045 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2048 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth statistics.");