1 /************************************************************************
2 * IRC - Internet Relay Chat, src/s_auth.c
3 * Copyright (C) 1992 Darren Reed
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 1, or (at your option)
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 * July 6, 1999 - Rewrote most of the code here. When a client connects
21 * to the server and passes initial socket validation checks, it
22 * is owned by this module (auth) which returns it to the rest of the
23 * server when dns and auth queries are finished. Until the client is
24 * released, the server does not know it exists and does not process
25 * any messages from it.
26 * --Bleep Thomas Helvey <tomh@inxpress.net>
28 * December 26, 2005 - Rewrite the flag handling and integrate that with
29 * an IRCnet-style IAuth protocol.
33 * @brief Implementation of DNS and ident lookups.
43 #include "ircd_alloc.h"
44 #include "ircd_chattr.h"
45 #include "ircd_events.h"
46 #include "ircd_features.h"
48 #include "ircd_osdep.h"
49 #include "ircd_reply.h"
50 #include "ircd_snprintf.h"
51 #include "ircd_string.h"
53 #include "msg.h" /* for MAXPARA */
55 #include "querycmds.h"
70 #include <sys/socket.h>
71 #include <sys/ioctl.h>
73 /** Pending operations during registration. */
74 enum AuthRequestFlag {
75 AR_AUTH_PENDING, /**< ident connecting or waiting for response */
76 AR_DNS_PENDING, /**< dns request sent, waiting for response */
77 AR_CAP_PENDING, /**< in middle of CAP negotiations */
78 AR_NEEDS_PONG, /**< user has not PONGed */
79 AR_NEEDS_USER, /**< user must send USER command */
80 AR_NEEDS_NICK, /**< user must send NICK command */
81 AR_LAST_SCAN = AR_NEEDS_NICK, /**< maximum flag to scan through */
82 AR_IAUTH_PENDING, /**< iauth request sent, waiting for response */
83 AR_IAUTH_HURRY, /**< we told iauth to hurry up */
84 AR_IAUTH_USERNAME, /**< iauth sent a username (preferred or forced) */
85 AR_IAUTH_FUSERNAME, /**< iauth sent a forced username */
86 AR_PASSWORD_CHECKED, /**< client password already checked */
90 DECLARE_FLAGSET(AuthRequestFlags, AR_NUM_FLAGS);
92 /** Stores registration state of a client. */
94 struct AuthRequest* next; /**< linked list node ptr */
95 struct AuthRequest* prev; /**< linked list node ptr */
96 struct Client* client; /**< pointer to client struct for request */
97 struct irc_sockaddr local; /**< local endpoint address */
98 struct irc_in_addr original; /**< original client IP address */
99 struct Socket socket; /**< socket descriptor for auth queries */
100 struct Timer timeout; /**< timeout timer for ident and dns queries */
101 struct AuthRequestFlags flags; /**< current state of request */
102 unsigned int cookie; /**< cookie the user must PONG */
103 unsigned short port; /**< client's remote port number */
106 /** Array of message text (with length) pairs for AUTH status
107 * messages. Indexed using #ReportType.
112 } HeaderMessages [] = {
113 #define MSG(STR) { STR, sizeof(STR) - 1 }
114 MSG("NOTICE AUTH :*** Looking up your hostname\r\n"),
115 MSG("NOTICE AUTH :*** Found your hostname\r\n"),
116 MSG("NOTICE AUTH :*** Couldn't look up your hostname\r\n"),
117 MSG("NOTICE AUTH :*** Checking Ident\r\n"),
118 MSG("NOTICE AUTH :*** Got ident response\r\n"),
119 MSG("NOTICE AUTH :*** No ident response\r\n"),
120 MSG("NOTICE AUTH :*** \r\n"),
121 MSG("NOTICE AUTH :*** Your forward and reverse DNS do not match, "
122 "ignoring hostname.\r\n"),
123 MSG("NOTICE AUTH :*** Invalid hostname\r\n")
127 /** Enum used to index messages in the HeaderMessages[] array. */
140 /** Sends response \a r (from #ReportType) to client \a c. */
141 #define sendheader(c, r) \
142 send(cli_fd(c), HeaderMessages[(r)].message, HeaderMessages[(r)].length, 0)
144 /** Enumeration of IAuth connection flags. */
147 IAUTH_BLOCKED, /**< socket buffer full */
148 IAUTH_CLOSING, /**< candidate to be disposed */
149 /* The following flags are controlled by iauth's "O" options command. */
150 IAUTH_ADDLINFO, /**< Send additional info
151 * (password and username). */
152 IAUTH_FIRST_OPTION = IAUTH_ADDLINFO, /**< First flag that is a policy option. */
153 IAUTH_REQUIRED, /**< IAuth completion required for registration. */
154 IAUTH_TIMEOUT, /**< Refuse new connections if IAuth is behind. */
155 IAUTH_EXTRAWAIT, /**< Give IAuth extra time to answer. */
156 IAUTH_UNDERNET, /**< Enable Undernet extensions. */
157 IAUTH_LAST_FLAG /**< total number of flags */
159 /** Declare a bitset structure indexed by IAuthFlag. */
160 DECLARE_FLAGSET(IAuthFlags, IAUTH_LAST_FLAG);
162 /** Describes state of an IAuth connection. */
164 struct MsgQ i_sendQ; /**< messages queued to send */
165 struct Socket i_socket; /**< main socket to iauth */
166 struct Socket i_stderr; /**< error socket for iauth */
167 struct IAuthFlags i_flags; /**< connection state/status/flags */
168 uint64_t i_recvB; /**< bytes received */
169 uint64_t i_sendB; /**< bytes sent */
170 time_t started; /**< time that this instance was started */
171 unsigned int i_recvM; /**< messages received */
172 unsigned int i_sendM; /**< messages sent */
173 unsigned int i_count; /**< characters used in i_buffer */
174 unsigned int i_errcount; /**< characters used in i_errbuf */
175 int i_debug; /**< debug level */
176 char i_buffer[BUFSIZE+1]; /**< partial unprocessed line from server */
177 char i_errbuf[BUFSIZE+1]; /**< partial unprocessed error line */
178 char *i_version; /**< iauth version string */
179 struct SLink *i_config; /**< configuration string list */
180 struct SLink *i_stats; /**< statistics string list */
181 char **i_argv; /**< argument list */
184 /** Return whether flag \a flag is set on \a iauth. */
185 #define IAuthHas(iauth, flag) ((iauth) && FlagHas(&(iauth)->i_flags, flag))
186 /** Set flag \a flag on \a iauth. */
187 #define IAuthSet(iauth, flag) FlagSet(&(iauth)->i_flags, flag)
188 /** Clear flag \a flag from \a iauth. */
189 #define IAuthClr(iauth, flag) FlagClr(&(iauth)->i_flags, flag)
190 /** Get connected flag for \a iauth. */
191 #define i_GetConnected(iauth) ((iauth) && s_fd(i_socket(iauth)) > -1)
193 /** Return socket event generator for \a iauth. */
194 #define i_socket(iauth) (&(iauth)->i_socket)
195 /** Return stderr socket for \a iauth. */
196 #define i_stderr(iauth) (&(iauth)->i_stderr)
197 /** Return outbound message queue for \a iauth. */
198 #define i_sendQ(iauth) (&(iauth)->i_sendQ)
199 /** Return debug level for \a iauth. */
200 #define i_debug(iauth) ((iauth)->i_debug)
202 /** Active instance of IAuth. */
205 static void iauth_sock_callback(struct Event *ev);
206 static void iauth_stderr_callback(struct Event *ev);
207 static int sendto_iauth(struct Client *cptr, const char *format, ...);
208 static int preregister_user(struct Client *cptr);
209 typedef int (*iauth_cmd_handler)(struct IAuth *iauth, struct Client *cli,
210 int parc, char **params);
212 /** Set username for user associated with \a auth.
213 * @param[in] auth Client authorization request to work on.
214 * @return Zero if client is kept, CPTR_KILLED if client rejected.
216 static int auth_set_username(struct AuthRequest *auth)
218 struct Client *sptr = auth->client;
219 struct User *user = cli_user(sptr);
230 short digitgroups = 0;
234 if (FlagHas(&auth->flags, AR_IAUTH_USERNAME))
236 ircd_strncpy(cli_user(sptr)->username, cli_username(sptr), USERLEN);
240 /* Copy username from source to destination. Since they may be the
241 * same, and we may prefix with a '~', use a buffer character (ch)
242 * to hold the next character to copy.
244 s = IsIdented(sptr) ? cli_username(sptr) : user->username;
247 if (HasFlag(sptr, FLAG_DOID) && !IsIdented(sptr))
252 while (last && !IsCntrl(last) && rlen--)
255 *d++ = IsUserChar(last) ? last : '_';
256 last = (ch != '~') ? ch : '_';
261 /* If username is empty or just ~, reject. */
262 if ((user->username[0] == '\0')
263 || ((user->username[0] == '~') && (user->username[1] == '\0')))
264 return exit_client(sptr, sptr, &me, "USER: Bogus userid.");
266 /* Check for K- or G-line. */
267 killreason = find_kill(sptr);
269 ServerStats->is_ref++;
270 return exit_client(sptr, sptr, &me,
271 (killreason == -1 ? "K-lined" : "G-lined"));
274 if (!FlagHas(&auth->flags, AR_IAUTH_FUSERNAME))
276 /* Check for mixed case usernames, meaning probably hacked. Jon2 3-94
277 * Explanations of rules moved to where it is checked Entrope 2-06
279 s = d = user->username + (user->username[0] == '~');
288 else if (IsUpper(ch))
291 /* Accept caps as leading if we haven't seen lower case or digits yet. */
292 if ((leadcaps || pos == 0) && !lower && !digits)
295 else if (IsDigit(ch))
298 if (pos == 0 || !IsDigit(last))
301 /* If more than two groups of digits, reject. */
306 else if (ch == '-' || ch == '_' || ch == '.')
309 /* If -_. exist at start, consecutively, or more than twice, reject. */
310 if (pos == 0 || last == '-' || last == '_' || last == '.' || other > 2)
313 else /* All other punctuation is rejected. */
317 /* If mixed case, first must be capital, but no more than three;
318 * but if three capitals, they must all be leading. */
319 if (lower && upper && (!leadcaps || leadcaps > 3 ||
320 (upper > 2 && upper > leadcaps)))
322 /* If two different groups of digits, one must be either at the
324 if (digitgroups == 2 && !(IsDigit(s[0]) || IsDigit(ch)))
326 /* Must have at least one letter. */
327 if (!lower && !upper)
329 /* Final character must not be punctuation. */
337 /* If we confirmed their username, and it is what they claimed,
339 if (IsIdented(sptr) && !strcmp(cli_username(sptr), user->username))
342 ServerStats->is_ref++;
343 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
344 ":Your username is invalid.");
345 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
346 ":Connect with your real username, in lowercase.");
347 send_reply(sptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
348 ":If your mail address were foo@bar.com, your username "
350 return exit_client(sptr, sptr, &me, "USER: Bad username");
353 /** Check whether an authorization request is complete.
354 * This means that no flags from 0 to #AR_LAST_SCAN are set on \a auth.
355 * If #AR_IAUTH_PENDING is set, optionally go into "hurry" state. If
356 * 0 through #AR_LAST_SCAN and #AR_IAUTH_PENDING are all clear,
357 * destroy \a auth, clear the password, set the username, and register
359 * @param[in] auth Authorization request to check.
360 * @return Zero if client is kept, CPTR_KILLED if client rejected.
362 static int check_auth_finished(struct AuthRequest *auth)
364 enum AuthRequestFlag flag;
367 /* Check non-iauth registration blocking flags. */
368 for (flag = 0; flag <= AR_LAST_SCAN; ++flag)
369 if (FlagHas(&auth->flags, flag))
371 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
372 cli_fd(auth->client), flag));
376 /* If appropriate, do preliminary assignment to connection class. */
377 if (IsUserPort(auth->client)
378 && !FlagHas(&auth->flags, AR_IAUTH_HURRY)
379 && preregister_user(auth->client))
382 /* If we have not done so, check client password. Do this as soon
383 * as possible so that iauth's challenge/response (which uses PASS
384 * for responses) is not confused with the client's password.
386 if (!FlagHas(&auth->flags, AR_PASSWORD_CHECKED))
388 struct ConfItem *aconf;
390 aconf = cli_confs(auth->client)->value.aconf;
391 if (!EmptyString(aconf->passwd)
392 && strcmp(cli_passwd(auth->client), aconf->passwd))
394 ServerStats->is_ref++;
395 send_reply(auth->client, ERR_PASSWDMISMATCH);
396 return exit_client(auth->client, auth->client, &me, "Bad Password");
398 FlagSet(&auth->flags, AR_PASSWORD_CHECKED);
401 /* Check if iauth is done. */
402 if (FlagHas(&auth->flags, AR_IAUTH_PENDING))
404 /* Switch auth request to hurry-up state. */
405 if (!FlagHas(&auth->flags, AR_IAUTH_HURRY))
407 /* Set "hurry" flag in auth request. */
408 FlagSet(&auth->flags, AR_IAUTH_HURRY);
410 /* If iauth wants it, send notification. */
411 if (IAuthHas(iauth, IAUTH_UNDERNET))
412 sendto_iauth(auth->client, "H %s", get_client_class(auth->client));
414 /* If iauth wants it, give client more time. */
415 if (IAuthHas(iauth, IAUTH_EXTRAWAIT))
416 cli_firsttime(auth->client) = CurrentTime;
419 Debug((DEBUG_INFO, "Auth %p [%d] still has flag %d", auth,
420 cli_fd(auth->client), AR_IAUTH_PENDING));
424 FlagSet(&auth->flags, AR_IAUTH_HURRY);
426 destroy_auth_request(auth);
427 if (!IsUserPort(auth->client))
429 memset(cli_passwd(auth->client), 0, sizeof(cli_passwd(auth->client)));
430 res = auth_set_username(auth);
432 res = register_user(auth->client, auth->client);
436 /** Verify that a hostname is valid, i.e., only contains characters
437 * valid for a hostname and that a hostname is not too long.
438 * @param host Hostname to check.
439 * @param maxlen Maximum length of hostname, not including NUL terminator.
440 * @return Non-zero if the hostname is valid.
443 auth_verify_hostname(const char *host, int maxlen)
447 /* Walk through the host name */
448 for (i = 0; host[i]; i++)
449 /* If it's not a hostname character or if it's too long, return false */
450 if (!IsHostChar(host[i]) || i >= maxlen)
453 return 1; /* it's a valid hostname */
456 /** Assign a client to a connection class.
457 * @param[in] cptr Client to assign to a class.
458 * @return Zero if client is kept, CPTR_KILLED if rejected.
460 static int preregister_user(struct Client *cptr)
462 static time_t last_too_many1;
463 static time_t last_too_many2;
465 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
466 ircd_strncpy(cli_user(cptr)->realhost, cli_sockhost(cptr), HOSTLEN);
468 switch (conf_check_client(cptr))
472 case ACR_NO_AUTHORIZATION:
473 sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
474 get_client_name(cptr, HIDE_IP));
475 ++ServerStats->is_ref;
476 return exit_client(cptr, cptr, &me,
477 "No Authorization - use another server");
478 case ACR_TOO_MANY_IN_CLASS:
479 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many1,
480 "Too many connections in class %s for %s.",
481 get_client_class(cptr),
482 get_client_name(cptr, SHOW_IP));
483 ++ServerStats->is_ref;
484 return exit_client(cptr, cptr, &me,
485 "Sorry, your connection class is full - try "
486 "again later or try another server");
487 case ACR_TOO_MANY_FROM_IP:
488 sendto_opmask_butone_ratelimited(0, SNO_TOOMANY, &last_too_many2,
489 "Too many connections from same IP for %s.",
490 get_client_name(cptr, SHOW_IP));
491 ++ServerStats->is_ref;
492 return exit_client(cptr, cptr, &me,
493 "Too many connections from your host");
494 case ACR_ALREADY_AUTHORIZED:
495 /* Can this ever happen? */
497 ++ServerStats->is_ref;
498 IPcheck_connect_fail(cptr);
499 return exit_client(cptr, cptr, &me, "Unknown error -- Try again");
504 /** Send the ident server a query giving "theirport , ourport". The
505 * write is only attempted *once* so it is deemed to be a fail if the
506 * entire write doesn't write all the data given. This shouldn't be a
507 * problem since the socket should have a write buffer far greater
508 * than this message to store it in should problems arise. -avalon
509 * @param[in] auth The request to send.
511 static void send_auth_query(struct AuthRequest* auth)
518 ircd_snprintf(0, authbuf, sizeof(authbuf), "%hu , %hu\r\n",
519 auth->port, auth->local.port);
521 if (IO_SUCCESS != os_send_nonb(s_fd(&auth->socket), authbuf, strlen(authbuf), &count)) {
522 close(s_fd(&auth->socket));
523 socket_del(&auth->socket);
524 s_fd(&auth->socket) = -1;
525 ++ServerStats->is_abad;
526 if (IsUserPort(auth->client))
527 sendheader(auth->client, REPORT_FAIL_ID);
528 FlagClr(&auth->flags, AR_AUTH_PENDING);
529 check_auth_finished(auth);
533 /** Enum used to index ident reply fields in a human-readable way. */
534 enum IdentReplyFields {
542 /** Parse an ident reply line and extract the userid from it.
543 * @param[in] reply The ident reply line.
544 * @return The userid, or NULL on parse failure.
546 static char* check_ident_reply(char* reply)
550 char* vector[USERID_TOKEN_COUNT];
551 int count = token_vector(reply, ':', vector, USERID_TOKEN_COUNT);
553 if (USERID_TOKEN_COUNT != count)
556 * second token is the reply type
558 token = vector[IDENT_REPLY_TYPE];
559 if (EmptyString(token))
562 while (IsSpace(*token))
565 if (0 != strncmp(token, "USERID", 6))
569 * third token is the os type
571 token = vector[IDENT_OS_TYPE];
572 if (EmptyString(token))
574 while (IsSpace(*token))
578 * Unless "OTHER" is specified as the operating system
579 * type, the server is expected to return the "normal"
580 * user identification of the owner of this connection.
581 * "Normal" in this context may be taken to mean a string
582 * of characters which uniquely identifies the connection
583 * owner such as a user identifier assigned by the system
584 * administrator and used by such user as a mail
585 * identifier, or as the "user" part of a user/password
586 * pair used to gain access to system resources. When an
587 * operating system is specified (e.g., anything but
588 * "OTHER"), the user identifier is expected to be in a
589 * more or less immediately useful form - e.g., something
590 * that could be used as an argument to "finger" or as a
593 if (0 == strncmp(token, "OTHER", 5))
596 * fourth token is the username
598 token = vector[IDENT_INFO];
599 if (EmptyString(token))
601 while (IsSpace(*token))
604 * look for the end of the username, terminators are '\0, @, <SPACE>, :'
606 for (end = token; *end; ++end) {
607 if (IsSpace(*end) || '@' == *end || ':' == *end)
614 /** Read the reply (if any) from the ident server we connected to. We
615 * only give it one shot, if the reply isn't good the first time fail
616 * the authentication entirely. --Bleep
617 * @param[in] auth The request to read.
619 static void read_auth_reply(struct AuthRequest* auth)
624 * rfc1453 sez we MUST accept 512 bytes
626 char buf[BUFSIZE + 1];
629 assert(0 != auth->client);
630 assert(auth == cli_auth(auth->client));
632 if (IO_SUCCESS == os_recv_nonb(s_fd(&auth->socket), buf, BUFSIZE, &len)) {
634 Debug((DEBUG_INFO, "Auth %p [%d] reply: %s", auth, cli_fd(auth->client), buf));
635 username = check_ident_reply(buf);
636 Debug((DEBUG_INFO, "Username: %s", username));
639 Debug((DEBUG_INFO, "Deleting auth [%d] socket %p", auth, cli_fd(auth->client)));
640 close(s_fd(&auth->socket));
641 socket_del(&auth->socket);
642 s_fd(&auth->socket) = -1;
644 if (EmptyString(username)) {
645 if (IsUserPort(auth->client))
646 sendheader(auth->client, REPORT_FAIL_ID);
647 ++ServerStats->is_abad;
649 if (IsUserPort(auth->client))
650 sendheader(auth->client, REPORT_FIN_ID);
651 ++ServerStats->is_asuc;
652 if (!FlagHas(&auth->flags, AR_IAUTH_USERNAME)) {
653 ircd_strncpy(cli_username(auth->client), username, USERLEN);
654 SetGotId(auth->client);
656 if (IAuthHas(iauth, IAUTH_UNDERNET))
657 sendto_iauth(auth->client, "u %s", username);
660 FlagClr(&auth->flags, AR_AUTH_PENDING);
661 check_auth_finished(auth);
664 /** Handle socket I/O activity.
665 * @param[in] ev A socket event whos associated data is the active
666 * struct AuthRequest.
668 static void auth_sock_callback(struct Event* ev)
670 struct AuthRequest* auth;
672 assert(0 != ev_socket(ev));
673 assert(0 != s_data(ev_socket(ev)));
675 auth = (struct AuthRequest*) s_data(ev_socket(ev));
677 switch (ev_type(ev)) {
678 case ET_DESTROY: /* being destroyed */
681 case ET_CONNECT: /* socket connection completed */
682 Debug((DEBUG_INFO, "Connection completed for auth %p [%d]; sending query",
683 auth, cli_fd(auth->client)));
684 socket_state(&auth->socket, SS_CONNECTED);
685 send_auth_query(auth);
688 case ET_READ: /* socket is readable */
689 case ET_EOF: /* end of file on socket */
690 case ET_ERROR: /* error on socket */
691 Debug((DEBUG_INFO, "Auth socket %p [%p] readable", auth, ev_socket(ev)));
692 read_auth_reply(auth);
696 assert(0 && "Unrecognized event in auth_socket_callback().");
701 /** Stop an auth request completely.
702 * @param[in] auth The struct AuthRequest to cancel.
704 void destroy_auth_request(struct AuthRequest* auth)
706 Debug((DEBUG_INFO, "Deleting auth request for %p", auth->client));
708 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
709 delete_resolver_queries(auth);
712 if (-1 < s_fd(&auth->socket)) {
713 close(s_fd(&auth->socket));
714 socket_del(&auth->socket);
715 s_fd(&auth->socket) = -1;
718 if (t_active(&auth->timeout))
719 timer_del(&auth->timeout);
720 cli_auth(auth->client) = NULL;
723 /** Handle a 'ping' (authorization) timeout for a client.
724 * @param[in] cptr The client whose session authorization has timed out.
725 * @return Zero if client is kept, CPTR_KILLED if client rejected.
727 int auth_ping_timeout(struct Client *cptr)
729 struct AuthRequest *auth;
730 enum AuthRequestFlag flag;
732 auth = cli_auth(cptr);
734 /* Check for a user-controlled timeout. */
735 for (flag = 0; flag < AR_LAST_SCAN; ++flag) {
736 if (FlagHas(&auth->flags, flag)) {
737 /* Display message if they have sent a NICK and a USER but no
740 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
741 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
742 ":Your client may not be compatible with this server.");
743 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
744 ":Compatible clients are available at %s",
745 feature_str(FEAT_URL_CLIENTS));
747 return exit_client_msg(cptr, cptr, &me, "Registration Timeout");
751 /* Check for iauth timeout. */
752 if (FlagHas(&auth->flags, AR_IAUTH_PENDING)) {
753 sendto_iauth(cptr, "T");
754 if (IAuthHas(iauth, IAUTH_REQUIRED)) {
755 sendheader(cptr, REPORT_FAIL_IAUTH);
756 return exit_client_msg(cptr, cptr, &me, "Authorization Timeout");
758 FlagClr(&auth->flags, AR_IAUTH_PENDING);
759 return check_auth_finished(auth);
762 assert(0 && "Unexpectedly reached end of auth_ping_timeout()");
766 /** Timeout a given auth request.
767 * @param[in] ev A timer event whose associated data is the expired
768 * struct AuthRequest.
770 static void auth_timeout_callback(struct Event* ev)
772 struct AuthRequest* auth;
774 assert(0 != ev_timer(ev));
775 assert(0 != t_data(ev_timer(ev)));
777 auth = (struct AuthRequest*) t_data(ev_timer(ev));
779 if (ev_type(ev) == ET_EXPIRE) {
780 /* Report the timeout in the log. */
781 log_write(LS_RESOLVER, L_INFO, 0, "Registration timeout %s",
782 get_client_name(auth->client, HIDE_IP));
784 /* Notify client if ident lookup failed. */
785 if (FlagHas(&auth->flags, AR_AUTH_PENDING)) {
786 FlagClr(&auth->flags, AR_AUTH_PENDING);
787 if (IsUserPort(auth->client))
788 sendheader(auth->client, REPORT_FAIL_ID);
791 /* Likewise if dns lookup failed. */
792 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
793 delete_resolver_queries(auth);
794 if (IsUserPort(auth->client))
795 sendheader(auth->client, REPORT_FAIL_DNS);
798 /* Try to register the client. */
799 check_auth_finished(auth);
803 /** Handle a complete DNS lookup. Send the client on it's way to a
804 * connection completion, regardless of success or failure -- unless
805 * there was a mismatch and KILL_IPMISMATCH is set.
806 * @param[in] vptr The pending struct AuthRequest.
807 * @param[in] addr IP address being resolved.
808 * @param[in] h_name Resolved name, or NULL if lookup failed.
810 static void auth_dns_callback(void* vptr, const struct irc_in_addr *addr, const char *h_name)
812 struct AuthRequest* auth = (struct AuthRequest*) vptr;
815 FlagClr(&auth->flags, AR_DNS_PENDING);
817 /* DNS entry was missing for the IP. */
818 if (IsUserPort(auth->client))
819 sendheader(auth->client, REPORT_FAIL_DNS);
820 sendto_iauth(auth->client, "d");
821 } else if (irc_in_addr_cmp(addr, &cli_ip(auth->client))
822 && irc_in_addr_cmp(addr, &auth->original)) {
823 /* IP for hostname did not match client's IP. */
824 sendto_opmask_butone(0, SNO_IPMISMATCH, "IP# Mismatch: %s != %s[%s]",
825 cli_sock_ip(auth->client), h_name,
827 if (IsUserPort(auth->client))
828 sendheader(auth->client, REPORT_IP_MISMATCH);
829 /* Clear DNS pending flag so free_client doesn't ask the resolver
830 * to delete the query that just finished.
832 if (feature_bool(FEAT_KILL_IPMISMATCH)) {
833 IPcheck_disconnect(auth->client);
834 Count_unknowndisconnects(UserStats);
835 free_client(auth->client);
837 } else if (!auth_verify_hostname(h_name, HOSTLEN)) {
838 /* Hostname did not look valid. */
839 if (IsUserPort(auth->client))
840 sendheader(auth->client, REPORT_INVAL_DNS);
841 sendto_iauth(auth->client, "d");
843 /* Hostname and mappings checked out. */
844 if (IsUserPort(auth->client))
845 sendheader(auth->client, REPORT_FIN_DNS);
846 ircd_strncpy(cli_sockhost(auth->client), h_name, HOSTLEN);
847 sendto_iauth(auth->client, "N %s", h_name);
849 check_auth_finished(auth);
852 /** Flag the client to show an attempt to contact the ident server on
853 * the client's host. Should the connect or any later phase of the
854 * identifying process fail, it is aborted and the user is given a
855 * username of "unknown".
856 * @param[in] auth The request for which to start the ident lookup.
858 static void start_auth_query(struct AuthRequest* auth)
860 struct irc_sockaddr remote_addr;
861 struct irc_sockaddr local_addr;
866 assert(0 != auth->client);
869 * get the local address of the client and bind to that to
870 * make the auth request. This used to be done only for
871 * ifdef VIRTUAL_HOST, but needs to be done for all clients
872 * since the ident request must originate from that same address--
873 * and machines with multiple IP addresses are common now
875 memcpy(&local_addr, &auth->local, sizeof(local_addr));
877 memcpy(&remote_addr.addr, &cli_ip(auth->client), sizeof(remote_addr.addr));
878 remote_addr.port = 113;
879 fd = os_socket(&local_addr, SOCK_STREAM, "auth query", 0);
881 ++ServerStats->is_abad;
882 if (IsUserPort(auth->client))
883 sendheader(auth->client, REPORT_FAIL_ID);
886 if (IsUserPort(auth->client))
887 sendheader(auth->client, REPORT_DO_ID);
889 if ((result = os_connect_nonb(fd, &remote_addr)) == IO_FAILURE ||
890 !socket_add(&auth->socket, auth_sock_callback, (void*) auth,
891 result == IO_SUCCESS ? SS_CONNECTED : SS_CONNECTING,
892 SOCK_EVENT_READABLE, fd)) {
893 ++ServerStats->is_abad;
894 if (IsUserPort(auth->client))
895 sendheader(auth->client, REPORT_FAIL_ID);
900 FlagSet(&auth->flags, AR_AUTH_PENDING);
901 if (result == IO_SUCCESS)
902 send_auth_query(auth);
905 /** Initiate DNS lookup for a client.
906 * @param[in] auth The auth request for which to start the DNS lookup.
908 static void start_dns_query(struct AuthRequest *auth)
910 if (feature_bool(FEAT_NODNS)) {
911 sendto_iauth(auth->client, "d");
915 if (irc_in_addr_is_loopback(&cli_ip(auth->client))) {
916 strcpy(cli_sockhost(auth->client), cli_name(&me));
917 sendto_iauth(auth->client, "N %s", cli_sockhost(auth->client));
921 if (IsUserPort(auth->client))
922 sendheader(auth->client, REPORT_DO_DNS);
924 FlagSet(&auth->flags, AR_DNS_PENDING);
925 gethost_byaddr(&cli_ip(auth->client), auth_dns_callback, auth);
928 /** Initiate IAuth check for a client.
929 * @param[in] auth The auth request for which to star the IAuth check.
931 static void start_iauth_query(struct AuthRequest *auth)
933 FlagSet(&auth->flags, AR_IAUTH_PENDING);
934 if (!sendto_iauth(auth->client, "C %s %hu %s %hu",
935 cli_sock_ip(auth->client), auth->port,
936 ircd_ntoa(&auth->local.addr), auth->local.port))
937 FlagClr(&auth->flags, AR_IAUTH_PENDING);
940 /** Starts auth (identd) and dns queries for a client.
941 * @param[in] client The client for which to start queries.
943 void start_auth(struct Client* client)
945 struct irc_sockaddr remote;
946 struct AuthRequest* auth;
949 Debug((DEBUG_INFO, "Beginning auth request on client %p", client));
951 /* Register with event handlers. */
952 cli_lasttime(client) = CurrentTime;
953 cli_since(client) = CurrentTime;
954 if (cli_fd(client) > HighestFd)
955 HighestFd = cli_fd(client);
956 LocalClientArray[cli_fd(client)] = client;
957 socket_events(&(cli_socket(client)), SOCK_ACTION_SET | SOCK_EVENT_READABLE);
959 /* Allocate the AuthRequest. */
960 auth = MyCalloc(1, sizeof(*auth));
962 auth->client = client;
963 cli_auth(client) = auth;
964 s_fd(&auth->socket) = -1;
965 timer_add(timer_init(&auth->timeout), auth_timeout_callback, (void*) auth,
966 TT_RELATIVE, feature_int(FEAT_AUTH_TIMEOUT));
968 /* Try to get socket endpoint addresses. */
969 if (!os_get_sockname(cli_fd(client), &auth->local)
970 || !os_get_peername(cli_fd(client), &remote)) {
971 ++ServerStats->is_abad;
972 if (IsUserPort(auth->client))
973 sendheader(auth->client, REPORT_FAIL_ID);
974 IPcheck_disconnect(auth->client);
975 Count_unknowndisconnects(UserStats);
976 free_client(auth->client);
979 auth->port = remote.port;
981 /* Try to start DNS lookup. */
982 start_dns_query(auth);
984 /* Try to start ident lookup. */
985 start_auth_query(auth);
987 /* Set required client inputs for users. */
988 if (IsUserPort(client)) {
989 cli_user(client) = make_user(client);
990 cli_user(client)->server = &me;
991 FlagSet(&auth->flags, AR_NEEDS_USER);
992 FlagSet(&auth->flags, AR_NEEDS_NICK);
994 /* Try to start iauth lookup. */
995 start_iauth_query(auth);
998 /* Add client to GlobalClientList. */
999 add_client_to_list(client);
1001 /* Check which auth events remain pending. */
1002 check_auth_finished(auth);
1005 /** Mark that a user has PONGed while unregistered.
1006 * @param[in] auth Authorization request for client.
1007 * @param[in] cookie PONG cookie value sent by client.
1008 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1010 int auth_set_pong(struct AuthRequest *auth, unsigned int cookie)
1012 assert(auth != NULL);
1013 if (!FlagHas(&auth->flags, AR_NEEDS_PONG))
1015 if (cookie != auth->cookie)
1017 send_reply(auth->client, SND_EXPLICIT | ERR_BADPING,
1018 ":To connect, type /QUOTE PONG %u", auth->cookie);
1021 cli_lasttime(auth->client) = CurrentTime;
1022 FlagClr(&auth->flags, AR_NEEDS_PONG);
1023 return check_auth_finished(auth);
1026 /** Record a user's claimed username and userinfo.
1027 * @param[in] auth Authorization request for client.
1028 * @param[in] username Client's asserted username.
1029 * @param[in] userinfo Client's asserted self-description.
1030 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1032 int auth_set_user(struct AuthRequest *auth, const char *username, const char *userinfo)
1034 struct Client *cptr;
1036 assert(auth != NULL);
1037 if (FlagHas(&auth->flags, AR_IAUTH_HURRY))
1039 FlagClr(&auth->flags, AR_NEEDS_USER);
1040 cptr = auth->client;
1041 ircd_strncpy(cli_info(cptr), userinfo, REALLEN);
1042 ircd_strncpy(cli_user(cptr)->username, username, USERLEN);
1043 ircd_strncpy(cli_user(cptr)->host, cli_sockhost(cptr), HOSTLEN);
1044 if (IAuthHas(iauth, IAUTH_UNDERNET))
1045 sendto_iauth(cptr, "U %s :%s", username, userinfo);
1046 else if (IAuthHas(iauth, IAUTH_ADDLINFO))
1047 sendto_iauth(cptr, "U %s", username);
1048 return check_auth_finished(auth);
1051 /** Handle authorization-related aspects of initial nickname selection.
1052 * This is called after verifying that the nickname is available.
1053 * @param[in] auth Authorization request for client.
1054 * @param[in] nickname Client's requested nickname.
1055 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1057 int auth_set_nick(struct AuthRequest *auth, const char *nickname)
1059 assert(auth != NULL);
1060 FlagClr(&auth->flags, AR_NEEDS_NICK);
1062 * If the client hasn't gotten a cookie-ping yet,
1063 * choose a cookie and send it. -record!jegelhof@cloud9.net
1065 if (!auth->cookie) {
1067 auth->cookie = ircrandom();
1068 } while (!auth->cookie);
1069 sendrawto_one(auth->client, "PING :%u", auth->cookie);
1070 FlagSet(&auth->flags, AR_NEEDS_PONG);
1072 if (IAuthHas(iauth, IAUTH_UNDERNET))
1073 sendto_iauth(auth->client, "n %s", nickname);
1074 return check_auth_finished(auth);
1077 /** Record a user's password.
1078 * @param[in] auth Authorization request for client.
1079 * @param[in] password Client's password.
1080 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1082 int auth_set_password(struct AuthRequest *auth, const char *password)
1084 assert(auth != NULL);
1085 if (IAuthHas(iauth, IAUTH_ADDLINFO))
1086 sendto_iauth(auth->client, "P :%s", password);
1090 /** Send exit notification for \a cptr to iauth.
1091 * @param[in] cptr Client who is exiting.
1093 void auth_send_exit(struct Client *cptr)
1095 sendto_iauth(cptr, "D");
1098 /** Mark that a user has started capabilities negotiation.
1099 * This blocks authorization until auth_cap_done() is called.
1100 * @param[in] auth Authorization request for client.
1101 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1103 int auth_cap_start(struct AuthRequest *auth)
1105 assert(auth != NULL);
1106 FlagSet(&auth->flags, AR_CAP_PENDING);
1110 /** Mark that a user has completed capabilities negotiation.
1111 * This unblocks authorization if auth_cap_start() was called.
1112 * @param[in] auth Authorization request for client.
1113 * @return Zero if client should be kept, CPTR_KILLED if rejected.
1115 int auth_cap_done(struct AuthRequest *auth)
1117 assert(auth != NULL);
1118 FlagClr(&auth->flags, AR_CAP_PENDING);
1119 return check_auth_finished(auth);
1122 /** Attempt to spawn the process for an IAuth instance.
1123 * @param[in] iauth IAuth descriptor.
1124 * @param[in] automatic If non-zero, apply sanity checks against
1125 * excessive automatic restarts.
1126 * @return 0 on success, non-zero on failure.
1128 int iauth_do_spawn(struct IAuth *iauth, int automatic)
1135 if (automatic && CurrentTime - iauth->started < 5)
1137 sendto_opmask_butone(NULL, SNO_AUTH, "IAuth crashed fast, leaving it dead.");
1141 /* Record time we tried to spawn the iauth process. */
1142 iauth->started = CurrentTime;
1144 /* Attempt to allocate a pair of sockets. */
1145 res = os_socketpair(s_io);
1149 /* Mark the parent's side of the pair (element 0) as non-blocking. */
1150 res = os_set_nonblocking(s_io[0]);
1158 /* Initialize the socket structure to talk to the child. */
1159 res = socket_add(i_socket(iauth), iauth_sock_callback, iauth,
1160 SS_CONNECTED, SOCK_EVENT_READABLE, s_io[0]);
1168 /* Allocate another pair for stderr. */
1169 res = os_socketpair(s_err);
1172 socket_del(i_socket(iauth));
1178 /* Mark parent side of this pair non-blocking, too. */
1179 res = os_set_nonblocking(s_err[0]);
1184 socket_del(i_socket(iauth));
1190 /* And set up i_stderr(iauth). */
1191 res = socket_add(i_stderr(iauth), iauth_stderr_callback, iauth,
1192 SS_CONNECTED, SOCK_EVENT_READABLE, s_err[0]);
1197 socket_del(i_socket(iauth));
1203 /* Attempt to fork a child process. */
1206 /* Error forking the child, still in parent. */
1208 socket_del(i_stderr(iauth));
1211 socket_del(i_socket(iauth));
1218 /* We are the parent process. Close the child's sockets. */
1221 /* Send our server name (supposedly for proxy checking purposes)
1222 * and maximum number of connections (for allocation hints).
1223 * Need to use conf_get_local() since &me may not be fully
1224 * initialized the first time we run.
1226 sendto_iauth(NULL, "M %s %d", conf_get_local()->name, MAXCONNECTIONS);
1227 /* Indicate success (until the child dies). */
1231 /* We are the child process.
1232 * Duplicate our end of the socket to stdin, stdout and stderr.
1233 * Then close all the higher-numbered FDs and exec the process.
1235 if (dup2(s_io[1], 0) == 0
1236 && dup2(s_io[1], 1) == 1
1237 && dup2(s_err[1], 2) == 2) {
1238 close_connections(0);
1239 execvp(iauth->i_argv[0], iauth->i_argv);
1242 /* If we got here, something was seriously wrong. */
1246 /** See if an %IAuth program must be spawned.
1247 * If a process is already running with the specified options, keep it.
1248 * Otherwise spawn a new child process to perform the %IAuth function.
1249 * @param[in] argc Number of parameters to use when starting process.
1250 * @param[in] argv Array of parameters to start process.
1251 * @return 0 on failure, 1 on new process, 2 on reuse of existing process.
1253 int auth_spawn(int argc, char *argv[])
1260 /* Check that incoming arguments all match pre-existing arguments. */
1261 for (ii = 0; same && (ii < argc); ++ii) {
1262 if (NULL == iauth->i_argv[ii]
1263 || 0 != strcmp(iauth->i_argv[ii], argv[ii]))
1266 /* Check that we have no more pre-existing arguments. */
1267 if (iauth->i_argv[ii])
1269 /* If they are the same and still connected, clear the "closing" flag and exit.*/
1270 if (same && i_GetConnected(iauth)) {
1271 IAuthClr(iauth, IAUTH_CLOSING);
1274 /* Deallocate old argv elements. */
1275 for (ii = 0; iauth->i_argv[ii]; ++ii)
1276 MyFree(iauth->i_argv[ii]);
1277 MyFree(iauth->i_argv);
1280 /* Need to initialize a new connection. */
1281 iauth = MyCalloc(1, sizeof(*iauth));
1282 msgq_init(i_sendQ(iauth));
1283 /* Populate iauth's argv array. */
1284 iauth->i_argv = MyCalloc(argc + 1, sizeof(iauth->i_argv[0]));
1285 for (ii = 0; ii < argc; ++ii)
1286 DupString(iauth->i_argv[ii], argv[ii]);
1287 iauth->i_argv[ii] = NULL;
1288 /* Try to spawn it, and handle the results. */
1289 if (iauth_do_spawn(iauth, 0))
1291 IAuthClr(iauth, IAUTH_CLOSING);
1295 /** Mark all %IAuth connections as closing. */
1296 void auth_mark_closing(void)
1299 IAuthSet(iauth, IAUTH_CLOSING);
1302 /** Complete disconnection of an %IAuth connection.
1303 * @param[in] iauth %Connection to fully close.
1305 static void iauth_disconnect(struct IAuth *iauth)
1307 if (!i_GetConnected(iauth))
1310 /* Close main socket. */
1311 close(s_fd(i_socket(iauth)));
1312 socket_del(i_socket(iauth));
1313 s_fd(i_socket(iauth)) = -1;
1315 /* Close error socket. */
1316 close(s_fd(i_stderr(iauth)));
1317 socket_del(i_stderr(iauth));
1318 s_fd(i_stderr(iauth)) = -1;
1321 /** Close all %IAuth connections marked as closing. */
1322 void auth_close_unused(void)
1324 if (IAuthHas(iauth, IAUTH_CLOSING)) {
1326 iauth_disconnect(iauth);
1327 if (iauth->i_argv) {
1328 for (ii = 0; iauth->i_argv[ii]; ++ii)
1329 MyFree(iauth->i_argv[ii]);
1330 MyFree(iauth->i_argv);
1336 /** Send queued output to \a iauth.
1337 * @param[in] iauth Writable connection with queued data.
1339 static void iauth_write(struct IAuth *iauth)
1341 unsigned int bytes_tried, bytes_sent;
1344 if (IAuthHas(iauth, IAUTH_BLOCKED))
1346 while (MsgQLength(i_sendQ(iauth)) > 0) {
1347 iores = os_sendv_nonb(s_fd(i_socket(iauth)), i_sendQ(iauth), &bytes_tried, &bytes_sent);
1350 msgq_delete(i_sendQ(iauth), bytes_sent);
1351 iauth->i_sendB += bytes_sent;
1352 if (bytes_tried == bytes_sent)
1354 /* If bytes_sent < bytes_tried, fall through to IO_BLOCKED. */
1356 IAuthSet(iauth, IAUTH_BLOCKED);
1357 socket_events(i_socket(iauth), SOCK_ACTION_ADD | SOCK_EVENT_WRITABLE);
1360 iauth_disconnect(iauth);
1364 /* We were able to flush all events, so remove notification. */
1365 socket_events(i_socket(iauth), SOCK_ACTION_DEL | SOCK_EVENT_WRITABLE);
1368 /** Send a message to iauth.
1369 * @param[in] cptr Optional client context for message.
1370 * @param[in] format Format string for message.
1371 * @return Non-zero on successful send or buffering, zero on failure.
1373 static int sendto_iauth(struct Client *cptr, const char *format, ...)
1378 /* Do not send requests when we have no iauth. */
1379 if (!i_GetConnected(iauth))
1381 /* Do not send for clients in the NORMAL state. */
1383 && (format[0] != 'D')
1384 && (!cli_auth(cptr) || !FlagHas(&cli_auth(cptr)->flags, AR_IAUTH_PENDING)))
1387 /* Build the message buffer. */
1388 vd.vd_format = format;
1389 va_start(vd.vd_args, format);
1391 mb = msgq_make(NULL, "-1 %v", &vd);
1393 mb = msgq_make(NULL, "%d %v", cli_fd(cptr), &vd);
1396 /* Tack it onto the iauth sendq and try to write it. */
1398 msgq_add(i_sendQ(iauth), mb, 0);
1403 /** Send text to interested operators (SNO_AUTH server notice).
1404 * @param[in] iauth Active IAuth session.
1405 * @param[in] cli Client referenced by command.
1406 * @param[in] parc Number of parameters (1).
1407 * @param[in] params Text to send.
1410 static int iauth_cmd_snotice(struct IAuth *iauth, struct Client *cli,
1411 int parc, char **params)
1413 sendto_opmask_butone(NULL, SNO_AUTH, "%s", params[0]);
1417 /** Set the debug level for the session.
1418 * @param[in] iauth Active IAuth session.
1419 * @param[in] cli Client referenced by command.
1420 * @param[in] parc Number of parameters (1).
1421 * @param[in] params String starting with an integer.
1424 static int iauth_cmd_debuglevel(struct IAuth *iauth, struct Client *cli,
1425 int parc, char **params)
1429 new_level = parc > 0 ? atoi(params[0]) : 0;
1430 if (i_debug(iauth) > 0 || new_level > 0) {
1431 /* The "ia_dbg" name is borrowed from (IRCnet) ircd. */
1432 sendto_opmask_butone(NULL, SNO_AUTH, "ia_dbg = %d", new_level);
1434 i_debug(iauth) = new_level;
1438 /** Set policy options for the session.
1439 * Old policy is forgotten, and any of the following characters in \a
1440 * params enable the corresponding policy:
1441 * \li A IAUTH_ADDLINFO
1442 * \li R IAUTH_REQUIRED
1443 * \li T IAUTH_TIMEOUT
1444 * \li W IAUTH_EXTRAWAIT
1445 * \li U IAUTH_UNDERNET
1447 * @param[in] iauth Active IAuth session.
1448 * @param[in] cli Client referenced by command.
1449 * @param[in] parc Number of parameters (1).
1450 * @param[in] params Zero or more policy options.
1453 static int iauth_cmd_policy(struct IAuth *iauth, struct Client *cli,
1454 int parc, char **params)
1456 enum IAuthFlag flag;
1459 /* Erase old policy first. */
1460 for (flag = IAUTH_FIRST_OPTION; flag < IAUTH_LAST_FLAG; ++flag)
1461 IAuthClr(iauth, flag);
1463 if (parc > 0) /* only try to parse if we were given a policy string */
1464 /* Parse new policy set. */
1465 for (p = params[0]; *p; p++) switch (*p) {
1466 case 'A': IAuthSet(iauth, IAUTH_ADDLINFO); break;
1467 case 'R': IAuthSet(iauth, IAUTH_REQUIRED); break;
1468 case 'T': IAuthSet(iauth, IAUTH_TIMEOUT); break;
1469 case 'W': IAuthSet(iauth, IAUTH_EXTRAWAIT); break;
1470 case 'U': IAuthSet(iauth, IAUTH_UNDERNET); break;
1473 /* Optionally notify operators. */
1474 if (i_debug(iauth) > 0)
1475 sendto_opmask_butone(NULL, SNO_AUTH, "iauth options: %s", params[0]);
1479 /** Set the iauth program version number.
1480 * @param[in] iauth Active IAuth session.
1481 * @param[in] cli Client referenced by command.
1482 * @param[in] parc Number of parameters (1).
1483 * @param[in] params Version number or name.
1486 static int iauth_cmd_version(struct IAuth *iauth, struct Client *cli,
1487 int parc, char **params)
1489 MyFree(iauth->i_version);
1490 DupString(iauth->i_version, parc > 0 ? params[0] : "<NONE>");
1491 sendto_opmask_butone(NULL, SNO_AUTH, "iauth version %s running.",
1496 /** Paste a parameter list together into a single string.
1497 * @param[in] parc Number of parameters.
1498 * @param[in] params Parameter list to paste together.
1499 * @return Pasted parameter list.
1501 static char *paste_params(int parc, char **params)
1504 int len = 0, lengths[MAXPARA], i;
1506 /* Compute the length... */
1507 for (i = 0; i < parc; i++)
1508 len += lengths[i] = strlen(params[i]);
1510 /* Allocate memory, accounting for string lengths, spaces (parc - 1), a
1511 * sentinel, and the trailing \0
1513 str = MyMalloc(len + parc + 1);
1515 /* Build the pasted string */
1516 for (tmp = str, i = 0; i < parc; i++) {
1517 if (i) /* add space separator... */
1519 if (i == parc - 1) /* add colon sentinel */
1522 /* Copy string component... */
1523 memcpy(tmp, params[i], lengths[i]);
1524 tmp += lengths[i]; /* move to end of string */
1527 /* terminate the string... */
1530 return str; /* return the pasted string */
1533 /** Clear cached iauth configuration information.
1534 * @param[in] iauth Active IAuth session.
1535 * @param[in] cli Client referenced by command.
1536 * @param[in] parc Number of parameters (0).
1537 * @param[in] params Parameter list (ignored).
1540 static int iauth_cmd_newconfig(struct IAuth *iauth, struct Client *cli,
1541 int parc, char **params)
1546 head = iauth->i_config;
1547 iauth->i_config = NULL;
1548 for (; head; head = next) {
1550 MyFree(head->value.cp);
1553 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth configuration.");
1557 /** Append iauth configuration information.
1558 * @param[in] iauth Active IAuth session.
1559 * @param[in] cli Client referenced by command.
1560 * @param[in] parc Number of parameters.
1561 * @param[in] params Description of configuration element.
1564 static int iauth_cmd_config(struct IAuth *iauth, struct Client *cli,
1565 int parc, char **params)
1569 if (iauth->i_config) {
1570 for (node = iauth->i_config; node->next; node = node->next) ;
1571 node = node->next = make_link();
1573 node = iauth->i_config = make_link();
1575 node->value.cp = paste_params(parc, params);
1576 node->next = 0; /* must be explicitly cleared */
1580 /** Clear cached iauth configuration information.
1581 * @param[in] iauth Active IAuth session.
1582 * @param[in] cli Client referenced by command.
1583 * @param[in] parc Number of parameters (0).
1584 * @param[in] params Parameter list (ignored).
1587 static int iauth_cmd_newstats(struct IAuth *iauth, struct Client *cli,
1588 int parc, char **params)
1593 head = iauth->i_stats;
1594 iauth->i_stats = NULL;
1595 for (; head; head = next) {
1597 MyFree(head->value.cp);
1600 sendto_opmask_butone(NULL, SNO_AUTH, "New iauth statistics.");
1604 /** Append iauth statistics information.
1605 * @param[in] iauth Active IAuth session.
1606 * @param[in] cli Client referenced by command.
1607 * @param[in] parc Number of parameters.
1608 * @param[in] params Statistics element.
1611 static int iauth_cmd_stats(struct IAuth *iauth, struct Client *cli,
1612 int parc, char **params)
1615 if (iauth->i_stats) {
1616 for (node = iauth->i_stats; node->next; node = node->next) ;
1617 node = node->next = make_link();
1619 node = iauth->i_stats = make_link();
1621 node->value.cp = paste_params(parc, params);
1622 node->next = 0; /* must be explicitly cleared */
1626 /** Set client's username to a trusted string even if it breaks the rules.
1627 * @param[in] iauth Active IAuth session.
1628 * @param[in] cli Client referenced by command.
1629 * @param[in] parc Number of parameters (1).
1630 * @param[in] params Forced username.
1633 static int iauth_cmd_username_forced(struct IAuth *iauth, struct Client *cli,
1634 int parc, char **params)
1636 assert(cli_auth(cli) != NULL);
1637 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1638 if (!EmptyString(params[0])) {
1639 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1641 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1642 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_FUSERNAME);
1647 /** Set client's username to a trusted string.
1648 * @param[in] iauth Active IAuth session.
1649 * @param[in] cli Client referenced by command.
1650 * @param[in] parc Number of parameters (1).
1651 * @param[in] params Trusted username.
1654 static int iauth_cmd_username_good(struct IAuth *iauth, struct Client *cli,
1655 int parc, char **params)
1657 assert(cli_auth(cli) != NULL);
1658 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1659 if (!EmptyString(params[0])) {
1660 ircd_strncpy(cli_username(cli), params[0], USERLEN);
1662 FlagSet(&cli_auth(cli)->flags, AR_IAUTH_USERNAME);
1667 /** Set client's username to an untrusted string.
1668 * @param[in] iauth Active IAuth session.
1669 * @param[in] cli Client referenced by command.
1670 * @param[in] parc Number of parameters (1).
1671 * @param[in] params Untrusted username.
1674 static int iauth_cmd_username_bad(struct IAuth *iauth, struct Client *cli,
1675 int parc, char **params)
1677 assert(cli_auth(cli) != NULL);
1678 FlagClr(&cli_auth(cli)->flags, AR_AUTH_PENDING);
1679 if (!EmptyString(params[0]))
1680 ircd_strncpy(cli_user(cli)->username, params[0], USERLEN);
1684 /** Set client's hostname.
1685 * @param[in] iauth Active IAuth session.
1686 * @param[in] cli Client referenced by command.
1687 * @param[in] parc Number of parameters (1).
1688 * @param[in] params New hostname for client.
1689 * @return Non-zero if \a cli authorization should be checked for completion.
1691 static int iauth_cmd_hostname(struct IAuth *iauth, struct Client *cli,
1692 int parc, char **params)
1694 struct AuthRequest *auth;
1696 if (EmptyString(params[0])) {
1697 sendto_iauth(cli, "E Missing :Missing hostname parameter");
1701 auth = cli_auth(cli);
1702 assert(auth != NULL);
1704 /* If a DNS request is pending, abort it. */
1705 if (FlagHas(&auth->flags, AR_DNS_PENDING)) {
1706 FlagClr(&auth->flags, AR_DNS_PENDING);
1707 delete_resolver_queries(auth);
1708 if (IsUserPort(cli))
1709 sendheader(cli, REPORT_FIN_DNS);
1711 /* Set hostname from params. */
1712 ircd_strncpy(cli_sockhost(cli), params[0], HOSTLEN);
1716 /** Set client's IP address.
1717 * @param[in] iauth Active IAuth session.
1718 * @param[in] cli Client referenced by command.
1719 * @param[in] parc Number of parameters (1).
1720 * @param[in] params New IP address for client in dotted quad or
1721 * standard IPv6 format.
1724 static int iauth_cmd_ip_address(struct IAuth *iauth, struct Client *cli,
1725 int parc, char **params)
1727 struct irc_in_addr addr;
1728 struct AuthRequest *auth;
1730 if (EmptyString(params[0])) {
1731 sendto_iauth(cli, "E Missing :Missing IP address parameter");
1735 /* Get AuthRequest for client. */
1736 auth = cli_auth(cli);
1737 assert(auth != NULL);
1739 /* Parse the client's new IP address. */
1740 if (!ircd_aton(&addr, params[0])) {
1741 sendto_iauth(cli, "E Invalid :Unable to parse IP address [%s]", params[0]);
1745 /* If this is the first IP override, save the client's original
1746 * address in case we get a DNS response later.
1748 if (!irc_in_addr_valid(&auth->original))
1749 memcpy(&auth->original, &cli_ip(cli), sizeof(auth->original));
1751 /* Undo original IP connection in IPcheck. */
1752 IPcheck_connect_fail(cli);
1753 ClearIPChecked(cli);
1755 /* Update the IP and charge them as a remote connect. */
1756 memcpy(&cli_ip(cli), &addr, sizeof(cli_ip(cli)));
1757 IPcheck_remote_connect(cli, 0);
1762 /** Find a ConfItem structure for a named connection class.
1763 * @param[in] class_name Name of configuration class to find.
1764 * @return A ConfItem of type CONF_CLIENT for the class, or NULL on failure.
1766 static struct ConfItem *auth_find_class_conf(const char *class_name)
1768 static struct ConfItem *aconf_list;
1769 struct ConnectionClass *class;
1770 struct ConfItem *aconf;
1772 /* Make sure the configuration class is valid. */
1773 class = find_class(class_name);
1777 /* Look for an existing ConfItem for the class. */
1778 for (aconf = aconf_list; aconf; aconf = aconf->next)
1779 if (aconf->conn_class == class)
1782 /* If no ConfItem, create one. */
1784 aconf = make_conf(CONF_CLIENT);
1786 sendto_opmask_butone(NULL, SNO_AUTH,
1787 "Unable to allocate ConfItem for class %s!",
1791 aconf->conn_class = class;
1792 aconf->next = aconf_list;
1799 /** Accept a client in IAuth.
1800 * @param[in] iauth Active IAuth session.
1801 * @param[in] cli Client referenced by command.
1802 * @param[in] parc Number of parameters.
1803 * @param[in] params Optional class name for client.
1806 static int iauth_cmd_done_client(struct IAuth *iauth, struct Client *cli,
1807 int parc, char **params)
1809 static time_t warn_time;
1811 /* Clear iauth pending flag. */
1812 assert(cli_auth(cli) != NULL);
1813 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1815 /* If a connection class was specified (and usable), assign the client to it. */
1816 if (!EmptyString(params[0])) {
1817 struct ConfItem *aconf;
1819 aconf = auth_find_class_conf(params[0]);
1821 attach_conf(cli, aconf);
1823 sendto_opmask_butone_ratelimited(NULL, SNO_AUTH, &warn_time,
1824 "iauth tried to use undefined class [%s]",
1831 /** Accept a client in IAuth and assign them to an account.
1832 * @param[in] iauth Active IAuth session.
1833 * @param[in] cli Client referenced by command.
1834 * @param[in] parc Number of parameters.
1835 * @param[in] params Account name and optional class name for client.
1836 * @return Non-zero if \a cli authorization should be checked for completion.
1838 static int iauth_cmd_done_account(struct IAuth *iauth, struct Client *cli,
1839 int parc, char **params)
1844 if (EmptyString(params[0])) {
1845 sendto_iauth(cli, "E Missing :Missing account parameter");
1848 /* Check length of account name. */
1849 len = strcspn(params[0], ": ");
1850 if (len > ACCOUNTLEN) {
1851 sendto_iauth(cli, "E Invalid :Account parameter too long");
1854 /* If account has a creation timestamp, use it. */
1855 assert(cli_user(cli) != NULL);
1856 if (params[0][len] == ':')
1857 cli_user(cli)->acc_create = strtoul(params[0] + len + 1, NULL, 10);
1859 /* Copy account name to User structure. */
1860 ircd_strncpy(cli_user(cli)->account, params[0], ACCOUNTLEN);
1863 /* Fall through to the normal "done" handler. */
1864 return iauth_cmd_done_client(iauth, cli, parc - 1, params + 1);
1867 /** Reject a client's connection.
1868 * @param[in] iauth Active IAuth session.
1869 * @param[in] cli Client referenced by command.
1870 * @param[in] parc Number of parameters (1).
1871 * @param[in] params Optional kill message.
1874 static int iauth_cmd_kill(struct IAuth *iauth, struct Client *cli,
1875 int parc, char **params)
1878 FlagClr(&cli_auth(cli)->flags, AR_IAUTH_PENDING);
1879 if (EmptyString(params[0]))
1880 params[0] = "Access denied";
1881 exit_client(cli, cli, &me, params[0]);
1885 /** Send a challenge string to the client.
1886 * @param[in] iauth Active IAuth session.
1887 * @param[in] cli Client referenced by command.
1888 * @param[in] parc Number of parameters (1).
1889 * @param[in] params Challenge message for client.
1892 static int iauth_cmd_challenge(struct IAuth *iauth, struct Client *cli,
1893 int parc, char **params)
1895 if (!EmptyString(params[0]))
1896 sendrawto_one(cli, "NOTICE AUTH :*** %s", params[0]);
1900 /** Parse a \a message from \a iauth.
1901 * @param[in] iauth Active IAuth session.
1902 * @param[in] message Message to be parsed.
1904 static void iauth_parse(struct IAuth *iauth, char *message)
1906 char *params[MAXPARA + 1]; /* leave space for NULL */
1908 iauth_cmd_handler handler;
1909 struct AuthRequest *auth;
1914 /* Find command handler... */
1915 switch (*(message++)) {
1916 case '>': handler = iauth_cmd_snotice; has_cli = 0; break;
1917 case 'G': handler = iauth_cmd_debuglevel; has_cli = 0; break;
1918 case 'O': handler = iauth_cmd_policy; has_cli = 0; break;
1919 case 'V': handler = iauth_cmd_version; has_cli = 0; break;
1920 case 'a': handler = iauth_cmd_newconfig; has_cli = 0; break;
1921 case 'A': handler = iauth_cmd_config; has_cli = 0; break;
1922 case 's': handler = iauth_cmd_newstats; has_cli = 0; break;
1923 case 'S': handler = iauth_cmd_stats; has_cli = 0; break;
1924 case 'o': handler = iauth_cmd_username_forced; has_cli = 1; break;
1925 case 'U': handler = iauth_cmd_username_good; has_cli = 1; break;
1926 case 'u': handler = iauth_cmd_username_bad; has_cli = 1; break;
1927 case 'N': handler = iauth_cmd_hostname; has_cli = 1; break;
1928 case 'I': handler = iauth_cmd_ip_address; has_cli = 1; break;
1929 case 'C': handler = iauth_cmd_challenge; has_cli = 1; break;
1930 case 'D': handler = iauth_cmd_done_client; has_cli = 1; break;
1931 case 'R': handler = iauth_cmd_done_account; has_cli = 1; break;
1932 case 'k': /* The 'k' command indicates the user should be booted
1933 * off without telling opers. There is no way to
1934 * signal that to exit_client(), so we fall through to
1935 * the case that we do implement.
1937 case 'K': handler = iauth_cmd_kill; has_cli = 2; break;
1938 case 'r': /* we handle termination directly */ return;
1939 default: sendto_iauth(NULL, "E Garbage :[%s]", message); return;
1942 while (parc < MAXPARA) {
1943 while (IsSpace(*message)) /* skip leading whitespace */
1946 if (!*message) /* hit the end of the string, break out */
1949 if (*message == ':') { /* found sentinel... */
1950 params[parc++] = message + 1;
1951 break; /* it's the last parameter anyway */
1954 params[parc++] = message; /* save the parameter */
1955 while (*message && !IsSpace(*message))
1956 message++; /* find the end of the parameter */
1958 if (*message) /* terminate the parameter */
1959 *(message++) = '\0';
1962 params[parc] = NULL; /* terminate the parameter list */
1964 /* Check to see if the command specifies a client... */
1966 /* Handler does not need a client. */
1967 handler(iauth, NULL, parc, params);
1969 /* Try to find the client associated with the request. */
1970 id = strtol(params[0], NULL, 10);
1971 if (id < 0 || id > HighestFd || !(cli = LocalClientArray[id]))
1972 /* Client no longer exists (or never existed). */
1973 sendto_iauth(NULL, "E Gone :[%s %s %s]", params[0], params[1],
1975 else if ((!(auth = cli_auth(cli)) ||
1976 !FlagHas(&auth->flags, AR_IAUTH_PENDING)) &&
1978 /* Client is done with IAuth checks. */
1979 sendto_iauth(cli, "E Done :[%s %s %s]", params[0], params[1], params[2]);
1981 struct irc_sockaddr addr;
1984 /* Parse IP address and port number from parameters */
1985 res = ipmask_parse(params[1], &addr.addr, NULL);
1986 addr.port = strtol(params[2], NULL, 10);
1988 /* Check IP address and port number against expected. */
1990 irc_in_addr_cmp(&addr.addr, &cli_ip(cli)) ||
1991 (auth && addr.port != auth->port))
1992 /* Report mismatch to iauth. */
1993 sendto_iauth(cli, "E Mismatch :[%s] != [%s]", params[1],
1994 ircd_ntoa(&cli_ip(cli)));
1995 else if (handler(iauth, cli, parc - 3, params + 3))
1996 /* Handler indicated a possible state change. */
1997 check_auth_finished(auth);
2002 /** Read input from \a iauth.
2003 * Reads up to SERVER_TCP_WINDOW bytes per pass.
2004 * @param[in] iauth Readable connection.
2006 static void iauth_read(struct IAuth *iauth)
2008 static char readbuf[SERVER_TCP_WINDOW];
2009 unsigned int length, count;
2013 /* Copy partial data to readbuf, append new data. */
2014 length = iauth->i_count;
2015 memcpy(readbuf, iauth->i_buffer, length);
2016 if (IO_SUCCESS != os_recv_nonb(s_fd(i_socket(iauth)),
2018 sizeof(readbuf) - length - 1,
2021 readbuf[length += count] = '\0';
2023 /* Parse each complete line. */
2024 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2026 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2029 /* If spammy debug, send the message to opers. */
2030 if (i_debug(iauth) > 1)
2031 sendto_opmask_butone(NULL, SNO_AUTH, "Parsing: \"%s\"", sol);
2033 /* Parse the line... */
2034 iauth_parse(iauth, sol);
2037 /* Put unused data back into connection's buffer. */
2038 iauth->i_count = strlen(sol);
2039 if (iauth->i_count > BUFSIZE)
2040 iauth->i_count = BUFSIZE;
2041 memcpy(iauth->i_buffer, sol, iauth->i_count);
2044 /** Handle socket activity for an %IAuth connection.
2045 * @param[in] ev &Socket event; the IAuth connection is the user data
2046 * pointer for the socket.
2048 static void iauth_sock_callback(struct Event *ev)
2050 struct IAuth *iauth;
2052 assert(0 != ev_socket(ev));
2053 iauth = (struct IAuth*) s_data(ev_socket(ev));
2056 switch (ev_type(ev)) {
2058 /* Hm, what happened here? */
2059 if (!IAuthHas(iauth, IAUTH_CLOSING))
2060 iauth_do_spawn(iauth, 1);
2066 IAuthClr(iauth, IAUTH_BLOCKED);
2070 log_write(LS_IAUTH, L_ERROR, 0, "IAuth socket error: %s", strerror(ev_data(ev)));
2071 /* and fall through to the ET_EOF case */
2073 iauth_disconnect(iauth);
2076 assert(0 && "Unrecognized event type");
2081 /** Read error input from \a iauth.
2082 * @param[in] iauth Readable connection.
2084 static void iauth_read_stderr(struct IAuth *iauth)
2086 static char readbuf[SERVER_TCP_WINDOW];
2087 unsigned int length, count;
2091 /* Copy partial data to readbuf, append new data. */
2092 length = iauth->i_errcount;
2093 memcpy(readbuf, iauth->i_errbuf, length);
2094 if (IO_SUCCESS != os_recv_nonb(s_fd(i_stderr(iauth)),
2096 sizeof(readbuf) - length - 1,
2099 readbuf[length += count] = '\0';
2101 /* Send each complete line to SNO_AUTH. */
2102 for (sol = readbuf; (eol = strchr(sol, '\n')) != NULL; sol = eol + 1) {
2104 if (*(eol - 1) == '\r') /* take out carriage returns, too... */
2106 Debug((DEBUG_ERROR, "IAuth error: %s", sol));
2107 log_write(LS_IAUTH, L_ERROR, 0, "IAuth error: %s", sol);
2108 sendto_opmask_butone(NULL, SNO_AUTH, "%s", sol);
2111 /* Put unused data back into connection's buffer. */
2112 iauth->i_errcount = strlen(sol);
2113 if (iauth->i_errcount > BUFSIZE)
2114 iauth->i_errcount = BUFSIZE;
2115 memcpy(iauth->i_errbuf, sol, iauth->i_errcount);
2118 /** Handle error socket activity for an %IAuth connection.
2119 * @param[in] ev &Socket event; the IAuth connection is the user data
2120 * pointer for the socket.
2122 static void iauth_stderr_callback(struct Event *ev)
2124 struct IAuth *iauth;
2126 assert(0 != ev_socket(ev));
2127 iauth = (struct IAuth*) s_data(ev_socket(ev));
2130 switch (ev_type(ev)) {
2132 iauth_read_stderr(iauth);
2135 log_write(LS_IAUTH, L_ERROR, 0, "IAuth stderr error: %s", strerror(ev_data(ev)));
2136 /* and fall through to the ET_EOF/ET_DESTROY case */
2141 assert(0 && "Unrecognized event type");
2146 /** Report active iauth's configuration to \a cptr.
2147 * @param[in] cptr Client requesting statistics.
2148 * @param[in] sd Stats descriptor for request.
2149 * @param[in] param Extra parameter from user (may be NULL).
2151 void report_iauth_conf(struct Client *cptr, const struct StatDesc *sd, char *param)
2155 if (iauth) for (link = iauth->i_config; link; link = link->next)
2157 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2160 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth configuration.");
2163 /** Report active iauth's statistics to \a cptr.
2164 * @param[in] cptr Client requesting statistics.
2165 * @param[in] sd Stats descriptor for request.
2166 * @param[in] param Extra parameter from user (may be NULL).
2168 void report_iauth_stats(struct Client *cptr, const struct StatDesc *sd, char *param)
2172 if (iauth) for (link = iauth->i_stats; link; link = link->next)
2174 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":%s",
2177 send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":End of IAuth statistics.");