1 /*- 2 * Copyright 1998 Juniper Networks, Inc. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 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. 13 * 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 24 * SUCH DAMAGE. 25 * 26 * $FreeBSD$ 27 */ 28 29 #include <sys/types.h> 30 #include <sys/socket.h> 31 #include <sys/time.h> 32 #include <netinet/in.h> 33 #include <arpa/inet.h> 34 35 #include <errno.h> 36 #include <md5.h> 37 #include <netdb.h> 38 #include <stdarg.h> 39 #include <stddef.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <string.h> 43 #include <unistd.h> 44 45 #include "radlib_private.h" 46 47 static void clear_password(struct rad_handle *); 48 static void generr(struct rad_handle *, const char *, ...) 49 __printflike(2, 3); 50 static void insert_scrambled_password(struct rad_handle *, int); 51 static int is_valid_response(struct rad_handle *, int, 52 const struct sockaddr_in *); 53 static int put_password_attr(struct rad_handle *, int, 54 const void *, size_t); 55 static int put_raw_attr(struct rad_handle *, int, 56 const void *, size_t); 57 static int split(char *, char *[], int, char *, size_t); 58 59 static void 60 clear_password(struct rad_handle *h) 61 { 62 if (h->pass_len != 0) { 63 memset(h->pass, 0, h->pass_len); 64 h->pass_len = 0; 65 h->pass_pos = 0; 66 } 67 } 68 69 static void 70 generr(struct rad_handle *h, const char *format, ...) 71 { 72 va_list ap; 73 74 va_start(ap, format); 75 vsnprintf(h->errmsg, ERRSIZE, format, ap); 76 va_end(ap); 77 } 78 79 static void 80 insert_scrambled_password(struct rad_handle *h, int srv) 81 { 82 MD5_CTX ctx; 83 unsigned char md5[16]; 84 const struct rad_server *srvp; 85 int padded_len; 86 int pos; 87 88 srvp = &h->servers[srv]; 89 padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf; 90 91 memcpy(md5, &h->request[POS_AUTH], LEN_AUTH); 92 for (pos = 0; pos < padded_len; pos += 16) { 93 int i; 94 95 /* Calculate the new scrambler */ 96 MD5Init(&ctx); 97 MD5Update(&ctx, srvp->secret, strlen(srvp->secret)); 98 MD5Update(&ctx, md5, 16); 99 MD5Final(md5, &ctx); 100 101 /* 102 * Mix in the current chunk of the password, and copy 103 * the result into the right place in the request. Also 104 * modify the scrambler in place, since we will use this 105 * in calculating the scrambler for next time. 106 */ 107 for (i = 0; i < 16; i++) 108 h->request[h->pass_pos + pos + i] = 109 md5[i] ^= h->pass[pos + i]; 110 } 111 } 112 113 /* 114 * Return true if the current response is valid for a request to the 115 * specified server. 116 */ 117 static int 118 is_valid_response(struct rad_handle *h, int srv, 119 const struct sockaddr_in *from) 120 { 121 MD5_CTX ctx; 122 unsigned char md5[16]; 123 const struct rad_server *srvp; 124 int len; 125 126 srvp = &h->servers[srv]; 127 128 /* Check the source address */ 129 if (from->sin_family != srvp->addr.sin_family || 130 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr || 131 from->sin_port != srvp->addr.sin_port) 132 return 0; 133 134 /* Check the message length */ 135 if (h->resp_len < POS_ATTRS) 136 return 0; 137 len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1]; 138 if (len > h->resp_len) 139 return 0; 140 141 /* Check the response authenticator */ 142 MD5Init(&ctx); 143 MD5Update(&ctx, &h->response[POS_CODE], POS_AUTH - POS_CODE); 144 MD5Update(&ctx, &h->request[POS_AUTH], LEN_AUTH); 145 MD5Update(&ctx, &h->response[POS_ATTRS], len - POS_ATTRS); 146 MD5Update(&ctx, srvp->secret, strlen(srvp->secret)); 147 MD5Final(md5, &ctx); 148 if (memcmp(&h->response[POS_AUTH], md5, sizeof md5) != 0) 149 return 0; 150 151 return 1; 152 } 153 154 static int 155 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len) 156 { 157 int padded_len; 158 int pad_len; 159 160 if (h->pass_pos != 0) { 161 generr(h, "Multiple User-Password attributes specified"); 162 return -1; 163 } 164 if (len > PASSSIZE) 165 len = PASSSIZE; 166 padded_len = len == 0 ? 16 : (len+15) & ~0xf; 167 pad_len = padded_len - len; 168 169 /* 170 * Put in a place-holder attribute containing all zeros, and 171 * remember where it is so we can fill it in later. 172 */ 173 clear_password(h); 174 put_raw_attr(h, type, h->pass, padded_len); 175 h->pass_pos = h->req_len - padded_len; 176 177 /* Save the cleartext password, padded as necessary */ 178 memcpy(h->pass, value, len); 179 h->pass_len = len; 180 memset(h->pass + len, 0, pad_len); 181 return 0; 182 } 183 184 static int 185 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len) 186 { 187 if (len > 253) { 188 generr(h, "Attribute too long"); 189 return -1; 190 } 191 if (h->req_len + 2 + len > MSGSIZE) { 192 generr(h, "Maximum message length exceeded"); 193 return -1; 194 } 195 h->request[h->req_len++] = type; 196 h->request[h->req_len++] = len + 2; 197 memcpy(&h->request[h->req_len], value, len); 198 h->req_len += len; 199 return 0; 200 } 201 202 int 203 rad_add_server(struct rad_handle *h, const char *host, int port, 204 const char *secret, int timeout, int tries) 205 { 206 struct rad_server *srvp; 207 208 if (h->num_servers >= MAXSERVERS) { 209 generr(h, "Too many RADIUS servers specified"); 210 return -1; 211 } 212 srvp = &h->servers[h->num_servers]; 213 214 memset(&srvp->addr, 0, sizeof srvp->addr); 215 srvp->addr.sin_len = sizeof srvp->addr; 216 srvp->addr.sin_family = AF_INET; 217 if (!inet_aton(host, &srvp->addr.sin_addr)) { 218 struct hostent *hent; 219 220 if ((hent = gethostbyname(host)) == NULL) { 221 generr(h, "%s: host not found", host); 222 return -1; 223 } 224 memcpy(&srvp->addr.sin_addr, hent->h_addr, 225 sizeof srvp->addr.sin_addr); 226 } 227 if (port != 0) 228 srvp->addr.sin_port = htons(port); 229 else { 230 struct servent *sent; 231 232 srvp->addr.sin_port = 233 (sent = getservbyname("radius", "udp")) != NULL ? 234 sent->s_port : htons(RADIUS_PORT); 235 } 236 if ((srvp->secret = strdup(secret)) == NULL) { 237 generr(h, "Out of memory"); 238 return -1; 239 } 240 srvp->timeout = timeout; 241 srvp->max_tries = tries; 242 srvp->num_tries = 0; 243 h->num_servers++; 244 return 0; 245 } 246 247 void 248 rad_close(struct rad_handle *h) 249 { 250 int srv; 251 252 if (h->fd != -1) 253 close(h->fd); 254 for (srv = 0; srv < h->num_servers; srv++) { 255 memset(h->servers[srv].secret, 0, 256 strlen(h->servers[srv].secret)); 257 free(h->servers[srv].secret); 258 } 259 clear_password(h); 260 free(h); 261 } 262 263 int 264 rad_config(struct rad_handle *h, const char *path) 265 { 266 FILE *fp; 267 char buf[MAXCONFLINE]; 268 int linenum; 269 int retval; 270 271 if (path == NULL) 272 path = PATH_RADIUS_CONF; 273 if ((fp = fopen(path, "r")) == NULL) { 274 generr(h, "Cannot open \"%s\": %s", path, strerror(errno)); 275 return -1; 276 } 277 retval = 0; 278 linenum = 0; 279 while (fgets(buf, sizeof buf, fp) != NULL) { 280 int len; 281 char *fields[4]; 282 int nfields; 283 char msg[ERRSIZE]; 284 char *host; 285 char *port_str; 286 char *secret; 287 char *timeout_str; 288 char *maxtries_str; 289 char *end; 290 unsigned long timeout; 291 unsigned long maxtries; 292 int port; 293 294 linenum++; 295 len = strlen(buf); 296 /* We know len > 0, else fgets would have returned NULL. */ 297 if (buf[len - 1] != '\n') { 298 if (len == sizeof buf - 1) 299 generr(h, "%s:%d: line too long", path, 300 linenum); 301 else 302 generr(h, "%s:%d: missing newline", path, 303 linenum); 304 retval = -1; 305 break; 306 } 307 buf[len - 1] = '\0'; 308 309 /* Extract the fields from the line. */ 310 nfields = split(buf, fields, 4, msg, sizeof msg); 311 if (nfields == -1) { 312 generr(h, "%s:%d: %s", path, linenum, msg); 313 retval = -1; 314 break; 315 } 316 if (nfields == 0) 317 continue; 318 if (nfields < 2) { 319 generr(h, "%s:%d: missing shared secret", path, 320 linenum); 321 retval = -1; 322 break; 323 } 324 host = fields[0]; 325 secret = fields[1]; 326 timeout_str = fields[2]; 327 maxtries_str = fields[3]; 328 329 /* Parse and validate the fields. */ 330 host = strtok(host, ":"); 331 port_str = strtok(NULL, ":"); 332 if (port_str != NULL) { 333 port = strtoul(port_str, &end, 10); 334 if (*end != '\0') { 335 generr(h, "%s:%d: invalid port", path, 336 linenum); 337 retval = -1; 338 break; 339 } 340 } else 341 port = 0; 342 if (timeout_str != NULL) { 343 timeout = strtoul(timeout_str, &end, 10); 344 if (*end != '\0') { 345 generr(h, "%s:%d: invalid timeout", path, 346 linenum); 347 retval = -1; 348 break; 349 } 350 } else 351 timeout = TIMEOUT; 352 if (maxtries_str != NULL) { 353 maxtries = strtoul(maxtries_str, &end, 10); 354 if (*end != '\0') { 355 generr(h, "%s:%d: invalid maxtries", path, 356 linenum); 357 retval = -1; 358 break; 359 } 360 } else 361 maxtries = MAXTRIES; 362 363 if (rad_add_server(h, host, port, secret, timeout, maxtries) == 364 -1) { 365 strcpy(msg, h->errmsg); 366 generr(h, "%s:%d: %s", path, linenum, msg); 367 retval = -1; 368 break; 369 } 370 } 371 /* Clear out the buffer to wipe a possible copy of a shared secret */ 372 memset(buf, 0, sizeof buf); 373 fclose(fp); 374 return retval; 375 } 376 377 /* 378 * rad_init_send_request() must have previously been called. 379 * Returns: 380 * 0 The application should select on *fd with a timeout of tv before 381 * calling rad_continue_send_request again. 382 * < 0 Failure 383 * > 0 Success 384 */ 385 int 386 rad_continue_send_request(struct rad_handle *h, int selected, int *fd, 387 struct timeval *tv) 388 { 389 int n; 390 391 if (selected) { 392 struct sockaddr_in from; 393 int fromlen; 394 395 fromlen = sizeof from; 396 h->resp_len = recvfrom(h->fd, h->response, 397 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen); 398 if (h->resp_len == -1) { 399 generr(h, "recvfrom: %s", strerror(errno)); 400 return -1; 401 } 402 if (is_valid_response(h, h->srv, &from)) { 403 h->resp_len = h->response[POS_LENGTH] << 8 | 404 h->response[POS_LENGTH+1]; 405 h->resp_pos = POS_ATTRS; 406 return h->response[POS_CODE]; 407 } 408 } 409 410 if (h->try == h->total_tries) { 411 generr(h, "No valid RADIUS responses received"); 412 return -1; 413 } 414 415 /* 416 * Scan round-robin to the next server that has some 417 * tries left. There is guaranteed to be one, or we 418 * would have exited this loop by now. 419 */ 420 while (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) 421 if (++h->srv >= h->num_servers) 422 h->srv = 0; 423 424 /* Insert the scrambled password into the request */ 425 if (h->pass_pos != 0) 426 insert_scrambled_password(h, h->srv); 427 428 /* Send the request */ 429 n = sendto(h->fd, h->request, h->req_len, 0, 430 (const struct sockaddr *)&h->servers[h->srv].addr, 431 sizeof h->servers[h->srv].addr); 432 if (n != h->req_len) { 433 if (n == -1) 434 generr(h, "sendto: %s", strerror(errno)); 435 else 436 generr(h, "sendto: short write"); 437 return -1; 438 } 439 440 h->try++; 441 h->servers[h->srv].num_tries++; 442 tv->tv_sec = h->servers[h->srv].timeout; 443 tv->tv_usec = 0; 444 *fd = h->fd; 445 446 return 0; 447 } 448 449 int 450 rad_create_request(struct rad_handle *h, int code) 451 { 452 int i; 453 454 h->request[POS_CODE] = code; 455 h->request[POS_IDENT] = ++h->ident; 456 /* Create a random authenticator */ 457 for (i = 0; i < LEN_AUTH; i += 2) { 458 long r; 459 r = random(); 460 h->request[POS_AUTH+i] = r; 461 h->request[POS_AUTH+i+1] = r >> 8; 462 } 463 h->req_len = POS_ATTRS; 464 clear_password(h); 465 return 0; 466 } 467 468 struct in_addr 469 rad_cvt_addr(const void *data) 470 { 471 struct in_addr value; 472 473 memcpy(&value.s_addr, data, sizeof value.s_addr); 474 return value; 475 } 476 477 u_int32_t 478 rad_cvt_int(const void *data) 479 { 480 u_int32_t value; 481 482 memcpy(&value, data, sizeof value); 483 return ntohl(value); 484 } 485 486 char * 487 rad_cvt_string(const void *data, size_t len) 488 { 489 char *s; 490 491 s = malloc(len + 1); 492 if (s != NULL) { 493 memcpy(s, data, len); 494 s[len] = '\0'; 495 } 496 return s; 497 } 498 499 /* 500 * Returns the attribute type. If none are left, returns 0. On failure, 501 * returns -1. 502 */ 503 int 504 rad_get_attr(struct rad_handle *h, const void **value, size_t *len) 505 { 506 int type; 507 508 if (h->resp_pos >= h->resp_len) 509 return 0; 510 if (h->resp_pos + 2 > h->resp_len) { 511 generr(h, "Malformed attribute in response"); 512 return -1; 513 } 514 type = h->response[h->resp_pos++]; 515 *len = h->response[h->resp_pos++] - 2; 516 if (h->resp_pos + *len > h->resp_len) { 517 generr(h, "Malformed attribute in response"); 518 return -1; 519 } 520 *value = &h->response[h->resp_pos]; 521 h->resp_pos += *len; 522 return type; 523 } 524 525 /* 526 * Returns -1 on error, 0 to indicate no event and >0 for success 527 */ 528 int 529 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv) 530 { 531 int srv; 532 533 /* Make sure we have a socket to use */ 534 if (h->fd == -1) { 535 struct sockaddr_in sin; 536 537 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { 538 generr(h, "Cannot create socket: %s", strerror(errno)); 539 return -1; 540 } 541 memset(&sin, 0, sizeof sin); 542 sin.sin_len = sizeof sin; 543 sin.sin_family = AF_INET; 544 sin.sin_addr.s_addr = INADDR_ANY; 545 sin.sin_port = htons(0); 546 if (bind(h->fd, (const struct sockaddr *)&sin, 547 sizeof sin) == -1) { 548 generr(h, "bind: %s", strerror(errno)); 549 close(h->fd); 550 h->fd = -1; 551 return -1; 552 } 553 } 554 555 /* Make sure the user gave us a password */ 556 if (h->pass_pos == 0 && !h->chap_pass) { 557 generr(h, "No User or Chap Password attributes given"); 558 return -1; 559 } 560 if (h->pass_pos != 0 && h->chap_pass) { 561 generr(h, "Both User and Chap Password attributes given"); 562 return -1; 563 } 564 565 /* Fill in the length field in the message */ 566 h->request[POS_LENGTH] = h->req_len >> 8; 567 h->request[POS_LENGTH+1] = h->req_len; 568 569 /* 570 * Count the total number of tries we will make, and zero the 571 * counter for each server. 572 */ 573 h->total_tries = 0; 574 for (srv = 0; srv < h->num_servers; srv++) { 575 h->total_tries += h->servers[srv].max_tries; 576 h->servers[srv].num_tries = 0; 577 } 578 if (h->total_tries == 0) { 579 generr(h, "No RADIUS servers specified"); 580 return -1; 581 } 582 583 h->try = h->srv = 0; 584 585 return rad_continue_send_request(h, 0, fd, tv); 586 } 587 588 /* 589 * Create and initialize a rad_handle structure, and return it to the 590 * caller. Can fail only if the necessary memory cannot be allocated. 591 * In that case, it returns NULL. 592 */ 593 struct rad_handle * 594 rad_open(void) 595 { 596 struct rad_handle *h; 597 598 h = (struct rad_handle *)malloc(sizeof(struct rad_handle)); 599 if (h != NULL) { 600 srandomdev(); 601 h->fd = -1; 602 h->num_servers = 0; 603 h->ident = random(); 604 h->errmsg[0] = '\0'; 605 memset(h->pass, 0, sizeof h->pass); 606 h->pass_len = 0; 607 h->pass_pos = 0; 608 h->chap_pass = 0; 609 } 610 return h; 611 } 612 613 int 614 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr) 615 { 616 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr); 617 } 618 619 int 620 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len) 621 { 622 int result; 623 624 if (type == RAD_USER_PASSWORD) 625 result = put_password_attr(h, type, value, len); 626 else { 627 result = put_raw_attr(h, type, value, len); 628 if (result == 0 && type == RAD_CHAP_PASSWORD) 629 h->chap_pass = 1; 630 } 631 632 return result; 633 } 634 635 int 636 rad_put_int(struct rad_handle *h, int type, u_int32_t value) 637 { 638 u_int32_t nvalue; 639 640 nvalue = htonl(value); 641 return rad_put_attr(h, type, &nvalue, sizeof nvalue); 642 } 643 644 int 645 rad_put_string(struct rad_handle *h, int type, const char *str) 646 { 647 return rad_put_attr(h, type, str, strlen(str)); 648 } 649 650 /* 651 * Returns the response type code on success, or -1 on failure. 652 */ 653 int 654 rad_send_request(struct rad_handle *h) 655 { 656 struct timeval timelimit; 657 struct timeval tv; 658 int fd; 659 int n; 660 661 n = rad_init_send_request(h, &fd, &tv); 662 663 if (n != 0) 664 return n; 665 666 gettimeofday(&timelimit, NULL); 667 timeradd(&tv, &timelimit, &timelimit); 668 669 for ( ; ; ) { 670 fd_set readfds; 671 672 FD_ZERO(&readfds); 673 FD_SET(fd, &readfds); 674 675 n = select(fd + 1, &readfds, NULL, NULL, &tv); 676 677 if (n == -1) { 678 generr(h, "select: %s", strerror(errno)); 679 return -1; 680 } 681 682 if (!FD_ISSET(fd, &readfds)) { 683 /* Compute a new timeout */ 684 gettimeofday(&tv, NULL); 685 timersub(&timelimit, &tv, &tv); 686 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0)) 687 /* Continue the select */ 688 continue; 689 } 690 691 n = rad_continue_send_request(h, n, &fd, &tv); 692 693 if (n != 0) 694 return n; 695 696 gettimeofday(&timelimit, NULL); 697 timeradd(&tv, &timelimit, &timelimit); 698 } 699 } 700 701 const char * 702 rad_strerror(struct rad_handle *h) 703 { 704 return h->errmsg; 705 } 706 707 /* 708 * Destructively split a string into fields separated by white space. 709 * `#' at the beginning of a field begins a comment that extends to the 710 * end of the string. Fields may be quoted with `"'. Inside quoted 711 * strings, the backslash escapes `\"' and `\\' are honored. 712 * 713 * Pointers to up to the first maxfields fields are stored in the fields 714 * array. Missing fields get NULL pointers. 715 * 716 * The return value is the actual number of fields parsed, and is always 717 * <= maxfields. 718 * 719 * On a syntax error, places a message in the msg string, and returns -1. 720 */ 721 static int 722 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen) 723 { 724 char *p; 725 int i; 726 static const char ws[] = " \t"; 727 728 for (i = 0; i < maxfields; i++) 729 fields[i] = NULL; 730 p = str; 731 i = 0; 732 while (*p != '\0') { 733 p += strspn(p, ws); 734 if (*p == '#' || *p == '\0') 735 break; 736 if (i >= maxfields) { 737 snprintf(msg, msglen, "line has too many fields"); 738 return -1; 739 } 740 if (*p == '"') { 741 char *dst; 742 743 dst = ++p; 744 fields[i] = dst; 745 while (*p != '"') { 746 if (*p == '\\') { 747 p++; 748 if (*p != '"' && *p != '\\' && 749 *p != '\0') { 750 snprintf(msg, msglen, 751 "invalid `\\' escape"); 752 return -1; 753 } 754 } 755 if (*p == '\0') { 756 snprintf(msg, msglen, 757 "unterminated quoted string"); 758 return -1; 759 } 760 *dst++ = *p++; 761 } 762 *dst = '\0'; 763 p++; 764 if (*fields[i] == '\0') { 765 snprintf(msg, msglen, 766 "empty quoted string not permitted"); 767 return -1; 768 } 769 if (*p != '\0' && strspn(p, ws) == 0) { 770 snprintf(msg, msglen, "quoted string not" 771 " followed by white space"); 772 return -1; 773 } 774 } else { 775 fields[i] = p; 776 p += strcspn(p, ws); 777 if (*p != '\0') 778 *p++ = '\0'; 779 } 780 i++; 781 } 782 return i; 783 } 784