2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afsconfig.h>
11 #include <afs/param.h>
21 #include <stdio.h> /* sprintf */
23 #include <afs/kautils.h>
24 #include <afs/cm_config.h>
26 #include <afs/krb_prot.h>
31 int krb_add_host (struct sockaddr_in *server_list_p);
32 static void krb_set_port(long port);
34 static long ka_AddHostProc(void *rockp, struct sockaddr_in *addrp, char *namep)
36 return krb_add_host(addrp);
39 static char bogusReason[100];
41 static char *ka_MapKerberosError(int code)
45 return "password was incorrect";
46 case KERB_ERR_PRINCIPAL_UNKNOWN:
47 return "user doesn't exist";
48 case KERB_ERR_SERVICE_EXP:
49 return "server and client clocks are badly skewed";
51 return "Authentication Server was unavailable";
53 return "server and client clocks are badly skewed";
55 sprintf(bogusReason, "unknown authentication error %d",
61 static int krb_get_in_tkt_ext(
68 struct ktc_encryptionKey *key1,
69 struct ktc_encryptionKey *key2,
72 struct ktc_encryptionKey *outKeyp,
78 afs_int32 ka_UserAuthenticateGeneral(
85 afs_int32 *password_expiresP,
90 struct ktc_encryptionKey key1, key2;
93 struct ktc_encryptionKey sessionKey;
100 struct ktc_principal server;
101 struct ktc_principal client;
102 struct ktc_token token;
104 if (instance == NULL) instance = "";
105 if (lifetime == 0) lifetime = MAXKTCTICKETLIFETIME;
107 code = cm_SearchCellFile(realm, fullRealm, ka_AddHostProc, NULL);
110 *reasonP = "specified realm is unknown";
114 strcpy(upperRealm, fullRealm);
117 /* encrypt password, both ways */
118 ka_StringToKey(password, upperRealm, &key1);
119 des_string_to_key(password, &key2);
121 /* set port number */
122 sp = getservbyname("kerberos", "udp");
123 if (sp) krb_set_port(ntohs(sp->s_port));
126 code = krb_get_in_tkt_ext(name, instance, upperRealm, "afs", "",
127 lifetime, &key1, &key2, &ticket, &ticketLen, &sessionKey,
128 &kvno, &expirationTime, reasonP);
130 if (code && *reasonP == NULL)
131 *reasonP = ka_MapKerberosError(code);
136 strcpy(server.name, "afs");
137 strcpy(server.instance, "");
138 strcpy(server.cell, fullRealm);
140 /* Would like to use Vice ID's; using raw names for now. */
141 strcpy(client.name, name);
142 strcpy(client.instance, instance);
143 strcpy(client.cell, upperRealm);
145 token.startTime = 0; /* XXX */
146 token.endTime = expirationTime;
147 token.sessionKey = sessionKey;
148 token.kvno = (short) kvno;
149 token.ticketLen = ticketLen;
150 memcpy(token.ticket, ticket, ticketLen);
152 code = ktc_SetToken(&server, &token, &client,
153 (flags & KA_USERAUTH_AUTHENT_LOGON) ? AFS_SETTOK_LOGON : 0);
155 if (code == KTC_NOCM || code == KTC_NOCMRPC)
156 *reasonP = "AFS service may not have started";
157 else if (code == KTC_RPC)
158 *reasonP = "RPC failure in AFS gateway";
159 else if (code == KTC_NOCELL)
160 *reasonP = "unknown cell";
162 *reasonP = "unknown error";
171 * This code is descended from kerberos files krb_get_in_tkt.c and
172 * send_to_kdc.c, and one.c.
176 * definition of variable set to 1.
177 * used in krb_conf.h to determine host byte order.
179 static int krbONE = 1;
181 #define HOST_BYTE_ORDER (* (char *) &krbONE)
186 * Copyright 1986, 1987, 1988 by the Massachusetts Institute
189 * For copying and distribution information, please see the file
199 #include <sys/types.h>
200 #include <winsock2.h>
202 static int swap_bytes;
205 * The kaserver defines these error codes *privately*. So we redefine them
206 * here, with a slight name change to show that they really are kaserver
209 #define KERB_KA_ERR_BAD_MSG_TYPE 99
210 #define KERB_KA_ERR_BAD_LIFETIME 98
211 #define KERB_KA_ERR_NONNULL_REALM 97
212 #define KERB_KA_ERR_PKT_LENGTH 96
213 #define KERB_KA_ERR_TEXT_LENGTH 95
215 static void swap_u_int32
218 *u = *u >> 24 | (*u & 0x00ff0000) >> 8 | (*u & 0x0000ff00) << 8 | *u << 24;
221 static void swap_u_int16
224 *u = *u >> 8 | *u << 8;
227 int pkt_clen(KTEXT pkt);
228 KTEXT pkt_cipher(KTEXT packet);
231 * The following routine has been hacked to make it work for two different
232 * possible string-to-key algorithms. This is a minimal displacement
237 * krb_get_in_tkt() gets a ticket for a given principal to use a given
238 * service and stores the returned ticket and session key for future
241 * The "user", "instance", and "realm" arguments give the identity of
242 * the client who will use the ticket. The "service" and "sinstance"
243 * arguments give the identity of the server that the client wishes
244 * to use. (The realm of the server is the same as the Kerberos server
245 * to whom the request is sent.) The "life" argument indicates the
246 * desired lifetime of the ticket; the "key_proc" argument is a pointer
247 * to the routine used for getting the client's private key to decrypt
248 * the reply from Kerberos. The "decrypt_proc" argument is a pointer
249 * to the routine used to decrypt the reply from Kerberos; and "arg"
250 * is an argument to be passed on to the "key_proc" routine.
252 * If all goes well, krb_get_in_tkt() returns INTK_OK, otherwise it
253 * returns an error code: If an AUTH_MSG_ERR_REPLY packet is returned
254 * by Kerberos, then the error code it contains is returned. Other
255 * error codes returned by this routine include INTK_PROT to indicate
256 * wrong protocol version, INTK_BADPW to indicate bad password (if
257 * decrypted ticket didn't make sense), INTK_ERR if the ticket was for
258 * the wrong server or the ticket store couldn't be initialized.
260 * The format of the message sent to Kerberos is as follows:
262 * Size Variable Field
263 * ---- -------- -----
265 * 1 byte KRB_PROT_VERSION protocol version number
266 * 1 byte AUTH_MSG_KDC_REQUEST | message type
267 * HOST_BYTE_ORDER local byte order in lsb
268 * string user client's name
269 * string instance client's instance
270 * string realm client's realm
271 * 4 bytes tlocal.tv_sec timestamp in seconds
272 * 1 byte life desired lifetime
273 * string service service's name
274 * string sinstance service's instance
278 * Check_response is a support routine for krb_get_in_tkt.
280 * Check the response with the supplied key. If the key is apparently
281 * wrong, return INTK_BADPW, otherwise zero.
283 static check_response
289 struct ktc_encryptionKey *key)
293 char s_service[SNAME_SZ];
294 char s_instance[INST_SZ];
295 char s_realm[REALM_SZ];
300 /* copy information from return packet into "cip" */
301 cip->length = pkt_clen(rpkt);
302 memcpy((char *)(cip->dat), (char *) pkt_cipher(rpkt), cip->length);
305 key_sched((char *) key, key_s);
306 pcbc_encrypt((C_Block *)cip->dat, (C_Block *)cip->dat,
307 (long) cip->length, key_s, (des_cblock *) key, 0);
309 /* Skip session key */
310 ptr = (char *) cip->dat + 8;
312 /* Check and extract server's name */
313 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
316 (void) strncpy(s_service, ptr, sizeof(s_service)-1);
317 s_service[sizeof(s_service)-1] = '\0';
318 ptr += strlen(s_service) + 1;
320 /* Check and extract server's instance */
321 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
324 (void) strncpy(s_instance,ptr, sizeof(s_instance)-1);
325 s_instance[sizeof(s_instance)-1] = '\0';
326 ptr += strlen(s_instance) + 1;
328 /* Check and extract server's realm */
329 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
332 (void) strncpy(s_realm,ptr, sizeof(s_realm));
333 s_realm[sizeof(s_realm)-1] = '\0';
334 ptr += strlen(s_realm) + 1;
336 /* Ignore ticket lifetime, server key version */
339 /* Extract and check ticket length */
340 ticket_len = (unsigned char) *ptr++;
342 if ((ticket_len < 0) ||
343 ((ticket_len + (ptr - (char *) cip->dat)) > (int) cip->length))
346 /* Check returned server name, instance, and realm fields */
348 * 7/23/98 - Deleting realm check. This allows cell name to differ
352 if (strcmp(s_service, service) || strcmp(s_instance, instance) ||
353 strcmp(s_realm, realm)) {
355 if (strcmp(s_service, service) || strcmp(s_instance, instance)) {
357 /* not what we asked for: assume decryption failed */
365 * The old kaserver (pre 3.4) returned zero error codes sometimes, leaving
366 * the kaserver error code in a string in the text of the error message.
367 * The new one does the same, but returns KDC_GEN_ERR rather than zero.
368 * We try to extract the actual error code.
370 static char bogus_kaerror[100];
371 static int kaserver_map_error_code
376 if (code == 0 || code == KDC_GEN_ERR) {
378 if (sscanf(etext, "code =%u: ", &mapcode) == 1) {
380 strcpy(bogus_kaerror, etext);
381 *reasonP = bogus_kaerror;
392 static int krb_get_in_tkt_ext(user, instance, realm, service, sinstance, life,
393 key1, key2, ticketpp, ticketLenp, outKeyp, kvnop, expp, reasonp)
400 struct ktc_encryptionKey *key1, *key2;
403 struct ktc_encryptionKey *outKeyp;
409 KTEXT pkt = &pkt_st; /* Packet to KDC */
411 KTEXT rpkt = &rpkt_st; /* Returned packet */
413 KTEXT cip = &cip_st; /* Returned Ciphertext */
415 KTEXT tkt = &tkt_st; /* Current ticket */
416 C_Block ses; /* Session key for tkt */
417 int kvno; /* Kvno for session key */
418 unsigned char *v = pkt->dat; /* Prot vers no */
419 unsigned char *t = (pkt->dat+1); /* Prot msg type */
421 char s_name[SNAME_SZ];
422 char s_instance[INST_SZ];
430 unsigned long t_local;
432 afs_uint32 rep_err_code;
436 /* BUILD REQUEST PACKET */
438 /* Set up the fixed part of the packet */
439 *v = (unsigned char) KRB_PROT_VERSION;
440 *t = (unsigned char) AUTH_MSG_KDC_REQUEST;
441 *t |= HOST_BYTE_ORDER;
443 /* Now for the variable info */
444 (void) strcpy((char *)(pkt->dat+2),user); /* aname */
445 pkt->length = 3 + strlen(user);
446 (void) strcpy((char *)(pkt->dat+pkt->length),
447 instance); /* instance */
448 pkt->length += 1 + strlen(instance);
449 (void) strcpy((char *)(pkt->dat+pkt->length),realm); /* realm */
450 pkt->length += 1 + strlen(realm);
453 (void) gettimeofday(&t_local,(struct timezone *) 0);
455 t_local = time((void *) 0);
458 memcpy((char *)(pkt->dat+pkt->length), (char *)&(t_local), 4);
462 kerberos_life = DEFAULT_TKT_LIFE;
464 kerberos_life = time_to_life(0, life);
465 if (kerberos_life == 0) {
466 kerberos_life = DEFAULT_TKT_LIFE;
470 *(pkt->dat+(pkt->length)++) = kerberos_life;
471 (void) strcpy((char *)(pkt->dat+pkt->length),service);
472 pkt->length += 1 + strlen(service);
473 (void) strcpy((char *)(pkt->dat+pkt->length),sinstance);
475 pkt->length += 1 + strlen(sinstance);
479 /* SEND THE REQUEST AND RECEIVE THE RETURN PACKET */
481 if (kerror = send_to_kdc(pkt, rpkt)) {
485 /* check packet version of the returned packet */
486 if (pkt_version(rpkt) != KRB_PROT_VERSION)
489 /* Check byte order */
490 msg_byte_order = pkt_msg_type(rpkt) & 1;
492 if (msg_byte_order != HOST_BYTE_ORDER) {
496 switch (pkt_msg_type(rpkt) & ~1) {
497 case AUTH_MSG_KDC_REPLY:
499 case AUTH_MSG_ERR_REPLY:
500 memcpy((char *) &rep_err_code, pkt_err_code(rpkt), 4);
501 if (swap_bytes) swap_u_int32(&rep_err_code);
502 /* kaservers return bogus error codes in different ways, so map it
503 from the error text if this is the case */
504 return kaserver_map_error_code(rep_err_code, pkt_err_text(rpkt), reasonp);
510 /* get the principal's expiration date */
511 memcpy((char *) &exp_date, pkt_x_date(rpkt), sizeof(exp_date));
512 if (swap_bytes) swap_u_int32(&exp_date);
514 /* Extract length. This will be re-extracted in check_response, below */
515 cip->length = pkt_clen(rpkt);
517 /* Length of zero seems to correspond to no principal (with kaserver) */
518 if (cip->length== 0) {
519 return (KERB_ERR_PRINCIPAL_UNKNOWN);
522 if ((cip->length < 0) || (cip->length > sizeof(cip->dat))) {
523 return(INTK_ERR); /* no appropriate error code
524 currently defined for INTK_ */
528 * Check the response against both possible keys, and use the one
531 if (check_response(rpkt, cip, service, sinstance, realm, key1) &&
532 check_response(rpkt, cip, service, sinstance, realm, key2)) {
537 * EXTRACT INFORMATION FROM RETURN PACKET
539 * Some of the fields, below are already checked for integrity by
542 ptr = (char *) cip->dat;
544 /* extract session key */
545 memcpy((char *)ses, ptr, 8);
548 /* extract server's name */
549 (void) strncpy(s_name,ptr, sizeof(s_name)-1);
550 s_name[sizeof(s_name)-1] = '\0';
551 ptr += strlen(s_name) + 1;
553 /* extract server's instance */
554 (void) strncpy(s_instance,ptr, sizeof(s_instance)-1);
555 s_instance[sizeof(s_instance)-1] = '\0';
556 ptr += strlen(s_instance) + 1;
558 /* extract server's realm */
559 (void) strncpy(rlm,ptr, sizeof(rlm));
560 rlm[sizeof(rlm)-1] = '\0';
561 ptr += strlen(rlm) + 1;
563 /* extract ticket lifetime, server key version, ticket length */
564 /* be sure to avoid sign extension on lifetime! */
565 lifetime = (unsigned char) ptr[0];
566 kvno = (unsigned char) ptr[1];
567 tkt->length = (unsigned char) ptr[2];
570 /* extract ticket itself */
571 memcpy((char *)(tkt->dat), ptr, tkt->length);
574 /* check KDC time stamp */
575 memcpy((char *)&kdc_time, ptr, 4); /* Time (coarse) */
576 if (swap_bytes) swap_u_int32(&kdc_time);
580 t_local = time((void *) 0);
581 if (abs((int)(t_local - kdc_time)) > CLOCK_SKEW) {
582 return(RD_AP_TIME); /* XXX should probably be better
586 /* copy out results; if *ticketpp is non-null, the caller has already
587 * allocated the buffer for us.
589 memcpy(outKeyp, ses, sizeof(struct ktc_encryptionKey));
590 if (*ticketpp == NULL) {
591 *ticketpp = malloc(tkt->length);
593 else if (tkt->length > (unsigned long) *ticketLenp) return -1;
594 *ticketLenp = tkt->length;
595 memcpy(*ticketpp, tkt->dat, tkt->length);
597 if (expp) *expp = life_to_time(kdc_time, (char) lifetime);
599 return(INTK_OK); /* this is zero */
604 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
606 * For copying and distribution information, please see the file
610 #define S_AD_SZ sizeof(struct sockaddr_in)
612 static int krb_debug;
614 /* CLIENT_KRB_TIMEOUT indicates the time to wait before
615 * retrying a server. It's defined in "krb.h".
617 static struct timeval timeout = { CLIENT_KRB_TIMEOUT, 0};
618 static char *prog = "dm";
622 * This file contains two routines, send_to_kdc() and send_recv().
623 * send_recv() is a static routine used by send_to_kdc().
627 * send_to_kdc() sends a message to the Kerberos authentication
628 * server(s) in the given realm and returns the reply message.
629 * The "pkt" argument points to the message to be sent to Kerberos;
630 * the "rpkt" argument will be filled in with Kerberos' reply.
631 * The "realm" argument indicates the realm of the Kerberos server(s)
632 * to transact with. If the realm is null, the local realm is used.
634 * If more than one Kerberos server is known for a given realm,
635 * different servers will be queried until one of them replies.
636 * Several attempts (retries) are made for each server before
637 * giving up entirely.
639 * If an answer was received from a Kerberos host, KSUCCESS is
640 * returned. The following errors can be returned:
642 * SKDC_CANT - can't get local realm
643 * - can't find "kerberos" in /etc/services database
644 * - can't open socket
645 * - can't bind socket
647 * - couldn't find any Kerberos host
649 * SKDC_RETRY - couldn't get an answer from any Kerberos server,
650 * after several retries
653 typedef struct krb_server {
654 struct krb_server *nextp;
655 struct sockaddr_in addr;
658 static long krb_udp_port = KRB_PORT; /* In host byte order */
659 static krb_server_t *krb_hosts_p = NULL;
660 static int krb_nhosts = 0;
662 static void krb_set_port
669 (struct sockaddr_in *server_list_p)
671 krb_server_t *krb_host_p;
673 krb_host_p = malloc(sizeof(krb_server_t));
675 /* add host to list */
676 krb_host_p->nextp = krb_hosts_p;
677 krb_hosts_p = krb_host_p;
680 /* copy in the data */
681 memcpy(&krb_host_p->addr, server_list_p, sizeof(struct sockaddr_in));
686 static send_to_kdc(pkt,rpkt)
694 struct sockaddr_in to;
695 int timeAvail, timePerIter, numIters;
697 memset((char *)&to, 0, sizeof(to));
698 if ((f = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
700 fprintf(stderr,"%s: Can't open socket\n", prog);
703 /* from now on, exit through rtn label for cleanup */
705 /* compute # of retries */
706 /* The SMB client seems to time out after 60 seconds. */
708 /* Leave ourselves some margin for fooling around
710 /* How long does one iteration take? */
711 timePerIter = krb_nhosts * CLIENT_KRB_TIMEOUT;
712 /* How many iters? */
713 numIters = timeAvail / timePerIter;
714 /* No more than max */
715 if (numIters > CLIENT_KRB_RETRY) numIters = CLIENT_KRB_RETRY;
717 if (numIters < 1) numIters = 1;
719 /* retry each host in sequence */
720 for (retry = 0; retry < numIters; ++retry) {
721 for(tsp = krb_hosts_p; tsp; tsp = tsp->nextp) {
723 to.sin_family = AF_INET;
724 to.sin_port = htons(((unsigned short)krb_udp_port));
725 if (send_recv(pkt, rpkt, f, &to)) {
735 (void) closesocket(f);
741 * try to send out and receive message.
742 * return 1 on success, 0 on failure
745 static send_recv(pkt,rpkt,f,_to)
749 struct sockaddr_in *_to;
752 struct sockaddr_in from;
758 if (_to->sin_family == AF_INET)
759 printf("Sending message to %s...",
760 inet_ntoa(_to->sin_addr));
762 printf("Sending message...");
763 (void) fflush(stdout);
765 if ((numsent = sendto(f,(char *)(pkt->dat), pkt->length, 0,
766 (struct sockaddr *)_to,
767 S_AD_SZ)) != (int) pkt->length) {
769 printf("sent only %d/%d\n",numsent, pkt->length);
773 printf("Sent\nWaiting for reply...");
774 (void) fflush(stdout);
779 /* select - either recv is ready, or timeout */
780 /* see if timeout or error or wrong descriptor */
781 if (select(f + 1, &readfds, (fd_set *)0, (fd_set *)0, &timeout) < 1
782 || !FD_ISSET(f, &readfds)) {
784 fprintf(stderr, "select failed: readfds=%x",
790 sin_size = sizeof(from);
791 if ((code = recvfrom(f, (char *)(rpkt->dat), sizeof(rpkt->dat), 0,
792 (struct sockaddr *)&from, &sin_size))
799 printf("received packet from %s\n", inet_ntoa(from.sin_addr));
807 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
810 * For copying and distribution information, please see the file
815 * This routine takes a reply packet from the Kerberos ticket-granting
816 * service and returns a pointer to the beginning of the ciphertext in it.
818 * See "krb_prot.h" for packet format.
821 static KTEXT pkt_cipher
824 unsigned char *ptr = pkt_a_realm(packet) + 6
825 + strlen((char *)pkt_a_realm(packet));
826 /* Skip a few more fields */
827 ptr += 3 + 4; /* add 4 for exp_date */
829 /* And return the pointer */
835 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
838 * For copying and distribution information, please see the file
843 * Given a pointer to an AUTH_MSG_KDC_REPLY packet, return the length of
844 * its ciphertext portion. The external variable "swap_bytes" is assumed
845 * to have been set to indicate whether or not the packet is in local
846 * byte order. pkt_clen() takes this into account when reading the
847 * ciphertext length out of the packet.
850 static int pkt_clen(KTEXT pkt)
854 /* Start of ticket list */
855 unsigned char *ptr = pkt_a_realm(pkt) + 10
856 + strlen((char *)pkt_a_realm(pkt));
858 /* Finally the length */
859 memcpy((char *)&temp, (char *)(++ptr), 2); /* alignment */
865 printf("Clen is %d\n", temp);
871 /* This defines the Andrew string_to_key function. It accepts a password
872 string as input and converts its via a one-way encryption algorithm to a DES
873 encryption key. It is compatible with the original Andrew authentication
874 service password database. */
876 static void Andrew_StringToKey (str, cell, key)
878 char *cell; /* cell for password */
879 struct ktc_encryptionKey *key;
880 { char password[8+1]; /* crypt's limit is 8 chars anyway */
884 memset(key, 0, sizeof(struct ktc_encryptionKey));
886 strncpy (password, cell, 8);
887 passlen = strlen (str);
888 if (passlen > 8) passlen = 8;
890 for (i=0; i<passlen; i++)
891 password[i] ^= str[i];
894 if (password[i] == '\0') password[i] = 'X';
896 /* crypt only considers the first 8 characters of password but for some
897 reason returns eleven characters of result (plus the two salt chars). */
898 strncpy((char *) key, (char *)crypt(password, "p1") + 2, sizeof(struct ktc_encryptionKey));
900 /* parity is inserted into the LSB so leftshift each byte up one bit. This
901 allows ascii characters with a zero MSB to retain as much significance
903 { char *keybytes = (char *)key;
906 for (i = 0; i < 8; i++) {
907 temp = (unsigned int) keybytes[i];
908 keybytes[i] = (unsigned char) (temp << 1);
911 des_fixup_key_parity ((unsigned char *) key);
915 static void StringToKey (str, cell, key)
917 char *cell; /* cell for password */
918 struct ktc_encryptionKey *key;
919 { des_key_schedule schedule;
922 char password[BUFSIZ];
925 strncpy (password, str, sizeof(password));
926 if ((passlen = strlen (password)) < sizeof(password)-1)
927 strncat (password, cell, sizeof(password)-passlen);
928 if ((passlen = strlen(password)) > sizeof(password))
929 passlen = sizeof(password);
931 memcpy(ivec, "kerberos", 8);
932 memcpy(temp_key, "kerberos", 8);
933 des_fixup_key_parity (temp_key);
934 des_key_sched (temp_key, schedule);
935 des_cbc_cksum (password, ivec, passlen, schedule, ivec);
937 memcpy(temp_key, ivec, 8);
938 des_fixup_key_parity (temp_key);
939 des_key_sched (temp_key, schedule);
940 des_cbc_cksum (password, (char *) key, passlen, schedule, ivec);
942 des_fixup_key_parity ((char *) key);