2 * Copyright 1998 Juniper Networks, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/types.h>
30 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
47 #include "taclib_private.h"
49 static int add_str_8(struct tac_handle *, u_int8_t *,
51 static int add_str_16(struct tac_handle *, u_int16_t *,
53 static int authen_version(int, int);
54 static void close_connection(struct tac_handle *);
55 static int conn_server(struct tac_handle *);
56 static void crypt_msg(struct tac_handle *, struct tac_msg *);
57 static void *dup_str(struct tac_handle *, const struct srvr_str *,
59 static int establish_connection(struct tac_handle *);
60 static void free_str(struct clnt_str *);
61 static void generr(struct tac_handle *, const char *, ...)
63 static void gen_session_id(struct tac_msg *);
64 static int get_srvr_end(struct tac_handle *);
65 static int get_srvr_str(struct tac_handle *, struct srvr_str *,
67 static void init_clnt_str(struct clnt_str *);
68 static void init_srvr_str(struct srvr_str *);
69 static int read_timed(struct tac_handle *, void *, size_t,
70 const struct timeval *);
71 static int recv_msg(struct tac_handle *);
72 static int save_str(struct tac_handle *, struct clnt_str *,
73 const void *, size_t);
74 static int send_msg(struct tac_handle *);
75 static int split(char *, char *[], int, char *, size_t);
76 static void *xmalloc(struct tac_handle *, size_t);
77 static char *xstrdup(struct tac_handle *, const char *);
80 * Append some optional data to the current request, and store its
81 * length into the 8-bit field referenced by "fld". Returns 0 on
82 * success, or -1 on failure.
84 * This function also frees the "cs" string data and initializes it
88 add_str_8(struct tac_handle *h, u_int8_t *fld, struct clnt_str *cs)
92 if (add_str_16(h, &len, cs) == -1)
96 generr(h, "Field too long");
104 * Append some optional data to the current request, and store its
105 * length into the 16-bit field (network byte order) referenced by
106 * "fld". Returns 0 on success, or -1 on failure.
108 * This function also frees the "cs" string data and initializes it
112 add_str_16(struct tac_handle *h, u_int16_t *fld, struct clnt_str *cs)
117 if (cs->data == NULL)
123 generr(h, "Field too long");
126 offset = ntohl(h->request.length);
127 if (offset + len > BODYSIZE) {
128 generr(h, "Message too long");
131 memcpy(h->request.u.body + offset, cs->data, len);
132 h->request.length = htonl(offset + len);
140 authen_version(int action, int type)
146 case TAC_AUTHEN_LOGIN:
149 case TAC_AUTHEN_TYPE_PAP:
150 case TAC_AUTHEN_TYPE_CHAP:
151 case TAC_AUTHEN_TYPE_MSCHAP:
152 case TAC_AUTHEN_TYPE_ARAP:
162 case TAC_AUTHEN_SENDAUTH:
171 return TAC_VER_MAJOR << 4 | minor;
175 close_connection(struct tac_handle *h)
184 conn_server(struct tac_handle *h)
186 const struct tac_server *srvp = &h->servers[h->cur_server];
189 if ((h->fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
190 generr(h, "Cannot create socket: %s", strerror(errno));
193 if ((flags = fcntl(h->fd, F_GETFL, 0)) == -1 ||
194 fcntl(h->fd, F_SETFL, flags | O_NONBLOCK) == -1) {
195 generr(h, "Cannot set non-blocking mode on socket: %s",
201 if (connect(h->fd, (struct sockaddr *)&srvp->addr,
202 sizeof srvp->addr) == 0)
205 if (errno == EINPROGRESS) {
209 struct sockaddr peer;
214 /* Wait for the connection to complete. */
216 FD_SET(h->fd, &wfds);
217 tv.tv_sec = srvp->timeout;
219 nfds = select(h->fd + 1, NULL, &wfds, NULL, &tv);
221 generr(h, "select: %s", strerror(errno));
227 generr(h, "connect: timed out");
233 /* See whether we are connected now. */
234 peerlen = sizeof peer;
235 if (getpeername(h->fd, &peer, &peerlen) == 0)
238 if (errno != ENOTCONN) {
239 generr(h, "getpeername: %s", strerror(errno));
245 /* Find out why the connect failed. */
247 getsockopt(h->fd, SOL_SOCKET, SO_ERROR, &err, &errlen);
250 generr(h, "connect: %s", strerror(errno));
257 * Encrypt or decrypt a message. The operations are symmetrical.
260 crypt_msg(struct tac_handle *h, struct tac_msg *msg)
265 unsigned char md5[16];
269 secret = h->servers[h->cur_server].secret;
270 if (secret[0] == '\0')
271 msg->flags |= TAC_UNENCRYPTED;
272 if (msg->flags & TAC_UNENCRYPTED)
275 msg_len = ntohl(msg->length);
278 MD5Update(&base_ctx, msg->session_id, sizeof msg->session_id);
279 MD5Update(&base_ctx, secret, strlen(secret));
280 MD5Update(&base_ctx, &msg->version, sizeof msg->version);
281 MD5Update(&base_ctx, &msg->seq_no, sizeof msg->seq_no);
284 for (chunk = 0; chunk < msg_len; chunk += sizeof md5) {
290 if ((chunk_len = msg_len - chunk) > sizeof md5)
291 chunk_len = sizeof md5;
292 for (i = 0; i < chunk_len; i++)
293 msg->u.body[chunk + i] ^= md5[i];
296 MD5Update(&ctx, md5, sizeof md5);
301 * Return a dynamically allocated copy of the given server string.
302 * The copy is null-terminated. If "len" is non-NULL, the length of
303 * the string (excluding the terminating null byte) is stored via it.
304 * Returns NULL on failure. Empty strings are still allocated even
305 * though they have no content.
308 dup_str(struct tac_handle *h, const struct srvr_str *ss, size_t *len)
312 if ((p = (unsigned char *)xmalloc(h, ss->len + 1)) == NULL)
314 if (ss->data != NULL && ss->len != 0)
315 memcpy(p, ss->data, ss->len);
323 establish_connection(struct tac_handle *h)
327 if (h->fd >= 0) /* Already connected. */
329 if (h->num_servers == 0) {
330 generr(h, "No TACACS+ servers specified");
334 * Try the servers round-robin. We begin with the one that
335 * worked for us the last time. That way, once we find a good
336 * server, we won't waste any more time trying the bad ones.
338 for (i = 0; i < h->num_servers; i++) {
339 if (conn_server(h) == 0) {
340 h->single_connect = (h->servers[h->cur_server].flags &
341 TAC_SRVR_SINGLE_CONNECT) != 0;
344 if (++h->cur_server >= h->num_servers) /* Wrap around */
347 /* Just return whatever error was last reported by conn_server(). */
352 * Free a client string, obliterating its contents first for security.
355 free_str(struct clnt_str *cs)
357 if (cs->data != NULL) {
358 memset(cs->data, 0, cs->len);
366 generr(struct tac_handle *h, const char *format, ...)
370 va_start(ap, format);
371 vsnprintf(h->errmsg, ERRSIZE, format, ap);
376 gen_session_id(struct tac_msg *msg)
381 msg->session_id[0] = r >> 8;
382 msg->session_id[1] = r;
384 msg->session_id[2] = r >> 8;
385 msg->session_id[3] = r;
389 * Verify that we are exactly at the end of the response message.
390 * Returns 0 on success, -1 on failure.
393 get_srvr_end(struct tac_handle *h)
395 if (h->srvr_pos != ntohl(h->response.length)) {
396 generr(h, "Invalid length field in response from server");
403 get_srvr_str(struct tac_handle *h, struct srvr_str *ss, size_t len)
405 if (h->srvr_pos + len > ntohl(h->response.length)) {
406 generr(h, "Invalid length field in response from server");
409 ss->data = len != 0 ? h->response.u.body + h->srvr_pos : NULL;
416 init_clnt_str(struct clnt_str *cs)
423 init_srvr_str(struct srvr_str *ss)
430 read_timed(struct tac_handle *h, void *buf, size_t len,
431 const struct timeval *deadline)
439 n = read(h->fd, ptr, len);
444 if (errno != EAGAIN) {
445 generr(h, "Network read error: %s",
450 /* Wait until we can read more data. */
451 gettimeofday(&tv, NULL);
452 timersub(deadline, &tv, &tv);
453 if (tv.tv_sec >= 0) {
457 FD_SET(h->fd, &rfds);
459 select(h->fd + 1, &rfds, NULL, NULL, &tv);
461 generr(h, "select: %s",
468 generr(h, "Network read timed out");
472 generr(h, "unexpected EOF from server");
483 * Receive a response from the server and decrypt it. Returns 0 on
484 * success, or -1 on failure.
487 recv_msg(struct tac_handle *h)
489 struct timeval deadline;
494 gettimeofday(&deadline, NULL);
495 deadline.tv_sec += h->servers[h->cur_server].timeout;
497 /* Read the message header and make sure it is reasonable. */
498 if (read_timed(h, msg, HDRSIZE, &deadline) == -1)
500 if (memcmp(msg->session_id, h->request.session_id,
501 sizeof msg->session_id) != 0) {
502 generr(h, "Invalid session ID in received message");
505 if (msg->type != h->request.type) {
506 generr(h, "Invalid type in received message");
509 len = ntohl(msg->length);
510 if (len > BODYSIZE) {
511 generr(h, "Received message too large");
514 if (msg->seq_no != ++h->last_seq_no) {
515 generr(h, "Invalid sequence number in received message");
519 /* Read the message body. */
520 if (read_timed(h, msg->u.body, len, &deadline) == -1)
527 * Turn off single-connection mode if the server isn't amenable
530 if (!(msg->flags & TAC_SINGLE_CONNECT))
531 h->single_connect = 0;
536 save_str(struct tac_handle *h, struct clnt_str *cs, const void *data,
540 if (data != NULL && len != 0) {
541 if ((cs->data = xmalloc(h, len)) == NULL)
544 memcpy(cs->data, data, len);
550 * Send the current request, after encrypting it. Returns 0 on success,
554 send_msg(struct tac_handle *h)
556 struct timeval deadline;
561 if (h->last_seq_no & 1) {
562 generr(h, "Attempt to send message out of sequence");
567 msg->seq_no = ++h->last_seq_no;
568 if (msg->seq_no == 1)
572 if (establish_connection(h) == -1)
575 if (h->single_connect)
576 msg->flags |= TAC_SINGLE_CONNECT;
578 msg->flags &= ~TAC_SINGLE_CONNECT;
579 gettimeofday(&deadline, NULL);
580 deadline.tv_sec += h->servers[h->cur_server].timeout;
581 len = HDRSIZE + ntohl(msg->length);
586 n = write(h->fd, ptr, len);
591 if (errno != EAGAIN) {
592 generr(h, "Network write error: %s",
597 /* Wait until we can write more data. */
598 gettimeofday(&tv, NULL);
599 timersub(&deadline, &tv, &tv);
600 if (tv.tv_sec >= 0) {
604 FD_SET(h->fd, &wfds);
606 select(h->fd + 1, NULL, &wfds, NULL, &tv);
608 generr(h, "select: %s",
615 generr(h, "Network write timed out");
627 * Destructively split a string into fields separated by white space.
628 * `#' at the beginning of a field begins a comment that extends to the
629 * end of the string. Fields may be quoted with `"'. Inside quoted
630 * strings, the backslash escapes `\"' and `\\' are honored.
632 * Pointers to up to the first maxfields fields are stored in the fields
633 * array. Missing fields get NULL pointers.
635 * The return value is the actual number of fields parsed, and is always
638 * On a syntax error, places a message in the msg string, and returns -1.
641 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
645 static const char ws[] = " \t";
647 for (i = 0; i < maxfields; i++)
653 if (*p == '#' || *p == '\0')
655 if (i >= maxfields) {
656 snprintf(msg, msglen, "line has too many fields");
667 if (*p != '"' && *p != '\\' &&
669 snprintf(msg, msglen,
670 "invalid `\\' escape");
675 snprintf(msg, msglen,
676 "unterminated quoted string");
683 if (*p != '\0' && strspn(p, ws) == 0) {
684 snprintf(msg, msglen, "quoted string not"
685 " followed by white space");
700 tac_add_server(struct tac_handle *h, const char *host, int port,
701 const char *secret, int timeout, int flags)
703 struct tac_server *srvp;
705 if (h->num_servers >= MAXSERVERS) {
706 generr(h, "Too many TACACS+ servers specified");
709 srvp = &h->servers[h->num_servers];
711 memset(&srvp->addr, 0, sizeof srvp->addr);
712 srvp->addr.sin_len = sizeof srvp->addr;
713 srvp->addr.sin_family = AF_INET;
714 if (!inet_aton(host, &srvp->addr.sin_addr)) {
715 struct hostent *hent;
717 if ((hent = gethostbyname(host)) == NULL) {
718 generr(h, "%s: host not found", host);
721 memcpy(&srvp->addr.sin_addr, hent->h_addr,
722 sizeof srvp->addr.sin_addr);
724 srvp->addr.sin_port = htons(port != 0 ? port : TACPLUS_PORT);
725 if ((srvp->secret = xstrdup(h, secret)) == NULL)
727 srvp->timeout = timeout;
734 tac_close(struct tac_handle *h)
740 for (srv = 0; srv < h->num_servers; srv++) {
741 memset(h->servers[srv].secret, 0,
742 strlen(h->servers[srv].secret));
743 free(h->servers[srv].secret);
747 free_str(&h->rem_addr);
749 free_str(&h->user_msg);
754 tac_config(struct tac_handle *h, const char *path)
757 char buf[MAXCONFLINE];
762 path = PATH_TACPLUS_CONF;
763 if ((fp = fopen(path, "r")) == NULL) {
764 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
769 while (fgets(buf, sizeof buf, fp) != NULL) {
780 unsigned long timeout;
786 /* We know len > 0, else fgets would have returned NULL. */
787 if (buf[len - 1] != '\n') {
788 if (len == sizeof buf - 1)
789 generr(h, "%s:%d: line too long", path,
792 generr(h, "%s:%d: missing newline", path,
799 /* Extract the fields from the line. */
800 nfields = split(buf, fields, 4, msg, sizeof msg);
802 generr(h, "%s:%d: %s", path, linenum, msg);
809 generr(h, "%s:%d: missing shared secret", path,
816 timeout_str = fields[2];
817 options_str = fields[3];
819 /* Parse and validate the fields. */
820 host = strtok(host, ":");
821 port_str = strtok(NULL, ":");
822 if (port_str != NULL) {
823 port = strtoul(port_str, &end, 10);
824 if (port_str[0] == '\0' || *end != '\0') {
825 generr(h, "%s:%d: invalid port", path,
832 if (timeout_str != NULL) {
833 timeout = strtoul(timeout_str, &end, 10);
834 if (timeout_str[0] == '\0' || *end != '\0') {
835 generr(h, "%s:%d: invalid timeout", path,
843 if (options_str != NULL) {
844 if (strcmp(options_str, "single-connection") == 0)
845 options |= TAC_SRVR_SINGLE_CONNECT;
847 generr(h, "%s:%d: invalid option \"%s\"",
848 path, linenum, options_str);
854 if (tac_add_server(h, host, port, secret, timeout,
858 strcpy(msg, h->errmsg);
859 generr(h, "%s:%d: %s", path, linenum, msg);
864 /* Clear out the buffer to wipe a possible copy of a shared secret */
865 memset(buf, 0, sizeof buf);
871 tac_create_authen(struct tac_handle *h, int action, int type, int service)
874 struct tac_authen_start *as;
879 msg->type = TAC_AUTHEN;
880 msg->version = authen_version(action, type);
883 as = &msg->u.authen_start;
885 as->priv_lvl = TAC_PRIV_LVL_USER;
886 as->authen_type = type;
887 as->service = service;
891 free_str(&h->rem_addr);
893 free_str(&h->user_msg);
895 /* XXX - more to do */
900 tac_get_data(struct tac_handle *h, size_t *len)
902 return dup_str(h, &h->srvr_data, len);
906 tac_get_msg(struct tac_handle *h)
908 return (char *)dup_str(h, &h->srvr_msg, NULL);
912 * Create and initialize a tac_handle structure, and return it to the
913 * caller. Can fail only if the necessary memory cannot be allocated.
914 * In that case, it returns NULL.
919 struct tac_handle *h;
921 h = (struct tac_handle *)malloc(sizeof(struct tac_handle));
927 init_clnt_str(&h->user);
928 init_clnt_str(&h->port);
929 init_clnt_str(&h->rem_addr);
930 init_clnt_str(&h->data);
931 init_clnt_str(&h->user_msg);
932 init_srvr_str(&h->srvr_msg);
933 init_srvr_str(&h->srvr_data);
940 tac_send_authen(struct tac_handle *h)
942 struct tac_authen_reply *ar;
944 if (h->last_seq_no == 0) { /* Authentication START packet */
945 struct tac_authen_start *as;
947 as = &h->request.u.authen_start;
949 htonl(offsetof(struct tac_authen_start, rest[0]));
950 if (add_str_8(h, &as->user_len, &h->user) == -1 ||
951 add_str_8(h, &as->port_len, &h->port) == -1 ||
952 add_str_8(h, &as->rem_addr_len, &h->rem_addr) == -1 ||
953 add_str_8(h, &as->data_len, &h->data) == -1)
955 } else { /* Authentication CONTINUE packet */
956 struct tac_authen_cont *ac;
958 ac = &h->request.u.authen_cont;
961 htonl(offsetof(struct tac_authen_cont, rest[0]));
962 if (add_str_16(h, &ac->user_msg_len, &h->user_msg) == -1 ||
963 add_str_16(h, &ac->data_len, &h->data) == -1)
967 /* Send the message and retrieve the reply. */
968 if (send_msg(h) == -1 || recv_msg(h) == -1)
971 /* Scan the optional fields in the reply. */
972 ar = &h->response.u.authen_reply;
973 h->srvr_pos = offsetof(struct tac_authen_reply, rest[0]);
974 if (get_srvr_str(h, &h->srvr_msg, ntohs(ar->msg_len)) == -1 ||
975 get_srvr_str(h, &h->srvr_data, ntohs(ar->data_len)) == -1 ||
976 get_srvr_end(h) == -1)
979 if (!h->single_connect &&
980 ar->status != TAC_AUTHEN_STATUS_GETDATA &&
981 ar->status != TAC_AUTHEN_STATUS_GETUSER &&
982 ar->status != TAC_AUTHEN_STATUS_GETPASS)
985 return ar->flags << 8 | ar->status;
989 tac_set_rem_addr(struct tac_handle *h, const char *addr)
991 return save_str(h, &h->rem_addr, addr, addr != NULL ? strlen(addr) : 0);
995 tac_set_data(struct tac_handle *h, const void *data, size_t data_len)
997 return save_str(h, &h->data, data, data_len);
1001 tac_set_msg(struct tac_handle *h, const char *msg)
1003 return save_str(h, &h->user_msg, msg, msg != NULL ? strlen(msg) : 0);
1007 tac_set_port(struct tac_handle *h, const char *port)
1009 return save_str(h, &h->port, port, port != NULL ? strlen(port) : 0);
1013 tac_set_priv(struct tac_handle *h, int priv)
1015 if (!(TAC_PRIV_LVL_MIN <= priv && priv <= TAC_PRIV_LVL_MAX)) {
1016 generr(h, "Attempt to set invalid privilege level");
1019 h->request.u.authen_start.priv_lvl = priv;
1024 tac_set_user(struct tac_handle *h, const char *user)
1026 return save_str(h, &h->user, user, user != NULL ? strlen(user) : 0);
1030 tac_strerror(struct tac_handle *h)
1036 xmalloc(struct tac_handle *h, size_t size)
1040 if ((r = malloc(size)) == NULL)
1041 generr(h, "Out of memory");
1046 xstrdup(struct tac_handle *h, const char *s)
1050 if ((r = strdup(s)) == NULL)
1051 generr(h, "Out of memory");