805ef25b06621984147c7aaba59f4781c38650a3
[openafs.git] / src / auth / ktc.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
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
8  */
9
10 /* ticket caching code */
11
12 #include <afsconfig.h>
13 #if defined(UKERNEL)
14 #include "afs/param.h"
15 #else
16 #include <afs/param.h>
17 #endif
18
19 RCSID
20     ("$Header$");
21
22 #if defined(UKERNEL)
23 #include "afs/sysincludes.h"
24 #include "afsincludes.h"
25 #include "afs/stds.h"
26 #include "afs/pthread_glock.h"
27 #include "afs/vice.h"
28 #include "afs/auth.h"
29 #include "afs/venus.h"
30 #include "afs/pthread_glock.h"
31 #include "afs/dirpath.h"
32
33 #if !defined(min)
34 #define min(a,b) ((a)<(b)?(a):(b))
35 #endif /* !defined(min) */
36
37 #else /* defined(UKERNEL) */
38
39 #ifdef  AFS_SUN5_ENV
40 #include <unistd.h>
41 #endif
42 #include <stdio.h>
43 #include <afs/stds.h>
44 #include <afs/pthread_glock.h>
45 #include <sys/types.h>
46 #include <ctype.h>
47 #include <sys/stat.h>
48 #include <signal.h>
49 #include <errno.h>
50 #include <sys/ioctl.h>
51 #include <netinet/in.h>
52 #ifdef HAVE_STRING_H
53 #include <string.h>
54 #else
55 #ifdef HAVE_STRINGS_H
56 #include <strings.h>
57 #endif
58 #endif
59 #include <afs/vice.h>
60 #ifdef  AFS_AIX_ENV
61 #include <sys/lockf.h>
62 #ifdef AFS_AIX51_ENV
63 #include <sys/cred.h>
64 #endif
65 #endif
66 #ifdef HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
69 #include "auth.h"
70 #include <afs/venus.h>
71 #include <afs/afsutil.h>
72
73 #endif /* defined(UKERNEL) */
74
75 /* For malloc() */
76 #include <stdlib.h>
77 #include "ktc.h"
78
79 #ifdef  notdef
80 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
81 #define AFS_KERBEROS_ENV
82 #endif
83
84 #ifdef AFS_KERBEROS_ENV
85 #include <fcntl.h>
86 #include <sys/file.h>
87 #include "cellconfig.h"
88 static char lcell[MAXCELLCHARS];
89
90 #define TKT_ROOT "/tmp/tkt"
91
92 #define KSUCCESS 0
93 #define KFAILURE 255
94
95 /* Definitions for ticket file utilities */
96 #define R_TKT_FIL       0
97 #define W_TKT_FIL       1
98
99 /* Error codes returned by ticket file utilities */
100 #define         NO_TKT_FIL      76      /* No ticket file found */
101 #define         TKT_FIL_ACC     77      /* Couldn't access tkt file */
102 #define         TKT_FIL_LCK     78      /* Couldn't lock ticket file */
103 #define         TKT_FIL_FMT     79      /* Bad ticket file format */
104 #define         TKT_FIL_INI     80      /* afs_tf_init not called first */
105
106 /* Values returned by get_credentials */
107 #define         RET_TKFIL      21       /* Can't read ticket file */
108
109 #ifndef BUFSIZ
110 #define BUFSIZ 4096
111 #endif
112
113 #ifdef  AFS_HPUX_ENV
114 #include <unistd.h>
115 #endif
116 #if     defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
117 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
118 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
119 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
120 #endif
121 #ifdef AFS_HPUX_ENV
122 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
123 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
124 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
125 #endif
126
127 #ifndef EOF
128 #define EOF (-1)
129 #endif
130
131 /* the following routines aren't static anymore on behalf of the kerberos IV
132  * compatibility library built in subtree krb.
133  */
134 int afs_tf_init(), afs_tf_get_pname(), afs_tf_get_pinst(), afs_tf_get_cred();
135 int afs_tf_save_cred(), afs_tf_close(), afs_tf_create();
136 int afs_tf_dest_tkt();
137 static void ktc_LocalCell();
138 #endif /* AFS_KERBEROS_ENV */
139
140 #ifdef AFS_DUX40_ENV
141 #define PIOCTL afs_pioctl
142 #elif defined(UKERNEL)
143 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
144 #else
145 #define PIOCTL pioctl
146 #endif
147
148
149 #ifdef KERNEL_KTC_COMPAT
150
151 #ifndef KTC_SYSCALL
152 #define KTC_SYSCALL     32
153 #endif
154
155 /* Kernel call opcode definitions */
156 #define KTC_OPCODE_BASE         4300
157 #define KTC_NO_OP               (0+KTC_OPCODE_BASE)
158 #define KTC_SETTOKEN_OP         (1+KTC_OPCODE_BASE)
159 #define KTC_GETTOKEN_OP         (2+KTC_OPCODE_BASE)
160 #define KTC_LISTTOKENS_OP       (3+KTC_OPCODE_BASE)
161 #define KTC_FORGETTOKEN_OP      (4+KTC_OPCODE_BASE)
162 #define KTC_FORGETALLTOKENS_OP  (5+KTC_OPCODE_BASE)
163 #define KTC_STATUS_OP           (6+KTC_OPCODE_BASE)
164 #define KTC_GC_OP               (7+KTC_OPCODE_BASE)
165
166 #define KTC_INTERFACE_VERSION 3
167
168 /* We have to determine if the kernel supports the ktc system call.  To do so
169  * we attempt to execute its noop function.  If this is successful we use the
170  * kernel calls in the future otherwise we let the old code run. */
171
172 /* To safely check to see whether a system call exists we have to intercept the
173  * SIGSYS signal which is caused by executing a non-existant system call.  If
174  * it is ignored the syscall routine returns EINVAL.  The SIGSYS is reset to
175  * its old value after the return from syscall.  */
176
177 static int kernelKTC = 0;
178
179 #ifdef  AFS_DECOSF_ENV
180 /*
181  * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems.  You need
182  * to ignore SIGTRAP too.  It is claimed to be fixed under v1.3, but...
183  */
184
185 #define CHECK_KERNEL                                                    \
186     if (kernelKTC == 0) {                                               \
187         int code, ecode;                                                \
188         int (*old)();                                                   \
189         int (*old_t)();                                                 \
190         old = (int (*)())signal(SIGSYS, SIG_IGN);                       \
191         old_t = (int (*)())signal(SIGTRAP, SIG_IGN);                    \
192         code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0);             \
193         ecode = errno;                                                  \
194         signal(SIGSYS, old);                                            \
195         signal(SIGTRAP, old_t);                                         \
196         if (code == 0) kernelKTC = 1;                                   \
197         else kernelKTC = 2;                                             \
198 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
199     }
200
201 #else /* AFS_DECOSF_ENV */
202
203 #define CHECK_KERNEL                                                    \
204     if (kernelKTC == 0) {                                               \
205         int code, ecode;                                                \
206         int (*old)();                                                   \
207         old = (int (*)())signal(SIGSYS, SIG_IGN);                       \
208         code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0);             \
209         ecode = errno;                                                  \
210         signal(SIGSYS, old);                                            \
211         if (code == 0) kernelKTC = 1;                                   \
212         else kernelKTC = 2;                                             \
213 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
214     }
215 #endif /* AFS_DECOSF_ENV */
216
217 #define TRY_KERNEL(cmd,a1,a2,a3,a4)                                     \
218 {   CHECK_KERNEL;                                                       \
219     if (kernelKTC == 1)                                                 \
220         return syscall (KTC_SYSCALL, cmd,                               \
221                         KTC_INTERFACE_VERSION, a1,a2,a3,a4);            \
222 }
223
224 #else
225 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
226 #endif /* KERNEL_KTC_COMPAT */
227
228 #if !defined(UKERNEL)
229 /* this is a structure used to communicate with the afs cache mgr, but is
230  * otherwise irrelevant */
231 struct ClearToken {
232     afs_int32 AuthHandle;
233     char HandShakeKey[8];
234     afs_int32 ViceId;
235     afs_int32 BeginTimestamp;
236     afs_int32 EndTimestamp;
237 };
238 #endif /* !defined(UKERNEL) */
239
240 #define MAXLOCALTOKENS 4
241
242 static struct {
243     int valid;
244     struct ktc_principal server;
245     struct ktc_principal client;
246     struct ktc_token token;
247 } local_tokens[MAXLOCALTOKENS] = { {
248 0}, {
249 0}, {
250 0}, {
251 0}};
252
253 /* new interface routines to the ticket cache.  Only handle afs service right
254  * now. */
255
256 static int
257 NewSetToken(aserver, atoken, aclient, flags)
258      struct ktc_principal *aserver;
259      struct ktc_principal *aclient;
260      struct ktc_token *atoken;
261      afs_int32 flags;
262 {
263     TRY_KERNEL(KTC_SETTOKEN_OP, aserver, aclient, atoken,
264                sizeof(struct ktc_token));
265     /* no kernel ticket cache */
266     return EINVAL;
267 }
268
269 #define MAXPIOCTLTOKENLEN \
270 (3*sizeof(afs_int32)+MAXKTCTICKETLEN+sizeof(struct ClearToken)+MAXKTCREALMLEN)
271
272 static int
273 OldSetToken(aserver, atoken, aclient, flags)
274      struct ktc_principal *aserver, *aclient;
275      struct ktc_token *atoken;
276      afs_int32 flags;
277 {
278     struct ViceIoctl iob;
279     char tbuffer[MAXPIOCTLTOKENLEN];
280     register char *tp;
281     struct ClearToken ct;
282     register afs_int32 code;
283     afs_int32 temp;
284
285     if (strcmp(aserver->name, "afs") != 0) {
286         int found = -1;
287         int i;
288         for (i = 0; i < MAXLOCALTOKENS; i++)
289             if (local_tokens[i].valid) {
290                 if ((strcmp(local_tokens[i].server.name, aserver->name) == 0)
291                     &&
292                     (strcmp
293                      (local_tokens[i].server.instance,
294                       aserver->instance) == 0)
295                     && (strcmp(local_tokens[i].server.cell, aserver->cell) ==
296                         0)) {
297                     found = i;  /* replace existing entry */
298                     break;
299                 } else          /* valid, but no match */
300                     ;
301             } else
302                 found = i;      /* remember this empty slot */
303         if (found == -1)
304             return KTC_NOENT;
305         memcpy(&local_tokens[found].token, atoken, sizeof(struct ktc_token));
306         local_tokens[found].server = *aserver;
307         local_tokens[found].client = *aclient;
308         local_tokens[found].valid = 1;
309         return 0;
310     }
311     tp = tbuffer;               /* start copying here */
312     if ((atoken->ticketLen < MINKTCTICKETLEN)
313         || (atoken->ticketLen > MAXKTCTICKETLEN))
314         return KTC_TOOBIG;
315     memcpy(tp, &atoken->ticketLen, sizeof(afs_int32));  /* copy in ticket length */
316     tp += sizeof(afs_int32);
317     memcpy(tp, atoken->ticket, atoken->ticketLen);      /* copy in ticket */
318     tp += atoken->ticketLen;
319     /* next, copy in the "clear token", describing who we are */
320     ct.AuthHandle = atoken->kvno;       /* hide auth handle here */
321     memcpy(ct.HandShakeKey, &atoken->sessionKey, 8);
322
323     ct.BeginTimestamp = atoken->startTime;
324     ct.EndTimestamp = atoken->endTime;
325     if (ct.BeginTimestamp == 0)
326         ct.BeginTimestamp = 1;
327
328     if ((strlen(aclient->name) > strlen("AFS ID "))
329         && (aclient->instance[0] == 0)) {
330         int sign = 1;
331         afs_int32 viceId = 0;
332         char *cp = aclient->name + strlen("AFS ID ");
333         if (*cp == '-') {
334             sign = -1;
335             cp++;
336         }
337         while (*cp) {
338             if (isdigit(*cp))
339                 viceId = viceId * 10 + (int)(*cp - '0');
340             else
341                 goto not_vice_id;
342             cp++;
343         }
344         ct.ViceId = viceId * sign;      /* OK to let any value here? */
345         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
346             ct.BeginTimestamp++;        /* force lifetime to be odd */
347     } else {
348       not_vice_id:
349         ct.ViceId = getuid();   /* wrong, but works in primary cell */
350         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
351             ct.BeginTimestamp++;        /* force lifetime to be even */
352     }
353
354 #ifdef UKERNEL
355     /*
356      * Information needed by the user space cache manager
357      */
358     u.u_expiration = ct.EndTimestamp;
359     u.u_viceid = ct.ViceId;
360 #endif
361
362     temp = sizeof(struct ClearToken);
363     memcpy(tp, &temp, sizeof(afs_int32));
364     tp += sizeof(afs_int32);
365     memcpy(tp, &ct, sizeof(struct ClearToken));
366     tp += sizeof(struct ClearToken);
367
368     /* next copy in primary flag */
369     temp = 0;
370
371     /*
372      * The following means that setpag will happen inside afs just before
373      * the authentication to prevent the setpag/klog race condition.
374      *
375      * The following means that setpag will affect the parent process as
376      * well as the current process.
377      */
378     if (flags & AFS_SETTOK_SETPAG)
379         temp |= 0x8000;
380
381     memcpy(tp, &temp, sizeof(afs_int32));
382     tp += sizeof(afs_int32);
383
384     /* finally copy in the cell name */
385     temp = strlen(aserver->cell);
386     if (temp >= MAXKTCREALMLEN)
387         return KTC_TOOBIG;
388     strcpy(tp, aserver->cell);
389     tp += temp + 1;
390
391     /* now setup for the pioctl */
392     iob.in = tbuffer;
393     iob.in_size = tp - tbuffer;
394     iob.out = tbuffer;
395     iob.out_size = sizeof(tbuffer);
396
397 #if defined(NO_AFS_CLIENT)
398     {
399         int fd;                 /* DEBUG */
400         char *tkfile;
401         if ((tkfile = getenv("TKTFILE"))
402             &&
403             ((fd =
404               open(tkfile, O_WRONLY | O_APPEND | O_TRUNC | O_CREAT,
405                    0644)) >= 0)) {
406             printf("Writing ticket to: %s\n", tkfile);
407             code = (write(fd, iob.in, iob.in_size) != iob.in_size);
408             close(fd);
409         } else
410             code = KTC_PIOCTLFAIL;
411     }
412 #else /* NO_AFS_CLIENT */
413     code = PIOCTL(0, VIOCSETTOK, &iob, 0);
414 #endif /* NO_AFS_CLIENT */
415     if (code)
416         return KTC_PIOCTLFAIL;
417     return 0;
418 }
419
420 int
421 ktc_SetToken(struct ktc_principal *aserver,
422     struct ktc_token *atoken,
423     struct ktc_principal *aclient,
424     afs_int32 flags)
425 {
426     int ncode, ocode;
427
428     LOCK_GLOBAL_MUTEX;
429 #ifdef AFS_KERBEROS_ENV
430     if (!lcell[0])
431         ktc_LocalCell();
432
433     if (                        /*!strcmp(aclient->cell, lcell) && this would only store local creds */
434            (strcmp(aserver->name, "AuthServer")
435             || strcmp(aserver->instance, "Admin"))) {
436         if (strcmp(aserver->name, "krbtgt") == 0) {
437             static char lrealm[MAXKTCREALMLEN];
438
439             if (!lrealm[0])
440                 ucstring(lrealm, lcell, MAXKTCREALMLEN);
441             if (strcmp(aserver->instance, lrealm) == 0) {
442                 afs_tf_create(aclient->name, aclient->instance);
443             }
444         }
445
446         ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
447         if (ncode == NO_TKT_FIL) {
448             (void)afs_tf_create(aclient->name, aclient->instance);
449             ncode = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
450         }
451
452         if (!ncode) {
453             afs_tf_save_cred(aserver, atoken, aclient);
454         }
455         afs_tf_close();
456 #ifdef NO_AFS_CLIENT
457         UNLOCK_GLOBAL_MUTEX;
458         return ncode;
459 #endif /* NO_AFS_CLIENT */
460     }
461 #endif
462
463 #ifndef NO_AFS_CLIENT
464     ncode = NewSetToken(aserver, atoken, aclient, flags);
465     if (ncode ||                /* new style failed */
466         (strcmp(aserver->name, "afs") == 0)) {  /* for afs tokens do both */
467         ocode = OldSetToken(aserver, atoken, aclient, flags);
468     } else
469         ocode = 0;
470     if (ncode && ocode) {
471         UNLOCK_GLOBAL_MUTEX;
472         if (ocode == -1)
473             ocode = errno;
474         else if (ocode == KTC_PIOCTLFAIL)
475             ocode = errno;
476         if (ocode == ESRCH)
477             return KTC_NOCELL;
478         if (ocode == EINVAL)
479             return KTC_NOPIOCTL;
480         if (ocode == EIO)
481             return KTC_NOCM;
482         return KTC_PIOCTLFAIL;
483     }
484 #endif /* NO_AFS_CLIENT */
485     UNLOCK_GLOBAL_MUTEX;
486     return 0;
487 }
488
489 /* get token, given server we need and token buffer.  aclient will eventually
490  * be set to our identity to the server.
491  */
492 ktc_GetToken(aserver, atoken, atokenLen, aclient)
493      struct ktc_principal *aserver, *aclient;
494      int atokenLen;
495      struct ktc_token *atoken;
496 {
497     struct ViceIoctl iob;
498     char tbuffer[MAXPIOCTLTOKENLEN];
499     register afs_int32 code;
500     int index;
501     char *stp, *cellp;          /* secret token ptr */
502     struct ClearToken ct;
503     register char *tp;
504     afs_int32 temp;
505     int maxLen;                 /* biggest ticket we can copy */
506     int tktLen;                 /* server ticket length */
507     char found = 0;
508
509     LOCK_GLOBAL_MUTEX;
510 #ifndef NO_AFS_CLIENT
511     TRY_KERNEL(KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
512 #endif /* NO_AFS_CLIENT */
513
514 #ifdef AFS_KERBEROS_ENV
515     if (!lcell[0])
516         ktc_LocalCell();
517 #endif
518 #ifndef NO_AFS_CLIENT
519     if (strcmp(aserver->name, "afs") != 0)
520 #endif /* NO_AFS_CLIENT */
521     {
522         int i;
523         /* try the local tokens */
524         for (i = 0; i < MAXLOCALTOKENS; i++)
525             if (local_tokens[i].valid
526                 && (strcmp(local_tokens[i].server.name, aserver->name) == 0)
527                 && (strcmp(local_tokens[i].server.instance, aserver->instance)
528                     == 0)
529                 && (strcmp(local_tokens[i].server.cell, aserver->cell) == 0)) {
530                 memcpy(atoken, &local_tokens[i].token,
531                        min(atokenLen, sizeof(struct ktc_token)));
532                 if (aclient)
533                     *aclient = local_tokens[i].client;
534                 UNLOCK_GLOBAL_MUTEX;
535                 return 0;
536             }
537 #ifdef AFS_KERBEROS_ENV
538         if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
539             if (aclient) {
540                 if (!afs_tf_get_pname(aclient->name)
541                     && !afs_tf_get_pinst(aclient->instance))
542                     found = 1;
543             } else {
544                 char tmpstring[MAXHOSTCHARS];
545                 afs_tf_get_pname(&tmpstring);
546                 afs_tf_get_pinst(&tmpstring);
547                 found = 1;
548             }
549         }
550         if (found) {
551             struct ktc_principal cprincipal;
552             struct ktc_token ctoken;
553
554             while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
555                 if (strcmp(cprincipal.name, aserver->name) == 0
556                     && strcmp(cprincipal.instance, aserver->instance) == 0
557                     && strcmp(cprincipal.cell, aserver->cell) == 0) {
558
559                     if (aclient)
560                         strcpy(aclient->cell, lcell);
561                     memcpy(atoken, &ctoken,
562                            min(atokenLen, sizeof(struct ktc_token)));
563
564                     afs_tf_close();
565                     UNLOCK_GLOBAL_MUTEX;
566                     return 0;
567                 }
568             }
569         }
570         afs_tf_close();
571 #endif
572         UNLOCK_GLOBAL_MUTEX;
573         return KTC_NOENT;
574     }
575 #ifndef NO_AFS_CLIENT
576     for (index = 0; index < 200; index++) {     /* sanity check in case pioctl fails */
577         iob.in = (char *)&index;
578         iob.in_size = sizeof(afs_int32);
579         iob.out = tbuffer;
580         iob.out_size = sizeof(tbuffer);
581
582         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
583
584         if (code) {
585             /* failed to retrieve specified token */
586             if (code < 0 && errno == EDOM) {
587                 UNLOCK_GLOBAL_MUTEX;
588                 return KTC_NOENT;
589             }
590         } else {
591             /* token retrieved; parse buffer */
592             tp = tbuffer;
593
594             /* get ticket length */
595             memcpy(&temp, tp, sizeof(afs_int32));
596             tktLen = temp;
597             tp += sizeof(afs_int32);
598
599             /* remember where ticket is and skip over it */
600             stp = tp;
601             tp += tktLen;
602
603             /* get size of clear token and verify */
604             memcpy(&temp, tp, sizeof(afs_int32));
605             if (temp != sizeof(struct ClearToken)) {
606                 UNLOCK_GLOBAL_MUTEX;
607                 return KTC_ERROR;
608             }
609             tp += sizeof(afs_int32);
610
611             /* copy clear token */
612             memcpy(&ct, tp, temp);
613             tp += temp;
614
615             /* skip over primary flag */
616             tp += sizeof(afs_int32);
617
618             /* remember where cell name is */
619             cellp = tp;
620
621             if ((strcmp(cellp, aserver->cell) == 0)
622 #ifdef  AFS_KERBEROS_ENV
623                 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
624 #endif
625                 ) {
626                 /* got token for cell; check that it will fit */
627                 maxLen =
628                     atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
629                 if (maxLen < tktLen) {
630                     UNLOCK_GLOBAL_MUTEX;
631                     return KTC_TOOBIG;
632                 }
633
634                 /* set return values */
635                 memcpy(atoken->ticket, stp, tktLen);
636                 atoken->startTime = ct.BeginTimestamp;
637                 atoken->endTime = ct.EndTimestamp;
638                 if (ct.AuthHandle == -1) {
639                     ct.AuthHandle = 999;
640                 }
641                 atoken->kvno = ct.AuthHandle;
642                 memcpy(&atoken->sessionKey, ct.HandShakeKey,
643                        sizeof(struct ktc_encryptionKey));
644                 atoken->ticketLen = tktLen;
645
646                 if (aclient) {
647                     strcpy(aclient->cell, cellp);
648                     aclient->instance[0] = 0;
649
650                     if ((atoken->kvno == 999) ||        /* old style bcrypt ticket */
651                         (ct.BeginTimestamp &&   /* new w/ prserver lookup */
652                          (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
653                         sprintf(aclient->name, "AFS ID %d", ct.ViceId);
654                     } else {
655                         sprintf(aclient->name, "Unix UID %d", ct.ViceId);
656                     }
657                 }
658                 UNLOCK_GLOBAL_MUTEX;
659                 return 0;
660             }
661         }
662     }
663 #endif /* NO_AFS_CLIENT */
664
665     UNLOCK_GLOBAL_MUTEX;
666     if ((code < 0) && (errno == EINVAL))
667         return KTC_NOPIOCTL;
668     return KTC_PIOCTLFAIL;      /* probable cause */
669 }
670
671 /*
672  * Forget tokens for this server and the calling user.
673  * NOT IMPLEMENTED YET!
674  */
675 #ifndef NO_AFS_CLIENT
676 ktc_ForgetToken(aserver)
677      struct ktc_principal *aserver;
678 {
679     int rc;
680
681     LOCK_GLOBAL_MUTEX;
682     TRY_KERNEL(KTC_FORGETTOKEN_OP, aserver, 0, 0, 0);
683
684     rc = ktc_ForgetAllTokens(); /* bogus, but better */
685     UNLOCK_GLOBAL_MUTEX;
686     return rc;
687 }
688 #endif /* NO_AFS_CLIENT */
689
690 /* ktc_ListTokens - list all tokens.  start aprevIndex at 0, it returns the
691  * next rock in (*aindex).  (*aserver) is set to the relevant ticket on
692  * success.  */
693
694 int
695 ktc_ListTokens(int aprevIndex,
696     int *aindex,
697     struct ktc_principal *aserver)
698 {
699     struct ViceIoctl iob;
700     char tbuffer[MAXPIOCTLTOKENLEN];
701     register afs_int32 code;
702     register char *tp;
703     afs_int32 temp, index;
704
705     memset(tbuffer, 0, sizeof(tbuffer));
706
707     LOCK_GLOBAL_MUTEX;
708 #ifndef NO_AFS_CLIENT
709     TRY_KERNEL(KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
710 #endif /* NO_AFS_CLIENT */
711
712     index = aprevIndex;
713 #ifdef NO_AFS_CLIENT
714     if (index < 214)
715         index = 214;
716 #endif /* NO_AFS_CLIENT */
717 #ifdef AFS_KERBEROS_ENV
718     if (index >= 214) {
719         int i;
720         struct ktc_principal cprincipal;
721         struct ktc_token ctoken;
722
723         if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL)
724             || afs_tf_get_pname(tbuffer) || afs_tf_get_pinst(tbuffer)) {
725             afs_tf_close();
726             UNLOCK_GLOBAL_MUTEX;
727             return KTC_NOENT;
728         }
729
730         for (i = 214; i < index; i++) {
731             if (afs_tf_get_cred(&cprincipal, &ctoken)) {
732                 afs_tf_close();
733                 UNLOCK_GLOBAL_MUTEX;
734                 return KTC_NOENT;
735             }
736         }
737
738       again:
739         if (afs_tf_get_cred(&cprincipal, &ctoken)) {
740             afs_tf_close();
741             UNLOCK_GLOBAL_MUTEX;
742             return KTC_NOENT;
743         }
744         index++;
745
746 #ifndef NO_AFS_CLIENT
747         if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0] == 0) {
748             goto again;
749         }
750 #endif /* NO_AFS_CLIENT */
751
752         for (i = 0; i < MAXLOCALTOKENS; i++) {
753             if (!strcmp(cprincipal.name, local_tokens[i].server.name)
754                 && !strcmp(cprincipal.instance,
755                            local_tokens[i].server.instance)
756                 && !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
757                 goto again;
758             }
759         }
760
761         *aserver = cprincipal;
762         *aindex = index;
763         afs_tf_close();
764         UNLOCK_GLOBAL_MUTEX;
765         return 0;
766     }
767 #endif
768
769 #ifndef NO_AFS_CLIENT
770     if (index >= 123) {         /* special hack for returning TCS */
771         while (index - 123 < MAXLOCALTOKENS) {
772             if (local_tokens[index - 123].valid) {
773                 *aserver = local_tokens[index - 123].server;
774                 *aindex = index + 1;
775                 UNLOCK_GLOBAL_MUTEX;
776                 return 0;
777             }
778             index++;
779         }
780         UNLOCK_GLOBAL_MUTEX;
781 #ifdef AFS_KERBEROS_ENV
782         return ktc_ListTokens(214, aindex, aserver);
783 #else
784         return KTC_NOENT;
785 #endif
786     }
787
788     /* get tokens from the kernel */
789     while (index < 200) {       /* sanity check in case pioctl fails */
790         iob.in = (char *)&index;
791         iob.in_size = sizeof(afs_int32);
792         iob.out = tbuffer;
793         iob.out_size = sizeof(tbuffer);
794         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
795         if (code < 0 && errno == EDOM) {
796             if (index < 123) {
797                 int rc;
798                 rc = ktc_ListTokens(123, aindex, aserver);
799                 UNLOCK_GLOBAL_MUTEX;
800                 return rc;
801             } else {
802                 UNLOCK_GLOBAL_MUTEX;
803                 return KTC_NOENT;
804             }
805         }
806         if (code == 0)
807             break;              /* got a ticket */
808         /* otherwise we should skip this ticket slot */
809         index++;
810     }
811     if (code < 0) {
812         UNLOCK_GLOBAL_MUTEX;
813         if (errno == EINVAL)
814             return KTC_NOPIOCTL;
815         return KTC_PIOCTLFAIL;
816     }
817
818     /* parse buffer */
819     tp = tbuffer;
820
821     /* next iterator determined by earlier loop */
822     *aindex = index + 1;
823
824     memcpy(&temp, tp, sizeof(afs_int32));       /* get size of secret token */
825     tp += sizeof(afs_int32);
826     tp += temp;                 /* skip ticket for now */
827     memcpy(&temp, tp, sizeof(afs_int32));       /* get size of clear token */
828     if (temp != sizeof(struct ClearToken)) {
829         UNLOCK_GLOBAL_MUTEX;
830         return KTC_ERROR;
831     }
832     tp += sizeof(afs_int32);    /* skip length */
833     tp += temp;                 /* skip clear token itself */
834     tp += sizeof(afs_int32);    /* skip primary flag */
835     /* tp now points to the cell name */
836     strcpy(aserver->cell, tp);
837     aserver->instance[0] = 0;
838     strcpy(aserver->name, "afs");
839 #endif /* NO_AFS_CLIENT */
840     UNLOCK_GLOBAL_MUTEX;
841     return 0;
842 }
843
844 /* discard all tokens from this user's cache */
845
846 static int
847 NewForgetAll(void)
848 {
849 #ifndef NO_AFS_CLIENT
850     TRY_KERNEL(KTC_FORGETALLTOKENS_OP, 0, 0, 0, 0);
851 #endif /* NO_AFS_CLIENT */
852     return EINVAL;
853 }
854
855 static int
856 OldForgetAll(void)
857 {
858     struct ViceIoctl iob;
859     register afs_int32 code;
860     int i;
861
862     for (i = 0; i < MAXLOCALTOKENS; i++)
863         local_tokens[i].valid = 0;
864
865     iob.in = 0;
866     iob.in_size = 0;
867     iob.out = 0;
868     iob.out_size = 0;
869 #ifndef NO_AFS_CLIENT
870     code = PIOCTL(0, VIOCUNPAG, &iob, 0);
871     if (code)
872         return KTC_PIOCTLFAIL;
873 #endif /* NO_AFS_CLIENT */
874     return 0;
875 }
876
877 int
878 ktc_ForgetAllTokens(void)
879 {
880     int ncode, ocode;
881
882     LOCK_GLOBAL_MUTEX;
883 #ifdef AFS_KERBEROS_ENV
884     (void)afs_tf_dest_tkt();
885 #endif
886
887     ncode = NewForgetAll();
888     ocode = OldForgetAll();
889     if (ncode && ocode) {
890         if (ocode == -1)
891             ocode = errno;
892         else if (ocode == KTC_PIOCTLFAIL)
893             ocode = errno;
894         UNLOCK_GLOBAL_MUTEX;
895         if (ocode == EINVAL)
896             return KTC_NOPIOCTL;
897         return KTC_PIOCTLFAIL;
898     }
899     UNLOCK_GLOBAL_MUTEX;
900     return 0;
901 }
902
903 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
904  * pioctl interface for delivering AFS tickets to the cache manager. */
905
906 ktc_OldPioctl()
907 {
908     int rc;
909     LOCK_GLOBAL_MUTEX;
910 #ifdef  KERNEL_KTC_COMPAT
911     CHECK_KERNEL;
912     rc = (kernelKTC != 1);      /* old style interface */
913 #else
914     rc = 1;
915 #endif
916     UNLOCK_GLOBAL_MUTEX;
917     return rc;
918 }
919
920
921 #ifdef AFS_KERBEROS_ENV
922  /*
923   * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
924   *
925   * For copying and distribution information, please see the file
926   * <mit-copyright.h>.
927   */
928
929 #if 0
930 #include <stdio.h>
931 #include <errno.h>
932 #include <sys/types.h>
933 #include <sys/stat.h>
934 #include <sys/file.h>
935 #include <krb.h>
936 #endif
937
938 #define TOO_BIG -1
939 #define TF_LCK_RETRY ((unsigned)2)      /* seconds to sleep before
940                                          * retry if ticket file is
941                                          * locked */
942
943 /*
944  * fd must be initialized to something that won't ever occur as a real
945  * file descriptor. Since open(2) returns only non-negative numbers as
946  * valid file descriptors, and afs_tf_init always stuffs the return value
947  * from open in here even if it is an error flag, we must
948  *      a. Initialize fd to a negative number, to indicate that it is
949  *         not initially valid.
950  *      b. When checking for a valid fd, assume that negative values
951  *         are invalid (ie. when deciding whether afs_tf_init has been
952  *         called.)
953  *      c. In tf_close, be sure it gets reinitialized to a negative
954  *         number. 
955  */
956 static fd = -1;
957 static curpos;                  /* Position in tfbfr */
958 static lastpos;                 /* End of tfbfr */
959 static char tfbfr[BUFSIZ];      /* Buffer for ticket data */
960
961 static tf_gets(), tf_read();
962
963 /*
964  * This file contains routines for manipulating the ticket cache file.
965  *
966  * The ticket file is in the following format:
967  *
968  *      principal's name        (null-terminated string)
969  *      principal's instance    (null-terminated string)
970  *      CREDENTIAL_1
971  *      CREDENTIAL_2
972  *      ...
973  *      CREDENTIAL_n
974  *      EOF
975  *
976  *      Where "CREDENTIAL_x" consists of the following fixed-length
977  *      fields from the CREDENTIALS structure (see "krb.h"):
978  *
979  *              char            service[MAXKTCNAMELEN]
980  *              char            instance[MAXKTCNAMELEN]
981  *              char            realm[REALM_SZ]
982  *              C_Block         session
983  *              int             lifetime
984  *              int             kvno
985  *              KTEXT_ST        ticket_st
986  *              afs_int32            issue_date
987  *
988  * Short description of routines:
989  *
990  * afs_tf_init() opens the ticket file and locks it.
991  *
992  * afs_tf_get_pname() returns the principal's name.
993  *
994  * afs_tf_get_pinst() returns the principal's instance (may be null).
995  *
996  * afs_tf_get_cred() returns the next CREDENTIALS record.
997  *
998  * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
999  *
1000  * afs_tf_close() closes the ticket file and releases the lock.
1001  *
1002  * tf_gets() returns the next null-terminated string.  It's an internal
1003  * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and 
1004  * afs_tf_get_cred().
1005  *
1006  * tf_read() reads a given number of bytes.  It's an internal routine
1007  * used by afs_tf_get_cred().
1008  */
1009
1010 /*
1011  * afs_tf_init() should be called before the other ticket file routines.
1012  * It takes the name of the ticket file to use, "tf_name", and a
1013  * read/write flag "rw" as arguments. 
1014  *
1015  * It tries to open the ticket file, checks the mode, and if everything
1016  * is okay, locks the file.  If it's opened for reading, the lock is
1017  * shared.  If it's opened for writing, the lock is exclusive. 
1018  *
1019  * Returns 0 if all went well, otherwise one of the following: 
1020  *
1021  * NO_TKT_FIL   - file wasn't there
1022  * TKT_FIL_ACC  - file was in wrong mode, etc.
1023  * TKT_FIL_LCK  - couldn't lock the file, even after a retry
1024  */
1025
1026 afs_tf_init(tf_name, rw)
1027      char *tf_name;
1028 {
1029     int wflag;
1030     int me;
1031     struct stat stat_buf;
1032
1033     switch (rw) {
1034     case R_TKT_FIL:
1035         wflag = 0;
1036         break;
1037     case W_TKT_FIL:
1038         wflag = 1;
1039         break;
1040     default:
1041         return TKT_FIL_ACC;
1042     }
1043     if (lstat(tf_name, &stat_buf) < 0)
1044         switch (errno) {
1045         case ENOENT:
1046             return NO_TKT_FIL;
1047         default:
1048             return TKT_FIL_ACC;
1049         }
1050     me = getuid();
1051     if ((stat_buf.st_uid != me && me != 0)
1052         || ((stat_buf.st_mode & S_IFMT) != S_IFREG))
1053         return TKT_FIL_ACC;
1054
1055     /*
1056      * If "wflag" is set, open the ticket file in append-writeonly mode
1057      * and lock the ticket file in exclusive mode.  If unable to lock
1058      * the file, sleep and try again.  If we fail again, return with the
1059      * proper error message. 
1060      */
1061
1062     curpos = sizeof(tfbfr);
1063
1064     if (wflag) {
1065         fd = open(tf_name, O_RDWR, 0600);
1066         if (fd < 0) {
1067             return TKT_FIL_ACC;
1068         }
1069 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1070         if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1071             sleep(TF_LCK_RETRY);
1072             if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1073 #else
1074         if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1075             sleep(TF_LCK_RETRY);
1076             if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1077 #endif
1078                 (void)close(fd);
1079                 fd = -1;
1080                 return TKT_FIL_LCK;
1081             }
1082         }
1083         return 0;
1084     }
1085     /*
1086      * Otherwise "wflag" is not set and the ticket file should be opened
1087      * for read-only operations and locked for shared access. 
1088      */
1089
1090     fd = open(tf_name, O_RDONLY, 0600);
1091     if (fd < 0) {
1092         return TKT_FIL_ACC;
1093     }
1094 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1095     if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1096         sleep(TF_LCK_RETRY);
1097         if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1098 #else
1099     if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1100         sleep(TF_LCK_RETRY);
1101         if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1102 #endif
1103             (void)close(fd);
1104             fd = -1;
1105             return TKT_FIL_LCK;
1106         }
1107     }
1108     return 0;
1109 }
1110
1111 /*
1112  * afs_tf_get_pname() reads the principal's name from the ticket file. It
1113  * should only be called after afs_tf_init() has been called.  The
1114  * principal's name is filled into the "p" parameter.  If all goes well,
1115  * 0 is returned.  If afs_tf_init() wasn't called, TKT_FIL_INI is
1116  * returned.  If the name was null, or EOF was encountered, or the name
1117  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. 
1118  */
1119
1120 afs_tf_get_pname(p)
1121      char *p;
1122 {
1123     if (fd < 0) {
1124         return TKT_FIL_INI;
1125     }
1126     if (tf_gets(p, MAXKTCNAMELEN) < 2)  /* can't be just a null */
1127         return TKT_FIL_FMT;
1128     return 0;
1129 }
1130
1131 /*
1132  * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1133  * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1134  * been called.  The instance is filled into the "inst" parameter.  If all
1135  * goes well, 0 is returned.  If afs_tf_init() wasn't called,
1136  * TKT_FIL_INI is returned.  If EOF was encountered, or the instance
1137  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.  Note that the
1138  * instance may be null. 
1139  */
1140
1141 afs_tf_get_pinst(inst)
1142      char *inst;
1143 {
1144     if (fd < 0) {
1145         return TKT_FIL_INI;
1146     }
1147     if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1148         return TKT_FIL_FMT;
1149     return 0;
1150 }
1151
1152 /*
1153  * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1154  * in the given structure "c".  It should only be called after afs_tf_init(),
1155  * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes 
1156  * well, 0 is returned.  Possible error codes are: 
1157  *
1158  * TKT_FIL_INI  - afs_tf_init wasn't called first
1159  * TKT_FIL_FMT  - bad format
1160  * EOF          - end of file encountered
1161  */
1162
1163 afs_tf_get_cred(principal, token)
1164      struct ktc_principal *principal;
1165      struct ktc_token *token;
1166 {
1167     int k_errno;
1168     int kvno, lifetime;
1169     long mit_compat;            /* MIT Kerberos 5 with Krb4 uses a "long" for issue_date */
1170
1171     if (fd < 0) {
1172         return TKT_FIL_INI;
1173     }
1174     if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1175         switch (k_errno) {
1176         case TOO_BIG:
1177         case 1:         /* can't be just a null */
1178             return TKT_FIL_FMT;
1179         case 0:
1180             return EOF;
1181         }
1182     if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1183         switch (k_errno) {
1184         case TOO_BIG:
1185             return TKT_FIL_FMT;
1186         case 0:
1187             return EOF;
1188         }
1189     if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1190         switch (k_errno) {
1191         case TOO_BIG:
1192         case 1:         /* can't be just a null */
1193             return TKT_FIL_FMT;
1194         case 0:
1195             return EOF;
1196         }
1197     lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1198     if (tf_read((char *)&(token->sessionKey), 8) < 1
1199         || tf_read((char *)&(lifetime), sizeof(lifetime)) < 1
1200         || tf_read((char *)&(kvno), sizeof(kvno)) < 1
1201         || tf_read((char *)&(token->ticketLen), sizeof(token->ticketLen))
1202         < 1 ||
1203         /* don't try to read a silly amount into ticket->dat */
1204         token->ticketLen > MAXKTCTICKETLEN
1205         || tf_read((char *)(token->ticket), token->ticketLen) < 1
1206         || tf_read((char *)&mit_compat, sizeof(mit_compat)) < 1) {
1207         return TKT_FIL_FMT;
1208     }
1209     token->startTime = mit_compat;
1210     token->endTime = life_to_time(token->startTime, lifetime);
1211     token->kvno = kvno;
1212     return 0;
1213 }
1214
1215 /*
1216  * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1217  * not a valid file descriptor, it just returns.  It also clears the
1218  * buffer used to read tickets.
1219  *
1220  * The return value is not defined.
1221  */
1222
1223 afs_tf_close()
1224 {
1225     if (!(fd < 0)) {
1226 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1227         (void)fcntl(fd, F_SETLK, &fileUlock);
1228 #else
1229         (void)flock(fd, LOCK_UN);
1230 #endif
1231         (void)close(fd);
1232         fd = -1;                /* see declaration of fd above */
1233     }
1234     memset(tfbfr, 0, sizeof(tfbfr));
1235 }
1236
1237 /*
1238  * tf_gets() is an internal routine.  It takes a string "s" and a count
1239  * "n", and reads from the file until either it has read "n" characters,
1240  * or until it reads a null byte. When finished, what has been read exists
1241  * in "s".
1242  *
1243  * Possible return values are:
1244  *
1245  * n            the number of bytes read (including null terminator)
1246  *              when all goes well
1247  *
1248  * 0            end of file or read error
1249  *
1250  * TOO_BIG      if "count" characters are read and no null is
1251  *              encountered. This is an indication that the ticket
1252  *              file is seriously ill.
1253  */
1254
1255 static
1256 tf_gets(s, n)
1257      register char *s;
1258 {
1259     register count;
1260
1261     if (fd < 0) {
1262         return TKT_FIL_INI;
1263     }
1264     for (count = n - 1; count > 0; --count) {
1265         if (curpos >= sizeof(tfbfr)) {
1266             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1267             curpos = 0;
1268         }
1269         if (curpos == lastpos) {
1270             return 0;
1271         }
1272         *s = tfbfr[curpos++];
1273         if (*s++ == '\0')
1274             return (n - count);
1275     }
1276     return TOO_BIG;
1277 }
1278
1279 /*
1280  * tf_read() is an internal routine.  It takes a string "s" and a count
1281  * "n", and reads from the file until "n" bytes have been read.  When
1282  * finished, what has been read exists in "s".
1283  *
1284  * Possible return values are:
1285  *
1286  * n            the number of bytes read when all goes well
1287  *
1288  * 0            on end of file or read error
1289  */
1290
1291 static
1292 tf_read(s, n)
1293      register char *s;
1294      register n;
1295 {
1296     register count;
1297
1298     for (count = n; count > 0; --count) {
1299         if (curpos >= sizeof(tfbfr)) {
1300             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1301             curpos = 0;
1302         }
1303         if (curpos == lastpos) {
1304             return 0;
1305         }
1306         *s++ = tfbfr[curpos++];
1307     }
1308     return n;
1309 }
1310
1311 char *tkt_string();
1312
1313 /*
1314  * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1315  * file.  You must call afs_tf_init() before calling afs_tf_save_cred().
1316  *
1317  * The "service", "instance", and "realm" arguments specify the
1318  * server's name; "aticket" contains the credential.
1319  *
1320  * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1321  * called previously, and KFAILURE for anything else that went wrong.
1322  */
1323
1324 afs_tf_save_cred(aserver, atoken, aclient)
1325      struct ktc_principal *aserver;
1326      struct ktc_principal *aclient;
1327      struct ktc_token *atoken;  /* Token */
1328 {
1329     char realm[MAXKTCREALMLEN + 1];
1330     char junk[MAXKTCNAMELEN];
1331     struct ktc_principal principal;
1332     struct ktc_token token;
1333     int status;
1334     off_t start;
1335     int lifetime, kvno;
1336     int count;                  /* count for write */
1337     long mit_compat;            /* MIT Kerberos 5 with Krb4 uses a "long" for issue_date */
1338
1339     if (fd < 0) {               /* fd is ticket file as set by afs_tf_init */
1340         return TKT_FIL_INI;
1341     }
1342
1343     ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1344     realm[MAXKTCREALMLEN] = '\0';
1345
1346     /* Look for a duplicate ticket */
1347     (void)lseek(fd, (off_t) 0L, 0);
1348     curpos = sizeof(tfbfr);
1349
1350     if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name)
1351         || afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance))
1352         goto bad;
1353
1354     do {
1355         start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1356         status = afs_tf_get_cred(&principal, &token);
1357     } while (status == 0
1358              && (strcmp(aserver->name, principal.name) != 0
1359                  || strcmp(aserver->instance, principal.instance) != 0
1360                  || strcmp(aserver->cell, principal.cell) != 0));
1361
1362     /*
1363      * Two tickets for the same user authenticating to the same service
1364      * should be the same length, but we check here just to make sure.
1365      */
1366     if (status == 0 && token.ticketLen != atoken->ticketLen)
1367         return KFAILURE;
1368     if (status && status != EOF)
1369         return status;
1370
1371     /* Position over the credential we just matched (or the EOF) */
1372     lseek(fd, start, 0);
1373     curpos = lastpos = sizeof(tfbfr);
1374
1375     /* Write the ticket and associated data */
1376     /* Service */
1377     count = strlen(aserver->name) + 1;
1378     if (write(fd, aserver->name, count) != count)
1379         goto bad;
1380     /* Instance */
1381     count = strlen(aserver->instance) + 1;
1382     if (write(fd, aserver->instance, count) != count)
1383         goto bad;
1384     /* Realm */
1385     count = strlen(realm) + 1;
1386     if (write(fd, realm, count) != count)
1387         goto bad;
1388     /* Session key */
1389     if (write(fd, (char *)&atoken->sessionKey, 8) != 8)
1390         goto bad;
1391     /* Lifetime */
1392     lifetime = time_to_life(atoken->startTime, atoken->endTime);
1393     if (write(fd, (char *)&lifetime, sizeof(int)) != sizeof(int))
1394         goto bad;
1395     /* Key vno */
1396     kvno = atoken->kvno;
1397     if (write(fd, (char *)&kvno, sizeof(int)) != sizeof(int))
1398         goto bad;
1399     /* Tkt length */
1400     if (write(fd, (char *)&(atoken->ticketLen), sizeof(int)) != sizeof(int))
1401         goto bad;
1402     /* Ticket */
1403     count = atoken->ticketLen;
1404     if (write(fd, atoken->ticket, count) != count)
1405         goto bad;
1406     /* Issue date */
1407     mit_compat = atoken->startTime;
1408     if (write(fd, (char *)&mit_compat, sizeof(mit_compat))
1409         != sizeof(mit_compat))
1410         goto bad;
1411
1412     /* Actually, we should check each write for success */
1413     return (0);
1414   bad:
1415     return (KFAILURE);
1416 }
1417
1418 /*
1419  * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1420  * of Technology.
1421  *
1422  * For copying and distribution information, please see the file
1423  * <mit-copyright.h>.
1424  */
1425
1426 char *getenv();
1427
1428 /*
1429  * This routine is used to generate the name of the file that holds
1430  * the user's cache of server tickets and associated session keys.
1431  *
1432  * If it is set, krb_ticket_string contains the ticket file name.
1433  * Otherwise, the filename is constructed as follows:
1434  *
1435  * If it is set, the environment variable "KRBTKFILE" will be used as
1436  * the ticket file name.  Otherwise TKT_ROOT (defined in "krb.h") and
1437  * the user's uid are concatenated to produce the ticket file name
1438  * (e.g., "/tmp/tkt123").  A pointer to the string containing the ticket
1439  * file name is returned.
1440  */
1441
1442 static char krb_ticket_string[4096] = "";
1443
1444 char *
1445 ktc_tkt_string(void)
1446 {
1447     return ktc_tkt_string_uid(getuid());
1448 }
1449
1450 char *
1451 ktc_tkt_string_uid(afs_uint32 uid)
1452 {
1453     char *env;
1454
1455     LOCK_GLOBAL_MUTEX;
1456     if (!*krb_ticket_string) {
1457         if (env = getenv("KRBTKFILE")) {
1458             (void)strncpy(krb_ticket_string, env,
1459                           sizeof(krb_ticket_string) - 1);
1460             krb_ticket_string[sizeof(krb_ticket_string) - 1] = '\0';
1461         } else {
1462             /* 32 bits of signed integer will always fit in 11 characters
1463              * (including the sign), so no need to worry about overflow */
1464             (void)sprintf(krb_ticket_string, "%s%d", TKT_ROOT, uid);
1465         }
1466     }
1467     UNLOCK_GLOBAL_MUTEX;
1468     return krb_ticket_string;
1469 }
1470
1471 /*
1472  * This routine is used to set the name of the file that holds the user's
1473  * cache of server tickets and associated session keys.
1474  *
1475  * The value passed in is copied into local storage.
1476  *
1477  * NOTE:  This routine should be called during initialization, before other
1478  * Kerberos routines are called; otherwise tkt_string() above may be called
1479  * and return an undesired ticket file name until this routine is called.
1480  */
1481
1482 void
1483 ktc_set_tkt_string(char * val)
1484 {
1485
1486     LOCK_GLOBAL_MUTEX;
1487     (void)strncpy(krb_ticket_string, val, sizeof(krb_ticket_string) - 1);
1488     krb_ticket_string[sizeof(krb_ticket_string) - 1] = '\0';
1489     UNLOCK_GLOBAL_MUTEX;
1490     return;
1491 }
1492
1493 /*
1494  * tf_create() is used to initialize the ticket store.  It creates the
1495  * file to contain the tickets and writes the given user's name "pname"
1496  * and instance "pinst" in the file.  in_tkt() returns KSUCCESS on
1497  * success, or KFAILURE if something goes wrong.
1498  */
1499
1500 afs_tf_create(pname, pinst)
1501      char *pname;
1502      char *pinst;
1503 {
1504     int tktfile;
1505     int me, metoo;
1506     int count;
1507     char *file = ktc_tkt_string();
1508     int fd;
1509     register int i;
1510     char zerobuf[1024];
1511     struct stat sbuf;
1512
1513     me = getuid();
1514     metoo = geteuid();
1515
1516     if (lstat(file, &sbuf) == 0) {
1517         if ((sbuf.st_uid != me && me != 0)
1518             || ((sbuf.st_mode & S_IFMT) != S_IFREG) || sbuf.st_mode & 077) {
1519             return KFAILURE;
1520         }
1521         /* file already exists, and permissions appear ok, so nuke it */
1522         if ((fd = open(file, O_RDWR, 0)) < 0)
1523             goto out;           /* can't zero it, but we can still try truncating it */
1524
1525         memset(zerobuf, 0, sizeof(zerobuf));
1526
1527         for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1528             if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1529                 (void)fsync(fd);
1530                 (void)close(fd);
1531                 goto out;
1532             }
1533
1534         (void)fsync(fd);
1535         (void)close(fd);
1536     }
1537
1538   out:
1539     /* arrange so the file is owned by the ruid
1540      * (swap real & effective uid if necessary).
1541      * This isn't a security problem, since the ticket file, if it already
1542      * exists, has the right uid (== ruid) and mode. */
1543     if (me != metoo) {
1544         if (setreuid(metoo, me) < 0) {
1545             return (KFAILURE);
1546         }
1547     }
1548     tktfile = creat(file, 0600);
1549     if (me != metoo) {
1550         if (setreuid(me, metoo) < 0) {
1551             /* can't switch??? fail! */
1552             return (KFAILURE);
1553         }
1554     }
1555     if (tktfile < 0) {
1556         return (KFAILURE);
1557     }
1558     count = strlen(pname) + 1;
1559     if (write(tktfile, pname, count) != count) {
1560         (void)close(tktfile);
1561         return (KFAILURE);
1562     }
1563     count = strlen(pinst) + 1;
1564     if (write(tktfile, pinst, count) != count) {
1565         (void)close(tktfile);
1566         return (KFAILURE);
1567     }
1568     (void)close(tktfile);
1569     return (KSUCCESS);
1570 }
1571
1572 /*
1573  * dest_tkt() is used to destroy the ticket store upon logout.
1574  * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1575  * Otherwise the function returns 0 on success, KFAILURE on
1576  * failure.
1577  */
1578
1579 afs_tf_dest_tkt()
1580 {
1581     char *file = ktc_tkt_string();
1582     int i, fd;
1583     struct stat statb;
1584     char buf[BUFSIZ];
1585
1586     errno = 0;
1587     if (lstat(file, &statb) < 0)
1588         goto out;
1589
1590     if (!(statb.st_mode & S_IFREG))
1591         goto out;
1592
1593     if ((fd = open(file, O_RDWR, 0)) < 0)
1594         goto out;
1595
1596     memset(buf, 0, BUFSIZ);
1597
1598     for (i = 0; i < statb.st_size; i += BUFSIZ)
1599         if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1600             (void)fsync(fd);
1601             (void)close(fd);
1602             goto out;
1603         }
1604
1605     (void)fsync(fd);
1606     (void)close(fd);
1607
1608     (void)unlink(file);
1609
1610   out:
1611     if (errno == ENOENT)
1612         return RET_TKFIL;
1613     else if (errno != 0)
1614         return KFAILURE;
1615     return 0;
1616 }
1617
1618 static afs_uint32
1619 curpag()
1620 {
1621 #if defined(AFS_AIX51_ENV)
1622     afs_int32 pag;
1623
1624     if (get_pag(PAG_AFS, &pag) < 0 || pag == 0)
1625         pag = NOPAG;
1626     return pag;
1627 #else
1628     gid_t groups[NGROUPS_MAX];
1629     afs_uint32 g0, g1;
1630     afs_uint32 h, l, ret;
1631
1632     if (getgroups(sizeof groups / sizeof groups[0], groups) < 2)
1633         return 0;
1634
1635     g0 = groups[0] & 0xffff;
1636     g1 = groups[1] & 0xffff;
1637     g0 -= 0x3f00;
1638     g1 -= 0x3f00;
1639     if (g0 < 0xc000 && g1 < 0xc000) {
1640         l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1641         h = (g0 >> 14);
1642         h = (g1 >> 14) + h + h + h;
1643         ret = ((h << 28) | l);
1644         /* Additional testing */
1645         if (((ret >> 24) & 0xff) == 'A')
1646             return ret;
1647         else
1648             return -1;
1649     }
1650     return -1;
1651 #endif
1652 }
1653
1654
1655 ktc_newpag()
1656 {
1657     extern char **environ;
1658
1659     afs_uint32 pag;
1660     struct stat sbuf;
1661     char fname[256], *prefix = "/ticket/";
1662     int numenv;
1663     char **newenv, **senv, **denv;
1664
1665     LOCK_GLOBAL_MUTEX;
1666     if (stat("/ticket", &sbuf) == -1) {
1667         prefix = "/tmp/tkt";
1668     }
1669
1670     pag = curpag() & 0xffffffff;
1671     if (pag == -1) {
1672         sprintf(fname, "%s%d", prefix, getuid());
1673     } else {
1674         sprintf(fname, "%sp%ld", prefix, pag);
1675     }
1676     ktc_set_tkt_string(fname);
1677
1678     for (senv = environ, numenv = 0; *senv; senv++)
1679         numenv++;
1680     newenv = (char **)malloc((numenv + 2) * sizeof(char *));
1681
1682     for (senv = environ, denv = newenv; *senv; *senv++) {
1683         if (strncmp(*senv, "KRBTKFILE=", 10) != 0)
1684             *denv++ = *senv;
1685     }
1686
1687     *denv = (char *)malloc(10 + strlen(fname) + 1);
1688     strcpy(*denv, "KRBTKFILE=");
1689     strcat(*denv, fname);
1690     *++denv = 0;
1691     environ = newenv;
1692     UNLOCK_GLOBAL_MUTEX;
1693 }
1694
1695 /*
1696  * BLETCH!  We have to invoke the entire afsconf package just to
1697  * find out what the local cell is.
1698  */
1699 static void
1700 ktc_LocalCell()
1701 {
1702     int code;
1703     struct afsconf_dir *conf;
1704
1705     if ((conf = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))
1706         || (conf = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH))) {
1707         code = afsconf_GetLocalCell(conf, lcell, sizeof(lcell));
1708         afsconf_Close(conf);
1709     }
1710     if (!conf || code) {
1711         printf("** Can't determine local cell name!\n");
1712     }
1713 }
1714
1715 #endif