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 /* ticket caching code */
12 #include <afsconfig.h>
14 #include "../afs/param.h"
16 #include <afs/param.h>
22 #include "../afs/sysincludes.h"
23 #include "../afs/afsincludes.h"
24 #include "../afs/stds.h"
25 #include "../afs/pthread_glock.h"
26 #include "../afs/vice.h"
27 #include "../afs/auth.h"
28 #include "../afs/venus.h"
29 #include "../afs/pthread_glock.h"
30 #include "../afs/dirpath.h"
33 #define min(a,b) ((a)<(b)?(a):(b))
34 #endif /* !defined(min) */
36 #else /* defined(UKERNEL) */
43 #include <afs/pthread_glock.h>
44 #include <sys/types.h>
49 #include <sys/ioctl.h>
50 #include <netinet/in.h>
60 #include <sys/lockf.h>
66 #include <afs/venus.h>
67 #include <afs/afsutil.h>
69 #endif /* defined(UKERNEL) */
76 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
77 #define AFS_KERBEROS_ENV
80 #ifdef AFS_KERBEROS_ENV
83 extern afs_uint32 life_to_time();
84 extern unsigned char time_to_life();
85 #include "cellconfig.h"
86 static char lcell[MAXCELLCHARS];
88 #define TKT_ROOT "/tmp/tkt"
93 /* Definitions for ticket file utilities */
97 /* Error codes returned by ticket file utilities */
98 #define NO_TKT_FIL 76 /* No ticket file found */
99 #define TKT_FIL_ACC 77 /* Couldn't access tkt file */
100 #define TKT_FIL_LCK 78 /* Couldn't lock ticket file */
101 #define TKT_FIL_FMT 79 /* Bad ticket file format */
102 #define TKT_FIL_INI 80 /* afs_tf_init not called first */
104 /* Values returned by get_credentials */
105 #define RET_TKFIL 21 /* Can't read ticket file */
114 #if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
115 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
116 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
117 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
120 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
121 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
122 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
129 /* the following routines aren't static anymore on behalf of the kerberos IV
130 * compatibility library built in subtree krb.
132 int afs_tf_init(), afs_tf_get_pname(), afs_tf_get_pinst(), afs_tf_get_cred();
133 int afs_tf_save_cred(), afs_tf_close(), afs_tf_create();
134 int afs_tf_dest_tkt(), ktc_LocalCell();
135 char *ktc_tkt_string();
136 #endif /* AFS_KERBEROS_ENV */
139 #define PIOCTL afs_pioctl
140 #elif defined(UKERNEL)
141 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
143 #define PIOCTL pioctl
147 #ifdef KERNEL_KTC_COMPAT
150 #define KTC_SYSCALL 32
153 /* Kernel call opcode definitions */
154 #define KTC_OPCODE_BASE 4300
155 #define KTC_NO_OP (0+KTC_OPCODE_BASE)
156 #define KTC_SETTOKEN_OP (1+KTC_OPCODE_BASE)
157 #define KTC_GETTOKEN_OP (2+KTC_OPCODE_BASE)
158 #define KTC_LISTTOKENS_OP (3+KTC_OPCODE_BASE)
159 #define KTC_FORGETTOKEN_OP (4+KTC_OPCODE_BASE)
160 #define KTC_FORGETALLTOKENS_OP (5+KTC_OPCODE_BASE)
161 #define KTC_STATUS_OP (6+KTC_OPCODE_BASE)
162 #define KTC_GC_OP (7+KTC_OPCODE_BASE)
164 #define KTC_INTERFACE_VERSION 3
166 /* We have to determine if the kernel supports the ktc system call. To do so
167 * we attempt to execute its noop function. If this is successful we use the
168 * kernel calls in the future otherwise we let the old code run. */
170 /* To safely check to see whether a system call exists we have to intercept the
171 * SIGSYS signal which is caused by executing a non-existant system call. If
172 * it is ignored the syscall routine returns EINVAL. The SIGSYS is reset to
173 * its old value after the return from syscall. */
175 static int kernelKTC = 0;
177 #ifdef AFS_DECOSF_ENV
179 * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems. You need
180 * to ignore SIGTRAP too. It is claimed to be fixed under v1.3, but...
183 #define CHECK_KERNEL \
184 if (kernelKTC == 0) { \
188 old = (int (*)())signal(SIGSYS, SIG_IGN); \
189 old_t = (int (*)())signal(SIGTRAP, SIG_IGN); \
190 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
192 signal(SIGSYS, old); \
193 signal(SIGTRAP, old_t); \
194 if (code == 0) kernelKTC = 1; \
195 else kernelKTC = 2; \
196 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
199 #else /* AFS_DECOSF_ENV */
201 #define CHECK_KERNEL \
202 if (kernelKTC == 0) { \
205 old = (int (*)())signal(SIGSYS, SIG_IGN); \
206 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
208 signal(SIGSYS, old); \
209 if (code == 0) kernelKTC = 1; \
210 else kernelKTC = 2; \
211 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
213 #endif /* AFS_DECOSF_ENV */
215 #define TRY_KERNEL(cmd,a1,a2,a3,a4) \
217 if (kernelKTC == 1) \
218 return syscall (KTC_SYSCALL, cmd, \
219 KTC_INTERFACE_VERSION, a1,a2,a3,a4); \
223 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
224 #endif /* KERNEL_KTC_COMPAT */
226 #if !defined(UKERNEL)
227 /* this is a structure used to communicate with the afs cache mgr, but is
228 * otherwise irrelevant */
230 afs_int32 AuthHandle;
231 char HandShakeKey[8];
233 afs_int32 BeginTimestamp;
234 afs_int32 EndTimestamp;
236 #endif /* !defined(UKERNEL) */
238 #define MAXLOCALTOKENS 4
242 struct ktc_principal server;
243 struct ktc_principal client;
244 struct ktc_token token;
245 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
247 /* new interface routines to the ticket cache. Only handle afs service right
250 static int NewSetToken (aserver, atoken, aclient, flags)
251 struct ktc_principal *aserver;
252 struct ktc_principal *aclient;
253 struct ktc_token *atoken;
256 TRY_KERNEL (KTC_SETTOKEN_OP,
257 aserver, aclient, atoken, sizeof(struct ktc_token));
258 /* no kernel ticket cache */
262 static int OldSetToken (aserver, atoken, aclient, flags)
263 struct ktc_principal *aserver, *aclient;
264 struct ktc_token *atoken;
267 struct ViceIoctl iob;
270 struct ClearToken ct;
271 register afs_int32 code;
274 if (strcmp(aserver->name, "afs") != 0) {
277 for (i=0; i<MAXLOCALTOKENS; i++)
278 if (local_tokens[i].valid) {
279 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
280 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
281 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
282 found = i; /* replace existing entry */
285 else /* valid, but no match */ ;
286 } else found = i; /* remember this empty slot */
287 if (found == -1) return KTC_NOENT;
288 memcpy(&local_tokens[found].token, atoken, sizeof(struct ktc_token));
289 local_tokens[found].server = *aserver;
290 local_tokens[found].client = *aclient;
291 local_tokens[found].valid = 1;
294 tp = tbuffer; /* start copying here */
295 if ((atoken->ticketLen < MINKTCTICKETLEN) ||
296 (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
297 memcpy(tp, &atoken->ticketLen, sizeof(afs_int32)); /* copy in ticket length */
298 tp += sizeof(afs_int32);
299 memcpy(tp, atoken->ticket, atoken->ticketLen); /* copy in ticket */
300 tp += atoken->ticketLen;
301 /* next, copy in the "clear token", describing who we are */
302 ct.AuthHandle = atoken->kvno; /* hide auth handle here */
303 memcpy(ct.HandShakeKey, &atoken->sessionKey, 8);
305 ct.BeginTimestamp = atoken->startTime;
306 ct.EndTimestamp = atoken->endTime;
307 if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
309 if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
310 (aclient->instance[0] == 0)) {
312 afs_int32 viceId = 0;
313 char *cp = aclient->name + strlen ("AFS ID ");
314 if (*cp == '-') { sign = -1; cp++; }
316 if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
317 else goto not_vice_id;
320 ct.ViceId = viceId * sign; /* OK to let any value here? */
321 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
322 ct.BeginTimestamp++; /* force lifetime to be odd */
325 ct.ViceId = getuid(); /* wrong, but works in primary cell */
326 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
327 ct.BeginTimestamp++; /* force lifetime to be even */
332 * Information needed by the user space cache manager
334 u.u_expiration = ct.EndTimestamp;
335 u.u_viceid = ct.ViceId;
338 temp = sizeof(struct ClearToken);
339 memcpy(tp, &temp, sizeof(afs_int32));
340 tp += sizeof(afs_int32);
341 memcpy(tp, &ct, sizeof(struct ClearToken));
342 tp += sizeof(struct ClearToken);
344 /* next copy in primary flag */
348 * The following means that setpag will happen inside afs just before
349 * the authentication to prevent the setpag/klog race condition.
351 * The following means that setpag will affect the parent process as
352 * well as the current process.
354 if (flags & AFS_SETTOK_SETPAG)
357 memcpy(tp, &temp, sizeof(afs_int32));
358 tp += sizeof(afs_int32);
360 /* finally copy in the cell name */
361 temp = strlen(aserver->cell);
362 if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
363 strcpy(tp, aserver->cell);
366 /* now setup for the pioctl */
368 iob.in_size = tp-tbuffer;
370 iob.out_size = sizeof(tbuffer);
372 #if defined(NO_AFS_CLIENT)
373 { int fd; /* DEBUG */
375 if ((tkfile=getenv("TKTFILE")) &&
376 ((fd=open(tkfile, O_WRONLY|O_APPEND|O_TRUNC|O_CREAT, 0644)) >= 0)) {
377 printf("Writing ticket to: %s\n", tkfile);
378 code = (write(fd, iob.in, iob.in_size) != iob.in_size);
382 code = KTC_PIOCTLFAIL;
384 #else /* NO_AFS_CLIENT */
385 code = PIOCTL(0, VIOCSETTOK, &iob, 0);
386 #endif /* NO_AFS_CLIENT */
387 if (code) return KTC_PIOCTLFAIL;
392 ktc_SetToken (aserver, atoken, aclient, flags)
393 struct ktc_principal *aserver;
394 struct ktc_principal *aclient;
395 struct ktc_token *atoken;
401 #ifdef AFS_KERBEROS_ENV
402 if (!lcell[0]) ktc_LocalCell();
404 if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
405 (strcmp(aserver->name, "AuthServer") ||
406 strcmp(aserver->instance, "Admin"))){
407 if (strcmp(aserver->name, "krbtgt") == 0) {
408 static char lrealm[MAXKTCREALMLEN];
410 if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
411 if (strcmp(aserver->instance, lrealm) == 0) {
412 afs_tf_create(aclient->name, aclient->instance);
416 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
417 if (ncode == NO_TKT_FIL) {
418 (void) afs_tf_create(aclient->name, aclient->instance);
419 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
423 afs_tf_save_cred(aserver, atoken, aclient);
429 #endif /* NO_AFS_CLIENT */
433 #ifndef NO_AFS_CLIENT
434 ncode = NewSetToken (aserver, atoken, aclient, flags);
435 if (ncode || /* new style failed */
436 (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
437 ocode = OldSetToken (aserver, atoken, aclient, flags);
439 if (ncode && ocode) {
441 if (ocode == -1) ocode = errno;
442 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
443 if (ocode == ESRCH) return KTC_NOCELL;
444 if (ocode == EINVAL) return KTC_NOPIOCTL;
445 if (ocode == EIO) return KTC_NOCM;
446 return KTC_PIOCTLFAIL;
448 #endif /* NO_AFS_CLIENT */
453 /* get token, given server we need and token buffer. aclient will eventually
454 * be set to our identity to the server.
456 ktc_GetToken(aserver, atoken, atokenLen, aclient)
457 struct ktc_principal *aserver, *aclient;
459 struct ktc_token *atoken; {
460 struct ViceIoctl iob;
462 register afs_int32 code;
464 char *stp, *cellp; /* secret token ptr */
465 struct ClearToken ct;
468 int maxLen; /* biggest ticket we can copy */
469 int tktLen; /* server ticket length */
473 #ifndef NO_AFS_CLIENT
474 TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
475 #endif /* NO_AFS_CLIENT */
477 #ifdef AFS_KERBEROS_ENV
478 if (!lcell[0]) ktc_LocalCell();
480 #ifndef NO_AFS_CLIENT
481 if (strcmp(aserver->name, "afs") != 0)
482 #endif /* NO_AFS_CLIENT */
485 /* try the local tokens */
486 for (i=0; i<MAXLOCALTOKENS; i++)
487 if (local_tokens[i].valid &&
488 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
489 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
490 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
491 memcpy (atoken, &local_tokens[i].token, min (atokenLen, sizeof(struct ktc_token)));
493 *aclient = local_tokens[i].client;
497 #ifdef AFS_KERBEROS_ENV
498 if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
500 if (!afs_tf_get_pname(aclient->name) &&
501 !afs_tf_get_pinst(aclient->instance))
504 char tmpstring[MAXHOSTCHARS];
505 afs_tf_get_pname(&tmpstring);
506 afs_tf_get_pinst(&tmpstring);
511 struct ktc_principal cprincipal;
512 struct ktc_token ctoken;
514 while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
515 if (strcmp(cprincipal.name, aserver->name) == 0 &&
516 strcmp(cprincipal.instance, aserver->instance) == 0 &&
517 strcmp(cprincipal.cell, aserver->cell) == 0) {
520 strcpy(aclient->cell, lcell);
521 memcpy(atoken, &ctoken,
522 min (atokenLen, sizeof(struct ktc_token)));
536 #ifndef NO_AFS_CLIENT
537 for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
538 iob.in = (char *) &index;
539 iob.in_size = sizeof(afs_int32);
541 iob.out_size = sizeof(tbuffer);
543 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
546 /* failed to retrieve specified token */
547 if (code < 0 && errno == EDOM) {
552 /* token retrieved; parse buffer */
555 /* get ticket length */
556 memcpy(&temp, tp, sizeof(afs_int32));
558 tp += sizeof(afs_int32);
560 /* remember where ticket is and skip over it */
564 /* get size of clear token and verify */
565 memcpy(&temp, tp, sizeof(afs_int32));
566 if (temp != sizeof(struct ClearToken)) {
570 tp += sizeof(afs_int32);
572 /* copy clear token */
573 memcpy(&ct, tp, temp);
576 /* skip over primary flag */
577 tp += sizeof(afs_int32);
579 /* remember where cell name is */
582 if ((strcmp(cellp, aserver->cell) == 0)
583 #ifdef AFS_KERBEROS_ENV
584 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
587 /* got token for cell; check that it will fit */
588 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
589 if (maxLen < tktLen) {
594 /* set return values */
595 memcpy(atoken->ticket, stp, tktLen);
596 atoken->startTime = ct.BeginTimestamp;
597 atoken->endTime = ct.EndTimestamp;
598 if (ct.AuthHandle == -1) {
601 atoken->kvno = ct.AuthHandle;
602 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
603 atoken->ticketLen = tktLen;
606 strcpy(aclient->cell, cellp);
607 aclient->instance[0] = 0;
609 if ((atoken->kvno == 999) || /* old style bcrypt ticket */
610 (ct.BeginTimestamp && /* new w/ prserver lookup */
611 (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
612 sprintf(aclient->name, "AFS ID %d", ct.ViceId);
614 sprintf(aclient->name, "Unix UID %d", ct.ViceId);
622 #endif /* NO_AFS_CLIENT */
625 if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
626 return KTC_PIOCTLFAIL; /* probable cause */
630 * Forget tokens for this server and the calling user.
631 * NOT IMPLEMENTED YET!
633 #ifndef NO_AFS_CLIENT
634 ktc_ForgetToken(aserver)
635 struct ktc_principal *aserver; {
639 TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
641 rc = ktc_ForgetAllTokens(); /* bogus, but better */
645 #endif /* NO_AFS_CLIENT */
647 /* ktc_ListTokens - list all tokens. start aprevIndex at 0, it returns the
648 * next rock in (*aindex). (*aserver) is set to the relevant ticket on
651 ktc_ListTokens(aprevIndex, aindex, aserver)
652 int aprevIndex, *aindex;
653 struct ktc_principal *aserver; {
654 struct ViceIoctl iob;
656 register afs_int32 code;
658 afs_int32 temp, index;
661 #ifndef NO_AFS_CLIENT
662 TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
663 #endif /* NO_AFS_CLIENT */
667 if (index < 214) index = 214;
668 #endif /* NO_AFS_CLIENT */
669 #ifdef AFS_KERBEROS_ENV
672 struct ktc_principal cprincipal;
673 struct ktc_token ctoken;
675 if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL) ||
676 afs_tf_get_pname(tbuffer) ||
677 afs_tf_get_pinst(tbuffer)) {
683 for (i=214; i<index; i++) {
684 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
692 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
699 #ifndef NO_AFS_CLIENT
700 if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
703 #endif /* NO_AFS_CLIENT */
705 for (i=0; i < MAXLOCALTOKENS; i++) {
706 if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
707 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
708 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
713 *aserver = cprincipal;
721 #ifndef NO_AFS_CLIENT
722 if (index >= 123) { /* special hack for returning TCS */
723 while (index-123 < MAXLOCALTOKENS) {
724 if (local_tokens[index-123].valid) {
725 *aserver = local_tokens[index-123].server;
733 #ifdef AFS_KERBEROS_ENV
734 return ktc_ListTokens(214, aindex, aserver);
740 /* get tokens from the kernel */
741 while (index<200) { /* sanity check in case pioctl fails */
742 iob.in = (char *) &index;
743 iob.in_size = sizeof(afs_int32);
745 iob.out_size = sizeof(tbuffer);
746 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
747 if (code < 0 && errno == EDOM) {
750 rc = ktc_ListTokens (123, aindex, aserver);
759 if (code == 0) break; /* got a ticket */
760 /* otherwise we should skip this ticket slot */
765 if (errno == EINVAL) return KTC_NOPIOCTL;
766 return KTC_PIOCTLFAIL;
772 /* next iterator determined by earlier loop */
775 memcpy(&temp, tp, sizeof(afs_int32)); /* get size of secret token */
776 tp += sizeof(afs_int32);
777 tp += temp; /* skip ticket for now */
778 memcpy(&temp, tp, sizeof(afs_int32)); /* get size of clear token */
779 if (temp != sizeof(struct ClearToken)) {
783 tp += sizeof(afs_int32); /* skip length */
784 tp += temp; /* skip clear token itself */
785 tp += sizeof(afs_int32); /* skip primary flag */
786 /* tp now points to the cell name */
787 strcpy(aserver->cell, tp);
788 aserver->instance[0] = 0;
789 strcpy(aserver->name, "afs");
790 #endif /* NO_AFS_CLIENT */
795 /* discard all tokens from this user's cache */
797 static int NewForgetAll ()
799 #ifndef NO_AFS_CLIENT
800 TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
801 #endif /* NO_AFS_CLIENT */
805 static int OldForgetAll ()
807 struct ViceIoctl iob;
808 register afs_int32 code;
811 for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
817 #ifndef NO_AFS_CLIENT
818 code = PIOCTL(0, VIOCUNPAG, &iob, 0);
819 if (code) return KTC_PIOCTLFAIL;
820 #endif /* NO_AFS_CLIENT */
824 int ktc_ForgetAllTokens()
829 #ifdef AFS_KERBEROS_ENV
830 (void) afs_tf_dest_tkt();
833 ncode = NewForgetAll ();
834 ocode = OldForgetAll ();
835 if (ncode && ocode) {
836 if (ocode == -1) ocode = errno;
837 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
839 if (ocode == EINVAL) return KTC_NOPIOCTL;
840 return KTC_PIOCTLFAIL;
846 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
847 * pioctl interface for delivering AFS tickets to the cache manager. */
853 #ifdef KERNEL_KTC_COMPAT
855 rc = (kernelKTC != 1); /* old style interface */
864 #ifdef AFS_KERBEROS_ENV
866 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
868 * For copying and distribution information, please see the file
875 #include <sys/types.h>
876 #include <sys/stat.h>
877 #include <sys/file.h>
882 #define TF_LCK_RETRY ((unsigned)2) /* seconds to sleep before
883 * retry if ticket file is
887 * fd must be initialized to something that won't ever occur as a real
888 * file descriptor. Since open(2) returns only non-negative numbers as
889 * valid file descriptors, and afs_tf_init always stuffs the return value
890 * from open in here even if it is an error flag, we must
891 * a. Initialize fd to a negative number, to indicate that it is
892 * not initially valid.
893 * b. When checking for a valid fd, assume that negative values
894 * are invalid (ie. when deciding whether afs_tf_init has been
896 * c. In tf_close, be sure it gets reinitialized to a negative
900 static curpos; /* Position in tfbfr */
901 static lastpos; /* End of tfbfr */
902 static char tfbfr[BUFSIZ]; /* Buffer for ticket data */
904 static tf_gets(), tf_read();
907 * This file contains routines for manipulating the ticket cache file.
909 * The ticket file is in the following format:
911 * principal's name (null-terminated string)
912 * principal's instance (null-terminated string)
919 * Where "CREDENTIAL_x" consists of the following fixed-length
920 * fields from the CREDENTIALS structure (see "krb.h"):
922 * char service[MAXKTCNAMELEN]
923 * char instance[MAXKTCNAMELEN]
924 * char realm[REALM_SZ]
929 * afs_int32 issue_date
931 * Short description of routines:
933 * afs_tf_init() opens the ticket file and locks it.
935 * afs_tf_get_pname() returns the principal's name.
937 * afs_tf_get_pinst() returns the principal's instance (may be null).
939 * afs_tf_get_cred() returns the next CREDENTIALS record.
941 * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
943 * afs_tf_close() closes the ticket file and releases the lock.
945 * tf_gets() returns the next null-terminated string. It's an internal
946 * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
949 * tf_read() reads a given number of bytes. It's an internal routine
950 * used by afs_tf_get_cred().
954 * afs_tf_init() should be called before the other ticket file routines.
955 * It takes the name of the ticket file to use, "tf_name", and a
956 * read/write flag "rw" as arguments.
958 * It tries to open the ticket file, checks the mode, and if everything
959 * is okay, locks the file. If it's opened for reading, the lock is
960 * shared. If it's opened for writing, the lock is exclusive.
962 * Returns 0 if all went well, otherwise one of the following:
964 * NO_TKT_FIL - file wasn't there
965 * TKT_FIL_ACC - file was in wrong mode, etc.
966 * TKT_FIL_LCK - couldn't lock the file, even after a retry
969 afs_tf_init(tf_name, rw)
974 struct stat stat_buf;
986 if (lstat(tf_name, &stat_buf) < 0)
994 if ((stat_buf.st_uid != me && me != 0) ||
995 ((stat_buf.st_mode & S_IFMT) != S_IFREG))
999 * If "wflag" is set, open the ticket file in append-writeonly mode
1000 * and lock the ticket file in exclusive mode. If unable to lock
1001 * the file, sleep and try again. If we fail again, return with the
1002 * proper error message.
1005 curpos = sizeof(tfbfr);
1008 fd = open(tf_name, O_RDWR, 0600);
1012 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1013 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1014 sleep(TF_LCK_RETRY);
1015 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1017 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1018 sleep(TF_LCK_RETRY);
1019 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1029 * Otherwise "wflag" is not set and the ticket file should be opened
1030 * for read-only operations and locked for shared access.
1033 fd = open(tf_name, O_RDONLY, 0600);
1037 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1038 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1039 sleep(TF_LCK_RETRY);
1040 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1042 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1043 sleep(TF_LCK_RETRY);
1044 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1055 * afs_tf_get_pname() reads the principal's name from the ticket file. It
1056 * should only be called after afs_tf_init() has been called. The
1057 * principal's name is filled into the "p" parameter. If all goes well,
1058 * 0 is returned. If afs_tf_init() wasn't called, TKT_FIL_INI is
1059 * returned. If the name was null, or EOF was encountered, or the name
1060 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1069 if (tf_gets(p, MAXKTCNAMELEN) < 2) /* can't be just a null */
1075 * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1076 * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1077 * been called. The instance is filled into the "inst" parameter. If all
1078 * goes well, 0 is returned. If afs_tf_init() wasn't called,
1079 * TKT_FIL_INI is returned. If EOF was encountered, or the instance
1080 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. Note that the
1081 * instance may be null.
1084 afs_tf_get_pinst(inst)
1090 if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1096 * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1097 * in the given structure "c". It should only be called after afs_tf_init(),
1098 * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1099 * well, 0 is returned. Possible error codes are:
1101 * TKT_FIL_INI - afs_tf_init wasn't called first
1102 * TKT_FIL_FMT - bad format
1103 * EOF - end of file encountered
1106 afs_tf_get_cred(principal, token)
1107 struct ktc_principal *principal;
1108 struct ktc_token *token;
1116 if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1119 case 1: /* can't be just a null */
1124 if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1131 if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1134 case 1: /* can't be just a null */
1139 lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1141 tf_read((char *) &(token->sessionKey), 8) < 1 ||
1142 tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1143 tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1144 tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1146 /* don't try to read a silly amount into ticket->dat */
1147 token->ticketLen > MAXKTCTICKETLEN ||
1148 tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1149 tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1153 token->endTime = life_to_time(token->startTime, lifetime);
1159 * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1160 * not a valid file descriptor, it just returns. It also clears the
1161 * buffer used to read tickets.
1163 * The return value is not defined.
1169 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1170 (void) fcntl(fd, F_SETLK, &fileUlock);
1172 (void) flock(fd, LOCK_UN);
1175 fd = -1; /* see declaration of fd above */
1177 memset(tfbfr, 0, sizeof(tfbfr));
1181 * tf_gets() is an internal routine. It takes a string "s" and a count
1182 * "n", and reads from the file until either it has read "n" characters,
1183 * or until it reads a null byte. When finished, what has been read exists
1186 * Possible return values are:
1188 * n the number of bytes read (including null terminator)
1189 * when all goes well
1191 * 0 end of file or read error
1193 * TOO_BIG if "count" characters are read and no null is
1194 * encountered. This is an indication that the ticket
1195 * file is seriously ill.
1207 for (count = n - 1; count > 0; --count) {
1208 if (curpos >= sizeof(tfbfr)) {
1209 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1212 if (curpos == lastpos) {
1215 *s = tfbfr[curpos++];
1223 * tf_read() is an internal routine. It takes a string "s" and a count
1224 * "n", and reads from the file until "n" bytes have been read. When
1225 * finished, what has been read exists in "s".
1227 * Possible return values are:
1229 * n the number of bytes read when all goes well
1231 * 0 on end of file or read error
1241 for (count = n; count > 0; --count) {
1242 if (curpos >= sizeof(tfbfr)) {
1243 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1246 if (curpos == lastpos) {
1249 *s++ = tfbfr[curpos++];
1257 * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1258 * file. You must call afs_tf_init() before calling afs_tf_save_cred().
1260 * The "service", "instance", and "realm" arguments specify the
1261 * server's name; "aticket" contains the credential.
1263 * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1264 * called previously, and KFAILURE for anything else that went wrong.
1267 afs_tf_save_cred(aserver, atoken, aclient)
1268 struct ktc_principal *aserver;
1269 struct ktc_principal *aclient;
1270 struct ktc_token *atoken; /* Token */
1272 char realm[MAXKTCREALMLEN+1];
1273 char junk[MAXKTCNAMELEN];
1274 struct ktc_principal principal;
1275 struct ktc_token token;
1277 off_t start, lseek();
1279 int count; /* count for write */
1281 if (fd < 0) { /* fd is ticket file as set by afs_tf_init */
1285 ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1286 realm[MAXKTCREALMLEN] = '\0';
1288 /* Look for a duplicate ticket */
1289 (void) lseek(fd, (off_t) 0L, 0);
1290 curpos = sizeof(tfbfr);
1292 if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1293 afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1296 start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1297 status = afs_tf_get_cred(&principal, &token);
1298 } while (status == 0 &&
1299 (strcmp(aserver->name, principal.name) != 0 ||
1300 strcmp(aserver->instance, principal.instance) != 0 ||
1301 strcmp(aserver->cell, principal.cell) != 0));
1304 * Two tickets for the same user authenticating to the same service
1305 * should be the same length, but we check here just to make sure.
1307 if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1308 if (status && status != EOF) return status;
1310 /* Position over the credential we just matched (or the EOF) */
1311 lseek(fd, start, 0);
1312 curpos = lastpos = sizeof(tfbfr);
1314 /* Write the ticket and associated data */
1316 count = strlen(aserver->name) + 1;
1317 if (write(fd, aserver->name, count) != count)
1320 count = strlen(aserver->instance) + 1;
1321 if (write(fd, aserver->instance, count) != count)
1324 count = strlen(realm) + 1;
1325 if (write(fd, realm, count) != count)
1328 if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1331 lifetime = time_to_life(atoken->startTime, atoken->endTime);
1332 if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1335 kvno = atoken->kvno;
1336 if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1339 if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1343 count = atoken->ticketLen;
1344 if (write(fd, atoken->ticket, count) != count)
1347 if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1348 != sizeof(afs_int32))
1351 /* Actually, we should check each write for success */
1358 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1361 * For copying and distribution information, please see the file
1362 * <mit-copyright.h>.
1368 * This routine is used to generate the name of the file that holds
1369 * the user's cache of server tickets and associated session keys.
1371 * If it is set, krb_ticket_string contains the ticket file name.
1372 * Otherwise, the filename is constructed as follows:
1374 * If it is set, the environment variable "KRBTKFILE" will be used as
1375 * the ticket file name. Otherwise TKT_ROOT (defined in "krb.h") and
1376 * the user's uid are concatenated to produce the ticket file name
1377 * (e.g., "/tmp/tkt123"). A pointer to the string containing the ticket
1378 * file name is returned.
1381 static char krb_ticket_string[4096] = "";
1383 char *ktc_tkt_string()
1388 if (!*krb_ticket_string) {
1389 if (env = getenv("KRBTKFILE")) {
1390 (void) strncpy(krb_ticket_string, env,
1391 sizeof(krb_ticket_string)-1);
1392 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1394 /* 32 bits of signed integer will always fit in 11 characters
1395 (including the sign), so no need to worry about overflow */
1396 (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1400 return krb_ticket_string;
1404 * This routine is used to set the name of the file that holds the user's
1405 * cache of server tickets and associated session keys.
1407 * The value passed in is copied into local storage.
1409 * NOTE: This routine should be called during initialization, before other
1410 * Kerberos routines are called; otherwise tkt_string() above may be called
1411 * and return an undesired ticket file name until this routine is called.
1415 ktc_set_tkt_string(val)
1420 (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1421 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1428 * tf_create() is used to initialize the ticket store. It creates the
1429 * file to contain the tickets and writes the given user's name "pname"
1430 * and instance "pinst" in the file. in_tkt() returns KSUCCESS on
1431 * success, or KFAILURE if something goes wrong.
1434 afs_tf_create(pname,pinst)
1441 char *file = ktc_tkt_string();
1450 if (lstat(file,&sbuf) == 0) {
1451 if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1452 sbuf.st_mode & 077) {
1455 /* file already exists, and permissions appear ok, so nuke it */
1456 if ((fd = open(file, O_RDWR, 0)) < 0)
1457 goto out; /* can't zero it, but we can still try truncating it */
1459 memset(zerobuf, 0, sizeof(zerobuf));
1461 for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1462 if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1473 /* arrange so the file is owned by the ruid
1474 (swap real & effective uid if necessary).
1475 This isn't a security problem, since the ticket file, if it already
1476 exists, has the right uid (== ruid) and mode. */
1478 if (setreuid(metoo, me) < 0) {
1482 tktfile = creat(file, 0600);
1484 if (setreuid(me, metoo) < 0) {
1485 /* can't switch??? fail! */
1492 count = strlen(pname)+1;
1493 if (write(tktfile,pname,count) != count) {
1494 (void) close(tktfile);
1497 count = strlen(pinst)+1;
1498 if (write(tktfile,pinst,count) != count) {
1499 (void) close(tktfile);
1502 (void) close(tktfile);
1507 * dest_tkt() is used to destroy the ticket store upon logout.
1508 * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1509 * Otherwise the function returns 0 on success, KFAILURE on
1515 char *file = ktc_tkt_string();
1521 if (lstat(file,&statb) < 0)
1524 if (!(statb.st_mode & S_IFREG))
1527 if ((fd = open(file, O_RDWR, 0)) < 0)
1530 memset(buf, 0, BUFSIZ);
1532 for (i = 0; i < statb.st_size; i += BUFSIZ)
1533 if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1542 (void) unlink(file);
1545 if (errno == ENOENT) return RET_TKFIL;
1546 else if (errno != 0) return KFAILURE;
1550 static afs_uint32 curpag()
1552 gid_t groups[NGROUPS_MAX];
1554 afs_uint32 h, l, ret;
1556 if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1558 g0 = groups[0] & 0xffff;
1559 g1 = groups[1] & 0xffff;
1562 if (g0 < 0xc000 && g1 < 0xc000) {
1563 l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1565 h = (g1 >> 14) + h + h + h;
1566 ret = ((h << 28) | l);
1567 /* Additional testing */
1568 if (((ret >> 24) & 0xff) == 'A')
1579 extern char **environ;
1583 char fname[256], *prefix = "/ticket/";
1585 char **newenv, **senv, **denv;
1588 if (stat("/ticket", &sbuf) == -1) {
1589 prefix = "/tmp/tkt";
1592 pag = curpag() & 0xffffffff;
1594 sprintf(fname, "%s%d", prefix, getuid());
1597 sprintf(fname, "%sp%ld", prefix, pag);
1599 ktc_set_tkt_string(fname);
1601 for (senv=environ, numenv=0; *senv; senv++) numenv++;
1602 newenv = (char **)malloc((numenv+2) * sizeof(char *));
1604 for (senv=environ, denv=newenv; *senv; *senv++) {
1605 if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1608 *denv = (char *)malloc(10 + strlen(fname) + 1);
1609 strcpy(*denv, "KRBTKFILE=");
1610 strcat(*denv, fname);
1617 * BLETCH! We have to invoke the entire afsconf package just to
1618 * find out what the local cell is.
1620 static ktc_LocalCell()
1623 struct afsconf_dir *conf;
1625 if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1626 (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1627 code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1628 afsconf_Close (conf);
1630 if (!conf || code) {
1631 printf("** Can't determine local cell name!\n");