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 "afsincludes.h"
25 #include "afs/pthread_glock.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 #include "cellconfig.h"
84 static char lcell[MAXCELLCHARS];
86 #define TKT_ROOT "/tmp/tkt"
91 /* Definitions for ticket file utilities */
95 /* Error codes returned by ticket file utilities */
96 #define NO_TKT_FIL 76 /* No ticket file found */
97 #define TKT_FIL_ACC 77 /* Couldn't access tkt file */
98 #define TKT_FIL_LCK 78 /* Couldn't lock ticket file */
99 #define TKT_FIL_FMT 79 /* Bad ticket file format */
100 #define TKT_FIL_INI 80 /* afs_tf_init not called first */
102 /* Values returned by get_credentials */
103 #define RET_TKFIL 21 /* Can't read ticket file */
112 #if defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
113 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
114 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
115 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
118 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
119 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
120 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
127 /* the following routines aren't static anymore on behalf of the kerberos IV
128 * compatibility library built in subtree krb.
130 int afs_tf_init(), afs_tf_get_pname(), afs_tf_get_pinst(), afs_tf_get_cred();
131 int afs_tf_save_cred(), afs_tf_close(), afs_tf_create();
132 int afs_tf_dest_tkt(), ktc_LocalCell();
133 char *ktc_tkt_string();
134 #endif /* AFS_KERBEROS_ENV */
137 #define PIOCTL afs_pioctl
138 #elif defined(UKERNEL)
139 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
141 #define PIOCTL pioctl
145 #ifdef KERNEL_KTC_COMPAT
148 #define KTC_SYSCALL 32
151 /* Kernel call opcode definitions */
152 #define KTC_OPCODE_BASE 4300
153 #define KTC_NO_OP (0+KTC_OPCODE_BASE)
154 #define KTC_SETTOKEN_OP (1+KTC_OPCODE_BASE)
155 #define KTC_GETTOKEN_OP (2+KTC_OPCODE_BASE)
156 #define KTC_LISTTOKENS_OP (3+KTC_OPCODE_BASE)
157 #define KTC_FORGETTOKEN_OP (4+KTC_OPCODE_BASE)
158 #define KTC_FORGETALLTOKENS_OP (5+KTC_OPCODE_BASE)
159 #define KTC_STATUS_OP (6+KTC_OPCODE_BASE)
160 #define KTC_GC_OP (7+KTC_OPCODE_BASE)
162 #define KTC_INTERFACE_VERSION 3
164 /* We have to determine if the kernel supports the ktc system call. To do so
165 * we attempt to execute its noop function. If this is successful we use the
166 * kernel calls in the future otherwise we let the old code run. */
168 /* To safely check to see whether a system call exists we have to intercept the
169 * SIGSYS signal which is caused by executing a non-existant system call. If
170 * it is ignored the syscall routine returns EINVAL. The SIGSYS is reset to
171 * its old value after the return from syscall. */
173 static int kernelKTC = 0;
175 #ifdef AFS_DECOSF_ENV
177 * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems. You need
178 * to ignore SIGTRAP too. It is claimed to be fixed under v1.3, but...
181 #define CHECK_KERNEL \
182 if (kernelKTC == 0) { \
186 old = (int (*)())signal(SIGSYS, SIG_IGN); \
187 old_t = (int (*)())signal(SIGTRAP, SIG_IGN); \
188 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
190 signal(SIGSYS, old); \
191 signal(SIGTRAP, old_t); \
192 if (code == 0) kernelKTC = 1; \
193 else kernelKTC = 2; \
194 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
197 #else /* AFS_DECOSF_ENV */
199 #define CHECK_KERNEL \
200 if (kernelKTC == 0) { \
203 old = (int (*)())signal(SIGSYS, SIG_IGN); \
204 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
206 signal(SIGSYS, old); \
207 if (code == 0) kernelKTC = 1; \
208 else kernelKTC = 2; \
209 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
211 #endif /* AFS_DECOSF_ENV */
213 #define TRY_KERNEL(cmd,a1,a2,a3,a4) \
215 if (kernelKTC == 1) \
216 return syscall (KTC_SYSCALL, cmd, \
217 KTC_INTERFACE_VERSION, a1,a2,a3,a4); \
221 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
222 #endif /* KERNEL_KTC_COMPAT */
224 #if !defined(UKERNEL)
225 /* this is a structure used to communicate with the afs cache mgr, but is
226 * otherwise irrelevant */
228 afs_int32 AuthHandle;
229 char HandShakeKey[8];
231 afs_int32 BeginTimestamp;
232 afs_int32 EndTimestamp;
234 #endif /* !defined(UKERNEL) */
236 #define MAXLOCALTOKENS 4
240 struct ktc_principal server;
241 struct ktc_principal client;
242 struct ktc_token token;
243 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
245 /* new interface routines to the ticket cache. Only handle afs service right
248 static int NewSetToken (aserver, atoken, aclient, flags)
249 struct ktc_principal *aserver;
250 struct ktc_principal *aclient;
251 struct ktc_token *atoken;
254 TRY_KERNEL (KTC_SETTOKEN_OP,
255 aserver, aclient, atoken, sizeof(struct ktc_token));
256 /* no kernel ticket cache */
260 static int OldSetToken (aserver, atoken, aclient, flags)
261 struct ktc_principal *aserver, *aclient;
262 struct ktc_token *atoken;
265 struct ViceIoctl iob;
268 struct ClearToken ct;
269 register afs_int32 code;
272 if (strcmp(aserver->name, "afs") != 0) {
275 for (i=0; i<MAXLOCALTOKENS; i++)
276 if (local_tokens[i].valid) {
277 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
278 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
279 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
280 found = i; /* replace existing entry */
283 else /* valid, but no match */ ;
284 } else found = i; /* remember this empty slot */
285 if (found == -1) return KTC_NOENT;
286 memcpy(&local_tokens[found].token, atoken, sizeof(struct ktc_token));
287 local_tokens[found].server = *aserver;
288 local_tokens[found].client = *aclient;
289 local_tokens[found].valid = 1;
292 tp = tbuffer; /* start copying here */
293 if ((atoken->ticketLen < MINKTCTICKETLEN) ||
294 (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
295 memcpy(tp, &atoken->ticketLen, sizeof(afs_int32)); /* copy in ticket length */
296 tp += sizeof(afs_int32);
297 memcpy(tp, atoken->ticket, atoken->ticketLen); /* copy in ticket */
298 tp += atoken->ticketLen;
299 /* next, copy in the "clear token", describing who we are */
300 ct.AuthHandle = atoken->kvno; /* hide auth handle here */
301 memcpy(ct.HandShakeKey, &atoken->sessionKey, 8);
303 ct.BeginTimestamp = atoken->startTime;
304 ct.EndTimestamp = atoken->endTime;
305 if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
307 if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
308 (aclient->instance[0] == 0)) {
310 afs_int32 viceId = 0;
311 char *cp = aclient->name + strlen ("AFS ID ");
312 if (*cp == '-') { sign = -1; cp++; }
314 if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
315 else goto not_vice_id;
318 ct.ViceId = viceId * sign; /* OK to let any value here? */
319 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
320 ct.BeginTimestamp++; /* force lifetime to be odd */
323 ct.ViceId = getuid(); /* wrong, but works in primary cell */
324 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
325 ct.BeginTimestamp++; /* force lifetime to be even */
330 * Information needed by the user space cache manager
332 u.u_expiration = ct.EndTimestamp;
333 u.u_viceid = ct.ViceId;
336 temp = sizeof(struct ClearToken);
337 memcpy(tp, &temp, sizeof(afs_int32));
338 tp += sizeof(afs_int32);
339 memcpy(tp, &ct, sizeof(struct ClearToken));
340 tp += sizeof(struct ClearToken);
342 /* next copy in primary flag */
346 * The following means that setpag will happen inside afs just before
347 * the authentication to prevent the setpag/klog race condition.
349 * The following means that setpag will affect the parent process as
350 * well as the current process.
352 if (flags & AFS_SETTOK_SETPAG)
355 memcpy(tp, &temp, sizeof(afs_int32));
356 tp += sizeof(afs_int32);
358 /* finally copy in the cell name */
359 temp = strlen(aserver->cell);
360 if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
361 strcpy(tp, aserver->cell);
364 /* now setup for the pioctl */
366 iob.in_size = tp-tbuffer;
368 iob.out_size = sizeof(tbuffer);
370 #if defined(NO_AFS_CLIENT)
371 { int fd; /* DEBUG */
373 if ((tkfile=getenv("TKTFILE")) &&
374 ((fd=open(tkfile, O_WRONLY|O_APPEND|O_TRUNC|O_CREAT, 0644)) >= 0)) {
375 printf("Writing ticket to: %s\n", tkfile);
376 code = (write(fd, iob.in, iob.in_size) != iob.in_size);
380 code = KTC_PIOCTLFAIL;
382 #else /* NO_AFS_CLIENT */
383 code = PIOCTL(0, VIOCSETTOK, &iob, 0);
384 #endif /* NO_AFS_CLIENT */
385 if (code) return KTC_PIOCTLFAIL;
390 ktc_SetToken (aserver, atoken, aclient, flags)
391 struct ktc_principal *aserver;
392 struct ktc_principal *aclient;
393 struct ktc_token *atoken;
399 #ifdef AFS_KERBEROS_ENV
400 if (!lcell[0]) ktc_LocalCell();
402 if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
403 (strcmp(aserver->name, "AuthServer") ||
404 strcmp(aserver->instance, "Admin"))){
405 if (strcmp(aserver->name, "krbtgt") == 0) {
406 static char lrealm[MAXKTCREALMLEN];
408 if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
409 if (strcmp(aserver->instance, lrealm) == 0) {
410 afs_tf_create(aclient->name, aclient->instance);
414 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
415 if (ncode == NO_TKT_FIL) {
416 (void) afs_tf_create(aclient->name, aclient->instance);
417 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
421 afs_tf_save_cred(aserver, atoken, aclient);
427 #endif /* NO_AFS_CLIENT */
431 #ifndef NO_AFS_CLIENT
432 ncode = NewSetToken (aserver, atoken, aclient, flags);
433 if (ncode || /* new style failed */
434 (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
435 ocode = OldSetToken (aserver, atoken, aclient, flags);
437 if (ncode && ocode) {
439 if (ocode == -1) ocode = errno;
440 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
441 if (ocode == ESRCH) return KTC_NOCELL;
442 if (ocode == EINVAL) return KTC_NOPIOCTL;
443 if (ocode == EIO) return KTC_NOCM;
444 return KTC_PIOCTLFAIL;
446 #endif /* NO_AFS_CLIENT */
451 /* get token, given server we need and token buffer. aclient will eventually
452 * be set to our identity to the server.
454 ktc_GetToken(aserver, atoken, atokenLen, aclient)
455 struct ktc_principal *aserver, *aclient;
457 struct ktc_token *atoken; {
458 struct ViceIoctl iob;
460 register afs_int32 code;
462 char *stp, *cellp; /* secret token ptr */
463 struct ClearToken ct;
466 int maxLen; /* biggest ticket we can copy */
467 int tktLen; /* server ticket length */
471 #ifndef NO_AFS_CLIENT
472 TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
473 #endif /* NO_AFS_CLIENT */
475 #ifdef AFS_KERBEROS_ENV
476 if (!lcell[0]) ktc_LocalCell();
478 #ifndef NO_AFS_CLIENT
479 if (strcmp(aserver->name, "afs") != 0)
480 #endif /* NO_AFS_CLIENT */
483 /* try the local tokens */
484 for (i=0; i<MAXLOCALTOKENS; i++)
485 if (local_tokens[i].valid &&
486 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
487 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
488 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
489 memcpy (atoken, &local_tokens[i].token, min (atokenLen, sizeof(struct ktc_token)));
491 *aclient = local_tokens[i].client;
495 #ifdef AFS_KERBEROS_ENV
496 if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
498 if (!afs_tf_get_pname(aclient->name) &&
499 !afs_tf_get_pinst(aclient->instance))
502 char tmpstring[MAXHOSTCHARS];
503 afs_tf_get_pname(&tmpstring);
504 afs_tf_get_pinst(&tmpstring);
509 struct ktc_principal cprincipal;
510 struct ktc_token ctoken;
512 while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
513 if (strcmp(cprincipal.name, aserver->name) == 0 &&
514 strcmp(cprincipal.instance, aserver->instance) == 0 &&
515 strcmp(cprincipal.cell, aserver->cell) == 0) {
518 strcpy(aclient->cell, lcell);
519 memcpy(atoken, &ctoken,
520 min (atokenLen, sizeof(struct ktc_token)));
534 #ifndef NO_AFS_CLIENT
535 for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
536 iob.in = (char *) &index;
537 iob.in_size = sizeof(afs_int32);
539 iob.out_size = sizeof(tbuffer);
541 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
544 /* failed to retrieve specified token */
545 if (code < 0 && errno == EDOM) {
550 /* token retrieved; parse buffer */
553 /* get ticket length */
554 memcpy(&temp, tp, sizeof(afs_int32));
556 tp += sizeof(afs_int32);
558 /* remember where ticket is and skip over it */
562 /* get size of clear token and verify */
563 memcpy(&temp, tp, sizeof(afs_int32));
564 if (temp != sizeof(struct ClearToken)) {
568 tp += sizeof(afs_int32);
570 /* copy clear token */
571 memcpy(&ct, tp, temp);
574 /* skip over primary flag */
575 tp += sizeof(afs_int32);
577 /* remember where cell name is */
580 if ((strcmp(cellp, aserver->cell) == 0)
581 #ifdef AFS_KERBEROS_ENV
582 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
585 /* got token for cell; check that it will fit */
586 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
587 if (maxLen < tktLen) {
592 /* set return values */
593 memcpy(atoken->ticket, stp, tktLen);
594 atoken->startTime = ct.BeginTimestamp;
595 atoken->endTime = ct.EndTimestamp;
596 if (ct.AuthHandle == -1) {
599 atoken->kvno = ct.AuthHandle;
600 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
601 atoken->ticketLen = tktLen;
604 strcpy(aclient->cell, cellp);
605 aclient->instance[0] = 0;
607 if ((atoken->kvno == 999) || /* old style bcrypt ticket */
608 (ct.BeginTimestamp && /* new w/ prserver lookup */
609 (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
610 sprintf(aclient->name, "AFS ID %d", ct.ViceId);
612 sprintf(aclient->name, "Unix UID %d", ct.ViceId);
620 #endif /* NO_AFS_CLIENT */
623 if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
624 return KTC_PIOCTLFAIL; /* probable cause */
628 * Forget tokens for this server and the calling user.
629 * NOT IMPLEMENTED YET!
631 #ifndef NO_AFS_CLIENT
632 ktc_ForgetToken(aserver)
633 struct ktc_principal *aserver; {
637 TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
639 rc = ktc_ForgetAllTokens(); /* bogus, but better */
643 #endif /* NO_AFS_CLIENT */
645 /* ktc_ListTokens - list all tokens. start aprevIndex at 0, it returns the
646 * next rock in (*aindex). (*aserver) is set to the relevant ticket on
649 ktc_ListTokens(aprevIndex, aindex, aserver)
650 int aprevIndex, *aindex;
651 struct ktc_principal *aserver; {
652 struct ViceIoctl iob;
654 register afs_int32 code;
656 afs_int32 temp, index;
659 #ifndef NO_AFS_CLIENT
660 TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
661 #endif /* NO_AFS_CLIENT */
665 if (index < 214) index = 214;
666 #endif /* NO_AFS_CLIENT */
667 #ifdef AFS_KERBEROS_ENV
670 struct ktc_principal cprincipal;
671 struct ktc_token ctoken;
673 if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL) ||
674 afs_tf_get_pname(tbuffer) ||
675 afs_tf_get_pinst(tbuffer)) {
681 for (i=214; i<index; i++) {
682 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
690 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
697 #ifndef NO_AFS_CLIENT
698 if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
701 #endif /* NO_AFS_CLIENT */
703 for (i=0; i < MAXLOCALTOKENS; i++) {
704 if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
705 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
706 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
711 *aserver = cprincipal;
719 #ifndef NO_AFS_CLIENT
720 if (index >= 123) { /* special hack for returning TCS */
721 while (index-123 < MAXLOCALTOKENS) {
722 if (local_tokens[index-123].valid) {
723 *aserver = local_tokens[index-123].server;
731 #ifdef AFS_KERBEROS_ENV
732 return ktc_ListTokens(214, aindex, aserver);
738 /* get tokens from the kernel */
739 while (index<200) { /* sanity check in case pioctl fails */
740 iob.in = (char *) &index;
741 iob.in_size = sizeof(afs_int32);
743 iob.out_size = sizeof(tbuffer);
744 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
745 if (code < 0 && errno == EDOM) {
748 rc = ktc_ListTokens (123, aindex, aserver);
757 if (code == 0) break; /* got a ticket */
758 /* otherwise we should skip this ticket slot */
763 if (errno == EINVAL) return KTC_NOPIOCTL;
764 return KTC_PIOCTLFAIL;
770 /* next iterator determined by earlier loop */
773 memcpy(&temp, tp, sizeof(afs_int32)); /* get size of secret token */
774 tp += sizeof(afs_int32);
775 tp += temp; /* skip ticket for now */
776 memcpy(&temp, tp, sizeof(afs_int32)); /* get size of clear token */
777 if (temp != sizeof(struct ClearToken)) {
781 tp += sizeof(afs_int32); /* skip length */
782 tp += temp; /* skip clear token itself */
783 tp += sizeof(afs_int32); /* skip primary flag */
784 /* tp now points to the cell name */
785 strcpy(aserver->cell, tp);
786 aserver->instance[0] = 0;
787 strcpy(aserver->name, "afs");
788 #endif /* NO_AFS_CLIENT */
793 /* discard all tokens from this user's cache */
795 static int NewForgetAll ()
797 #ifndef NO_AFS_CLIENT
798 TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
799 #endif /* NO_AFS_CLIENT */
803 static int OldForgetAll ()
805 struct ViceIoctl iob;
806 register afs_int32 code;
809 for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
815 #ifndef NO_AFS_CLIENT
816 code = PIOCTL(0, VIOCUNPAG, &iob, 0);
817 if (code) return KTC_PIOCTLFAIL;
818 #endif /* NO_AFS_CLIENT */
822 int ktc_ForgetAllTokens()
827 #ifdef AFS_KERBEROS_ENV
828 (void) afs_tf_dest_tkt();
831 ncode = NewForgetAll ();
832 ocode = OldForgetAll ();
833 if (ncode && ocode) {
834 if (ocode == -1) ocode = errno;
835 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
837 if (ocode == EINVAL) return KTC_NOPIOCTL;
838 return KTC_PIOCTLFAIL;
844 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
845 * pioctl interface for delivering AFS tickets to the cache manager. */
851 #ifdef KERNEL_KTC_COMPAT
853 rc = (kernelKTC != 1); /* old style interface */
862 #ifdef AFS_KERBEROS_ENV
864 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
866 * For copying and distribution information, please see the file
873 #include <sys/types.h>
874 #include <sys/stat.h>
875 #include <sys/file.h>
880 #define TF_LCK_RETRY ((unsigned)2) /* seconds to sleep before
881 * retry if ticket file is
885 * fd must be initialized to something that won't ever occur as a real
886 * file descriptor. Since open(2) returns only non-negative numbers as
887 * valid file descriptors, and afs_tf_init always stuffs the return value
888 * from open in here even if it is an error flag, we must
889 * a. Initialize fd to a negative number, to indicate that it is
890 * not initially valid.
891 * b. When checking for a valid fd, assume that negative values
892 * are invalid (ie. when deciding whether afs_tf_init has been
894 * c. In tf_close, be sure it gets reinitialized to a negative
898 static curpos; /* Position in tfbfr */
899 static lastpos; /* End of tfbfr */
900 static char tfbfr[BUFSIZ]; /* Buffer for ticket data */
902 static tf_gets(), tf_read();
905 * This file contains routines for manipulating the ticket cache file.
907 * The ticket file is in the following format:
909 * principal's name (null-terminated string)
910 * principal's instance (null-terminated string)
917 * Where "CREDENTIAL_x" consists of the following fixed-length
918 * fields from the CREDENTIALS structure (see "krb.h"):
920 * char service[MAXKTCNAMELEN]
921 * char instance[MAXKTCNAMELEN]
922 * char realm[REALM_SZ]
927 * afs_int32 issue_date
929 * Short description of routines:
931 * afs_tf_init() opens the ticket file and locks it.
933 * afs_tf_get_pname() returns the principal's name.
935 * afs_tf_get_pinst() returns the principal's instance (may be null).
937 * afs_tf_get_cred() returns the next CREDENTIALS record.
939 * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
941 * afs_tf_close() closes the ticket file and releases the lock.
943 * tf_gets() returns the next null-terminated string. It's an internal
944 * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
947 * tf_read() reads a given number of bytes. It's an internal routine
948 * used by afs_tf_get_cred().
952 * afs_tf_init() should be called before the other ticket file routines.
953 * It takes the name of the ticket file to use, "tf_name", and a
954 * read/write flag "rw" as arguments.
956 * It tries to open the ticket file, checks the mode, and if everything
957 * is okay, locks the file. If it's opened for reading, the lock is
958 * shared. If it's opened for writing, the lock is exclusive.
960 * Returns 0 if all went well, otherwise one of the following:
962 * NO_TKT_FIL - file wasn't there
963 * TKT_FIL_ACC - file was in wrong mode, etc.
964 * TKT_FIL_LCK - couldn't lock the file, even after a retry
967 afs_tf_init(tf_name, rw)
972 struct stat stat_buf;
984 if (lstat(tf_name, &stat_buf) < 0)
992 if ((stat_buf.st_uid != me && me != 0) ||
993 ((stat_buf.st_mode & S_IFMT) != S_IFREG))
997 * If "wflag" is set, open the ticket file in append-writeonly mode
998 * and lock the ticket file in exclusive mode. If unable to lock
999 * the file, sleep and try again. If we fail again, return with the
1000 * proper error message.
1003 curpos = sizeof(tfbfr);
1006 fd = open(tf_name, O_RDWR, 0600);
1010 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1011 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1012 sleep(TF_LCK_RETRY);
1013 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1015 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1016 sleep(TF_LCK_RETRY);
1017 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1027 * Otherwise "wflag" is not set and the ticket file should be opened
1028 * for read-only operations and locked for shared access.
1031 fd = open(tf_name, O_RDONLY, 0600);
1035 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1036 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1037 sleep(TF_LCK_RETRY);
1038 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1040 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1041 sleep(TF_LCK_RETRY);
1042 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1053 * afs_tf_get_pname() reads the principal's name from the ticket file. It
1054 * should only be called after afs_tf_init() has been called. The
1055 * principal's name is filled into the "p" parameter. If all goes well,
1056 * 0 is returned. If afs_tf_init() wasn't called, TKT_FIL_INI is
1057 * returned. If the name was null, or EOF was encountered, or the name
1058 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1067 if (tf_gets(p, MAXKTCNAMELEN) < 2) /* can't be just a null */
1073 * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1074 * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1075 * been called. The instance is filled into the "inst" parameter. If all
1076 * goes well, 0 is returned. If afs_tf_init() wasn't called,
1077 * TKT_FIL_INI is returned. If EOF was encountered, or the instance
1078 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. Note that the
1079 * instance may be null.
1082 afs_tf_get_pinst(inst)
1088 if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1094 * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1095 * in the given structure "c". It should only be called after afs_tf_init(),
1096 * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1097 * well, 0 is returned. Possible error codes are:
1099 * TKT_FIL_INI - afs_tf_init wasn't called first
1100 * TKT_FIL_FMT - bad format
1101 * EOF - end of file encountered
1104 afs_tf_get_cred(principal, token)
1105 struct ktc_principal *principal;
1106 struct ktc_token *token;
1114 if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1117 case 1: /* can't be just a null */
1122 if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1129 if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1132 case 1: /* can't be just a null */
1137 lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1139 tf_read((char *) &(token->sessionKey), 8) < 1 ||
1140 tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1141 tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1142 tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1144 /* don't try to read a silly amount into ticket->dat */
1145 token->ticketLen > MAXKTCTICKETLEN ||
1146 tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1147 tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1151 token->endTime = life_to_time(token->startTime, lifetime);
1157 * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1158 * not a valid file descriptor, it just returns. It also clears the
1159 * buffer used to read tickets.
1161 * The return value is not defined.
1167 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1168 (void) fcntl(fd, F_SETLK, &fileUlock);
1170 (void) flock(fd, LOCK_UN);
1173 fd = -1; /* see declaration of fd above */
1175 memset(tfbfr, 0, sizeof(tfbfr));
1179 * tf_gets() is an internal routine. It takes a string "s" and a count
1180 * "n", and reads from the file until either it has read "n" characters,
1181 * or until it reads a null byte. When finished, what has been read exists
1184 * Possible return values are:
1186 * n the number of bytes read (including null terminator)
1187 * when all goes well
1189 * 0 end of file or read error
1191 * TOO_BIG if "count" characters are read and no null is
1192 * encountered. This is an indication that the ticket
1193 * file is seriously ill.
1205 for (count = n - 1; count > 0; --count) {
1206 if (curpos >= sizeof(tfbfr)) {
1207 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1210 if (curpos == lastpos) {
1213 *s = tfbfr[curpos++];
1221 * tf_read() is an internal routine. It takes a string "s" and a count
1222 * "n", and reads from the file until "n" bytes have been read. When
1223 * finished, what has been read exists in "s".
1225 * Possible return values are:
1227 * n the number of bytes read when all goes well
1229 * 0 on end of file or read error
1239 for (count = n; count > 0; --count) {
1240 if (curpos >= sizeof(tfbfr)) {
1241 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1244 if (curpos == lastpos) {
1247 *s++ = tfbfr[curpos++];
1255 * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1256 * file. You must call afs_tf_init() before calling afs_tf_save_cred().
1258 * The "service", "instance", and "realm" arguments specify the
1259 * server's name; "aticket" contains the credential.
1261 * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1262 * called previously, and KFAILURE for anything else that went wrong.
1265 afs_tf_save_cred(aserver, atoken, aclient)
1266 struct ktc_principal *aserver;
1267 struct ktc_principal *aclient;
1268 struct ktc_token *atoken; /* Token */
1270 char realm[MAXKTCREALMLEN+1];
1271 char junk[MAXKTCNAMELEN];
1272 struct ktc_principal principal;
1273 struct ktc_token token;
1277 int count; /* count for write */
1279 if (fd < 0) { /* fd is ticket file as set by afs_tf_init */
1283 ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1284 realm[MAXKTCREALMLEN] = '\0';
1286 /* Look for a duplicate ticket */
1287 (void) lseek(fd, (off_t) 0L, 0);
1288 curpos = sizeof(tfbfr);
1290 if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1291 afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1294 start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1295 status = afs_tf_get_cred(&principal, &token);
1296 } while (status == 0 &&
1297 (strcmp(aserver->name, principal.name) != 0 ||
1298 strcmp(aserver->instance, principal.instance) != 0 ||
1299 strcmp(aserver->cell, principal.cell) != 0));
1302 * Two tickets for the same user authenticating to the same service
1303 * should be the same length, but we check here just to make sure.
1305 if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1306 if (status && status != EOF) return status;
1308 /* Position over the credential we just matched (or the EOF) */
1309 lseek(fd, start, 0);
1310 curpos = lastpos = sizeof(tfbfr);
1312 /* Write the ticket and associated data */
1314 count = strlen(aserver->name) + 1;
1315 if (write(fd, aserver->name, count) != count)
1318 count = strlen(aserver->instance) + 1;
1319 if (write(fd, aserver->instance, count) != count)
1322 count = strlen(realm) + 1;
1323 if (write(fd, realm, count) != count)
1326 if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1329 lifetime = time_to_life(atoken->startTime, atoken->endTime);
1330 if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1333 kvno = atoken->kvno;
1334 if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1337 if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1341 count = atoken->ticketLen;
1342 if (write(fd, atoken->ticket, count) != count)
1345 if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1346 != sizeof(afs_int32))
1349 /* Actually, we should check each write for success */
1356 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1359 * For copying and distribution information, please see the file
1360 * <mit-copyright.h>.
1366 * This routine is used to generate the name of the file that holds
1367 * the user's cache of server tickets and associated session keys.
1369 * If it is set, krb_ticket_string contains the ticket file name.
1370 * Otherwise, the filename is constructed as follows:
1372 * If it is set, the environment variable "KRBTKFILE" will be used as
1373 * the ticket file name. Otherwise TKT_ROOT (defined in "krb.h") and
1374 * the user's uid are concatenated to produce the ticket file name
1375 * (e.g., "/tmp/tkt123"). A pointer to the string containing the ticket
1376 * file name is returned.
1379 static char krb_ticket_string[4096] = "";
1381 char *ktc_tkt_string()
1386 if (!*krb_ticket_string) {
1387 if (env = getenv("KRBTKFILE")) {
1388 (void) strncpy(krb_ticket_string, env,
1389 sizeof(krb_ticket_string)-1);
1390 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1392 /* 32 bits of signed integer will always fit in 11 characters
1393 (including the sign), so no need to worry about overflow */
1394 (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1398 return krb_ticket_string;
1402 * This routine is used to set the name of the file that holds the user's
1403 * cache of server tickets and associated session keys.
1405 * The value passed in is copied into local storage.
1407 * NOTE: This routine should be called during initialization, before other
1408 * Kerberos routines are called; otherwise tkt_string() above may be called
1409 * and return an undesired ticket file name until this routine is called.
1413 ktc_set_tkt_string(val)
1418 (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1419 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1426 * tf_create() is used to initialize the ticket store. It creates the
1427 * file to contain the tickets and writes the given user's name "pname"
1428 * and instance "pinst" in the file. in_tkt() returns KSUCCESS on
1429 * success, or KFAILURE if something goes wrong.
1432 afs_tf_create(pname,pinst)
1439 char *file = ktc_tkt_string();
1448 if (lstat(file,&sbuf) == 0) {
1449 if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1450 sbuf.st_mode & 077) {
1453 /* file already exists, and permissions appear ok, so nuke it */
1454 if ((fd = open(file, O_RDWR, 0)) < 0)
1455 goto out; /* can't zero it, but we can still try truncating it */
1457 memset(zerobuf, 0, sizeof(zerobuf));
1459 for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1460 if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1471 /* arrange so the file is owned by the ruid
1472 (swap real & effective uid if necessary).
1473 This isn't a security problem, since the ticket file, if it already
1474 exists, has the right uid (== ruid) and mode. */
1476 if (setreuid(metoo, me) < 0) {
1480 tktfile = creat(file, 0600);
1482 if (setreuid(me, metoo) < 0) {
1483 /* can't switch??? fail! */
1490 count = strlen(pname)+1;
1491 if (write(tktfile,pname,count) != count) {
1492 (void) close(tktfile);
1495 count = strlen(pinst)+1;
1496 if (write(tktfile,pinst,count) != count) {
1497 (void) close(tktfile);
1500 (void) close(tktfile);
1505 * dest_tkt() is used to destroy the ticket store upon logout.
1506 * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1507 * Otherwise the function returns 0 on success, KFAILURE on
1513 char *file = ktc_tkt_string();
1519 if (lstat(file,&statb) < 0)
1522 if (!(statb.st_mode & S_IFREG))
1525 if ((fd = open(file, O_RDWR, 0)) < 0)
1528 memset(buf, 0, BUFSIZ);
1530 for (i = 0; i < statb.st_size; i += BUFSIZ)
1531 if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1540 (void) unlink(file);
1543 if (errno == ENOENT) return RET_TKFIL;
1544 else if (errno != 0) return KFAILURE;
1548 static afs_uint32 curpag()
1550 gid_t groups[NGROUPS_MAX];
1552 afs_uint32 h, l, ret;
1554 if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1556 g0 = groups[0] & 0xffff;
1557 g1 = groups[1] & 0xffff;
1560 if (g0 < 0xc000 && g1 < 0xc000) {
1561 l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1563 h = (g1 >> 14) + h + h + h;
1564 ret = ((h << 28) | l);
1565 /* Additional testing */
1566 if (((ret >> 24) & 0xff) == 'A')
1577 extern char **environ;
1581 char fname[256], *prefix = "/ticket/";
1583 char **newenv, **senv, **denv;
1586 if (stat("/ticket", &sbuf) == -1) {
1587 prefix = "/tmp/tkt";
1590 pag = curpag() & 0xffffffff;
1592 sprintf(fname, "%s%d", prefix, getuid());
1595 sprintf(fname, "%sp%ld", prefix, pag);
1597 ktc_set_tkt_string(fname);
1599 for (senv=environ, numenv=0; *senv; senv++) numenv++;
1600 newenv = (char **)malloc((numenv+2) * sizeof(char *));
1602 for (senv=environ, denv=newenv; *senv; *senv++) {
1603 if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1606 *denv = (char *)malloc(10 + strlen(fname) + 1);
1607 strcpy(*denv, "KRBTKFILE=");
1608 strcat(*denv, fname);
1615 * BLETCH! We have to invoke the entire afsconf package just to
1616 * find out what the local cell is.
1618 static ktc_LocalCell()
1621 struct afsconf_dir *conf;
1623 if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1624 (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1625 code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1626 afsconf_Close (conf);
1628 if (!conf || code) {
1629 printf("** Can't determine local cell name!\n");