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 /* Check if iauth is done. */
374 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
376 /* Switch auth request to hurry-up state. */
377 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
379 struct ConfItem* aconf;
381 /* Set "hurry" flag in auth request. */
382 FlagSet(&auth->flags, AR_IAUTH_HURRY);
384 /* Do preliminary assignment to connection class. */
385 if (preregister_user(auth->client))
388 /* Check password now (to avoid challenge/response conflicts). */
389 aconf = cli_confs(auth->client)->value.aconf;
390 if (!EmptyString(aconf->passwd)
391 && strcmp(cli_passwd(auth->client), aconf->passwd))
393 ServerStats->is_ref++;
394 send_reply(auth->client, ERR_PASSWDMISMATCH);
395 return exit_client(auth->client, auth->client, &me, "Bad Password");
398 /* If iauth wants it, send notification. */
399 if (IAuthHas(iauth, IAUTH_UNDERNET))
400 sendto_iauth(auth->client, "H %s", ConfClass(aconf));
402 /* If iauth wants it, give client more time. */
403 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
404 timer_chg(&auth->timeout, TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
407 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
408 cli_fd(auth->client), AR_IAUTH_PENDING));
412 destroy_auth_request(auth, send_reports);
413 if (!IsUserPort(auth->client))
415 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
416 res = auth_set_username(auth);
418 res = register_user(auth->client, auth->client);
422 /** Verify that a hostname is valid, i.e., only contains characters
423 * valid for a hostname and that a hostname is not too long.
424 * @param host Hostname to check.
425 * @param maxlen Maximum length of hostname, not including NUL terminator.
426 * @return Non-zero if the hostname is valid.
429 auth_verify_hostname(const char *host, int maxlen)
433 /* Walk through the host name */
434 for (i = 0; host[i]; i++)
435 /* If it's not a hostname character or if it's too long, return false */
436 if (!IsHostChar(host[i]) || i >= maxlen)
439 return 1; /* it's a valid hostname */
442 /** Assign a client to a connection class.
443 * @param[in] cptr Client to assign to a class.
444 * @return Zero if client is kept, CPTR_KILLED if rejected.
446 static int preregister_user(struct Client *cptr)
448 static time_t last_too_many1;
449 static time_t last_too_many2;
451 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
452 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
454 switch (conf_check_client(cptr))
458 case ACR_NO_AUTHORIZATION:
459 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
460 get_client_name(cptr, HIDE_IP));
461 ++ServerStats->is_ref;
462 return exit_client(cptr, cptr, &me,
463 "No Authorization - use another server");
464 case ACR_TOO_MANY_IN_CLASS:
465 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
466 "Too many connections in class %s for %s.",
467 get_client_class(cptr),
468 get_client_name(cptr, SHOW_IP));
469 ++ServerStats->is_ref;
470 return exit_client(cptr, cptr, &me,
471 "Sorry, your connection class is full - try "
472 "again later or try another server");
473 case ACR_TOO_MANY_FROM_IP:
474 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
475 "Too many connections from same IP for %s.",
476 get_client_name(cptr, SHOW_IP));
477 ++ServerStats->is_ref;
478 return exit_client(cptr, cptr, &me,
479 "Too many connections from your host");
480 case ACR_ALREADY_AUTHORIZED:
481 /* Can this ever happen? */
483 ++ServerStats->is_ref;
484 IPcheck_connect_fail(cptr);
485 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
490 /** Send the ident server a query giving "theirport , ourport". The
491 * write is only attempted *once* so it is deemed to be a fail if the
492 * entire write doesn't write all the data given. This shouldn't be a
493 * problem since the socket should have a write buffer far greater
494 * than this message to store it in should problems arise. -avalon
495 * @param[in] auth The request to send.
497 static void send_auth_query(struct AuthRequest* auth)
504 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
505 auth->port, auth->local.port);
507 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
508 close(s_fd(&auth->socket));
509 socket_del(&auth->socket);
510 s_fd(&auth->socket) = -1;
511 ++ServerStats->is_abad;
512 if (IsUserPort(auth->client))
513 sendheader(auth->client, REPORT_FAIL_ID);
514 FlagClr(&auth->flags, AR_AUTH_PENDING);
515 check_auth_finished(auth, 0);
519 /** Enum used to index ident reply fields in a human-readable way. */
520 enum IdentReplyFields {
528 /** Parse an ident reply line and extract the userid from it.
529 * @param[in] reply The ident reply line.
530 * @return The userid, or NULL on parse failure.
532 static char* check_ident_reply(char* reply)
536 char* vector[USERID_TOKEN_COUNT];
537 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
539 if (USERID_TOKEN_COUNT != count)
542 * second token is the reply type
544 token = vector[IDENT_REPLY_TYPE];
545 if (EmptyString(token))
548 while (IsSpace(*token))
551 if (0 != strncmp(token, "USERID", 6))
555 * third token is the os type
557 token = vector[IDENT_OS_TYPE];
558 if (EmptyString(token))
560 while (IsSpace(*token))
564 * Unless "OTHER" is specified as the operating system
565 * type, the server is expected to return the "normal"
566 * user identification of the owner of this connection.
567 * "Normal" in this context may be taken to mean a string
568 * of characters which uniquely identifies the connection
569 * owner such as a user identifier assigned by the system
570 * administrator and used by such user as a mail
571 * identifier, or as the "user" part of a user/password
572 * pair used to gain access to system resources. When an
573 * operating system is specified (e.g., anything but
574 * "OTHER"), the user identifier is expected to be in a
575 * more or less immediately useful form - e.g., something
576 * that could be used as an argument to "finger" or as a
579 if (0 == strncmp(token, "OTHER", 5))
582 * fourth token is the username
584 token = vector[IDENT_INFO];
585 if (EmptyString(token))
587 while (IsSpace(*token))
590 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
592 for (end = token; *end; ++end) {
593 if (IsSpace(*end) || '@' == *end || ':' == *end)
600 /** Read the reply (if any) from the ident server we connected to. We
601 * only give it one shot, if the reply isn't good the first time fail
602 * the authentication entirely. --Bleep
603 * @param[in] auth The request to read.
605 static void read_auth_reply(struct AuthRequest* auth)
610 * rfc1453 sez we MUST accept 512 bytes
612 char buf[BUFSIZE + 1];
615 assert(0 != auth->client);
616 assert(auth == cli_auth(auth->client));
618 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
620 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
621 username = check_ident_reply(buf);
622 Debug((DEBUG_INFO, "Username: %s", username));
625 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
626 close(s_fd(&auth->socket));
627 socket_del(&auth->socket);
628 s_fd(&auth->socket) = -1;
630 if (EmptyString(username)) {
631 if (IsUserPort(auth->client))
632 sendheader(auth->client, REPORT_FAIL_ID);
633 ++ServerStats->is_abad;
635 if (IsUserPort(auth->client))
636 sendheader(auth->client, REPORT_FIN_ID);
637 ++ServerStats->is_asuc;
638 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
639 ircd_strncpy(cli_username(auth->client), username, USERLEN);
640 SetGotId(auth->client);
642 if (IAuthHas(iauth, IAUTH_UNDERNET))
643 sendto_iauth(auth->client, "u %s", username);
646 FlagClr(&auth->flags, AR_AUTH_PENDING);
647 check_auth_finished(auth, 0);
650 /** Handle socket I/O activity.
651 * @param[in] ev A socket event whos associated data is the active
652 * struct AuthRequest.
654 static void auth_sock_callback(struct Event* ev)
656 struct AuthRequest* auth;
658 assert(0 != ev_socket(ev));
659 assert(0 != s_data(ev_socket(ev)));
661 auth = (struct AuthRequest*) s_data(ev_socket(ev));
663 switch (ev_type(ev)) {
664 case ET_DESTROY: /* being destroyed */
667 case ET_CONNECT: /* socket connection completed */
668 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
669 auth, cli_fd(auth->client)));
670 socket_state(&auth->socket, SS_CONNECTED);
671 send_auth_query(auth);
674 case ET_READ: /* socket is readable */
675 case ET_EOF: /* end of file on socket */
676 case ET_ERROR: /* error on socket */
677 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
678 read_auth_reply(auth);
682 assert(0 && "Unrecognized event in auth_socket_callback().");
687 /** Stop an auth request completely.
688 * @param[in] auth The struct AuthRequest to cancel.
689 * @param[in] send_reports If non-zero, report the failure to the user.
691 void destroy_auth_request(struct AuthRequest* auth, int send_reports)
693 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
695 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
696 if (send_reports && IsUserPort(auth->client))
697 sendheader(auth->client, REPORT_FAIL_ID);
700 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
701 delete_resolver_queries(auth);
702 if (send_reports && IsUserPort(auth->client))
703 sendheader(auth->client, REPORT_FAIL_DNS);
706 if (-1 < s_fd(&auth->socket)) {
707 close(s_fd(&auth->socket));
708 socket_del(&auth->socket);
709 s_fd(&auth->socket) = -1;
712 timer_del(&auth->timeout);
713 cli_auth(auth->client) = NULL;
716 /** Timeout a given auth request.
717 * @param[in] ev A timer event whose associated data is the expired
718 * struct AuthRequest.
720 static void auth_timeout_callback(struct Event* ev)
722 struct AuthRequest* auth;
724 assert(0 != ev_timer(ev));
725 assert(0 != t_data(ev_timer(ev)));
727 auth = (struct AuthRequest*) t_data(ev_timer(ev));
729 if (ev_type(ev) == ET_EXPIRE) {
730 /* Report the timeout in the log. */
731 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
732 get_client_name(auth->client, HIDE_IP));
733 /* Tell iauth if we will let the client on. */
734 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)
735 && !IAuthHas(iauth, IAUTH_REQUIRED))
737 sendto_iauth(auth->client, "T");
738 FlagClr(&auth->flags , AR_IAUTH_PENDING);
740 /* Try to register the client. */
741 check_auth_finished(auth, 1);
742 /* If that failed, kick them off. */
743 if (!IsUser(auth->client))
744 exit_client(auth->client, auth->client, &me, "Authorization timed out");
748 /** Handle a complete DNS lookup. Send the client on it's way to a
749 * connection completion, regardless of success or failure -- unless
750 * there was a mismatch and KILL_IPMISMATCH is set.
751 * @param[in] vptr The pending struct AuthRequest.
752 * @param[in] addr IP address being resolved.
753 * @param[in] h_name Resolved name, or NULL if lookup failed.
755 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
757 struct AuthRequest* auth = (struct AuthRequest*) vptr;
760 FlagClr(&auth->flags, AR_DNS_PENDING);
762 /* DNS entry was missing for the IP. */
763 if (IsUserPort(auth->client))
764 sendheader(auth->client, REPORT_FAIL_DNS);
765 sendto_iauth(auth->client, "d");
766 } else if (irc_in_addr_cmp(addr, &cli_ip(auth->client))
767 && irc_in_addr_cmp(addr, &auth->original)) {
768 /* IP for hostname did not match client's IP. */
769 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
770 cli_sock_ip(auth->client), h_name,
772 if (IsUserPort(auth->client))
773 sendheader(auth->client, REPORT_IP_MISMATCH);
774 /* Clear DNS pending flag so free_client doesn't ask the resolver
775 * to delete the query that just finished.
777 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
778 IPcheck_disconnect(auth->client);
779 Count_unknowndisconnects(UserStats);
780 free_client(auth->client);
782 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
783 /* Hostname did not look valid. */
784 if (IsUserPort(auth->client))
785 sendheader(auth->client, REPORT_INVAL_DNS);
786 sendto_iauth(auth->client, "d");
788 /* Hostname and mappings checked out. */
789 if (IsUserPort(auth->client))
790 sendheader(auth->client, REPORT_FIN_DNS);
791 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
792 sendto_iauth(auth->client, "N %s", h_name);
794 check_auth_finished(auth, 0);
797 /** Flag the client to show an attempt to contact the ident server on
798 * the client's host. Should the connect or any later phase of the
799 * identifying process fail, it is aborted and the user is given a
800 * username of "unknown".
801 * @param[in] auth The request for which to start the ident lookup.
803 static void start_auth_query(struct AuthRequest* auth)
805 struct irc_sockaddr remote_addr;
806 struct irc_sockaddr local_addr;
811 assert(0 != auth->client);
814 * get the local address of the client and bind to that to
815 * make the auth request. This used to be done only for
816 * ifdef VIRTUAL_HOST, but needs to be done for all clients
817 * since the ident request must originate from that same address--
818 * and machines with multiple IP addresses are common now
820 memcpy(&local_addr, &auth->local, sizeof(local_addr));
822 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
823 remote_addr.port = 113;
824 fd = os_socket(&local_addr, SOCK_STREAM, "auth query");
826 ++ServerStats->is_abad;
827 if (IsUserPort(auth->client))
828 sendheader(auth->client, REPORT_FAIL_ID);
831 if (IsUserPort(auth->client))
832 sendheader(auth->client, REPORT_DO_ID);
834 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
835 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
836 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
837 SOCK_EVENT_READABLE, fd)) {
838 ++ServerStats->is_abad;
839 if (IsUserPort(auth->client))
840 sendheader(auth->client, REPORT_FAIL_ID);
845 FlagSet(&auth->flags, AR_AUTH_PENDING);
846 if (result == IO_SUCCESS)
847 send_auth_query(auth);
850 /** Initiate DNS lookup for a client.
851 * @param[in] auth The auth request for which to start the DNS lookup.
853 static void start_dns_query(struct AuthRequest *auth)
855 if (feature_bool(FEAT_NODNS)) {
856 sendto_iauth(auth->client, "d");
860 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
861 strcpy(cli_sockhost(auth->client), cli_name(&me));
862 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
866 if (IsUserPort(auth->client))
867 sendheader(auth->client, REPORT_DO_DNS);
869 FlagSet(&auth->flags, AR_DNS_PENDING);
870 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
873 /** Initiate IAuth check for a client.
874 * @param[in] auth The auth request for which to star the IAuth check.
876 static void start_iauth_query(struct AuthRequest *auth)
878 FlagSet(&auth->flags, AR_IAUTH_PENDING);
879 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
880 cli_sock_ip(auth->client), auth->port,
881 ircd_ntoa(&auth->local.addr), auth->local.port))
882 FlagClr(&auth->flags, AR_IAUTH_PENDING);
885 /** Starts auth (identd) and dns queries for a client.
886 * @param[in] client The client for which to start queries.
888 void start_auth(struct Client* client)
890 struct irc_sockaddr remote;
891 struct AuthRequest* auth;
894 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
896 /* Register with event handlers. */
897 cli_lasttime(client) = CurrentTime;
898 cli_since(client) = CurrentTime;
899 if (cli_fd(client) > HighestFd)
900 HighestFd = cli_fd(client);
901 LocalClientArray[cli_fd(client)] = client;
902 add_client_to_list(client);
903 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
905 /* Allocate the AuthRequest. */
906 auth = MyCalloc(1, sizeof(*auth));
908 auth->client = client;
909 cli_auth(client) = auth;
910 s_fd(&auth->socket) = -1;
911 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
912 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
914 /* Try to get socket endpoint addresses. */
915 if (!os_get_sockname(cli_fd(client), &auth->local)
916 || !os_get_peername(cli_fd(client), &remote)) {
917 ++ServerStats->is_abad;
918 if (IsUserPort(auth->client))
919 sendheader(auth->client, REPORT_FAIL_ID);
920 IPcheck_disconnect(auth->client);
921 Count_unknowndisconnects(UserStats);
922 free_client(auth->client);
925 auth->port = remote.port;
927 /* Try to start DNS lookup. */
928 start_dns_query(auth);
930 /* Try to start ident lookup. */
931 start_auth_query(auth);
933 /* Set required client inputs for users. */
934 if (IsUserPort(client)) {
935 cli_user(client) = make_user(client);
936 cli_user(client)->server = &me;
937 FlagSet(&auth->flags, AR_NEEDS_USER);
938 FlagSet(&auth->flags, AR_NEEDS_NICK);
940 /* Try to start iauth lookup. */
941 start_iauth_query(auth);
944 /* Check which auth events remain pending. */
945 check_auth_finished(auth, 0);
948 /** Mark that a user has PONGed while unregistered.
949 * @param[in] auth Authorization request for client.
950 * @param[in] cookie PONG cookie value sent by client.
951 * @return Zero if client should be kept, CPTR_KILLED if rejected.
953 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
955 assert(auth != NULL);
956 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
958 if (cookie != auth->cookie)
960 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
961 ":To connect, type /QUOTE PONG %u", auth->cookie);
964 FlagClr(&auth->flags, AR_NEEDS_PONG);
965 return check_auth_finished(auth, 0);
968 /** Record a user's claimed username and userinfo.
969 * @param[in] auth Authorization request for client.
970 * @param[in] username Client's asserted username.
971 * @param[in] userinfo Client's asserted self-description.
972 * @return Zero if client should be kept, CPTR_KILLED if rejected.
974 int auth_set_user(struct AuthRequest *auth, const char *username, const char *userinfo)
978 assert(auth != NULL);
979 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
981 FlagClr(&auth->flags, AR_NEEDS_USER);
983 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
984 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
985 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
986 if (IAuthHas(iauth, IAUTH_UNDERNET))
987 sendto_iauth(cptr, "U %s %s", username, userinfo);
988 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
989 sendto_iauth(cptr, "U %s", username);
990 return check_auth_finished(auth, 0);
993 /** Handle authorization-related aspects of initial nickname selection.
994 * This is called after verifying that the nickname is available.
995 * @param[in] auth Authorization request for client.
996 * @param[in] nickname Client's requested nickname.
997 * @return Zero if client should be kept, CPTR_KILLED if rejected.
999 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1001 assert(auth != NULL);
1002 FlagClr(&auth->flags, AR_NEEDS_NICK);
1004 * If the client hasn't gotten a cookie-ping yet,
1005 * choose a cookie and send it. -record!jegelhof@cloud9.net
1007 if (!auth->cookie) {
1009 auth->cookie = ircrandom();
1010 } while (!auth->cookie);
1011 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1012 FlagSet(&auth->flags, AR_NEEDS_PONG);
1014 if (IAuthHas(iauth, IAUTH_UNDERNET))
1015 sendto_iauth(auth->client, "n %s", nickname);
1016 return check_auth_finished(auth, 0);
1019 /** Record a user's password.
1020 * @param[in] auth Authorization request for client.
1021 * @param[in] password Client's password.
1022 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1024 int auth_set_password(struct AuthRequest *auth, const char *password)
1026 assert(auth != NULL);
1027 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1028 sendto_iauth(auth->client, "P %s", password);
1032 /** Send exit notification for \a cptr to iauth.
1033 * @param[in] cptr Client who is exiting.
1035 void auth_send_exit(struct Client *cptr)
1037 sendto_iauth(cptr, "D");
1040 /** Mark that a user has started capabilities negotiation.
1041 * This blocks authorization until auth_cap_done() is called.
1042 * @param[in] auth Authorization request for client.
1043 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1045 int auth_cap_start(struct AuthRequest *auth)
1047 assert(auth != NULL);
1048 FlagSet(&auth->flags, AR_CAP_PENDING);
1052 /** Mark that a user has completed capabilities negotiation.
1053 * This unblocks authorization if auth_cap_start() was called.
1054 * @param[in] auth Authorization request for client.
1055 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1057 int auth_cap_done(struct AuthRequest *auth)
1059 assert(auth != NULL);
1060 FlagClr(&auth->flags, AR_CAP_PENDING);
1061 return check_auth_finished(auth, 0);
1064 /** Attempt to spawn the process for an IAuth instance.
1065 * @param[in] iauth IAuth descriptor.
1066 * @param[in] automatic If non-zero, apply sanity checks against
1067 * excessive automatic restarts.
1068 * @return 0 on success, non-zero on failure.
1070 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1077 if (automatic && CurrentTime - iauth->started < 5)
1079 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1083 /* Record time we tried to spawn the iauth process. */
1084 iauth->started = CurrentTime;
1086 /* Attempt to allocate a pair of sockets. */
1087 res = os_socketpair(s_io);
1091 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1092 res = os_set_nonblocking(s_io[0]);
1100 /* Initialize the socket structure to talk to the child. */
1101 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1102 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1110 /* Allocate another pair for stderr. */
1111 res = os_socketpair(s_err);
1114 socket_del(i_socket(iauth));
1120 /* Mark parent side of this pair non-blocking, too. */
1121 res = os_set_nonblocking(s_err[0]);
1126 socket_del(i_socket(iauth));
1132 /* And set up i_stderr(iauth). */
1133 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1134 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1139 socket_del(i_socket(iauth));
1145 /* Attempt to fork a child process. */
1148 /* Error forking the child, still in parent. */
1150 socket_del(i_stderr(iauth));
1153 socket_del(i_socket(iauth));
1160 /* We are the parent process. Close the child's sockets. */
1163 /* Send our server name (supposedly for proxy checking purposes)
1164 * and maximum number of connections (for allocation hints).
1165 * Need to use conf_get_local() since &me may not be fully
1166 * initialized the first time we run.
1168 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1169 /* Indicate success (until the child dies). */
1173 /* We are the child process.
1174 * Duplicate our end of the socket to stdin, stdout and stderr.
1175 * Then close all the higher-numbered FDs and exec the process.
1177 if (dup2(s_io[1], 0) == 0
1178 && dup2(s_io[1], 1) == 1
1179 && dup2(s_err[1], 2) == 2) {
1180 close_connections(0);
1181 execvp(iauth->i_argv[0], iauth->i_argv);
1184 /* If we got here, something was seriously wrong. */
1188 /** See if an %IAuth program must be spawned.
1189 * If a process is already running with the specified options, keep it.
1190 * Otherwise spawn a new child process to perform the %IAuth function.
1191 * @param[in] argc Number of parameters to use when starting process.
1192 * @param[in] argv Array of parameters to start process.
1193 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1195 int auth_spawn(int argc, char *argv[])
1202 /* Check that incoming arguments all match pre-existing arguments. */
1203 for (ii = 0; same && (ii < argc); ++ii) {
1204 if (NULL == iauth->i_argv[ii]
1205 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1208 /* Check that we have no more pre-existing arguments. */
1209 if (iauth->i_argv[ii])
1211 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1212 if (same && i_GetConnected(iauth)) {
1213 IAuthClr(iauth, IAUTH_CLOSING);
1216 /* Deallocate old argv elements. */
1217 for (ii = 0; iauth->i_argv[ii]; ++ii)
1218 MyFree(iauth->i_argv[ii]);
1219 MyFree(iauth->i_argv);
1222 /* Need to initialize a new connection. */
1223 iauth = MyCalloc(1, sizeof(*iauth));
1224 msgq_init(i_sendQ(iauth));
1225 /* Populate iauth's argv array. */
1226 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1227 for (ii = 0; ii < argc; ++ii)
1228 DupString(iauth->i_argv[ii], argv[ii]);
1229 iauth->i_argv[ii] = NULL;
1230 /* Try to spawn it, and handle the results. */
1231 if (iauth_do_spawn(iauth, 0))
1233 IAuthClr(iauth, IAUTH_CLOSING);
1237 /** Mark all %IAuth connections as closing. */
1238 void auth_mark_closing(void)
1241 IAuthSet(iauth, IAUTH_CLOSING);
1244 /** Complete disconnection of an %IAuth connection.
1245 * @param[in] iauth %Connection to fully close.
1247 static void iauth_disconnect(struct IAuth *iauth)
1249 if (!i_GetConnected(iauth))
1252 /* Close main socket. */
1253 close(s_fd(i_socket(iauth)));
1254 socket_del(i_socket(iauth));
1255 s_fd(i_socket(iauth)) = -1;
1257 /* Close error socket. */
1258 close(s_fd(i_stderr(iauth)));
1259 socket_del(i_stderr(iauth));
1260 s_fd(i_stderr(iauth)) = -1;
1263 /** Close all %IAuth connections marked as closing. */
1264 void auth_close_unused(void)
1266 if (iauth && IAuthHas(iauth, IAUTH_CLOSING)) {
1268 iauth_disconnect(iauth);
1269 if (iauth->i_argv) {
1270 for (ii = 0; iauth->i_argv[ii]; ++ii)
1271 MyFree(iauth->i_argv[ii]);
1272 MyFree(iauth->i_argv);
1278 /** Send queued output to \a iauth.
1279 * @param[in] iauth Writable connection with queued data.
1281 static void iauth_write(struct IAuth *iauth)
1283 unsigned int bytes_tried, bytes_sent;
1286 if (IAuthHas(iauth, IAUTH_BLOCKED))
1288 while (MsgQLength(i_sendQ(iauth)) > 0) {
1289 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1292 msgq_delete(i_sendQ(iauth), bytes_sent);
1293 iauth->i_sendB += bytes_sent;
1294 if (bytes_tried == bytes_sent)
1296 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1298 IAuthSet(iauth, IAUTH_BLOCKED);
1299 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1302 iauth_disconnect(iauth);
1306 /* We were able to flush all events, so remove notification. */
1307 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1310 /** Send a message to iauth.
1311 * @param[in] cptr Optional client context for message.
1312 * @param[in] format Format string for message.
1313 * @return Non-zero on successful send or buffering, zero on failure.
1315 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1320 /* Do not send requests when we have no iauth. */
1321 if (!i_GetConnected(iauth))
1323 /* Do not send for clients in the NORMAL state. */
1325 && (format[0] != 'D')
1326 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1329 /* Build the message buffer. */
1330 vd.vd_format = format;
1331 va_start(vd.vd_args, format);
1333 mb = msgq_make(NULL, "-1 %v", &vd);
1335 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1338 /* Tack it onto the iauth sendq and try to write it. */
1340 msgq_add(i_sendQ(iauth), mb, 0);
1345 /** Send text to interested operators (SNO_AUTH server notice).
1346 * @param[in] iauth Active IAuth session.
1347 * @param[in] cli Client referenced by command.
1348 * @param[in] params Text to send.
1351 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli, char *params)
1353 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params);
1357 /** Set the debug level for the session.
1358 * @param[in] iauth Active IAuth session.
1359 * @param[in] cli Client referenced by command.
1360 * @param[in] params String starting with an integer.
1363 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli, char *params)
1367 new_level = atoi(params);
1368 if (i_debug(iauth) > 0 || new_level > 0) {
1369 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1370 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1372 i_debug(iauth) = new_level;
1376 /** Set policy options for the session.
1377 * Old policy is forgotten, and any of the following characters in \a
1378 * params enable the corresponding policy:
1379 * \li A IAUTH_ADDLINFO
1380 * \li R IAUTH_REQUIRED
1381 * \li T IAUTH_TIMEOUT
1382 * \li W IAUTH_EXTRAWAIT
1383 * \li U IAUTH_UNDERNET
1385 * @param[in] iauth Active IAuth session.
1386 * @param[in] cli Client referenced by command.
1387 * @param[in] params Zero or more policy options.
1390 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli, char *params)
1392 enum IAuthFlag flag;
1395 /* Erase old policy first. */
1396 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1397 IAuthClr(iauth, flag);
1399 /* Parse new policy set. */
1400 for (p = params; *p; p++) switch (*p) {
1401 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1402 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1403 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1404 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1405 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1408 /* Optionally notify operators. */
1409 if (i_debug(iauth) > 0)
1410 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params);
1414 /** Set the iauth program version number.
1415 * @param[in] iauth Active IAuth session.
1416 * @param[in] cli Client referenced by command.
1417 * @param[in] params Version number or name.
1420 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli, char *params)
1422 MyFree(iauth->i_version);
1423 while (IsSpace(*params))
1425 DupString(iauth->i_version, params);
1426 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.", iauth->i_version);
1430 /** Clear cached iauth configuration information.
1431 * @param[in] iauth Active IAuth session.
1432 * @param[in] cli Client referenced by command.
1433 * @param[in] params Parameter list (ignored).
1436 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli, char *params)
1441 head = iauth->i_config;
1442 iauth->i_config = NULL;
1443 for (; head; head = next) {
1445 MyFree(head->value.cp);
1448 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1452 /** Append iauth configuration information.
1453 * @param[in] iauth Active IAuth session.
1454 * @param[in] cli Client referenced by command.
1455 * @param[in] params Description of configuration element.
1458 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli, char *params)
1462 if (iauth->i_config) {
1463 for (node = iauth->i_config; node->next; node = node->next) ;
1464 node = node->next = make_link();
1466 node = iauth->i_config = make_link();
1468 while (IsSpace(*params))
1470 DupString(node->value.cp, params);
1474 /** Clear cached iauth configuration information.
1475 * @param[in] iauth Active IAuth session.
1476 * @param[in] cli Client referenced by command.
1477 * @param[in] params Parameter list (ignored).
1480 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli, char *params)
1485 head = iauth->i_stats;
1486 iauth->i_stats = NULL;
1487 for (; head; head = next) {
1489 MyFree(head->value.cp);
1492 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1496 /** Append iauth statistics information.
1497 * @param[in] iauth Active IAuth session.
1498 * @param[in] cli Client referenced by command.
1499 * @param[in] params Statistics element.
1502 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli, char *params)
1505 if (iauth->i_stats) {
1506 for (node = iauth->i_stats; node->next; node = node->next) ;
1507 node = node->next = make_link();
1509 node = iauth->i_stats = make_link();
1511 while (IsSpace(*params))
1513 DupString(node->value.cp, params);
1517 /** Set client's username to a trusted string even if it breaks the rules.
1518 * @param[in] iauth Active IAuth session.
1519 * @param[in] cli Client referenced by command.
1520 * @param[in] params Forced username.
1523 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli, char *params)
1525 assert(cli_auth(cli) != NULL);
1526 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1527 if (!EmptyString(params)) {
1528 ircd_strncpy(cli_username(cli), params, USERLEN);
1530 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1531 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1536 /** Set client's username to a trusted string.
1537 * @param[in] iauth Active IAuth session.
1538 * @param[in] cli Client referenced by command.
1539 * @param[in] params Trusted username.
1542 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli, char *params)
1544 assert(cli_auth(cli) != NULL);
1545 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1546 if (!EmptyString(params)) {
1547 ircd_strncpy(cli_username(cli), params, USERLEN);
1549 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1554 /** Set client's username to an untrusted string.
1555 * @param[in] iauth Active IAuth session.
1556 * @param[in] cli Client referenced by command.
1557 * @param[in] params Untrusted username.
1560 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli, char *params)
1562 assert(cli_auth(cli) != NULL);
1563 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1564 if (!EmptyString(params))
1565 ircd_strncpy(cli_user(cli)->username, params, USERLEN);
1569 /** Set client's hostname.
1570 * @param[in] iauth Active IAuth session.
1571 * @param[in] cli Client referenced by command.
1572 * @param[in] params New hostname for client.
1573 * @return Non-zero if \a cli authorization should be checked for completion.
1575 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli, char *params)
1577 struct AuthRequest *auth;
1579 if (EmptyString(params)) {
1580 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1584 auth = cli_auth(cli);
1585 assert(auth != NULL);
1587 /* If a DNS request is pending, abort it. */
1588 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1589 FlagClr(&auth->flags, AR_DNS_PENDING);
1590 delete_resolver_queries(auth);
1591 if (IsUserPort(cli))
1592 sendheader(cli, REPORT_FIN_DNS);
1594 /* Set hostname from params. */
1595 ircd_strncpy(cli_sockhost(cli), params, HOSTLEN);
1599 /** Set client's IP address.
1600 * @param[in] iauth Active IAuth session.
1601 * @param[in] cli Client referenced by command.
1602 * @param[in] params New IP address for client in dotted quad or
1603 * standard IPv6 format.
1606 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli, char *params)
1608 struct irc_in_addr addr;
1609 struct AuthRequest *auth;
1611 /* Get AuthRequest for client. */
1612 auth = cli_auth(cli);
1613 assert(auth != NULL);
1615 /* Parse the client's new IP address. */
1616 if (!ircd_aton(&addr, params)) {
1617 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params);
1621 /* If this is the first IP override, save the client's original
1622 * address in case we get a DNS response later.
1624 if (!irc_in_addr_valid(&auth->original))
1625 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1627 /* Undo original IP connection in IPcheck. */
1628 IPcheck_connect_fail(cli);
1629 ClearIPChecked(cli);
1631 /* Update the IP and charge them as a remote connect. */
1632 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1633 IPcheck_remote_connect(cli, 0);
1638 /** Find a ConfItem structure for a named connection class.
1639 * @param[in] class_name Name of configuration class to find.
1640 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1642 static struct ConfItem *auth_find_class_conf(const char *class_name)
1644 static struct ConfItem *aconf_list;
1645 struct ConnectionClass *class;
1646 struct ConfItem *aconf;
1648 /* Make sure the configuration class is valid. */
1649 class = find_class(class_name);
1653 /* Look for an existing ConfItem for the class. */
1654 for (aconf = aconf_list; aconf; aconf = aconf->next)
1655 if (aconf->conn_class == class)
1658 /* If no ConfItem, create one. */
1660 aconf = make_conf(CONF_CLIENT);
1662 sendto_opmask_butone(NULL, SNO_AUTH,
1663 "Unable to allocate ConfItem for class %s!",
1667 aconf->conn_class = class;
1668 aconf->next = aconf_list;
1675 /** Accept a client in IAuth.
1676 * @param[in] iauth Active IAuth session.
1677 * @param[in] cli Client referenced by command.
1678 * @param[in] params Optional class name for client.
1681 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli, char *params)
1683 static time_t warn_time;
1685 /* Clear iauth pending flag. */
1686 assert(cli_auth(cli) != NULL);
1687 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1689 /* If a connection class was specified (and usable), assign the client to it. */
1690 if (!EmptyString(params)) {
1691 struct ConfItem *aconf;
1693 aconf = auth_find_class_conf(params);
1695 attach_conf(cli, aconf);
1697 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1698 "iauth tried to use undefined class [%s]",
1705 /** Accept a client in IAuth and assign them to an account.
1706 * @param[in] iauth Active IAuth session.
1707 * @param[in] cli Client referenced by command.
1708 * @param[in] params Account name and optional class name for client.
1709 * @return Non-zero if \a cli authorization should be checked for completion.
1711 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli, char *params)
1717 if (EmptyString(params)) {
1718 sendto_iauth(cli, "E Missing :Missing account parameter");
1721 /* Check length of account name. */
1722 len = strcspn(params, ": ");
1723 if (len > ACCOUNTLEN) {
1724 sendto_iauth(cli, "E Invalid :Account parameter too long");
1727 /* If account has a creation timestamp, use it. */
1728 assert(cli_user(cli) != NULL);
1729 if (params[len] == ':')
1730 cli_user(cli)->acc_create = strtoul(params + len + 1, &end, 10);
1733 /* Copy account name to User structure. */
1734 ircd_strncpy(cli_user(cli)->account, params, ACCOUNTLEN);
1736 /* Skip whitespace before next argument. */
1737 while (IsSpace(*end))
1739 /* Fall through to the normal "done" handler. */
1740 return iauth_cmd_done_client(iauth, cli, end);
1743 /** Reject a client's connection.
1744 * @param[in] iauth Active IAuth session.
1745 * @param[in] cli Client referenced by command.
1746 * @param[in] params Optional kill message.
1749 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli, char *params)
1752 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1753 if (EmptyString(params))
1754 params = "Access denied";
1755 exit_client(cli, cli, &me, params);
1759 /** Send a challenge string to the client.
1760 * @param[in] iauth Active IAuth session.
1761 * @param[in] cli Client referenced by command.
1762 * @param[in] params Challenge message for client.
1765 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli, char *params)
1767 sendrawto_one(cli, "NOTICE AUTH :*** %s", params);
1771 /** Read input from \a iauth.
1772 * Reads up to SERVER_TCP_WINDOW bytes per pass.
1773 * @param[in] iauth Readable connection.
1775 static void iauth_read(struct IAuth *iauth)
1777 static char readbuf[SERVER_TCP_WINDOW];
1778 iauth_cmd_handler handler;
1779 struct AuthRequest *auth;
1785 unsigned int length;
1790 switch (os_recv_nonb(s_fd(i_socket(iauth)), readbuf, sizeof(readbuf), &length))
1792 case IO_SUCCESS: break;
1793 case IO_FAILURE: iauth_disconnect(iauth);
1794 case IO_BLOCKED: return;
1796 iauth->i_recvB += length;
1797 old_buffer = iauth->i_buffer;
1798 endp = old_buffer + iauth->i_count;
1799 for (src = readbuf; length > 0; --length) {
1802 /* Terminate line, reset buffer and update statistics. */
1807 /* If spammy debug, send the message to opers. */
1808 if (i_debug(iauth) > 1)
1809 sendto_opmask_butone(NULL, SNO_AUTH, "%s", endp);
1811 /* Find command handler. A lot of the handlers would be simpler
1812 * with an argument splitter like in parse.c, but some commands
1813 * (notably '>') do not use delimiters that way.
1815 switch (*(endp = old_buffer)) {
1816 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1817 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1818 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1819 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1820 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1821 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1822 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1823 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1824 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1825 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1826 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1827 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1828 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1829 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1830 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1831 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1832 case 'k': /* The 'k' command indicates the user should be booted
1833 * off without telling opers. There is no way to
1834 * signal that to exit_client(), so we fall through to
1835 * the case that we do implement.
1837 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1838 case 'r': /* we handle termination directly */ continue;
1839 default: sendto_iauth(NULL, "E Garbage :[%s]", endp); continue;
1842 /* Skip whitespace at start of arguments. */
1843 while (IsSpace(*++endp)) ;
1845 /* At this point, has_cli has one of three values:
1846 * 0 - no client is identified
1847 * 1 - a client is identified and must still be registering
1848 * 2 - a client is identified but may be fully registered
1851 /* Figure out how to handle the command. */
1853 /* Handler does not need a client. */
1854 handler(iauth, NULL, endp);
1856 /* Try to find the client associated with the request. */
1857 id = strtol(endp, ¶ms, 10);
1858 while (IsSpace(*params))
1860 if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id])) {
1861 /* Client no longer exists (or never existed). */
1862 sendto_iauth(NULL, "E Gone :[%s]", params);
1863 } else if ((!(auth = cli_auth(cli))
1864 || !FlagHas(&auth->flags, AR_IAUTH_PENDING))
1865 && (has_cli == 1)) {
1866 /* Client is done with IAuth checks. */
1867 sendto_iauth(cli, "E Done :[%s]", params);
1869 struct irc_sockaddr addr;
1872 /* Skip whitespace before IP address. */
1873 while (IsSpace(*params))
1875 /* Record start of IP address, then null terminate it. */
1877 while (!IsSpace(*params) && *params != '\0')
1879 if (IsSpace(*params))
1881 /* Parse out client IP address and port number. */
1882 res = ipmask_parse(orig_ip, &addr.addr, NULL);
1883 addr.port = strtol(params, ¶ms, 10);
1884 /* Skip whitespace and optional sentinel after port number. */
1885 while (IsSpace(*params))
1889 /* Check IP address and port number against expected. */
1891 || irc_in_addr_cmp(&addr.addr, &cli_ip(cli))
1892 || (auth && addr.port != auth->port)) {
1893 /* Report mismatch to iauth. */
1894 sendto_iauth(cli, "E Mismatch :[%s] != [%s]",
1895 orig_ip, ircd_ntoa(&cli_ip(cli)));
1896 } else if (handler(iauth, cli, params)) {
1897 /* Handler indicated a possible state change. */
1898 check_auth_finished(auth, 0);
1903 /* Reset buffer pointer to read next line. */
1906 else if (endp < old_buffer + BUFSIZE)
1909 iauth->i_count = endp - old_buffer;
1912 /** Handle socket activity for an %IAuth connection.
1913 * @param[in] ev &Socket event; the IAuth connection is the user data
1914 * pointer for the socket.
1916 static void iauth_sock_callback(struct Event *ev)
1918 struct IAuth *iauth;
1920 assert(0 != ev_socket(ev));
1921 iauth = (struct IAuth*) s_data(ev_socket(ev));
1924 switch (ev_type(ev)) {
1926 /* Hm, what happened here? */
1927 if (!IAuthHas(iauth, IAUTH_CLOSING))
1928 iauth_do_spawn(iauth, 1);
1934 IAuthClr(iauth, IAUTH_BLOCKED);
1938 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
1939 /* and fall through to the ET_EOF case */
1941 iauth_disconnect(iauth);
1944 assert(0 && "Unrecognized event type");
1949 /** Read error input from \a iauth.
1950 * @param[in] iauth Readable connection.
1952 static void iauth_read_stderr(struct IAuth *iauth)
1954 static char readbuf[SERVER_TCP_WINDOW];
1955 unsigned int length;
1959 /* Copy partial data to readbuf, append new data. */
1960 length = iauth->i_errcount;
1961 memcpy(readbuf, iauth->i_errbuf, length);
1962 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
1964 sizeof(readbuf) - length - 1,
1967 readbuf[length] = '\0';
1969 /* Send each complete line to SNO_AUTH. */
1970 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
1972 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
1973 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
1974 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
1977 /* Put unused data back into connection's buffer. */
1978 iauth->i_errcount = strlen(sol);
1979 if (iauth->i_errcount > BUFSIZE)
1980 iauth->i_errcount = BUFSIZE;
1981 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
1984 /** Handle error socket activity for an %IAuth connection.
1985 * @param[in] ev &Socket event; the IAuth connection is the user data
1986 * pointer for the socket.
1988 static void iauth_stderr_callback(struct Event *ev)
1990 struct IAuth *iauth;
1992 assert(0 != ev_socket(ev));
1993 iauth = (struct IAuth*) s_data(ev_socket(ev));
1996 switch (ev_type(ev)) {
1998 iauth_read_stderr(iauth);
2001 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2002 /* and fall through to the ET_EOF/ET_DESTROY case */
2007 assert(0 && "Unrecognized event type");
2012 /** Report active iauth's configuration to \a cptr.
2013 * @param[in] cptr Client requesting statistics.
2014 * @param[in] sd Stats descriptor for request.
2015 * @param[in] param Extra parameter from user (may be NULL).
2017 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2021 for (link = iauth->i_config; link; link = link->next)
2023 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2026 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth configuration.");
2029 /** Report active iauth's statistics to \a cptr.
2030 * @param[in] cptr Client requesting statistics.
2031 * @param[in] sd Stats descriptor for request.
2032 * @param[in] param Extra parameter from user (may be NULL).
2034 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2038 for (link = iauth->i_stats; link; link = link->next)
2040 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2043 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth statistics.");