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 */
13 #include "../afs/param.h"
15 #include <afs/param.h>
17 #include <afsconfig.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>
53 #include <sys/lockf.h>
56 #include <afs/venus.h>
57 #include <afs/afsutil.h>
59 #endif /* defined(UKERNEL) */
66 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
67 #define AFS_KERBEROS_ENV
70 #ifdef AFS_KERBEROS_ENV
73 extern afs_uint32 life_to_time();
74 extern unsigned char time_to_life();
75 #include "cellconfig.h"
76 static char lcell[MAXCELLCHARS];
78 #define TKT_ROOT "/tmp/tkt"
83 /* Definitions for ticket file utilities */
87 /* Error codes returned by ticket file utilities */
88 #define NO_TKT_FIL 76 /* No ticket file found */
89 #define TKT_FIL_ACC 77 /* Couldn't access tkt file */
90 #define TKT_FIL_LCK 78 /* Couldn't lock ticket file */
91 #define TKT_FIL_FMT 79 /* Bad ticket file format */
92 #define TKT_FIL_INI 80 /* afs_tf_init not called first */
94 /* Values returned by get_credentials */
95 #define RET_TKFIL 21 /* Can't read ticket file */
104 #if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
105 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
106 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
107 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
110 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
111 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
112 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
119 /* the following routines aren't static anymore on behalf of the kerberos IV
120 * compatibility library built in subtree krb.
122 int afs_tf_init(), afs_tf_get_pname(), afs_tf_get_pinst(), afs_tf_get_cred();
123 int afs_tf_save_cred(), afs_tf_close(), afs_tf_create();
124 int afs_tf_dest_tkt(), ktc_LocalCell();
125 char *ktc_tkt_string();
126 #endif /* AFS_KERBEROS_ENV */
129 #define PIOCTL afs_pioctl
130 #elif defined(UKERNEL)
131 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
133 #define PIOCTL pioctl
137 #ifdef KERNEL_KTC_COMPAT
140 #define KTC_SYSCALL 32
143 /* Kernel call opcode definitions */
144 #define KTC_OPCODE_BASE 4300
145 #define KTC_NO_OP (0+KTC_OPCODE_BASE)
146 #define KTC_SETTOKEN_OP (1+KTC_OPCODE_BASE)
147 #define KTC_GETTOKEN_OP (2+KTC_OPCODE_BASE)
148 #define KTC_LISTTOKENS_OP (3+KTC_OPCODE_BASE)
149 #define KTC_FORGETTOKEN_OP (4+KTC_OPCODE_BASE)
150 #define KTC_FORGETALLTOKENS_OP (5+KTC_OPCODE_BASE)
151 #define KTC_STATUS_OP (6+KTC_OPCODE_BASE)
152 #define KTC_GC_OP (7+KTC_OPCODE_BASE)
154 #define KTC_INTERFACE_VERSION 3
156 /* We have to determine if the kernel supports the ktc system call. To do so
157 * we attempt to execute its noop function. If this is successful we use the
158 * kernel calls in the future otherwise we let the old code run. */
160 /* To safely check to see whether a system call exists we have to intercept the
161 * SIGSYS signal which is caused by executing a non-existant system call. If
162 * it is ignored the syscall routine returns EINVAL. The SIGSYS is reset to
163 * its old value after the return from syscall. */
165 static int kernelKTC = 0;
167 #ifdef AFS_DECOSF_ENV
169 * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems. You need
170 * to ignore SIGTRAP too. It is claimed to be fixed under v1.3, but...
173 #define CHECK_KERNEL \
174 if (kernelKTC == 0) { \
178 old = (int (*)())signal(SIGSYS, SIG_IGN); \
179 old_t = (int (*)())signal(SIGTRAP, SIG_IGN); \
180 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
182 signal(SIGSYS, old); \
183 signal(SIGTRAP, old_t); \
184 if (code == 0) kernelKTC = 1; \
185 else kernelKTC = 2; \
186 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
189 #else /* AFS_DECOSF_ENV */
191 #define CHECK_KERNEL \
192 if (kernelKTC == 0) { \
195 old = (int (*)())signal(SIGSYS, SIG_IGN); \
196 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
198 signal(SIGSYS, old); \
199 if (code == 0) kernelKTC = 1; \
200 else kernelKTC = 2; \
201 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
203 #endif /* AFS_DECOSF_ENV */
205 #define TRY_KERNEL(cmd,a1,a2,a3,a4) \
207 if (kernelKTC == 1) \
208 return syscall (KTC_SYSCALL, cmd, \
209 KTC_INTERFACE_VERSION, a1,a2,a3,a4); \
213 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
214 #endif /* KERNEL_KTC_COMPAT */
216 #if !defined(UKERNEL)
217 /* this is a structure used to communicate with the afs cache mgr, but is
218 * otherwise irrelevant */
220 afs_int32 AuthHandle;
221 char HandShakeKey[8];
223 afs_int32 BeginTimestamp;
224 afs_int32 EndTimestamp;
226 #endif /* !defined(UKERNEL) */
228 #define MAXLOCALTOKENS 4
232 struct ktc_principal server;
233 struct ktc_principal client;
234 struct ktc_token token;
235 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
237 /* new interface routines to the ticket cache. Only handle afs service right
240 static int NewSetToken (aserver, atoken, aclient, flags)
241 struct ktc_principal *aserver;
242 struct ktc_principal *aclient;
243 struct ktc_token *atoken;
246 TRY_KERNEL (KTC_SETTOKEN_OP,
247 aserver, aclient, atoken, sizeof(struct ktc_token));
248 /* no kernel ticket cache */
252 static int OldSetToken (aserver, atoken, aclient, flags)
253 struct ktc_principal *aserver, *aclient;
254 struct ktc_token *atoken;
257 struct ViceIoctl iob;
260 struct ClearToken ct;
261 register afs_int32 code;
264 if (strcmp(aserver->name, "afs") != 0) {
267 for (i=0; i<MAXLOCALTOKENS; i++)
268 if (local_tokens[i].valid) {
269 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
270 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
271 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
272 found = i; /* replace existing entry */
275 else /* valid, but no match */ ;
276 } else found = i; /* remember this empty slot */
277 if (found == -1) return KTC_NOENT;
278 bcopy (atoken, &local_tokens[found].token, sizeof(struct ktc_token));
279 local_tokens[found].server = *aserver;
280 local_tokens[found].client = *aclient;
281 local_tokens[found].valid = 1;
284 tp = tbuffer; /* start copying here */
285 if ((atoken->ticketLen < MINKTCTICKETLEN) ||
286 (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
287 bcopy(&atoken->ticketLen, tp, sizeof(afs_int32)); /* copy in ticket length */
288 tp += sizeof(afs_int32);
289 bcopy(atoken->ticket, tp, atoken->ticketLen); /* copy in ticket */
290 tp += atoken->ticketLen;
291 /* next, copy in the "clear token", describing who we are */
292 ct.AuthHandle = atoken->kvno; /* hide auth handle here */
293 bcopy(&atoken->sessionKey, ct.HandShakeKey, 8);
295 ct.BeginTimestamp = atoken->startTime;
296 ct.EndTimestamp = atoken->endTime;
297 if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
299 if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
300 (aclient->instance[0] == 0)) {
302 afs_int32 viceId = 0;
303 char *cp = aclient->name + strlen ("AFS ID ");
304 if (*cp == '-') { sign = -1; cp++; }
306 if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
307 else goto not_vice_id;
310 ct.ViceId = viceId * sign; /* OK to let any value here? */
311 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
312 ct.BeginTimestamp++; /* force lifetime to be odd */
315 ct.ViceId = getuid(); /* wrong, but works in primary cell */
316 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
317 ct.BeginTimestamp++; /* force lifetime to be even */
322 * Information needed by the user space cache manager
324 u.u_expiration = ct.EndTimestamp;
325 u.u_viceid = ct.ViceId;
328 temp = sizeof(struct ClearToken);
329 bcopy(&temp, tp, sizeof(afs_int32));
330 tp += sizeof(afs_int32);
331 bcopy(&ct, tp, sizeof(struct ClearToken));
332 tp += sizeof(struct ClearToken);
334 /* next copy in primary flag */
338 * The following means that setpag will happen inside afs just before
339 * the authentication to prevent the setpag/klog race condition.
341 * The following means that setpag will affect the parent process as
342 * well as the current process.
344 if (flags & AFS_SETTOK_SETPAG)
347 bcopy(&temp, tp, sizeof(afs_int32));
348 tp += sizeof(afs_int32);
350 /* finally copy in the cell name */
351 temp = strlen(aserver->cell);
352 if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
353 strcpy(tp, aserver->cell);
356 /* now setup for the pioctl */
358 iob.in_size = tp-tbuffer;
360 iob.out_size = sizeof(tbuffer);
362 #if defined(NO_AFS_CLIENT)
363 { int fd; /* DEBUG */
365 if ((tkfile=getenv("TKTFILE")) &&
366 ((fd=open(tkfile, O_WRONLY|O_APPEND|O_TRUNC|O_CREAT, 0644)) >= 0)) {
367 printf("Writing ticket to: %s\n", tkfile);
368 code = (write(fd, iob.in, iob.in_size) != iob.in_size);
372 code = KTC_PIOCTLFAIL;
374 #else /* NO_AFS_CLIENT */
375 code = PIOCTL(0, VIOCSETTOK, &iob, 0);
376 #endif /* NO_AFS_CLIENT */
377 if (code) return KTC_PIOCTLFAIL;
382 ktc_SetToken (aserver, atoken, aclient, flags)
383 struct ktc_principal *aserver;
384 struct ktc_principal *aclient;
385 struct ktc_token *atoken;
391 #ifdef AFS_KERBEROS_ENV
392 if (!lcell[0]) ktc_LocalCell();
394 if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
395 (strcmp(aserver->name, "AuthServer") ||
396 strcmp(aserver->instance, "Admin"))){
397 if (strcmp(aserver->name, "krbtgt") == 0) {
398 static char lrealm[MAXKTCREALMLEN];
400 if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
401 if (strcmp(aserver->instance, lrealm) == 0) {
402 afs_tf_create(aclient->name, aclient->instance);
406 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
407 if (ncode == NO_TKT_FIL) {
408 (void) afs_tf_create(aclient->name, aclient->instance);
409 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
413 afs_tf_save_cred(aserver, atoken, aclient);
419 #endif /* NO_AFS_CLIENT */
423 #ifndef NO_AFS_CLIENT
424 ncode = NewSetToken (aserver, atoken, aclient, flags);
425 if (ncode || /* new style failed */
426 (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
427 ocode = OldSetToken (aserver, atoken, aclient, flags);
429 if (ncode && ocode) {
431 if (ocode == -1) ocode = errno;
432 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
433 if (ocode == ESRCH) return KTC_NOCELL;
434 if (ocode == EINVAL) return KTC_NOPIOCTL;
435 if (ocode == EIO) return KTC_NOCM;
436 return KTC_PIOCTLFAIL;
438 #endif /* NO_AFS_CLIENT */
443 /* get token, given server we need and token buffer. aclient will eventually
444 * be set to our identity to the server.
446 ktc_GetToken(aserver, atoken, atokenLen, aclient)
447 struct ktc_principal *aserver, *aclient;
449 struct ktc_token *atoken; {
450 struct ViceIoctl iob;
452 register afs_int32 code;
454 char *stp, *cellp; /* secret token ptr */
455 struct ClearToken ct;
458 int maxLen; /* biggest ticket we can copy */
459 int tktLen; /* server ticket length */
463 #ifndef NO_AFS_CLIENT
464 TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
465 #endif /* NO_AFS_CLIENT */
467 #ifdef AFS_KERBEROS_ENV
468 if (!lcell[0]) ktc_LocalCell();
470 #ifndef NO_AFS_CLIENT
471 if (strcmp(aserver->name, "afs") != 0)
472 #endif /* NO_AFS_CLIENT */
475 /* try the local tokens */
476 for (i=0; i<MAXLOCALTOKENS; i++)
477 if (local_tokens[i].valid &&
478 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
479 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
480 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
481 bcopy (&local_tokens[i].token, atoken, min (atokenLen, sizeof(struct ktc_token)));
483 *aclient = local_tokens[i].client;
487 #ifdef AFS_KERBEROS_ENV
488 if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
490 if (!afs_tf_get_pname(aclient->name) &&
491 !afs_tf_get_pinst(aclient->instance))
494 char tmpstring[MAXHOSTCHARS];
495 afs_tf_get_pname(&tmpstring);
496 afs_tf_get_pinst(&tmpstring);
501 struct ktc_principal cprincipal;
502 struct ktc_token ctoken;
504 while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
505 if (strcmp(cprincipal.name, aserver->name) == 0 &&
506 strcmp(cprincipal.instance, aserver->instance) == 0 &&
507 strcmp(cprincipal.cell, aserver->cell) == 0) {
510 strcpy(aclient->cell, lcell);
511 bcopy(&ctoken, atoken,
512 min (atokenLen, sizeof(struct ktc_token)));
526 #ifndef NO_AFS_CLIENT
527 for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
528 iob.in = (char *) &index;
529 iob.in_size = sizeof(afs_int32);
531 iob.out_size = sizeof(tbuffer);
533 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
536 /* failed to retrieve specified token */
537 if (code < 0 && errno == EDOM) {
542 /* token retrieved; parse buffer */
545 /* get ticket length */
546 memcpy(&temp, tp, sizeof(afs_int32));
548 tp += sizeof(afs_int32);
550 /* remember where ticket is and skip over it */
554 /* get size of clear token and verify */
555 memcpy(&temp, tp, sizeof(afs_int32));
556 if (temp != sizeof(struct ClearToken)) {
560 tp += sizeof(afs_int32);
562 /* copy clear token */
563 memcpy(&ct, tp, temp);
566 /* skip over primary flag */
567 tp += sizeof(afs_int32);
569 /* remember where cell name is */
572 if ((strcmp(cellp, aserver->cell) == 0)
573 #ifdef AFS_KERBEROS_ENV
574 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
577 /* got token for cell; check that it will fit */
578 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
579 if (maxLen < tktLen) {
584 /* set return values */
585 memcpy(atoken->ticket, stp, tktLen);
586 atoken->startTime = ct.BeginTimestamp;
587 atoken->endTime = ct.EndTimestamp;
588 if (ct.AuthHandle == -1) {
591 atoken->kvno = ct.AuthHandle;
592 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
593 atoken->ticketLen = tktLen;
596 strcpy(aclient->cell, cellp);
597 aclient->instance[0] = 0;
599 if ((atoken->kvno == 999) || /* old style bcrypt ticket */
600 (ct.BeginTimestamp && /* new w/ prserver lookup */
601 (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
602 sprintf(aclient->name, "AFS ID %d", ct.ViceId);
604 sprintf(aclient->name, "Unix UID %d", ct.ViceId);
612 #endif /* NO_AFS_CLIENT */
615 if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
616 return KTC_PIOCTLFAIL; /* probable cause */
620 * Forget tokens for this server and the calling user.
621 * NOT IMPLEMENTED YET!
623 #ifndef NO_AFS_CLIENT
624 ktc_ForgetToken(aserver)
625 struct ktc_principal *aserver; {
629 TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
631 rc = ktc_ForgetAllTokens(); /* bogus, but better */
635 #endif /* NO_AFS_CLIENT */
637 /* ktc_ListTokens - list all tokens. start aprevIndex at 0, it returns the
638 * next rock in (*aindex). (*aserver) is set to the relevant ticket on
641 ktc_ListTokens(aprevIndex, aindex, aserver)
642 int aprevIndex, *aindex;
643 struct ktc_principal *aserver; {
644 struct ViceIoctl iob;
646 register afs_int32 code;
648 afs_int32 temp, index;
651 #ifndef NO_AFS_CLIENT
652 TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
653 #endif /* NO_AFS_CLIENT */
657 if (index < 214) index = 214;
658 #endif /* NO_AFS_CLIENT */
659 #ifdef AFS_KERBEROS_ENV
662 struct ktc_principal cprincipal;
663 struct ktc_token ctoken;
665 if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL) ||
666 afs_tf_get_pname(tbuffer) ||
667 afs_tf_get_pinst(tbuffer)) {
673 for (i=214; i<index; i++) {
674 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
682 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
689 #ifndef NO_AFS_CLIENT
690 if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
693 #endif /* NO_AFS_CLIENT */
695 for (i=0; i < MAXLOCALTOKENS; i++) {
696 if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
697 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
698 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
703 *aserver = cprincipal;
711 #ifndef NO_AFS_CLIENT
712 if (index >= 123) { /* special hack for returning TCS */
713 while (index-123 < MAXLOCALTOKENS) {
714 if (local_tokens[index-123].valid) {
715 *aserver = local_tokens[index-123].server;
723 #ifdef AFS_KERBEROS_ENV
724 return ktc_ListTokens(214, aindex, aserver);
730 /* get tokens from the kernel */
731 while (index<200) { /* sanity check in case pioctl fails */
732 iob.in = (char *) &index;
733 iob.in_size = sizeof(afs_int32);
735 iob.out_size = sizeof(tbuffer);
736 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
737 if (code < 0 && errno == EDOM) {
740 rc = ktc_ListTokens (123, aindex, aserver);
749 if (code == 0) break; /* got a ticket */
750 /* otherwise we should skip this ticket slot */
755 if (errno == EINVAL) return KTC_NOPIOCTL;
756 return KTC_PIOCTLFAIL;
762 /* next iterator determined by earlier loop */
765 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of secret token */
766 tp += sizeof(afs_int32);
767 tp += temp; /* skip ticket for now */
768 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of clear token */
769 if (temp != sizeof(struct ClearToken)) {
773 tp += sizeof(afs_int32); /* skip length */
774 tp += temp; /* skip clear token itself */
775 tp += sizeof(afs_int32); /* skip primary flag */
776 /* tp now points to the cell name */
777 strcpy(aserver->cell, tp);
778 aserver->instance[0] = 0;
779 strcpy(aserver->name, "afs");
780 #endif /* NO_AFS_CLIENT */
785 /* discard all tokens from this user's cache */
787 static int NewForgetAll ()
789 #ifndef NO_AFS_CLIENT
790 TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
791 #endif /* NO_AFS_CLIENT */
795 static int OldForgetAll ()
797 struct ViceIoctl iob;
798 register afs_int32 code;
801 for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
807 #ifndef NO_AFS_CLIENT
808 code = PIOCTL(0, VIOCUNPAG, &iob, 0);
809 if (code) return KTC_PIOCTLFAIL;
810 #endif /* NO_AFS_CLIENT */
814 int ktc_ForgetAllTokens()
819 #ifdef AFS_KERBEROS_ENV
820 (void) afs_tf_dest_tkt();
823 ncode = NewForgetAll ();
824 ocode = OldForgetAll ();
825 if (ncode && ocode) {
826 if (ocode == -1) ocode = errno;
827 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
829 if (ocode == EINVAL) return KTC_NOPIOCTL;
830 return KTC_PIOCTLFAIL;
836 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
837 * pioctl interface for delivering AFS tickets to the cache manager. */
843 #ifdef KERNEL_KTC_COMPAT
845 rc = (kernelKTC != 1); /* old style interface */
854 #ifdef AFS_KERBEROS_ENV
856 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
858 * For copying and distribution information, please see the file
865 #include <sys/types.h>
866 #include <sys/stat.h>
867 #include <sys/file.h>
872 #define TF_LCK_RETRY ((unsigned)2) /* seconds to sleep before
873 * retry if ticket file is
877 * fd must be initialized to something that won't ever occur as a real
878 * file descriptor. Since open(2) returns only non-negative numbers as
879 * valid file descriptors, and afs_tf_init always stuffs the return value
880 * from open in here even if it is an error flag, we must
881 * a. Initialize fd to a negative number, to indicate that it is
882 * not initially valid.
883 * b. When checking for a valid fd, assume that negative values
884 * are invalid (ie. when deciding whether afs_tf_init has been
886 * c. In tf_close, be sure it gets reinitialized to a negative
890 static curpos; /* Position in tfbfr */
891 static lastpos; /* End of tfbfr */
892 static char tfbfr[BUFSIZ]; /* Buffer for ticket data */
894 static tf_gets(), tf_read();
897 * This file contains routines for manipulating the ticket cache file.
899 * The ticket file is in the following format:
901 * principal's name (null-terminated string)
902 * principal's instance (null-terminated string)
909 * Where "CREDENTIAL_x" consists of the following fixed-length
910 * fields from the CREDENTIALS structure (see "krb.h"):
912 * char service[MAXKTCNAMELEN]
913 * char instance[MAXKTCNAMELEN]
914 * char realm[REALM_SZ]
919 * afs_int32 issue_date
921 * Short description of routines:
923 * afs_tf_init() opens the ticket file and locks it.
925 * afs_tf_get_pname() returns the principal's name.
927 * afs_tf_get_pinst() returns the principal's instance (may be null).
929 * afs_tf_get_cred() returns the next CREDENTIALS record.
931 * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
933 * afs_tf_close() closes the ticket file and releases the lock.
935 * tf_gets() returns the next null-terminated string. It's an internal
936 * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
939 * tf_read() reads a given number of bytes. It's an internal routine
940 * used by afs_tf_get_cred().
944 * afs_tf_init() should be called before the other ticket file routines.
945 * It takes the name of the ticket file to use, "tf_name", and a
946 * read/write flag "rw" as arguments.
948 * It tries to open the ticket file, checks the mode, and if everything
949 * is okay, locks the file. If it's opened for reading, the lock is
950 * shared. If it's opened for writing, the lock is exclusive.
952 * Returns 0 if all went well, otherwise one of the following:
954 * NO_TKT_FIL - file wasn't there
955 * TKT_FIL_ACC - file was in wrong mode, etc.
956 * TKT_FIL_LCK - couldn't lock the file, even after a retry
959 afs_tf_init(tf_name, rw)
964 struct stat stat_buf;
976 if (lstat(tf_name, &stat_buf) < 0)
984 if ((stat_buf.st_uid != me && me != 0) ||
985 ((stat_buf.st_mode & S_IFMT) != S_IFREG))
989 * If "wflag" is set, open the ticket file in append-writeonly mode
990 * and lock the ticket file in exclusive mode. If unable to lock
991 * the file, sleep and try again. If we fail again, return with the
992 * proper error message.
995 curpos = sizeof(tfbfr);
998 fd = open(tf_name, O_RDWR, 0600);
1002 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1003 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1004 sleep(TF_LCK_RETRY);
1005 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1007 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1008 sleep(TF_LCK_RETRY);
1009 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1019 * Otherwise "wflag" is not set and the ticket file should be opened
1020 * for read-only operations and locked for shared access.
1023 fd = open(tf_name, O_RDONLY, 0600);
1027 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1028 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1029 sleep(TF_LCK_RETRY);
1030 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1032 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1033 sleep(TF_LCK_RETRY);
1034 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1045 * afs_tf_get_pname() reads the principal's name from the ticket file. It
1046 * should only be called after afs_tf_init() has been called. The
1047 * principal's name is filled into the "p" parameter. If all goes well,
1048 * 0 is returned. If afs_tf_init() wasn't called, TKT_FIL_INI is
1049 * returned. If the name was null, or EOF was encountered, or the name
1050 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1059 if (tf_gets(p, MAXKTCNAMELEN) < 2) /* can't be just a null */
1065 * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1066 * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1067 * been called. The instance is filled into the "inst" parameter. If all
1068 * goes well, 0 is returned. If afs_tf_init() wasn't called,
1069 * TKT_FIL_INI is returned. If EOF was encountered, or the instance
1070 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. Note that the
1071 * instance may be null.
1074 afs_tf_get_pinst(inst)
1080 if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1086 * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1087 * in the given structure "c". It should only be called after afs_tf_init(),
1088 * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1089 * well, 0 is returned. Possible error codes are:
1091 * TKT_FIL_INI - afs_tf_init wasn't called first
1092 * TKT_FIL_FMT - bad format
1093 * EOF - end of file encountered
1096 afs_tf_get_cred(principal, token)
1097 struct ktc_principal *principal;
1098 struct ktc_token *token;
1106 if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1109 case 1: /* can't be just a null */
1114 if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1121 if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1124 case 1: /* can't be just a null */
1129 lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1131 tf_read((char *) &(token->sessionKey), 8) < 1 ||
1132 tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1133 tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1134 tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1136 /* don't try to read a silly amount into ticket->dat */
1137 token->ticketLen > MAXKTCTICKETLEN ||
1138 tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1139 tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1143 token->endTime = life_to_time(token->startTime, lifetime);
1149 * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1150 * not a valid file descriptor, it just returns. It also clears the
1151 * buffer used to read tickets.
1153 * The return value is not defined.
1159 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1160 (void) fcntl(fd, F_SETLK, &fileUlock);
1162 (void) flock(fd, LOCK_UN);
1165 fd = -1; /* see declaration of fd above */
1167 bzero(tfbfr, sizeof(tfbfr));
1171 * tf_gets() is an internal routine. It takes a string "s" and a count
1172 * "n", and reads from the file until either it has read "n" characters,
1173 * or until it reads a null byte. When finished, what has been read exists
1176 * Possible return values are:
1178 * n the number of bytes read (including null terminator)
1179 * when all goes well
1181 * 0 end of file or read error
1183 * TOO_BIG if "count" characters are read and no null is
1184 * encountered. This is an indication that the ticket
1185 * file is seriously ill.
1197 for (count = n - 1; count > 0; --count) {
1198 if (curpos >= sizeof(tfbfr)) {
1199 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1202 if (curpos == lastpos) {
1205 *s = tfbfr[curpos++];
1213 * tf_read() is an internal routine. It takes a string "s" and a count
1214 * "n", and reads from the file until "n" bytes have been read. When
1215 * finished, what has been read exists in "s".
1217 * Possible return values are:
1219 * n the number of bytes read when all goes well
1221 * 0 on end of file or read error
1231 for (count = n; count > 0; --count) {
1232 if (curpos >= sizeof(tfbfr)) {
1233 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1236 if (curpos == lastpos) {
1239 *s++ = tfbfr[curpos++];
1247 * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1248 * file. You must call afs_tf_init() before calling afs_tf_save_cred().
1250 * The "service", "instance", and "realm" arguments specify the
1251 * server's name; "aticket" contains the credential.
1253 * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1254 * called previously, and KFAILURE for anything else that went wrong.
1257 afs_tf_save_cred(aserver, atoken, aclient)
1258 struct ktc_principal *aserver;
1259 struct ktc_principal *aclient;
1260 struct ktc_token *atoken; /* Token */
1262 char realm[MAXKTCREALMLEN+1];
1263 char junk[MAXKTCNAMELEN];
1264 struct ktc_principal principal;
1265 struct ktc_token token;
1267 off_t start, lseek();
1269 int count; /* count for write */
1271 if (fd < 0) { /* fd is ticket file as set by afs_tf_init */
1275 ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1276 realm[MAXKTCREALMLEN] = '\0';
1278 /* Look for a duplicate ticket */
1279 (void) lseek(fd, (off_t) 0L, 0);
1280 curpos = sizeof(tfbfr);
1282 if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1283 afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1286 start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1287 status = afs_tf_get_cred(&principal, &token);
1288 } while (status == 0 &&
1289 (strcmp(aserver->name, principal.name) != 0 ||
1290 strcmp(aserver->instance, principal.instance) != 0 ||
1291 strcmp(aserver->cell, principal.cell) != 0));
1294 * Two tickets for the same user authenticating to the same service
1295 * should be the same length, but we check here just to make sure.
1297 if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1298 if (status && status != EOF) return status;
1300 /* Position over the credential we just matched (or the EOF) */
1301 lseek(fd, start, 0);
1302 curpos = lastpos = sizeof(tfbfr);
1304 /* Write the ticket and associated data */
1306 count = strlen(aserver->name) + 1;
1307 if (write(fd, aserver->name, count) != count)
1310 count = strlen(aserver->instance) + 1;
1311 if (write(fd, aserver->instance, count) != count)
1314 count = strlen(realm) + 1;
1315 if (write(fd, realm, count) != count)
1318 if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1321 lifetime = time_to_life(atoken->startTime, atoken->endTime);
1322 if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1325 kvno = atoken->kvno;
1326 if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1329 if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1333 count = atoken->ticketLen;
1334 if (write(fd, atoken->ticket, count) != count)
1337 if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1338 != sizeof(afs_int32))
1341 /* Actually, we should check each write for success */
1348 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1351 * For copying and distribution information, please see the file
1352 * <mit-copyright.h>.
1358 * This routine is used to generate the name of the file that holds
1359 * the user's cache of server tickets and associated session keys.
1361 * If it is set, krb_ticket_string contains the ticket file name.
1362 * Otherwise, the filename is constructed as follows:
1364 * If it is set, the environment variable "KRBTKFILE" will be used as
1365 * the ticket file name. Otherwise TKT_ROOT (defined in "krb.h") and
1366 * the user's uid are concatenated to produce the ticket file name
1367 * (e.g., "/tmp/tkt123"). A pointer to the string containing the ticket
1368 * file name is returned.
1371 static char krb_ticket_string[4096] = "";
1373 char *ktc_tkt_string()
1378 if (!*krb_ticket_string) {
1379 if (env = getenv("KRBTKFILE")) {
1380 (void) strncpy(krb_ticket_string, env,
1381 sizeof(krb_ticket_string)-1);
1382 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1384 /* 32 bits of signed integer will always fit in 11 characters
1385 (including the sign), so no need to worry about overflow */
1386 (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1390 return krb_ticket_string;
1394 * This routine is used to set the name of the file that holds the user's
1395 * cache of server tickets and associated session keys.
1397 * The value passed in is copied into local storage.
1399 * NOTE: This routine should be called during initialization, before other
1400 * Kerberos routines are called; otherwise tkt_string() above may be called
1401 * and return an undesired ticket file name until this routine is called.
1405 ktc_set_tkt_string(val)
1410 (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1411 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1418 * tf_create() is used to initialize the ticket store. It creates the
1419 * file to contain the tickets and writes the given user's name "pname"
1420 * and instance "pinst" in the file. in_tkt() returns KSUCCESS on
1421 * success, or KFAILURE if something goes wrong.
1424 afs_tf_create(pname,pinst)
1431 char *file = ktc_tkt_string();
1440 if (lstat(file,&sbuf) == 0) {
1441 if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1442 sbuf.st_mode & 077) {
1445 /* file already exists, and permissions appear ok, so nuke it */
1446 if ((fd = open(file, O_RDWR, 0)) < 0)
1447 goto out; /* can't zero it, but we can still try truncating it */
1449 bzero(zerobuf, sizeof(zerobuf));
1451 for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1452 if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1463 /* arrange so the file is owned by the ruid
1464 (swap real & effective uid if necessary).
1465 This isn't a security problem, since the ticket file, if it already
1466 exists, has the right uid (== ruid) and mode. */
1468 if (setreuid(metoo, me) < 0) {
1472 tktfile = creat(file, 0600);
1474 if (setreuid(me, metoo) < 0) {
1475 /* can't switch??? fail! */
1482 count = strlen(pname)+1;
1483 if (write(tktfile,pname,count) != count) {
1484 (void) close(tktfile);
1487 count = strlen(pinst)+1;
1488 if (write(tktfile,pinst,count) != count) {
1489 (void) close(tktfile);
1492 (void) close(tktfile);
1497 * dest_tkt() is used to destroy the ticket store upon logout.
1498 * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1499 * Otherwise the function returns 0 on success, KFAILURE on
1505 char *file = ktc_tkt_string();
1511 if (lstat(file,&statb) < 0)
1514 if (!(statb.st_mode & S_IFREG))
1517 if ((fd = open(file, O_RDWR, 0)) < 0)
1522 for (i = 0; i < statb.st_size; i += BUFSIZ)
1523 if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1532 (void) unlink(file);
1535 if (errno == ENOENT) return RET_TKFIL;
1536 else if (errno != 0) return KFAILURE;
1540 static afs_uint32 curpag()
1542 gid_t groups[NGROUPS_MAX];
1544 afs_uint32 h, l, ret;
1546 if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1548 g0 = groups[0] & 0xffff;
1549 g1 = groups[1] & 0xffff;
1552 if (g0 < 0xc000 && g1 < 0xc000) {
1553 l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1555 h = (g1 >> 14) + h + h + h;
1556 ret = ((h << 28) | l);
1557 /* Additional testing */
1558 if (((ret >> 24) & 0xff) == 'A')
1569 extern char **environ;
1573 char fname[256], *prefix = "/ticket/";
1575 char **newenv, **senv, **denv;
1578 if (stat("/ticket", &sbuf) == -1) {
1579 prefix = "/tmp/tkt";
1582 pag = curpag() & 0xffffffff;
1584 sprintf(fname, "%s%d", prefix, getuid());
1587 sprintf(fname, "%sp%ld", prefix, pag);
1589 ktc_set_tkt_string(fname);
1591 for (senv=environ, numenv=0; *senv; senv++) numenv++;
1592 newenv = (char **)malloc((numenv+2) * sizeof(char *));
1594 for (senv=environ, denv=newenv; *senv; *senv++) {
1595 if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1598 *denv = (char *)malloc(10 + strlen(fname) + 1);
1599 strcpy(*denv, "KRBTKFILE=");
1600 strcat(*denv, fname);
1607 * BLETCH! We have to invoke the entire afsconf package just to
1608 * find out what the local cell is.
1610 static ktc_LocalCell()
1613 struct afsconf_dir *conf;
1615 if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1616 (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1617 code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1618 afsconf_Close (conf);
1620 if (!conf || code) {
1621 printf("** Can't determine local cell name!\n");