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
139 /* In case there is no include file. */
143 #define KTC_SYSCALL 32
146 /* Kernel call opcode definitions */
147 #define KTC_OPCODE_BASE 4300
148 #define KTC_NO_OP (0+KTC_OPCODE_BASE)
149 #define KTC_SETTOKEN_OP (1+KTC_OPCODE_BASE)
150 #define KTC_GETTOKEN_OP (2+KTC_OPCODE_BASE)
151 #define KTC_LISTTOKENS_OP (3+KTC_OPCODE_BASE)
152 #define KTC_FORGETTOKEN_OP (4+KTC_OPCODE_BASE)
153 #define KTC_FORGETALLTOKENS_OP (5+KTC_OPCODE_BASE)
154 #define KTC_STATUS_OP (6+KTC_OPCODE_BASE)
155 #define KTC_GC_OP (7+KTC_OPCODE_BASE)
157 #define KTC_INTERFACE_VERSION 3
163 /* We have to determine if the kernel supports the ktc system call. To do so
164 * we attempt to execute its noop function. If this is successful we use the
165 * kernel calls in the future otherwise we let the old code run. */
167 /* To safely check to see whether a system call exists we have to intercept the
168 * SIGSYS signal which is caused by executing a non-existant system call. If
169 * it is ignored the syscall routine returns EINVAL. The SIGSYS is reset to
170 * its old value after the return from syscall. */
172 static int kernelKTC = 0;
174 #ifdef AFS_DECOSF_ENV
176 * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems. You need
177 * to ignore SIGTRAP too. It is claimed to be fixed under v1.3, but...
180 #define CHECK_KERNEL \
181 if (kernelKTC == 0) { \
185 old = (int (*)())signal(SIGSYS, SIG_IGN); \
186 old_t = (int (*)())signal(SIGTRAP, SIG_IGN); \
187 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
189 signal(SIGSYS, old); \
190 signal(SIGTRAP, old_t); \
191 if (code == 0) kernelKTC = 1; \
192 else kernelKTC = 2; \
193 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
196 #else /* AFS_DECOSF_ENV */
198 #define CHECK_KERNEL \
199 if (kernelKTC == 0) { \
202 old = (int (*)())signal(SIGSYS, SIG_IGN); \
203 code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0); \
205 signal(SIGSYS, old); \
206 if (code == 0) kernelKTC = 1; \
207 else kernelKTC = 2; \
208 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
210 #endif /* AFS_DECOSF_ENV */
212 #define TRY_KERNEL(cmd,a1,a2,a3,a4) \
214 if (kernelKTC == 1) \
215 return syscall (KTC_SYSCALL, cmd, \
216 KTC_INTERFACE_VERSION, a1,a2,a3,a4); \
220 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
221 #endif /* KERNEL_KTC_COMPAT */
223 #if !defined(UKERNEL)
224 /* this is a structure used to communicate with the afs cache mgr, but is
225 * otherwise irrelevant */
227 afs_int32 AuthHandle;
228 char HandShakeKey[8];
230 afs_int32 BeginTimestamp;
231 afs_int32 EndTimestamp;
233 #endif /* !defined(UKERNEL) */
235 #define MAXLOCALTOKENS 4
239 struct ktc_principal server;
240 struct ktc_principal client;
241 struct ktc_token token;
242 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
244 /* new interface routines to the ticket cache. Only handle afs service right
247 static int NewSetToken (aserver, atoken, aclient, flags)
248 struct ktc_principal *aserver;
249 struct ktc_principal *aclient;
250 struct ktc_token *atoken;
253 TRY_KERNEL (KTC_SETTOKEN_OP,
254 aserver, aclient, atoken, sizeof(struct ktc_token));
255 /* no kernel ticket cache */
259 static int OldSetToken (aserver, atoken, aclient, flags)
260 struct ktc_principal *aserver, *aclient;
261 struct ktc_token *atoken;
264 struct ViceIoctl iob;
267 struct ClearToken ct;
268 register afs_int32 code;
271 if (strcmp(aserver->name, "afs") != 0) {
274 for (i=0; i<MAXLOCALTOKENS; i++)
275 if (local_tokens[i].valid) {
276 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
277 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
278 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
279 found = i; /* replace existing entry */
282 else /* valid, but no match */ ;
283 } else found = i; /* remember this empty slot */
284 if (found == -1) return KTC_NOENT;
285 bcopy (atoken, &local_tokens[found].token, sizeof(struct ktc_token));
286 local_tokens[found].server = *aserver;
287 local_tokens[found].client = *aclient;
288 local_tokens[found].valid = 1;
291 tp = tbuffer; /* start copying here */
292 if ((atoken->ticketLen < MINKTCTICKETLEN) ||
293 (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
294 bcopy(&atoken->ticketLen, tp, sizeof(afs_int32)); /* copy in ticket length */
295 tp += sizeof(afs_int32);
296 bcopy(atoken->ticket, tp, atoken->ticketLen); /* copy in ticket */
297 tp += atoken->ticketLen;
298 /* next, copy in the "clear token", describing who we are */
299 ct.AuthHandle = atoken->kvno; /* hide auth handle here */
300 bcopy(&atoken->sessionKey, ct.HandShakeKey, 8);
302 ct.BeginTimestamp = atoken->startTime;
303 ct.EndTimestamp = atoken->endTime;
304 if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
306 if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
307 (aclient->instance[0] == 0)) {
309 afs_int32 viceId = 0;
310 char *cp = aclient->name + strlen ("AFS ID ");
311 if (*cp == '-') { sign = -1; cp++; }
313 if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
314 else goto not_vice_id;
317 ct.ViceId = viceId * sign; /* OK to let any value here? */
318 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
319 ct.BeginTimestamp++; /* force lifetime to be odd */
322 ct.ViceId = getuid(); /* wrong, but works in primary cell */
323 if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
324 ct.BeginTimestamp++; /* force lifetime to be even */
329 * Information needed by the user space cache manager
331 u.u_expiration = ct.EndTimestamp;
332 u.u_viceid = ct.ViceId;
335 temp = sizeof(struct ClearToken);
336 bcopy(&temp, tp, sizeof(afs_int32));
337 tp += sizeof(afs_int32);
338 bcopy(&ct, tp, sizeof(struct ClearToken));
339 tp += sizeof(struct ClearToken);
341 /* next copy in primary flag */
345 * The following means that setpag will happen inside afs just before
346 * the authentication to prevent the setpag/klog race condition.
348 * The following means that setpag will affect the parent process as
349 * well as the current process.
351 if (flags & AFS_SETTOK_SETPAG)
354 bcopy(&temp, tp, sizeof(afs_int32));
355 tp += sizeof(afs_int32);
357 /* finally copy in the cell name */
358 temp = strlen(aserver->cell);
359 if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
360 strcpy(tp, aserver->cell);
363 /* now setup for the pioctl */
365 iob.in_size = tp-tbuffer;
367 iob.out_size = sizeof(tbuffer);
369 #if defined(NO_AFS_CLIENT)
370 { int fd; /* DEBUG */
372 if ((tkfile=getenv("TKTFILE")) &&
373 ((fd=open(tkfile, O_WRONLY|O_APPEND|O_TRUNC|O_CREAT, 0644)) >= 0)) {
374 printf("Writing ticket to: %s\n", tkfile);
375 code = (write(fd, iob.in, iob.in_size) != iob.in_size);
379 code = KTC_PIOCTLFAIL;
381 #else /* NO_AFS_CLIENT */
382 code = PIOCTL(0, VIOCSETTOK, &iob, 0);
383 #endif /* NO_AFS_CLIENT */
384 if (code) return KTC_PIOCTLFAIL;
389 ktc_SetToken (aserver, atoken, aclient, flags)
390 struct ktc_principal *aserver;
391 struct ktc_principal *aclient;
392 struct ktc_token *atoken;
398 #ifdef AFS_KERBEROS_ENV
399 if (!lcell[0]) ktc_LocalCell();
401 if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
402 (strcmp(aserver->name, "AuthServer") ||
403 strcmp(aserver->instance, "Admin"))){
404 if (strcmp(aserver->name, "krbtgt") == 0) {
405 static char lrealm[MAXKTCREALMLEN];
407 if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
408 if (strcmp(aserver->instance, lrealm) == 0) {
409 afs_tf_create(aclient->name, aclient->instance);
413 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
414 if (ncode == NO_TKT_FIL) {
415 (void) afs_tf_create(aclient->name, aclient->instance);
416 ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
420 afs_tf_save_cred(aserver, atoken, aclient);
426 #endif /* NO_AFS_CLIENT */
430 #ifndef NO_AFS_CLIENT
431 ncode = NewSetToken (aserver, atoken, aclient, flags);
432 if (ncode || /* new style failed */
433 (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
434 ocode = OldSetToken (aserver, atoken, aclient, flags);
436 if (ncode && ocode) {
438 if (ocode == -1) ocode = errno;
439 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
440 if (ocode == ESRCH) return KTC_NOCELL;
441 if (ocode == EINVAL) return KTC_NOPIOCTL;
442 if (ocode == EIO) return KTC_NOCM;
443 return KTC_PIOCTLFAIL;
445 #endif /* NO_AFS_CLIENT */
450 /* get token, given server we need and token buffer. aclient will eventually
451 * be set to our identity to the server.
453 ktc_GetToken(aserver, atoken, atokenLen, aclient)
454 struct ktc_principal *aserver, *aclient;
456 struct ktc_token *atoken; {
457 struct ViceIoctl iob;
459 register afs_int32 code;
461 char *stp, *cellp; /* secret token ptr */
462 struct ClearToken ct;
465 int maxLen; /* biggest ticket we can copy */
466 int tktLen; /* server ticket length */
470 #ifndef NO_AFS_CLIENT
471 TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
472 #endif /* NO_AFS_CLIENT */
474 #ifdef AFS_KERBEROS_ENV
475 if (!lcell[0]) ktc_LocalCell();
477 #ifndef NO_AFS_CLIENT
478 if (strcmp(aserver->name, "afs") != 0)
479 #endif /* NO_AFS_CLIENT */
482 /* try the local tokens */
483 for (i=0; i<MAXLOCALTOKENS; i++)
484 if (local_tokens[i].valid &&
485 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
486 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
487 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
488 bcopy (&local_tokens[i].token, atoken, min (atokenLen, sizeof(struct ktc_token)));
490 *aclient = local_tokens[i].client;
494 #ifdef AFS_KERBEROS_ENV
495 if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
497 if (!afs_tf_get_pname(aclient->name) &&
498 !afs_tf_get_pinst(aclient->instance))
501 char tmpstring[MAXHOSTCHARS];
502 afs_tf_get_pname(&tmpstring);
503 afs_tf_get_pinst(&tmpstring);
508 struct ktc_principal cprincipal;
509 struct ktc_token ctoken;
511 while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
512 if (strcmp(cprincipal.name, aserver->name) == 0 &&
513 strcmp(cprincipal.instance, aserver->instance) == 0 &&
514 strcmp(cprincipal.cell, aserver->cell) == 0) {
517 strcpy(aclient->cell, lcell);
518 bcopy(&ctoken, atoken,
519 min (atokenLen, sizeof(struct ktc_token)));
533 #ifndef NO_AFS_CLIENT
534 for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
535 iob.in = (char *) &index;
536 iob.in_size = sizeof(afs_int32);
538 iob.out_size = sizeof(tbuffer);
540 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
543 /* failed to retrieve specified token */
544 if (code < 0 && errno == EDOM) {
549 /* token retrieved; parse buffer */
552 /* get ticket length */
553 memcpy(&temp, tp, sizeof(afs_int32));
555 tp += sizeof(afs_int32);
557 /* remember where ticket is and skip over it */
561 /* get size of clear token and verify */
562 memcpy(&temp, tp, sizeof(afs_int32));
563 if (temp != sizeof(struct ClearToken)) {
567 tp += sizeof(afs_int32);
569 /* copy clear token */
570 memcpy(&ct, tp, temp);
573 /* skip over primary flag */
574 tp += sizeof(afs_int32);
576 /* remember where cell name is */
579 if ((strcmp(cellp, aserver->cell) == 0)
580 #ifdef AFS_KERBEROS_ENV
581 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
584 /* got token for cell; check that it will fit */
585 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
586 if (maxLen < tktLen) {
591 /* set return values */
592 memcpy(atoken->ticket, stp, tktLen);
593 atoken->startTime = ct.BeginTimestamp;
594 atoken->endTime = ct.EndTimestamp;
595 if (ct.AuthHandle == -1) {
598 atoken->kvno = ct.AuthHandle;
599 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
600 atoken->ticketLen = tktLen;
603 strcpy(aclient->cell, cellp);
604 aclient->instance[0] = 0;
606 if ((atoken->kvno == 999) || /* old style bcrypt ticket */
607 (ct.BeginTimestamp && /* new w/ prserver lookup */
608 (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
609 sprintf(aclient->name, "AFS ID %d", ct.ViceId);
611 sprintf(aclient->name, "Unix UID %d", ct.ViceId);
619 #endif /* NO_AFS_CLIENT */
622 if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
623 return KTC_PIOCTLFAIL; /* probable cause */
627 * Forget tokens for this server and the calling user.
628 * NOT IMPLEMENTED YET!
630 #ifndef NO_AFS_CLIENT
631 ktc_ForgetToken(aserver)
632 struct ktc_principal *aserver; {
636 TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
638 rc = ktc_ForgetAllTokens(); /* bogus, but better */
642 #endif /* NO_AFS_CLIENT */
644 /* ktc_ListTokens - list all tokens. start aprevIndex at 0, it returns the
645 * next rock in (*aindex). (*aserver) is set to the relevant ticket on
648 ktc_ListTokens(aprevIndex, aindex, aserver)
649 int aprevIndex, *aindex;
650 struct ktc_principal *aserver; {
651 struct ViceIoctl iob;
653 register afs_int32 code;
655 afs_int32 temp, index;
658 #ifndef NO_AFS_CLIENT
659 TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
660 #endif /* NO_AFS_CLIENT */
664 if (index < 214) index = 214;
665 #endif /* NO_AFS_CLIENT */
666 #ifdef AFS_KERBEROS_ENV
669 struct ktc_principal cprincipal;
670 struct ktc_token ctoken;
672 if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL) ||
673 afs_tf_get_pname(tbuffer) ||
674 afs_tf_get_pinst(tbuffer)) {
680 for (i=214; i<index; i++) {
681 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
689 if (afs_tf_get_cred(&cprincipal, &ctoken)) {
696 #ifndef NO_AFS_CLIENT
697 if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
700 #endif /* NO_AFS_CLIENT */
702 for (i=0; i < MAXLOCALTOKENS; i++) {
703 if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
704 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
705 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
710 *aserver = cprincipal;
718 #ifndef NO_AFS_CLIENT
719 if (index >= 123) { /* special hack for returning TCS */
720 while (index-123 < MAXLOCALTOKENS) {
721 if (local_tokens[index-123].valid) {
722 *aserver = local_tokens[index-123].server;
730 #ifdef AFS_KERBEROS_ENV
731 return ktc_ListTokens(214, aindex, aserver);
737 /* get tokens from the kernel */
738 while (index<200) { /* sanity check in case pioctl fails */
739 iob.in = (char *) &index;
740 iob.in_size = sizeof(afs_int32);
742 iob.out_size = sizeof(tbuffer);
743 code = PIOCTL(0, VIOCGETTOK, &iob, 0);
744 if (code < 0 && errno == EDOM) {
747 rc = ktc_ListTokens (123, aindex, aserver);
756 if (code == 0) break; /* got a ticket */
757 /* otherwise we should skip this ticket slot */
762 if (errno == EINVAL) return KTC_NOPIOCTL;
763 return KTC_PIOCTLFAIL;
769 /* next iterator determined by earlier loop */
772 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of secret token */
773 tp += sizeof(afs_int32);
774 tp += temp; /* skip ticket for now */
775 bcopy(tp, &temp, sizeof(afs_int32)); /* get size of clear token */
776 if (temp != sizeof(struct ClearToken)) {
780 tp += sizeof(afs_int32); /* skip length */
781 tp += temp; /* skip clear token itself */
782 tp += sizeof(afs_int32); /* skip primary flag */
783 /* tp now points to the cell name */
784 strcpy(aserver->cell, tp);
785 aserver->instance[0] = 0;
786 strcpy(aserver->name, "afs");
787 #endif /* NO_AFS_CLIENT */
792 /* discard all tokens from this user's cache */
794 static int NewForgetAll ()
796 #ifndef NO_AFS_CLIENT
797 TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
798 #endif /* NO_AFS_CLIENT */
802 static int OldForgetAll ()
804 struct ViceIoctl iob;
805 register afs_int32 code;
808 for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
814 #ifndef NO_AFS_CLIENT
815 code = PIOCTL(0, VIOCUNPAG, &iob, 0);
816 if (code) return KTC_PIOCTLFAIL;
817 #endif /* NO_AFS_CLIENT */
821 int ktc_ForgetAllTokens()
826 #ifdef AFS_KERBEROS_ENV
827 (void) afs_tf_dest_tkt();
830 ncode = NewForgetAll ();
831 ocode = OldForgetAll ();
832 if (ncode && ocode) {
833 if (ocode == -1) ocode = errno;
834 else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
836 if (ocode == EINVAL) return KTC_NOPIOCTL;
837 return KTC_PIOCTLFAIL;
843 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
844 * pioctl interface for delivering AFS tickets to the cache manager. */
850 #ifdef KERNEL_KTC_COMPAT
852 rc = (kernelKTC != 1); /* old style interface */
861 #ifdef AFS_KERBEROS_ENV
863 * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
865 * For copying and distribution information, please see the file
872 #include <sys/types.h>
873 #include <sys/stat.h>
874 #include <sys/file.h>
879 #define TF_LCK_RETRY ((unsigned)2) /* seconds to sleep before
880 * retry if ticket file is
884 * fd must be initialized to something that won't ever occur as a real
885 * file descriptor. Since open(2) returns only non-negative numbers as
886 * valid file descriptors, and afs_tf_init always stuffs the return value
887 * from open in here even if it is an error flag, we must
888 * a. Initialize fd to a negative number, to indicate that it is
889 * not initially valid.
890 * b. When checking for a valid fd, assume that negative values
891 * are invalid (ie. when deciding whether afs_tf_init has been
893 * c. In tf_close, be sure it gets reinitialized to a negative
897 static curpos; /* Position in tfbfr */
898 static lastpos; /* End of tfbfr */
899 static char tfbfr[BUFSIZ]; /* Buffer for ticket data */
901 static tf_gets(), tf_read();
904 * This file contains routines for manipulating the ticket cache file.
906 * The ticket file is in the following format:
908 * principal's name (null-terminated string)
909 * principal's instance (null-terminated string)
916 * Where "CREDENTIAL_x" consists of the following fixed-length
917 * fields from the CREDENTIALS structure (see "krb.h"):
919 * char service[MAXKTCNAMELEN]
920 * char instance[MAXKTCNAMELEN]
921 * char realm[REALM_SZ]
926 * afs_int32 issue_date
928 * Short description of routines:
930 * afs_tf_init() opens the ticket file and locks it.
932 * afs_tf_get_pname() returns the principal's name.
934 * afs_tf_get_pinst() returns the principal's instance (may be null).
936 * afs_tf_get_cred() returns the next CREDENTIALS record.
938 * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
940 * afs_tf_close() closes the ticket file and releases the lock.
942 * tf_gets() returns the next null-terminated string. It's an internal
943 * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
946 * tf_read() reads a given number of bytes. It's an internal routine
947 * used by afs_tf_get_cred().
951 * afs_tf_init() should be called before the other ticket file routines.
952 * It takes the name of the ticket file to use, "tf_name", and a
953 * read/write flag "rw" as arguments.
955 * It tries to open the ticket file, checks the mode, and if everything
956 * is okay, locks the file. If it's opened for reading, the lock is
957 * shared. If it's opened for writing, the lock is exclusive.
959 * Returns 0 if all went well, otherwise one of the following:
961 * NO_TKT_FIL - file wasn't there
962 * TKT_FIL_ACC - file was in wrong mode, etc.
963 * TKT_FIL_LCK - couldn't lock the file, even after a retry
966 afs_tf_init(tf_name, rw)
971 struct stat stat_buf;
983 if (lstat(tf_name, &stat_buf) < 0)
991 if ((stat_buf.st_uid != me && me != 0) ||
992 ((stat_buf.st_mode & S_IFMT) != S_IFREG))
996 * If "wflag" is set, open the ticket file in append-writeonly mode
997 * and lock the ticket file in exclusive mode. If unable to lock
998 * the file, sleep and try again. If we fail again, return with the
999 * proper error message.
1002 curpos = sizeof(tfbfr);
1005 fd = open(tf_name, O_RDWR, 0600);
1009 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1010 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1011 sleep(TF_LCK_RETRY);
1012 if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1014 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1015 sleep(TF_LCK_RETRY);
1016 if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1026 * Otherwise "wflag" is not set and the ticket file should be opened
1027 * for read-only operations and locked for shared access.
1030 fd = open(tf_name, O_RDONLY, 0600);
1034 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1035 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1036 sleep(TF_LCK_RETRY);
1037 if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1039 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1040 sleep(TF_LCK_RETRY);
1041 if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1052 * afs_tf_get_pname() reads the principal's name from the ticket file. It
1053 * should only be called after afs_tf_init() has been called. The
1054 * principal's name is filled into the "p" parameter. If all goes well,
1055 * 0 is returned. If afs_tf_init() wasn't called, TKT_FIL_INI is
1056 * returned. If the name was null, or EOF was encountered, or the name
1057 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1066 if (tf_gets(p, MAXKTCNAMELEN) < 2) /* can't be just a null */
1072 * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1073 * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1074 * been called. The instance is filled into the "inst" parameter. If all
1075 * goes well, 0 is returned. If afs_tf_init() wasn't called,
1076 * TKT_FIL_INI is returned. If EOF was encountered, or the instance
1077 * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. Note that the
1078 * instance may be null.
1081 afs_tf_get_pinst(inst)
1087 if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1093 * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1094 * in the given structure "c". It should only be called after afs_tf_init(),
1095 * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1096 * well, 0 is returned. Possible error codes are:
1098 * TKT_FIL_INI - afs_tf_init wasn't called first
1099 * TKT_FIL_FMT - bad format
1100 * EOF - end of file encountered
1103 afs_tf_get_cred(principal, token)
1104 struct ktc_principal *principal;
1105 struct ktc_token *token;
1113 if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1116 case 1: /* can't be just a null */
1121 if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1128 if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1131 case 1: /* can't be just a null */
1136 lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1138 tf_read((char *) &(token->sessionKey), 8) < 1 ||
1139 tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1140 tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1141 tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1143 /* don't try to read a silly amount into ticket->dat */
1144 token->ticketLen > MAXKTCTICKETLEN ||
1145 tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1146 tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1150 token->endTime = life_to_time(token->startTime, lifetime);
1156 * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1157 * not a valid file descriptor, it just returns. It also clears the
1158 * buffer used to read tickets.
1160 * The return value is not defined.
1166 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1167 (void) fcntl(fd, F_SETLK, &fileUlock);
1169 (void) flock(fd, LOCK_UN);
1172 fd = -1; /* see declaration of fd above */
1174 bzero(tfbfr, sizeof(tfbfr));
1178 * tf_gets() is an internal routine. It takes a string "s" and a count
1179 * "n", and reads from the file until either it has read "n" characters,
1180 * or until it reads a null byte. When finished, what has been read exists
1183 * Possible return values are:
1185 * n the number of bytes read (including null terminator)
1186 * when all goes well
1188 * 0 end of file or read error
1190 * TOO_BIG if "count" characters are read and no null is
1191 * encountered. This is an indication that the ticket
1192 * file is seriously ill.
1204 for (count = n - 1; count > 0; --count) {
1205 if (curpos >= sizeof(tfbfr)) {
1206 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1209 if (curpos == lastpos) {
1212 *s = tfbfr[curpos++];
1220 * tf_read() is an internal routine. It takes a string "s" and a count
1221 * "n", and reads from the file until "n" bytes have been read. When
1222 * finished, what has been read exists in "s".
1224 * Possible return values are:
1226 * n the number of bytes read when all goes well
1228 * 0 on end of file or read error
1238 for (count = n; count > 0; --count) {
1239 if (curpos >= sizeof(tfbfr)) {
1240 lastpos = read(fd, tfbfr, sizeof(tfbfr));
1243 if (curpos == lastpos) {
1246 *s++ = tfbfr[curpos++];
1254 * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1255 * file. You must call afs_tf_init() before calling afs_tf_save_cred().
1257 * The "service", "instance", and "realm" arguments specify the
1258 * server's name; "aticket" contains the credential.
1260 * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1261 * called previously, and KFAILURE for anything else that went wrong.
1264 afs_tf_save_cred(aserver, atoken, aclient)
1265 struct ktc_principal *aserver;
1266 struct ktc_principal *aclient;
1267 struct ktc_token *atoken; /* Token */
1269 char realm[MAXKTCREALMLEN+1];
1270 char junk[MAXKTCNAMELEN];
1271 struct ktc_principal principal;
1272 struct ktc_token token;
1274 off_t start, lseek();
1276 int count; /* count for write */
1278 if (fd < 0) { /* fd is ticket file as set by afs_tf_init */
1282 ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1283 realm[MAXKTCREALMLEN] = '\0';
1285 /* Look for a duplicate ticket */
1286 (void) lseek(fd, (off_t) 0L, 0);
1287 curpos = sizeof(tfbfr);
1289 if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1290 afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1293 start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1294 status = afs_tf_get_cred(&principal, &token);
1295 } while (status == 0 &&
1296 (strcmp(aserver->name, principal.name) != 0 ||
1297 strcmp(aserver->instance, principal.instance) != 0 ||
1298 strcmp(aserver->cell, principal.cell) != 0));
1301 * Two tickets for the same user authenticating to the same service
1302 * should be the same length, but we check here just to make sure.
1304 if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1305 if (status && status != EOF) return status;
1307 /* Position over the credential we just matched (or the EOF) */
1308 lseek(fd, start, 0);
1309 curpos = lastpos = sizeof(tfbfr);
1311 /* Write the ticket and associated data */
1313 count = strlen(aserver->name) + 1;
1314 if (write(fd, aserver->name, count) != count)
1317 count = strlen(aserver->instance) + 1;
1318 if (write(fd, aserver->instance, count) != count)
1321 count = strlen(realm) + 1;
1322 if (write(fd, realm, count) != count)
1325 if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1328 lifetime = time_to_life(atoken->startTime, atoken->endTime);
1329 if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1332 kvno = atoken->kvno;
1333 if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1336 if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1340 count = atoken->ticketLen;
1341 if (write(fd, atoken->ticket, count) != count)
1344 if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1345 != sizeof(afs_int32))
1348 /* Actually, we should check each write for success */
1355 * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1358 * For copying and distribution information, please see the file
1359 * <mit-copyright.h>.
1365 * This routine is used to generate the name of the file that holds
1366 * the user's cache of server tickets and associated session keys.
1368 * If it is set, krb_ticket_string contains the ticket file name.
1369 * Otherwise, the filename is constructed as follows:
1371 * If it is set, the environment variable "KRBTKFILE" will be used as
1372 * the ticket file name. Otherwise TKT_ROOT (defined in "krb.h") and
1373 * the user's uid are concatenated to produce the ticket file name
1374 * (e.g., "/tmp/tkt123"). A pointer to the string containing the ticket
1375 * file name is returned.
1378 static char krb_ticket_string[4096] = "";
1380 char *ktc_tkt_string()
1385 if (!*krb_ticket_string) {
1386 if (env = getenv("KRBTKFILE")) {
1387 (void) strncpy(krb_ticket_string, env,
1388 sizeof(krb_ticket_string)-1);
1389 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1391 /* 32 bits of signed integer will always fit in 11 characters
1392 (including the sign), so no need to worry about overflow */
1393 (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1397 return krb_ticket_string;
1401 * This routine is used to set the name of the file that holds the user's
1402 * cache of server tickets and associated session keys.
1404 * The value passed in is copied into local storage.
1406 * NOTE: This routine should be called during initialization, before other
1407 * Kerberos routines are called; otherwise tkt_string() above may be called
1408 * and return an undesired ticket file name until this routine is called.
1412 ktc_set_tkt_string(val)
1417 (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1418 krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1425 * tf_create() is used to initialize the ticket store. It creates the
1426 * file to contain the tickets and writes the given user's name "pname"
1427 * and instance "pinst" in the file. in_tkt() returns KSUCCESS on
1428 * success, or KFAILURE if something goes wrong.
1431 afs_tf_create(pname,pinst)
1438 char *file = ktc_tkt_string();
1447 if (lstat(file,&sbuf) == 0) {
1448 if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1449 sbuf.st_mode & 077) {
1452 /* file already exists, and permissions appear ok, so nuke it */
1453 if ((fd = open(file, O_RDWR, 0)) < 0)
1454 goto out; /* can't zero it, but we can still try truncating it */
1456 bzero(zerobuf, sizeof(zerobuf));
1458 for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1459 if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1470 /* arrange so the file is owned by the ruid
1471 (swap real & effective uid if necessary).
1472 This isn't a security problem, since the ticket file, if it already
1473 exists, has the right uid (== ruid) and mode. */
1475 if (setreuid(metoo, me) < 0) {
1479 tktfile = creat(file, 0600);
1481 if (setreuid(me, metoo) < 0) {
1482 /* can't switch??? fail! */
1489 count = strlen(pname)+1;
1490 if (write(tktfile,pname,count) != count) {
1491 (void) close(tktfile);
1494 count = strlen(pinst)+1;
1495 if (write(tktfile,pinst,count) != count) {
1496 (void) close(tktfile);
1499 (void) close(tktfile);
1504 * dest_tkt() is used to destroy the ticket store upon logout.
1505 * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1506 * Otherwise the function returns 0 on success, KFAILURE on
1512 char *file = ktc_tkt_string();
1518 if (lstat(file,&statb) < 0)
1521 if (!(statb.st_mode & S_IFREG))
1524 if ((fd = open(file, O_RDWR, 0)) < 0)
1529 for (i = 0; i < statb.st_size; i += BUFSIZ)
1530 if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1539 (void) unlink(file);
1542 if (errno == ENOENT) return RET_TKFIL;
1543 else if (errno != 0) return KFAILURE;
1547 static afs_uint32 curpag()
1549 gid_t groups[NGROUPS_MAX];
1551 afs_uint32 h, l, ret;
1553 if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1555 g0 = groups[0] & 0xffff;
1556 g1 = groups[1] & 0xffff;
1559 if (g0 < 0xc000 && g1 < 0xc000) {
1560 l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1562 h = (g1 >> 14) + h + h + h;
1563 ret = ((h << 28) | l);
1564 /* Additional testing */
1565 if (((ret >> 24) & 0xff) == 'A')
1576 extern char **environ;
1580 char fname[256], *prefix = "/ticket/";
1582 char **newenv, **senv, **denv;
1585 if (stat("/ticket", &sbuf) == -1) {
1586 prefix = "/tmp/tkt";
1589 pag = curpag() & 0xffffffff;
1591 sprintf(fname, "%s%d", prefix, getuid());
1594 sprintf(fname, "%sp%ld", prefix, pag);
1596 ktc_set_tkt_string(fname);
1598 for (senv=environ, numenv=0; *senv; senv++) numenv++;
1599 newenv = (char **)malloc((numenv+2) * sizeof(char *));
1601 for (senv=environ, denv=newenv; *senv; *senv++) {
1602 if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1605 *denv = (char *)malloc(10 + strlen(fname) + 1);
1606 strcpy(*denv, "KRBTKFILE=");
1607 strcat(*denv, fname);
1614 * BLETCH! We have to invoke the entire afsconf package just to
1615 * find out what the local cell is.
1617 static ktc_LocalCell()
1620 struct afsconf_dir *conf;
1622 if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1623 (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1624 code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1625 afsconf_Close (conf);
1627 if (!conf || code) {
1628 printf("** Can't determine local cell name!\n");