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