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 */
14 #include "../afs/param.h"
15 #include "../afs/sysincludes.h"
16 #include "../afs/afsincludes.h"
17 #include "../afs/stds.h"
18 #include "../afs/pthread_glock.h"
19 #include "../afs/vice.h"
20 #include "../afs/auth.h"
21 #include "../afs/venus.h"
22 #include "../afs/pthread_glock.h"
23 #include "../afs/dirpath.h"
26 #define min(a,b) ((a)<(b)?(a):(b))
27 #endif /* !defined(min) */
29 #else /* defined(UKERNEL) */
34 #include <afs/param.h>
37 #include <afs/pthread_glock.h>
38 #include <sys/types.h>
43 #include <sys/ioctl.h>
44 #include <netinet/in.h>
47 #include <sys/lockf.h>
50 #include <afs/venus.h>
51 #include <afs/afsutil.h>
53 #endif /* defined(UKERNEL) */
60 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
61 #define AFS_KERBEROS_ENV
64 #ifdef AFS_KERBEROS_ENV
67 extern afs_uint32 life_to_time();
68 extern unsigned char time_to_life();
69 #include "cellconfig.h"
70 static char lcell[MAXCELLCHARS];
72 #define TKT_ROOT "/tmp/tkt"
77 /* Definitions for ticket file utilities */
81 /* Error codes returned by ticket file utilities */
82 #define NO_TKT_FIL 76 /* No ticket file found */
83 #define TKT_FIL_ACC 77 /* Couldn't access tkt file */
84 #define TKT_FIL_LCK 78 /* Couldn't lock ticket file */
85 #define TKT_FIL_FMT 79 /* Bad ticket file format */
86 #define TKT_FIL_INI 80 /* afs_tf_init not called first */
88 /* Values returned by get_credentials */
89 #define RET_TKFIL 21 /* Can't read ticket file */
98 #if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
99 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
100 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
101 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
104 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
105 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
106 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
113 /* the following routines aren't static anymore on behalf of the kerberos IV
114 * compatibility library built in subtree krb.
116 int afs_tf_init(), afs_tf_get_pname(), afs_tf_get_pinst(), afs_tf_get_cred();
117 int afs_tf_save_cred(), afs_tf_close(), afs_tf_create();
118 int afs_tf_dest_tkt(), ktc_LocalCell();
119 char *ktc_tkt_string();
120 #endif /* AFS_KERBEROS_ENV */
123 #define PIOCTL afs_pioctl
124 #elif defined(UKERNEL)
125 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
127 #define PIOCTL pioctl
131 #ifdef KERNEL_KTC_COMPAT
133 /* In case there is no include file. */
137 #define KTC_SYSCALL 32
140 /* Kernel call opcode definitions */
141 #define KTC_OPCODE_BASE 4300
142 #define KTC_NO_OP (0+KTC_OPCODE_BASE)
143 #define KTC_SETTOKEN_OP (1+KTC_OPCODE_BASE)
144 #define KTC_GETTOKEN_OP (2+KTC_OPCODE_BASE)
145 #define KTC_LISTTOKENS_OP (3+KTC_OPCODE_BASE)
146 #define KTC_FORGETTOKEN_OP (4+KTC_OPCODE_BASE)
147 #define KTC_FORGETALLTOKENS_OP (5+KTC_OPCODE_BASE)
148 #define KTC_STATUS_OP (6+KTC_OPCODE_BASE)
149 #define KTC_GC_OP (7+KTC_OPCODE_BASE)
151 #define KTC_INTERFACE_VERSION 3
157 /* We have to determine if the kernel supports the ktc system call. To do so
158 * we attempt to execute its noop function. If this is successful we use the
159 * kernel calls in the future otherwise we let the old code run. */
161 /* To safely check to see whether a system call exists we have to intercept the
162 * SIGSYS signal which is caused by executing a non-existant system call. If
163 * it is ignored the syscall routine returns EINVAL. The SIGSYS is reset to
164 * its old value after the return from syscall. */
166 static int kernelKTC = 0;
168 #ifdef AFS_DECOSF_ENV
170 * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems. You need
171 * to ignore SIGTRAP too. It is claimed to be fixed under v1.3, but...
174 #define CHECK_KERNEL \
175 if (kernelKTC == 0) { \
179 old = (int (*)())signal(SIGSYS, SIG_IGN); \
180 old_t = (int (*)())signal(SIGTRAP, SIG_IGN); \
181 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
183 signal(SIGSYS, old); \
184 signal(SIGTRAP, old_t); \
185 if (code == 0) kernelKTC = 1; \
186 else kernelKTC = 2; \
187 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
190 #else /* AFS_DECOSF_ENV */
192 #define CHECK_KERNEL \
193 if (kernelKTC == 0) { \
196 old = (int (*)())signal(SIGSYS, SIG_IGN); \
197 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
199 signal(SIGSYS, old); \
200 if (code == 0) kernelKTC = 1; \
201 else kernelKTC = 2; \
202 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
204 #endif /* AFS_DECOSF_ENV */
206 #define TRY_KERNEL(cmd,a1,a2,a3,a4) \
208 if (kernelKTC == 1) \
209 return syscall (KTC_SYSCALL, cmd, \
210 KTC_INTERFACE_VERSION, a1,a2,a3,a4); \
214 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
215 #endif /* KERNEL_KTC_COMPAT */
217 #if !defined(UKERNEL)
218 /* this is a structure used to communicate with the afs cache mgr, but is
219 * otherwise irrelevant */
221 afs_int32 AuthHandle;
222 char HandShakeKey[8];
224 afs_int32 BeginTimestamp;
225 afs_int32 EndTimestamp;
227 #endif /* !defined(UKERNEL) */
229 #define MAXLOCALTOKENS 4
233 struct ktc_principal server;
234 struct ktc_principal client;
235 struct ktc_token token;
236 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
238 /* new interface routines to the ticket cache. Only handle afs service right
241 static int NewSetToken (aserver, atoken, aclient, flags)
242 struct ktc_principal *aserver;
243 struct ktc_principal *aclient;
244 struct ktc_token *atoken;
247 TRY_KERNEL (KTC_SETTOKEN_OP,
248 aserver, aclient, atoken, sizeof(struct ktc_token));
249 /* no kernel ticket cache */
253 static int OldSetToken (aserver, atoken, aclient, flags)
254 struct ktc_principal *aserver, *aclient;
255 struct ktc_token *atoken;
258 struct ViceIoctl iob;
261 struct ClearToken ct;
262 register afs_int32 code;
265 if (strcmp(aserver->name, "afs") != 0) {
268 for (i=0; i<MAXLOCALTOKENS; i++)
269 if (local_tokens[i].valid) {
270 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
271 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
272 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
273 found = i; /* replace existing entry */
276 else /* valid, but no match */ ;
277 } else found = i; /* remember this empty slot */
278 if (found == -1) return KTC_NOENT;
279 bcopy (atoken, &local_tokens[found].token, sizeof(struct ktc_token));
280 local_tokens[found].server = *aserver;
281 local_tokens[found].client = *aclient;
282 local_tokens[found].valid = 1;
285 tp = tbuffer; /* start copying here */
286 if ((atoken->ticketLen < MINKTCTICKETLEN) ||
287 (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
288 bcopy(&atoken->ticketLen, tp, sizeof(afs_int32)); /* copy in ticket length */
289 tp += sizeof(afs_int32);
290 bcopy(atoken->ticket, tp, atoken->ticketLen); /* copy in ticket */
291 tp += atoken->ticketLen;
292 /* next, copy in the "clear token", describing who we are */
293 ct.AuthHandle = atoken->kvno; /* hide auth handle here */
294 bcopy(&atoken->sessionKey, ct.HandShakeKey, 8);
296 ct.BeginTimestamp = atoken->startTime;
297 ct.EndTimestamp = atoken->endTime;
298 if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
300 if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
301 (aclient->instance[0] == 0)) {
303 afs_int32 viceId = 0;
304 char *cp = aclient->name + strlen ("AFS ID ");
305 if (*cp == '-') { sign = -1; cp++; }
307 if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
308 else goto not_vice_id;
311 ct.ViceId = viceId * sign; /* OK to let any value here? */
312 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
313 ct.BeginTimestamp++; /* force lifetime to be odd */
316 ct.ViceId = getuid(); /* wrong, but works in primary cell */
317 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
318 ct.BeginTimestamp++; /* force lifetime to be even */
323 * Information needed by the user space cache manager
325 u.u_expiration = ct.EndTimestamp;
326 u.u_viceid = ct.ViceId;
329 temp = sizeof(struct ClearToken);
330 bcopy(&temp, tp, sizeof(afs_int32));
331 tp += sizeof(afs_int32);
332 bcopy(&ct, tp, sizeof(struct ClearToken));
333 tp += sizeof(struct ClearToken);
335 /* next copy in primary flag */
339 * The following means that setpag will happen inside afs just before
340 * the authentication to prevent the setpag/klog race condition.
342 * The following means that setpag will affect the parent process as
343 * well as the current process.
345 if (flags & AFS_SETTOK_SETPAG)
348 bcopy(&temp, tp, sizeof(afs_int32));
349 tp += sizeof(afs_int32);
351 /* finally copy in the cell name */
352 temp = strlen(aserver->cell);
353 if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
354 strcpy(tp, aserver->cell);
357 /* now setup for the pioctl */
359 iob.in_size = tp-tbuffer;
361 iob.out_size = sizeof(tbuffer);
363 #if defined(NO_AFS_CLIENT)
364 { int fd; /* DEBUG */
366 if ((tkfile=getenv("TKTFILE")) &&
367 ((fd=open(tkfile, O_WRONLY|O_APPEND|O_TRUNC|O_CREAT, 0644)) >= 0)) {
368 printf("Writing ticket to: %s\n", tkfile);
369 code = (write(fd, iob.in, iob.in_size) != iob.in_size);
373 code = KTC_PIOCTLFAIL;
375 #else /* NO_AFS_CLIENT */
376 code = PIOCTL(0, VIOCSETTOK, &iob, 0);
377 #endif /* NO_AFS_CLIENT */
378 if (code) return KTC_PIOCTLFAIL;
383 ktc_SetToken (aserver, atoken, aclient, flags)
384 struct ktc_principal *aserver;
385 struct ktc_principal *aclient;
386 struct ktc_token *atoken;
392 #ifdef AFS_KERBEROS_ENV
393 if (!lcell[0]) ktc_LocalCell();
395 if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
396 (strcmp(aserver->name, "AuthServer") ||
397 strcmp(aserver->instance, "Admin"))){
398 if (strcmp(aserver->name, "krbtgt") == 0) {
399 static char lrealm[MAXKTCREALMLEN];
401 if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
402 if (strcmp(aserver->instance, lrealm) == 0) {
403 afs_tf_create(aclient->name, aclient->instance);
407 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
408 if (ncode == NO_TKT_FIL) {
409 (void) afs_tf_create(aclient->name, aclient->instance);
410 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
414 afs_tf_save_cred(aserver, atoken, aclient);
420 #endif /* NO_AFS_CLIENT */
424 #ifndef NO_AFS_CLIENT
425 ncode = NewSetToken (aserver, atoken, aclient, flags);
426 if (ncode || /* new style failed */
427 (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
428 ocode = OldSetToken (aserver, atoken, aclient, flags);
430 if (ncode && ocode) {
432 if (ocode == -1) ocode = errno;
433 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
434 if (ocode == ESRCH) return KTC_NOCELL;
435 if (ocode == EINVAL) return KTC_NOPIOCTL;
436 if (ocode == EIO) return KTC_NOCM;
437 return KTC_PIOCTLFAIL;
439 #endif /* NO_AFS_CLIENT */
444 /* get token, given server we need and token buffer. aclient will eventually
445 * be set to our identity to the server.
447 ktc_GetToken(aserver, atoken, atokenLen, aclient)
448 struct ktc_principal *aserver, *aclient;
450 struct ktc_token *atoken; {
451 struct ViceIoctl iob;
453 register afs_int32 code;
455 char *stp, *cellp; /* secret token ptr */
456 struct ClearToken ct;
459 int maxLen; /* biggest ticket we can copy */
460 int tktLen; /* server ticket length */
464 #ifndef NO_AFS_CLIENT
465 TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
466 #endif /* NO_AFS_CLIENT */
468 #ifdef AFS_KERBEROS_ENV
469 if (!lcell[0]) ktc_LocalCell();
471 #ifndef NO_AFS_CLIENT
472 if (strcmp(aserver->name, "afs") != 0)
473 #endif /* NO_AFS_CLIENT */
476 /* try the local tokens */
477 for (i=0; i<MAXLOCALTOKENS; i++)
478 if (local_tokens[i].valid &&
479 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
480 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
481 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
482 bcopy (&local_tokens[i].token, atoken, min (atokenLen, sizeof(struct ktc_token)));
484 *aclient = local_tokens[i].client;
488 #ifdef AFS_KERBEROS_ENV
489 if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
491 if (!afs_tf_get_pname(aclient->name) &&
492 !afs_tf_get_pinst(aclient->instance))
495 char tmpstring[MAXHOSTCHARS];
496 afs_tf_get_pname(&tmpstring);
497 afs_tf_get_pinst(&tmpstring);
502 struct ktc_principal cprincipal;
503 struct ktc_token ctoken;
505 while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
506 if (strcmp(cprincipal.name, aserver->name) == 0 &&
507 strcmp(cprincipal.instance, aserver->instance) == 0 &&
508 strcmp(cprincipal.cell, aserver->cell) == 0) {
511 strcpy(aclient->cell, lcell);
512 bcopy(&ctoken, atoken,
513 min (atokenLen, sizeof(struct ktc_token)));
527 #ifndef NO_AFS_CLIENT
528 for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
529 iob.in = (char *) &index;
530 iob.in_size = sizeof(afs_int32);
532 iob.out_size = sizeof(tbuffer);
534 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
537 /* failed to retrieve specified token */
538 if (code < 0 && errno == EDOM) {
543 /* token retrieved; parse buffer */
546 /* get ticket length */
547 memcpy(&temp, tp, sizeof(afs_int32));
549 tp += sizeof(afs_int32);
551 /* remember where ticket is and skip over it */
555 /* get size of clear token and verify */
556 memcpy(&temp, tp, sizeof(afs_int32));
557 if (temp != sizeof(struct ClearToken)) {
561 tp += sizeof(afs_int32);
563 /* copy clear token */
564 memcpy(&ct, tp, temp);
567 /* skip over primary flag */
568 tp += sizeof(afs_int32);
570 /* remember where cell name is */
573 if ((strcmp(cellp, aserver->cell) == 0)
574 #ifdef AFS_KERBEROS_ENV
575 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
578 /* got token for cell; check that it will fit */
579 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
580 if (maxLen < tktLen) {
585 /* set return values */
586 memcpy(atoken->ticket, stp, tktLen);
587 atoken->startTime = ct.BeginTimestamp;
588 atoken->endTime = ct.EndTimestamp;
589 if (ct.AuthHandle == -1) {
592 atoken->kvno = ct.AuthHandle;
593 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
594 atoken->ticketLen = tktLen;
597 strcpy(aclient->cell, cellp);
598 aclient->instance[0] = 0;
600 if ((atoken->kvno == 999) || /* old style bcrypt ticket */
601 (ct.BeginTimestamp && /* new w/ prserver lookup */
602 (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
603 sprintf(aclient->name, "AFS ID %d", ct.ViceId);
605 sprintf(aclient->name, "Unix UID %d", ct.ViceId);
613 #endif /* NO_AFS_CLIENT */
616 if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
617 return KTC_PIOCTLFAIL; /* probable cause */
621 * Forget tokens for this server and the calling user.
622 * NOT IMPLEMENTED YET!
624 #ifndef NO_AFS_CLIENT
625 ktc_ForgetToken(aserver)
626 struct ktc_principal *aserver; {
630 TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
632 rc = ktc_ForgetAllTokens(); /* bogus, but better */
636 #endif /* NO_AFS_CLIENT */
638 /* ktc_ListTokens - list all tokens. start aprevIndex at 0, it returns the
639 * next rock in (*aindex). (*aserver) is set to the relevant ticket on
642 ktc_ListTokens(aprevIndex, aindex, aserver)
643 int aprevIndex, *aindex;
644 struct ktc_principal *aserver; {
645 struct ViceIoctl iob;
647 register afs_int32 code;
649 afs_int32 temp, index;
652 #ifndef NO_AFS_CLIENT
653 TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
654 #endif /* NO_AFS_CLIENT */
658 if (index < 214) index = 214;
659 #endif /* NO_AFS_CLIENT */
660 #ifdef AFS_KERBEROS_ENV
663 struct ktc_principal cprincipal;
664 struct ktc_token ctoken;
666 if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL) ||
667 afs_tf_get_pname(tbuffer) ||
668 afs_tf_get_pinst(tbuffer)) {
674 for (i=214; i<index; i++) {
675 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
683 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
690 #ifndef NO_AFS_CLIENT
691 if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
694 #endif /* NO_AFS_CLIENT */
696 for (i=0; i < MAXLOCALTOKENS; i++) {
697 if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
698 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
699 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
704 *aserver = cprincipal;
712 #ifndef NO_AFS_CLIENT
713 if (index >= 123) { /* special hack for returning TCS */
714 while (index-123 < MAXLOCALTOKENS) {
715 if (local_tokens[index-123].valid) {
716 *aserver = local_tokens[index-123].server;
724 #ifdef AFS_KERBEROS_ENV
725 return ktc_ListTokens(214, aindex, aserver);
731 /* get tokens from the kernel */
732 while (index<200) { /* sanity check in case pioctl fails */
733 iob.in = (char *) &index;
734 iob.in_size = sizeof(afs_int32);
736 iob.out_size = sizeof(tbuffer);
737 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
738 if (code < 0 && errno == EDOM) {
741 rc = ktc_ListTokens (123, aindex, aserver);
750 if (code == 0) break; /* got a ticket */
751 /* otherwise we should skip this ticket slot */
756 if (errno == EINVAL) return KTC_NOPIOCTL;
757 return KTC_PIOCTLFAIL;
763 /* next iterator determined by earlier loop */
766 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of secret token */
767 tp += sizeof(afs_int32);
768 tp += temp; /* skip ticket for now */
769 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of clear token */
770 if (temp != sizeof(struct ClearToken)) {
774 tp += sizeof(afs_int32); /* skip length */
775 tp += temp; /* skip clear token itself */
776 tp += sizeof(afs_int32); /* skip primary flag */
777 /* tp now points to the cell name */
778 strcpy(aserver->cell, tp);
779 aserver->instance[0] = 0;
780 strcpy(aserver->name, "afs");
781 #endif /* NO_AFS_CLIENT */
786 /* discard all tokens from this user's cache */
788 static int NewForgetAll ()
790 #ifndef NO_AFS_CLIENT
791 TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
792 #endif /* NO_AFS_CLIENT */
796 static int OldForgetAll ()
798 struct ViceIoctl iob;
799 register afs_int32 code;
802 for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
808 #ifndef NO_AFS_CLIENT
809 code = PIOCTL(0, VIOCUNPAG, &iob, 0);
810 if (code) return KTC_PIOCTLFAIL;
811 #endif /* NO_AFS_CLIENT */
815 int ktc_ForgetAllTokens()
820 #ifdef AFS_KERBEROS_ENV
821 (void) afs_tf_dest_tkt();
824 ncode = NewForgetAll ();
825 ocode = OldForgetAll ();
826 if (ncode && ocode) {
827 if (ocode == -1) ocode = errno;
828 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
830 if (ocode == EINVAL) return KTC_NOPIOCTL;
831 return KTC_PIOCTLFAIL;
837 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
838 * pioctl interface for delivering AFS tickets to the cache manager. */
844 #ifdef KERNEL_KTC_COMPAT
846 rc = (kernelKTC != 1); /* old style interface */
855 #ifdef AFS_KERBEROS_ENV
857 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
859 * For copying and distribution information, please see the file
866 #include <sys/types.h>
867 #include <sys/stat.h>
868 #include <sys/file.h>
873 #define TF_LCK_RETRY ((unsigned)2) /* seconds to sleep before
874 * retry if ticket file is
878 * fd must be initialized to something that won't ever occur as a real
879 * file descriptor. Since open(2) returns only non-negative numbers as
880 * valid file descriptors, and afs_tf_init always stuffs the return value
881 * from open in here even if it is an error flag, we must
882 * a. Initialize fd to a negative number, to indicate that it is
883 * not initially valid.
884 * b. When checking for a valid fd, assume that negative values
885 * are invalid (ie. when deciding whether afs_tf_init has been
887 * c. In tf_close, be sure it gets reinitialized to a negative
891 static curpos; /* Position in tfbfr */
892 static lastpos; /* End of tfbfr */
893 static char tfbfr[BUFSIZ]; /* Buffer for ticket data */
895 static tf_gets(), tf_read();
898 * This file contains routines for manipulating the ticket cache file.
900 * The ticket file is in the following format:
902 * principal's name (null-terminated string)
903 * principal's instance (null-terminated string)
910 * Where "CREDENTIAL_x" consists of the following fixed-length
911 * fields from the CREDENTIALS structure (see "krb.h"):
913 * char service[MAXKTCNAMELEN]
914 * char instance[MAXKTCNAMELEN]
915 * char realm[REALM_SZ]
920 * afs_int32 issue_date
922 * Short description of routines:
924 * afs_tf_init() opens the ticket file and locks it.
926 * afs_tf_get_pname() returns the principal's name.
928 * afs_tf_get_pinst() returns the principal's instance (may be null).
930 * afs_tf_get_cred() returns the next CREDENTIALS record.
932 * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
934 * afs_tf_close() closes the ticket file and releases the lock.
936 * tf_gets() returns the next null-terminated string. It's an internal
937 * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
940 * tf_read() reads a given number of bytes. It's an internal routine
941 * used by afs_tf_get_cred().
945 * afs_tf_init() should be called before the other ticket file routines.
946 * It takes the name of the ticket file to use, "tf_name", and a
947 * read/write flag "rw" as arguments.
949 * It tries to open the ticket file, checks the mode, and if everything
950 * is okay, locks the file. If it's opened for reading, the lock is
951 * shared. If it's opened for writing, the lock is exclusive.
953 * Returns 0 if all went well, otherwise one of the following:
955 * NO_TKT_FIL - file wasn't there
956 * TKT_FIL_ACC - file was in wrong mode, etc.
957 * TKT_FIL_LCK - couldn't lock the file, even after a retry
960 afs_tf_init(tf_name, rw)
965 struct stat stat_buf;
977 if (lstat(tf_name, &stat_buf) < 0)
985 if ((stat_buf.st_uid != me && me != 0) ||
986 ((stat_buf.st_mode & S_IFMT) != S_IFREG))
990 * If "wflag" is set, open the ticket file in append-writeonly mode
991 * and lock the ticket file in exclusive mode. If unable to lock
992 * the file, sleep and try again. If we fail again, return with the
993 * proper error message.
996 curpos = sizeof(tfbfr);
999 fd = open(tf_name, O_RDWR, 0600);
1003 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1004 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1005 sleep(TF_LCK_RETRY);
1006 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1008 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1009 sleep(TF_LCK_RETRY);
1010 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1020 * Otherwise "wflag" is not set and the ticket file should be opened
1021 * for read-only operations and locked for shared access.
1024 fd = open(tf_name, O_RDONLY, 0600);
1028 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1029 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1030 sleep(TF_LCK_RETRY);
1031 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1033 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1034 sleep(TF_LCK_RETRY);
1035 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1046 * afs_tf_get_pname() reads the principal's name from the ticket file. It
1047 * should only be called after afs_tf_init() has been called. The
1048 * principal's name is filled into the "p" parameter. If all goes well,
1049 * 0 is returned. If afs_tf_init() wasn't called, TKT_FIL_INI is
1050 * returned. If the name was null, or EOF was encountered, or the name
1051 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1060 if (tf_gets(p, MAXKTCNAMELEN) < 2) /* can't be just a null */
1066 * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1067 * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1068 * been called. The instance is filled into the "inst" parameter. If all
1069 * goes well, 0 is returned. If afs_tf_init() wasn't called,
1070 * TKT_FIL_INI is returned. If EOF was encountered, or the instance
1071 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. Note that the
1072 * instance may be null.
1075 afs_tf_get_pinst(inst)
1081 if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1087 * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1088 * in the given structure "c". It should only be called after afs_tf_init(),
1089 * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1090 * well, 0 is returned. Possible error codes are:
1092 * TKT_FIL_INI - afs_tf_init wasn't called first
1093 * TKT_FIL_FMT - bad format
1094 * EOF - end of file encountered
1097 afs_tf_get_cred(principal, token)
1098 struct ktc_principal *principal;
1099 struct ktc_token *token;
1107 if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1110 case 1: /* can't be just a null */
1115 if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1122 if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1125 case 1: /* can't be just a null */
1130 lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1132 tf_read((char *) &(token->sessionKey), 8) < 1 ||
1133 tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1134 tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1135 tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1137 /* don't try to read a silly amount into ticket->dat */
1138 token->ticketLen > MAXKTCTICKETLEN ||
1139 tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1140 tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1144 token->endTime = life_to_time(token->startTime, lifetime);
1150 * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1151 * not a valid file descriptor, it just returns. It also clears the
1152 * buffer used to read tickets.
1154 * The return value is not defined.
1160 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1161 (void) fcntl(fd, F_SETLK, &fileUlock);
1163 (void) flock(fd, LOCK_UN);
1166 fd = -1; /* see declaration of fd above */
1168 bzero(tfbfr, sizeof(tfbfr));
1172 * tf_gets() is an internal routine. It takes a string "s" and a count
1173 * "n", and reads from the file until either it has read "n" characters,
1174 * or until it reads a null byte. When finished, what has been read exists
1177 * Possible return values are:
1179 * n the number of bytes read (including null terminator)
1180 * when all goes well
1182 * 0 end of file or read error
1184 * TOO_BIG if "count" characters are read and no null is
1185 * encountered. This is an indication that the ticket
1186 * file is seriously ill.
1198 for (count = n - 1; count > 0; --count) {
1199 if (curpos >= sizeof(tfbfr)) {
1200 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1203 if (curpos == lastpos) {
1206 *s = tfbfr[curpos++];
1214 * tf_read() is an internal routine. It takes a string "s" and a count
1215 * "n", and reads from the file until "n" bytes have been read. When
1216 * finished, what has been read exists in "s".
1218 * Possible return values are:
1220 * n the number of bytes read when all goes well
1222 * 0 on end of file or read error
1232 for (count = n; count > 0; --count) {
1233 if (curpos >= sizeof(tfbfr)) {
1234 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1237 if (curpos == lastpos) {
1240 *s++ = tfbfr[curpos++];
1248 * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1249 * file. You must call afs_tf_init() before calling afs_tf_save_cred().
1251 * The "service", "instance", and "realm" arguments specify the
1252 * server's name; "aticket" contains the credential.
1254 * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1255 * called previously, and KFAILURE for anything else that went wrong.
1258 afs_tf_save_cred(aserver, atoken, aclient)
1259 struct ktc_principal *aserver;
1260 struct ktc_principal *aclient;
1261 struct ktc_token *atoken; /* Token */
1263 char realm[MAXKTCREALMLEN+1];
1264 char junk[MAXKTCNAMELEN];
1265 struct ktc_principal principal;
1266 struct ktc_token token;
1268 off_t start, lseek();
1270 int count; /* count for write */
1272 if (fd < 0) { /* fd is ticket file as set by afs_tf_init */
1276 ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1277 realm[MAXKTCREALMLEN] = '\0';
1279 /* Look for a duplicate ticket */
1280 (void) lseek(fd, (off_t) 0L, 0);
1281 curpos = sizeof(tfbfr);
1283 if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1284 afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1287 start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1288 status = afs_tf_get_cred(&principal, &token);
1289 } while (status == 0 &&
1290 (strcmp(aserver->name, principal.name) != 0 ||
1291 strcmp(aserver->instance, principal.instance) != 0 ||
1292 strcmp(aserver->cell, principal.cell) != 0));
1295 * Two tickets for the same user authenticating to the same service
1296 * should be the same length, but we check here just to make sure.
1298 if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1299 if (status && status != EOF) return status;
1301 /* Position over the credential we just matched (or the EOF) */
1302 lseek(fd, start, 0);
1303 curpos = lastpos = sizeof(tfbfr);
1305 /* Write the ticket and associated data */
1307 count = strlen(aserver->name) + 1;
1308 if (write(fd, aserver->name, count) != count)
1311 count = strlen(aserver->instance) + 1;
1312 if (write(fd, aserver->instance, count) != count)
1315 count = strlen(realm) + 1;
1316 if (write(fd, realm, count) != count)
1319 if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1322 lifetime = time_to_life(atoken->startTime, atoken->endTime);
1323 if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1326 kvno = atoken->kvno;
1327 if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1330 if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1334 count = atoken->ticketLen;
1335 if (write(fd, atoken->ticket, count) != count)
1338 if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1339 != sizeof(afs_int32))
1342 /* Actually, we should check each write for success */
1349 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1352 * For copying and distribution information, please see the file
1353 * <mit-copyright.h>.
1359 * This routine is used to generate the name of the file that holds
1360 * the user's cache of server tickets and associated session keys.
1362 * If it is set, krb_ticket_string contains the ticket file name.
1363 * Otherwise, the filename is constructed as follows:
1365 * If it is set, the environment variable "KRBTKFILE" will be used as
1366 * the ticket file name. Otherwise TKT_ROOT (defined in "krb.h") and
1367 * the user's uid are concatenated to produce the ticket file name
1368 * (e.g., "/tmp/tkt123"). A pointer to the string containing the ticket
1369 * file name is returned.
1372 static char krb_ticket_string[4096] = "";
1374 char *ktc_tkt_string()
1379 if (!*krb_ticket_string) {
1380 if (env = getenv("KRBTKFILE")) {
1381 (void) strncpy(krb_ticket_string, env,
1382 sizeof(krb_ticket_string)-1);
1383 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1385 /* 32 bits of signed integer will always fit in 11 characters
1386 (including the sign), so no need to worry about overflow */
1387 (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1391 return krb_ticket_string;
1395 * This routine is used to set the name of the file that holds the user's
1396 * cache of server tickets and associated session keys.
1398 * The value passed in is copied into local storage.
1400 * NOTE: This routine should be called during initialization, before other
1401 * Kerberos routines are called; otherwise tkt_string() above may be called
1402 * and return an undesired ticket file name until this routine is called.
1406 ktc_set_tkt_string(val)
1411 (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1412 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1419 * tf_create() is used to initialize the ticket store. It creates the
1420 * file to contain the tickets and writes the given user's name "pname"
1421 * and instance "pinst" in the file. in_tkt() returns KSUCCESS on
1422 * success, or KFAILURE if something goes wrong.
1425 afs_tf_create(pname,pinst)
1432 char *file = ktc_tkt_string();
1441 if (lstat(file,&sbuf) == 0) {
1442 if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1443 sbuf.st_mode & 077) {
1446 /* file already exists, and permissions appear ok, so nuke it */
1447 if ((fd = open(file, O_RDWR, 0)) < 0)
1448 goto out; /* can't zero it, but we can still try truncating it */
1450 bzero(zerobuf, sizeof(zerobuf));
1452 for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1453 if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1464 /* arrange so the file is owned by the ruid
1465 (swap real & effective uid if necessary).
1466 This isn't a security problem, since the ticket file, if it already
1467 exists, has the right uid (== ruid) and mode. */
1469 if (setreuid(metoo, me) < 0) {
1473 tktfile = creat(file, 0600);
1475 if (setreuid(me, metoo) < 0) {
1476 /* can't switch??? fail! */
1483 count = strlen(pname)+1;
1484 if (write(tktfile,pname,count) != count) {
1485 (void) close(tktfile);
1488 count = strlen(pinst)+1;
1489 if (write(tktfile,pinst,count) != count) {
1490 (void) close(tktfile);
1493 (void) close(tktfile);
1498 * dest_tkt() is used to destroy the ticket store upon logout.
1499 * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1500 * Otherwise the function returns 0 on success, KFAILURE on
1506 char *file = ktc_tkt_string();
1512 if (lstat(file,&statb) < 0)
1515 if (!(statb.st_mode & S_IFREG))
1518 if ((fd = open(file, O_RDWR, 0)) < 0)
1523 for (i = 0; i < statb.st_size; i += BUFSIZ)
1524 if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1533 (void) unlink(file);
1536 if (errno == ENOENT) return RET_TKFIL;
1537 else if (errno != 0) return KFAILURE;
1541 static afs_uint32 curpag()
1543 gid_t groups[NGROUPS_MAX];
1545 afs_uint32 h, l, ret;
1547 if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1549 g0 = groups[0] & 0xffff;
1550 g1 = groups[1] & 0xffff;
1553 if (g0 < 0xc000 && g1 < 0xc000) {
1554 l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1556 h = (g1 >> 14) + h + h + h;
1557 ret = ((h << 28) | l);
1558 /* Additional testing */
1559 if (((ret >> 24) & 0xff) == 'A')
1570 extern char **environ;
1574 char fname[256], *prefix = "/ticket/";
1576 char **newenv, **senv, **denv;
1579 if (stat("/ticket", &sbuf) == -1) {
1580 prefix = "/tmp/tkt";
1583 pag = curpag() & 0xffffffff;
1585 sprintf(fname, "%s%d", prefix, getuid());
1588 sprintf(fname, "%sp%ld", prefix, pag);
1590 ktc_set_tkt_string(fname);
1592 for (senv=environ, numenv=0; *senv; senv++) numenv++;
1593 newenv = (char **)malloc((numenv+2) * sizeof(char *));
1595 for (senv=environ, denv=newenv; *senv; *senv++) {
1596 if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1599 *denv = (char *)malloc(10 + strlen(fname) + 1);
1600 strcpy(*denv, "KRBTKFILE=");
1601 strcat(*denv, fname);
1608 * BLETCH! We have to invoke the entire afsconf package just to
1609 * find out what the local cell is.
1611 static ktc_LocalCell()
1614 struct afsconf_dir *conf;
1616 if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1617 (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1618 code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1619 afsconf_Close (conf);
1621 if (!conf || code) {
1622 printf("** Can't determine local cell name!\n");