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 <afs/param.h>
17 #include <stdio.h> /* sprintf */
19 #include <afs/kautils.h>
20 #include <afs/cm_config.h>
22 #include <afs/krb_prot.h>
27 int krb_add_host (struct sockaddr_in *server_list_p);
28 static void krb_set_port(long port);
30 static long ka_AddHostProc(void *rockp, struct sockaddr_in *addrp, char *namep)
32 return krb_add_host(addrp);
35 static char bogusReason[100];
37 static char *ka_MapKerberosError(int code)
41 return "password was incorrect";
42 case KERB_ERR_PRINCIPAL_UNKNOWN:
43 return "user doesn't exist";
44 case KERB_ERR_SERVICE_EXP:
45 return "server and client clocks are badly skewed";
47 return "Authentication Server was unavailable";
49 sprintf(bogusReason, "unknown authentication error %d",
55 static int krb_get_in_tkt_ext(
62 struct ktc_encryptionKey *key1,
63 struct ktc_encryptionKey *key2,
66 struct ktc_encryptionKey *outKeyp,
72 afs_int32 ka_UserAuthenticateGeneral(
79 afs_int32 *password_expiresP,
84 struct ktc_encryptionKey key1, key2;
87 struct ktc_encryptionKey sessionKey;
94 struct ktc_principal server;
95 struct ktc_principal client;
96 struct ktc_token token;
98 if (instance == NULL) instance = "";
99 if (lifetime == 0) lifetime = MAXKTCTICKETLIFETIME;
101 code = cm_SearchCellFile(realm, fullRealm, ka_AddHostProc, NULL);
104 *reasonP = "specified realm is unknown";
108 strcpy(upperRealm, fullRealm);
111 /* encrypt password, both ways */
112 ka_StringToKey(password, upperRealm, &key1);
113 des_string_to_key(password, &key2);
115 /* set port number */
116 sp = getservbyname("kerberos", "udp");
117 if (sp) krb_set_port(ntohs(sp->s_port));
120 code = krb_get_in_tkt_ext(name, instance, upperRealm, "afs", "",
121 lifetime, &key1, &key2, &ticket, &ticketLen, &sessionKey,
122 &kvno, &expirationTime, reasonP);
124 if (code && *reasonP == NULL)
125 *reasonP = ka_MapKerberosError(code);
130 strcpy(server.name, "afs");
131 strcpy(server.instance, "");
132 strcpy(server.cell, fullRealm);
134 /* Would like to use Vice ID's; using raw names for now. */
135 strcpy(client.name, name);
136 strcpy(client.instance, instance);
137 strcpy(client.cell, upperRealm);
139 token.startTime = 0; /* XXX */
140 token.endTime = expirationTime;
141 token.sessionKey = sessionKey;
142 token.kvno = (short) kvno;
143 token.ticketLen = ticketLen;
144 memcpy(token.ticket, ticket, ticketLen);
146 code = ktc_SetToken(&server, &token, &client,
147 (flags & KA_USERAUTH_AUTHENT_LOGON) ? AFS_SETTOK_LOGON : 0);
149 if (code == KTC_NOCM || code == KTC_NOCMRPC)
150 *reasonP = "AFS service may not have started";
151 else if (code == KTC_RPC)
152 *reasonP = "RPC failure in AFS gateway";
153 else if (code == KTC_NOCELL)
154 *reasonP = "unknown cell";
156 *reasonP = "unknown error";
165 * This code is descended from kerberos files krb_get_in_tkt.c and
166 * send_to_kdc.c, and one.c.
170 * definition of variable set to 1.
171 * used in krb_conf.h to determine host byte order.
173 static int krbONE = 1;
175 #define HOST_BYTE_ORDER (* (char *) &krbONE)
180 * Copyright 1986, 1987, 1988 by the Massachusetts Institute
183 * For copying and distribution information, please see the file
193 #include <sys/types.h>
194 #include <winsock2.h>
196 static int swap_bytes;
199 * The kaserver defines these error codes *privately*. So we redefine them
200 * here, with a slight name change to show that they really are kaserver
203 #define KERB_KA_ERR_BAD_MSG_TYPE 99
204 #define KERB_KA_ERR_BAD_LIFETIME 98
205 #define KERB_KA_ERR_NONNULL_REALM 97
206 #define KERB_KA_ERR_PKT_LENGTH 96
207 #define KERB_KA_ERR_TEXT_LENGTH 95
209 static void swap_u_int32
212 *u = *u >> 24 | (*u & 0x00ff0000) >> 8 | (*u & 0x0000ff00) << 8 | *u << 24;
215 static void swap_u_int16
218 *u = *u >> 8 | *u << 8;
221 int pkt_clen(KTEXT pkt);
222 KTEXT pkt_cipher(KTEXT packet);
225 * The following routine has been hacked to make it work for two different
226 * possible string-to-key algorithms. This is a minimal displacement
231 * krb_get_in_tkt() gets a ticket for a given principal to use a given
232 * service and stores the returned ticket and session key for future
235 * The "user", "instance", and "realm" arguments give the identity of
236 * the client who will use the ticket. The "service" and "sinstance"
237 * arguments give the identity of the server that the client wishes
238 * to use. (The realm of the server is the same as the Kerberos server
239 * to whom the request is sent.) The "life" argument indicates the
240 * desired lifetime of the ticket; the "key_proc" argument is a pointer
241 * to the routine used for getting the client's private key to decrypt
242 * the reply from Kerberos. The "decrypt_proc" argument is a pointer
243 * to the routine used to decrypt the reply from Kerberos; and "arg"
244 * is an argument to be passed on to the "key_proc" routine.
246 * If all goes well, krb_get_in_tkt() returns INTK_OK, otherwise it
247 * returns an error code: If an AUTH_MSG_ERR_REPLY packet is returned
248 * by Kerberos, then the error code it contains is returned. Other
249 * error codes returned by this routine include INTK_PROT to indicate
250 * wrong protocol version, INTK_BADPW to indicate bad password (if
251 * decrypted ticket didn't make sense), INTK_ERR if the ticket was for
252 * the wrong server or the ticket store couldn't be initialized.
254 * The format of the message sent to Kerberos is as follows:
256 * Size Variable Field
257 * ---- -------- -----
259 * 1 byte KRB_PROT_VERSION protocol version number
260 * 1 byte AUTH_MSG_KDC_REQUEST | message type
261 * HOST_BYTE_ORDER local byte order in lsb
262 * string user client's name
263 * string instance client's instance
264 * string realm client's realm
265 * 4 bytes tlocal.tv_sec timestamp in seconds
266 * 1 byte life desired lifetime
267 * string service service's name
268 * string sinstance service's instance
272 * Check_response is a support routine for krb_get_in_tkt.
274 * Check the response with the supplied key. If the key is apparently
275 * wrong, return INTK_BADPW, otherwise zero.
277 static check_response
283 struct ktc_encryptionKey *key)
287 char s_service[SNAME_SZ];
288 char s_instance[INST_SZ];
289 char s_realm[REALM_SZ];
294 /* copy information from return packet into "cip" */
295 cip->length = pkt_clen(rpkt);
296 memcpy((char *)(cip->dat), (char *) pkt_cipher(rpkt), cip->length);
299 key_sched((char *) key, key_s);
300 pcbc_encrypt((C_Block *)cip->dat, (C_Block *)cip->dat,
301 (long) cip->length, key_s, (des_cblock *) key, 0);
303 /* Skip session key */
304 ptr = (char *) cip->dat + 8;
306 /* Check and extract server's name */
307 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
310 (void) strncpy(s_service, ptr, sizeof(s_service)-1);
311 s_service[sizeof(s_service)-1] = '\0';
312 ptr += strlen(s_service) + 1;
314 /* Check and extract server's instance */
315 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
318 (void) strncpy(s_instance,ptr, sizeof(s_instance)-1);
319 s_instance[sizeof(s_instance)-1] = '\0';
320 ptr += strlen(s_instance) + 1;
322 /* Check and extract server's realm */
323 if ((strlen(ptr) + (ptr - (char *) cip->dat)) > cip->length)
326 (void) strncpy(s_realm,ptr, sizeof(s_realm));
327 s_realm[sizeof(s_realm)-1] = '\0';
328 ptr += strlen(s_realm) + 1;
330 /* Ignore ticket lifetime, server key version */
333 /* Extract and check ticket length */
334 ticket_len = (unsigned char) *ptr++;
336 if ((ticket_len < 0) ||
337 ((ticket_len + (ptr - (char *) cip->dat)) > (int) cip->length))
340 /* Check returned server name, instance, and realm fields */
342 * 7/23/98 - Deleting realm check. This allows cell name to differ
346 if (strcmp(s_service, service) || strcmp(s_instance, instance) ||
347 strcmp(s_realm, realm)) {
349 if (strcmp(s_service, service) || strcmp(s_instance, instance)) {
351 /* not what we asked for: assume decryption failed */
359 * The old kaserver (pre 3.4) returned zero error codes sometimes, leaving
360 * the kaserver error code in a string in the text of the error message.
361 * The new one does the same, but returns KDC_GEN_ERR rather than zero.
362 * We try to extract the actual error code.
364 static char bogus_kaerror[100];
365 static int kaserver_map_error_code
370 if (code == 0 || code == KDC_GEN_ERR) {
372 if (sscanf(etext, "code =%u: ", &mapcode) == 1) {
374 strcpy(bogus_kaerror, etext);
375 *reasonP = bogus_kaerror;
386 static int krb_get_in_tkt_ext(user, instance, realm, service, sinstance, life,
387 key1, key2, ticketpp, ticketLenp, outKeyp, kvnop, expp, reasonp)
394 struct ktc_encryptionKey *key1, *key2;
397 struct ktc_encryptionKey *outKeyp;
403 KTEXT pkt = &pkt_st; /* Packet to KDC */
405 KTEXT rpkt = &rpkt_st; /* Returned packet */
407 KTEXT cip = &cip_st; /* Returned Ciphertext */
409 KTEXT tkt = &tkt_st; /* Current ticket */
410 C_Block ses; /* Session key for tkt */
411 int kvno; /* Kvno for session key */
412 unsigned char *v = pkt->dat; /* Prot vers no */
413 unsigned char *t = (pkt->dat+1); /* Prot msg type */
415 char s_name[SNAME_SZ];
416 char s_instance[INST_SZ];
424 unsigned long t_local;
426 afs_uint32 rep_err_code;
430 /* BUILD REQUEST PACKET */
432 /* Set up the fixed part of the packet */
433 *v = (unsigned char) KRB_PROT_VERSION;
434 *t = (unsigned char) AUTH_MSG_KDC_REQUEST;
435 *t |= HOST_BYTE_ORDER;
437 /* Now for the variable info */
438 (void) strcpy((char *)(pkt->dat+2),user); /* aname */
439 pkt->length = 3 + strlen(user);
440 (void) strcpy((char *)(pkt->dat+pkt->length),
441 instance); /* instance */
442 pkt->length += 1 + strlen(instance);
443 (void) strcpy((char *)(pkt->dat+pkt->length),realm); /* realm */
444 pkt->length += 1 + strlen(realm);
447 (void) gettimeofday(&t_local,(struct timezone *) 0);
449 t_local = time((void *) 0);
452 memcpy((char *)(pkt->dat+pkt->length), (char *)&(t_local), 4);
456 kerberos_life = DEFAULT_TKT_LIFE;
458 kerberos_life = time_to_life(0, life);
459 if (kerberos_life == 0) {
460 kerberos_life = DEFAULT_TKT_LIFE;
464 *(pkt->dat+(pkt->length)++) = kerberos_life;
465 (void) strcpy((char *)(pkt->dat+pkt->length),service);
466 pkt->length += 1 + strlen(service);
467 (void) strcpy((char *)(pkt->dat+pkt->length),sinstance);
469 pkt->length += 1 + strlen(sinstance);
473 /* SEND THE REQUEST AND RECEIVE THE RETURN PACKET */
475 if (kerror = send_to_kdc(pkt, rpkt)) {
479 /* check packet version of the returned packet */
480 if (pkt_version(rpkt) != KRB_PROT_VERSION)
483 /* Check byte order */
484 msg_byte_order = pkt_msg_type(rpkt) & 1;
486 if (msg_byte_order != HOST_BYTE_ORDER) {
490 switch (pkt_msg_type(rpkt) & ~1) {
491 case AUTH_MSG_KDC_REPLY:
493 case AUTH_MSG_ERR_REPLY:
494 memcpy((char *) &rep_err_code, pkt_err_code(rpkt), 4);
495 if (swap_bytes) swap_u_int32(&rep_err_code);
496 /* kaservers return bogus error codes in different ways, so map it
497 from the error text if this is the case */
498 return kaserver_map_error_code(rep_err_code, pkt_err_text(rpkt), reasonp);
504 /* get the principal's expiration date */
505 memcpy((char *) &exp_date, pkt_x_date(rpkt), sizeof(exp_date));
506 if (swap_bytes) swap_u_int32(&exp_date);
508 /* Extract length. This will be re-extracted in check_response, below */
509 cip->length = pkt_clen(rpkt);
511 /* Length of zero seems to correspond to no principal (with kaserver) */
512 if (cip->length== 0) {
513 return (KERB_ERR_PRINCIPAL_UNKNOWN);
516 if ((cip->length < 0) || (cip->length > sizeof(cip->dat))) {
517 return(INTK_ERR); /* no appropriate error code
518 currently defined for INTK_ */
522 * Check the response against both possible keys, and use the one
525 if (check_response(rpkt, cip, service, sinstance, realm, key1) &&
526 check_response(rpkt, cip, service, sinstance, realm, key2)) {
531 * EXTRACT INFORMATION FROM RETURN PACKET
533 * Some of the fields, below are already checked for integrity by
536 ptr = (char *) cip->dat;
538 /* extract session key */
539 memcpy((char *)ses, ptr, 8);
542 /* extract server's name */
543 (void) strncpy(s_name,ptr, sizeof(s_name)-1);
544 s_name[sizeof(s_name)-1] = '\0';
545 ptr += strlen(s_name) + 1;
547 /* extract server's instance */
548 (void) strncpy(s_instance,ptr, sizeof(s_instance)-1);
549 s_instance[sizeof(s_instance)-1] = '\0';
550 ptr += strlen(s_instance) + 1;
552 /* extract server's realm */
553 (void) strncpy(rlm,ptr, sizeof(rlm));
554 rlm[sizeof(rlm)-1] = '\0';
555 ptr += strlen(rlm) + 1;
557 /* extract ticket lifetime, server key version, ticket length */
558 /* be sure to avoid sign extension on lifetime! */
559 lifetime = (unsigned char) ptr[0];
560 kvno = (unsigned char) ptr[1];
561 tkt->length = (unsigned char) ptr[2];
564 /* extract ticket itself */
565 memcpy((char *)(tkt->dat), ptr, tkt->length);
568 /* check KDC time stamp */
569 memcpy((char *)&kdc_time, ptr, 4); /* Time (coarse) */
570 if (swap_bytes) swap_u_int32(&kdc_time);
574 t_local = time((void *) 0);
575 if (abs((int)(t_local - kdc_time)) > CLOCK_SKEW) {
576 return(RD_AP_TIME); /* XXX should probably be better
580 /* copy out results; if *ticketpp is non-null, the caller has already
581 * allocated the buffer for us.
583 memcpy(outKeyp, ses, sizeof(struct ktc_encryptionKey));
584 if (*ticketpp == NULL) {
585 *ticketpp = malloc(tkt->length);
587 else if (tkt->length > (unsigned long) *ticketLenp) return -1;
588 *ticketLenp = tkt->length;
589 memcpy(*ticketpp, tkt->dat, tkt->length);
591 if (expp) *expp = life_to_time(kdc_time, (char) lifetime);
593 return(INTK_OK); /* this is zero */
598 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
600 * For copying and distribution information, please see the file
604 #define S_AD_SZ sizeof(struct sockaddr_in)
606 static int krb_debug;
608 /* CLIENT_KRB_TIMEOUT indicates the time to wait before
609 * retrying a server. It's defined in "krb.h".
611 static struct timeval timeout = { CLIENT_KRB_TIMEOUT, 0};
612 static char *prog = "dm";
616 * This file contains two routines, send_to_kdc() and send_recv().
617 * send_recv() is a static routine used by send_to_kdc().
621 * send_to_kdc() sends a message to the Kerberos authentication
622 * server(s) in the given realm and returns the reply message.
623 * The "pkt" argument points to the message to be sent to Kerberos;
624 * the "rpkt" argument will be filled in with Kerberos' reply.
625 * The "realm" argument indicates the realm of the Kerberos server(s)
626 * to transact with. If the realm is null, the local realm is used.
628 * If more than one Kerberos server is known for a given realm,
629 * different servers will be queried until one of them replies.
630 * Several attempts (retries) are made for each server before
631 * giving up entirely.
633 * If an answer was received from a Kerberos host, KSUCCESS is
634 * returned. The following errors can be returned:
636 * SKDC_CANT - can't get local realm
637 * - can't find "kerberos" in /etc/services database
638 * - can't open socket
639 * - can't bind socket
641 * - couldn't find any Kerberos host
643 * SKDC_RETRY - couldn't get an answer from any Kerberos server,
644 * after several retries
647 typedef struct krb_server {
648 struct krb_server *nextp;
649 struct sockaddr_in addr;
652 static long krb_udp_port = KRB_PORT; /* In host byte order */
653 static krb_server_t *krb_hosts_p = NULL;
654 static int krb_nhosts = 0;
656 static void krb_set_port
663 (struct sockaddr_in *server_list_p)
665 krb_server_t *krb_host_p;
667 krb_host_p = malloc(sizeof(krb_server_t));
669 /* add host to list */
670 krb_host_p->nextp = krb_hosts_p;
671 krb_hosts_p = krb_host_p;
674 /* copy in the data */
675 memcpy(&krb_host_p->addr, server_list_p, sizeof(struct sockaddr_in));
680 static send_to_kdc(pkt,rpkt)
688 struct sockaddr_in to;
689 int timeAvail, timePerIter, numIters;
691 memset((char *)&to, 0, sizeof(to));
692 if ((f = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
694 fprintf(stderr,"%s: Can't open socket\n", prog);
697 /* from now on, exit through rtn label for cleanup */
699 /* compute # of retries */
700 /* The SMB client seems to time out after 60 seconds. */
702 /* Leave ourselves some margin for fooling around
704 /* How long does one iteration take? */
705 timePerIter = krb_nhosts * CLIENT_KRB_TIMEOUT;
706 /* How many iters? */
707 numIters = timeAvail / timePerIter;
708 /* No more than max */
709 if (numIters > CLIENT_KRB_RETRY) numIters = CLIENT_KRB_RETRY;
711 if (numIters < 1) numIters = 1;
713 /* retry each host in sequence */
714 for (retry = 0; retry < numIters; ++retry) {
715 for(tsp = krb_hosts_p; tsp; tsp = tsp->nextp) {
717 to.sin_family = AF_INET;
718 to.sin_port = htons(((unsigned short)krb_udp_port));
719 if (send_recv(pkt, rpkt, f, &to)) {
729 (void) closesocket(f);
735 * try to send out and receive message.
736 * return 1 on success, 0 on failure
739 static send_recv(pkt,rpkt,f,_to)
743 struct sockaddr_in *_to;
746 struct sockaddr_in from;
752 if (_to->sin_family == AF_INET)
753 printf("Sending message to %s...",
754 inet_ntoa(_to->sin_addr));
756 printf("Sending message...");
757 (void) fflush(stdout);
759 if ((numsent = sendto(f,(char *)(pkt->dat), pkt->length, 0,
760 (struct sockaddr *)_to,
761 S_AD_SZ)) != (int) pkt->length) {
763 printf("sent only %d/%d\n",numsent, pkt->length);
767 printf("Sent\nWaiting for reply...");
768 (void) fflush(stdout);
773 /* select - either recv is ready, or timeout */
774 /* see if timeout or error or wrong descriptor */
775 if (select(f + 1, &readfds, (fd_set *)0, (fd_set *)0, &timeout) < 1
776 || !FD_ISSET(f, &readfds)) {
778 fprintf(stderr, "select failed: readfds=%x",
784 sin_size = sizeof(from);
785 if ((code = recvfrom(f, (char *)(rpkt->dat), sizeof(rpkt->dat), 0,
786 (struct sockaddr *)&from, &sin_size))
793 printf("received packet from %s\n", inet_ntoa(from.sin_addr));
801 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
804 * For copying and distribution information, please see the file
809 * This routine takes a reply packet from the Kerberos ticket-granting
810 * service and returns a pointer to the beginning of the ciphertext in it.
812 * See "krb_prot.h" for packet format.
815 static KTEXT pkt_cipher
818 unsigned char *ptr = pkt_a_realm(packet) + 6
819 + strlen((char *)pkt_a_realm(packet));
820 /* Skip a few more fields */
821 ptr += 3 + 4; /* add 4 for exp_date */
823 /* And return the pointer */
829 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
832 * For copying and distribution information, please see the file
837 * Given a pointer to an AUTH_MSG_KDC_REPLY packet, return the length of
838 * its ciphertext portion. The external variable "swap_bytes" is assumed
839 * to have been set to indicate whether or not the packet is in local
840 * byte order. pkt_clen() takes this into account when reading the
841 * ciphertext length out of the packet.
844 static int pkt_clen(KTEXT pkt)
848 /* Start of ticket list */
849 unsigned char *ptr = pkt_a_realm(pkt) + 10
850 + strlen((char *)pkt_a_realm(pkt));
852 /* Finally the length */
853 memcpy((char *)&temp, (char *)(++ptr), 2); /* alignment */
859 printf("Clen is %d\n", temp);
865 /* This defines the Andrew string_to_key function. It accepts a password
866 string as input and converts its via a one-way encryption algorithm to a DES
867 encryption key. It is compatible with the original Andrew authentication
868 service password database. */
870 static void Andrew_StringToKey (str, cell, key)
872 char *cell; /* cell for password */
873 struct ktc_encryptionKey *key;
874 { char password[8+1]; /* crypt's limit is 8 chars anyway */
878 memset(key, 0, sizeof(struct ktc_encryptionKey));
880 strncpy (password, cell, 8);
881 passlen = strlen (str);
882 if (passlen > 8) passlen = 8;
884 for (i=0; i<passlen; i++)
885 password[i] ^= str[i];
888 if (password[i] == '\0') password[i] = 'X';
890 /* crypt only considers the first 8 characters of password but for some
891 reason returns eleven characters of result (plus the two salt chars). */
892 strncpy((char *) key, (char *)crypt(password, "p1") + 2, sizeof(struct ktc_encryptionKey));
894 /* parity is inserted into the LSB so leftshift each byte up one bit. This
895 allows ascii characters with a zero MSB to retain as much significance
897 { char *keybytes = (char *)key;
900 for (i = 0; i < 8; i++) {
901 temp = (unsigned int) keybytes[i];
902 keybytes[i] = (unsigned char) (temp << 1);
905 des_fixup_key_parity ((unsigned char *) key);
909 static void StringToKey (str, cell, key)
911 char *cell; /* cell for password */
912 struct ktc_encryptionKey *key;
913 { des_key_schedule schedule;
916 char password[BUFSIZ];
919 strncpy (password, str, sizeof(password));
920 if ((passlen = strlen (password)) < sizeof(password)-1)
921 strncat (password, cell, sizeof(password)-passlen);
922 if ((passlen = strlen(password)) > sizeof(password))
923 passlen = sizeof(password);
925 memcpy(ivec, "kerberos", 8);
926 memcpy(temp_key, "kerberos", 8);
927 des_fixup_key_parity (temp_key);
928 des_key_sched (temp_key, schedule);
929 des_cbc_cksum (password, ivec, passlen, schedule, ivec);
931 memcpy(temp_key, ivec, 8);
932 des_fixup_key_parity (temp_key);
933 des_key_sched (temp_key, schedule);
934 des_cbc_cksum (password, (char *) key, passlen, schedule, ivec);
936 des_fixup_key_parity ((char *) key);