a33314c554dd8ca990350b74608f7451c18d87fa
[openafs.git] / src / aklog / aklog_main.c
1 /* 
2  * $Id$
3  *
4  * Copyright 1990,1991 by the Massachusetts Institute of Technology
5  * For distribution and copying rights, see the file "mit-copyright.h"
6  */
7 /*
8  * Copyright (c) 2005, 2006                                     
9  * The Linux Box Corporation                                    
10  * ALL RIGHTS RESERVED                                          
11  *                                                              
12  * Permission is granted to use, copy, create derivative works  
13  * and redistribute this software and such derivative works     
14  * for any purpose, so long as the name of the Linux Box        
15  * Corporation is not used in any advertising or publicity      
16  * pertaining to the use or distribution of this software       
17  * without specific, written prior authorization.  If the       
18  * above copyright notice or any other identification of the    
19  * Linux Box Corporation is included in any copy of any         
20  * portion of this software, then the disclaimer below must     
21  * also be included.                                            
22  *                                                              
23  * This software is provided as is, without representation      
24  * from the Linux Box Corporation as to its fitness for any     
25  * purpose, and without warranty by the Linux Box Corporation   
26  * of any kind, either express or implied, including            
27  * without limitation the implied warranties of                 
28  * merchantability and fitness for a particular purpose.  The   
29  * regents of the Linux Box Corporation shall not be liable     
30  * for any damages, including special, indirect, incidental, or 
31  * consequential damages, with respect to any claim arising     
32  * out of or in connection with the use of the software, even   
33  * if it has been or is hereafter advised of the possibility of 
34  * such damages.                                                
35  */
36
37 #include <afsconfig.h>
38 RCSID
39     ("$Header$");
40
41 #include <stdio.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <sys/types.h>
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef HAVE_STDLIB_H
49 #include <stdlib.h>
50 #endif
51 #ifdef HAVE_MEMORY_H
52 #include <memory.h>
53 #endif
54 #include <errno.h>
55
56 #include <sys/stat.h>
57 #include <fcntl.h>
58
59 #include <sys/param.h>
60 #include <sys/errno.h>
61 #include <netdb.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <arpa/inet.h>
65 #include <pwd.h>
66
67 #include <afs/stds.h>
68 #include <krb5.h>
69
70 #ifndef HAVE_KERBEROSV_HEIM_ERR_H
71 #include <afs/com_err.h>
72 #endif
73
74 #include <afs/param.h>
75 #ifdef AFS_SUN5_ENV
76 #include <sys/ioccom.h>
77 #endif
78 #include <afs/auth.h>
79 #include <afs/cellconfig.h>
80 #include <afs/vice.h>
81 #include <afs/venus.h>
82 #include <afs/ptserver.h>
83 #include <afs/ptuser.h>
84 #include <afs/dirpath.h>
85
86 #include "aklog.h"
87 #include "linked_list.h"
88
89 #ifdef HAVE_KRB5_CREDS_KEYBLOCK
90 #define USING_MIT 1
91 #endif
92 #ifdef HAVE_KRB5_CREDS_SESSION
93 #define USING_HEIMDAL 1
94 #endif
95
96 #define AFSKEY "afs"
97 #define AFSINST ""
98
99 #ifndef AFS_TRY_FULL_PRINC
100 #define AFS_TRY_FULL_PRINC 1
101 #endif /* AFS_TRY_FULL_PRINC */
102
103 #define AKLOG_TRYAGAIN -1
104 #define AKLOG_SUCCESS 0
105 #define AKLOG_USAGE 1
106 #define AKLOG_SOMETHINGSWRONG 2
107 #define AKLOG_AFS 3
108 #define AKLOG_KERBEROS 4
109 #define AKLOG_TOKEN 5
110 #define AKLOG_BADPATH 6
111 #define AKLOG_MISC 7
112
113 #ifndef NULL
114 #define NULL 0
115 #endif
116
117 #ifndef TRUE
118 #define TRUE 1
119 #endif
120
121 #ifndef FALSE
122 #define FALSE 0
123 #endif
124
125 #ifndef MAXSYMLINKS
126 /* RedHat 4.x doesn't seem to define this */
127 #define MAXSYMLINKS     5
128 #endif
129
130 #define DIR '/'                 /* Character that divides directories */
131 #define DIRSTRING "/"           /* String form of above */
132 #define VOLMARKER ':'           /* Character separating cellname from mntpt */
133 #define VOLMARKERSTRING ":"     /* String form of above */
134
135 typedef struct {
136     char cell[BUFSIZ];
137     char realm[REALM_SZ];
138 } cellinfo_t;
139
140 struct afsconf_cell ak_cellconfig; /* General information about the cell */
141 static char linkedcell[MAXCELLCHARS+1];
142 static char linkedcell2[MAXCELLCHARS+1];
143 static krb5_ccache  _krb425_ccache = NULL;
144
145 /*
146  * Why doesn't AFS provide these prototypes?
147  */
148
149 extern int pioctl(char *, afs_int32, struct ViceIoctl *, afs_int32);
150
151 /*
152  * Other prototypes
153  */
154
155 extern char *afs_realm_of_cell(krb5_context, struct afsconf_cell *, int);
156 static int isdir(char *, unsigned char *);
157 static krb5_error_code get_credv5(krb5_context context, char *, char *,
158                                   char *, krb5_creds **);
159 static int get_user_realm(krb5_context, char *);
160
161 #define TRYAGAIN(x) (x == AKLOG_TRYAGAIN || \
162                      x == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || \
163                      x == KRB5KRB_ERR_GENERIC)
164
165 #if defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
166
167 #define get_princ_str(c, p, n) krb5_princ_component(c, p, n)->data
168 #define get_princ_len(c, p, n) krb5_princ_component(c, p, n)->length
169 #define second_comp(c, p) (krb5_princ_size(c, p) > 1)
170 #define realm_data(c, p) krb5_princ_realm(c, p)->data
171 #define realm_len(c, p) krb5_princ_realm(c, p)->length
172
173 #elif defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
174
175 #define get_princ_str(c, p, n) krb5_principal_get_comp_string(c, p, n)
176 #define get_princ_len(c, p, n) strlen(krb5_principal_get_comp_string(c, p, n))
177 #define second_comp(c, p) (krb5_principal_get_comp_string(c, p, 1) != NULL)
178 #define realm_data(c, p) krb5_realm_data(krb5_principal_get_realm(c, p))
179 #define realm_len(c, p) krb5_realm_length(krb5_principal_get_realm(c, p))
180
181 #else
182 #error "Must have either krb5_princ_size or krb5_principal_get_comp_string"
183 #endif
184
185 #if !defined(HAVE_KRB5_ENCRYPT_TKT_PART) && defined(HAVE_ENCODE_KRB5_ENC_TKT_PART) && defined(HAVE_KRB5_C_ENCRYPT) 
186 krb5_error_code
187 krb5_encrypt_tkt_part(krb5_context context,
188                       const krb5_keyblock *key,
189                       krb5_ticket *ticket)
190 {
191     krb5_data *data = 0;
192     int code;
193     size_t enclen;
194     
195     if ((code = encode_krb5_enc_tkt_part(ticket->enc_part2, &data)))
196         goto Done;
197     if ((code = krb5_c_encrypt_length(context, key->enctype,
198                                       data->length, &enclen)))
199         goto Done;
200     ticket->enc_part.ciphertext.length = enclen;
201     if (!(ticket->enc_part.ciphertext.data = malloc(enclen))) {
202         code = ENOMEM;
203         goto Done;
204     }
205     if ((code = krb5_c_encrypt(context, key, KRB5_KEYUSAGE_KDC_REP_TICKET,
206                                0, data, &ticket->enc_part))) {
207         free(ticket->enc_part.ciphertext.data);
208         ticket->enc_part.ciphertext.data = 0;
209     }
210 Done:
211     if (data) {
212         if (data->data)
213             free(data->data);
214         free(data);
215     }
216     return code;
217 }
218 #endif
219
220 #if defined(HAVE_KRB5_CREDS_KEYBLOCK)
221
222 #define get_cred_keydata(c) c->keyblock.contents
223 #define get_cred_keylen(c) c->keyblock.length
224 #define get_creds_enctype(c) c->keyblock.enctype
225
226 #elif defined(HAVE_KRB5_CREDS_SESSION)
227
228 #define get_cred_keydata(c) c->session.keyvalue.data
229 #define get_cred_keylen(c) c->session.keyvalue.length
230 #define get_creds_enctype(c) c->session.keytype
231
232 #else
233 #error "Must have either keyblock or session member of krb5_creds"
234 #endif
235
236 #if !defined(HAVE_KRB5_524_CONVERT_CREDS) && defined(HAVE_KRB524_CONVERT_CREDS_KDC)
237 #define krb5_524_convert_creds krb524_convert_creds_kdc
238 #elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC)
239 #define HAVE_NO_KRB5_524
240 #endif
241
242 #if USING_HEIMDAL
243 #define deref_keyblock_enctype(kb)              \
244     ((kb)->keytype)
245
246 #define deref_entry_keyblock(entry)             \
247     entry->keyblock
248
249 #define deref_session_key(creds)                \
250     creds->session
251
252 #define deref_enc_tkt_addrs(tkt)                \
253     tkt->caddr
254
255 #define deref_enc_length(enc)                   \
256     ((enc)->cipher.length)
257
258 #define deref_enc_data(enc)                     \
259     ((enc)->cipher.data)
260
261 #define krb5_free_keytab_entry_contents krb5_kt_free_entry
262
263 #else
264 #define deref_keyblock_enctype(kb)              \
265     ((kb)->enctype)
266
267 #define deref_entry_keyblock(entry)             \
268     entry->key
269
270 #define deref_session_key(creds)                \
271     creds->keyblock
272
273 #define deref_enc_tkt_addrs(tkt)                \
274     tkt->caddrs
275
276 #define deref_enc_length(enc)                   \
277     ((enc)->ciphertext.length)
278
279 #define deref_enc_data(enc)                     \
280     ((enc)->ciphertext.data)
281
282 #endif
283
284 #define deref_entry_enctype(entry)                      \
285     deref_keyblock_enctype(&deref_entry_keyblock(entry))
286
287 /*
288  * Provide a replacement for strerror if we don't have it
289  */
290
291 #ifndef HAVE_STRERROR
292 extern char *sys_errlist[];
293 #define strerror(x) sys_errlist[x]
294 #endif /* HAVE_STRERROR */
295
296 static char *progname = NULL;   /* Name of this program */
297 static int dflag = FALSE;       /* Give debugging information */
298 static int noauth = FALSE;      /* If true, don't try to get tokens */
299 static int zsubs = FALSE;       /* Are we keeping track of zephyr subs? */
300 static int hosts = FALSE;       /* Are we keeping track of hosts? */
301 static int noprdb = FALSE;      /* Skip resolving name to id? */
302 static int linked = FALSE;      /* try for both AFS nodes */
303 static int afssetpag = FALSE;   /* setpag for AFS */
304 static int force = FALSE;       /* Bash identical tokens? */
305 static int do524 = FALSE;       /* Should we do 524 instead of rxkad2b? */
306 static char *keytab = NULL;     /* keytab for akimpersonate */
307 static char *client = NULL;     /* client principal for akimpersonate */
308 static linked_list zsublist;    /* List of zephyr subscriptions */
309 static linked_list hostlist;    /* List of host addresses */
310 static linked_list authedcells; /* List of cells already logged to */
311
312 /* ANL - CMU lifetime convert routine */
313 /* for K5.4.1 don't use this for now. Need to see if it is needed */
314 /* maybe needed in the krb524d module as well */
315 /* extern unsigned long krb_life_to_time(); */
316
317 static char *copy_cellinfo(cellinfo_t *cellinfo)
318 {
319     cellinfo_t *new_cellinfo;
320
321     if ((new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t))))
322         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
323     
324     return ((char *)new_cellinfo);
325 }
326
327
328 static int get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell, char *linkedcell)
329 {
330     int status = AKLOG_SUCCESS;
331     struct afsconf_dir *configdir;
332
333     memset(local_cell, 0, sizeof(local_cell));
334     memset((char *)cellconfig, 0, sizeof(*cellconfig));
335
336     if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
337         fprintf(stderr, 
338                 "%s: can't get afs configuration (afsconf_Open(%s))\n",
339                 progname, AFSDIR_CLIENT_ETC_DIRPATH);
340         exit(AKLOG_AFS);
341     }
342
343     if (afsconf_GetLocalCell(configdir, local_cell, MAXCELLCHARS)) {
344         fprintf(stderr, "%s: can't determine local cell.\n", progname);
345         exit(AKLOG_AFS);
346     }
347
348     if ((cell == NULL) || (cell[0] == 0))
349         cell = local_cell;
350
351         linkedcell[0] = '\0';
352     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
353         fprintf(stderr, "%s: Can't get information about cell %s.\n",
354                 progname, cell);
355         status = AKLOG_AFS;
356     }
357         if (cellconfig->linkedCell) 
358                 strncpy(linkedcell,cellconfig->linkedCell,MAXCELLCHARS);
359
360     (void) afsconf_Close(configdir);
361
362     return(status);
363 }
364
365 /* 
366  * Log to a cell.  If the cell has already been logged to, return without
367  * doing anything.  Otherwise, log to it and mark that it has been logged
368  * to.
369  */
370 static int auth_to_cell(krb5_context context, char *cell, char *realm)
371 {
372     int status = AKLOG_SUCCESS;
373     char username[BUFSIZ];      /* To hold client username structure */
374     afs_int32 viceId;           /* AFS uid of user */
375
376     char realm_of_user[REALM_SZ]; /* Kerberos realm of user */
377     char *realm_from_princ = 0 ;  /* Calculated realm data */
378     char *realm_of_cell = 0;      /* Pointer to realm we're using */    
379     int retry;                    /* round, and round we go ... */
380     
381     char local_cell[MAXCELLCHARS+1];
382     char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
383     static char lastcell[MAXCELLCHARS+1] = { 0 };
384     static char confname[512] = { 0 };
385     krb5_creds *v5cred = NULL;
386     struct ktc_principal aserver;
387     struct ktc_principal aclient;
388     struct ktc_token atoken, btoken;
389
390     memset(realm_of_user, 0, sizeof(realm_of_user));
391
392     if (confname[0] == '\0') {
393         strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
394         confname[sizeof(confname) - 2] = '\0';
395     }
396
397     /* NULL or empty cell returns information on local cell */
398     if ((status = get_cellconfig(cell, &ak_cellconfig,
399                          local_cell, linkedcell)))
400         return(status);
401
402     strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
403     cell_to_use[MAXCELLCHARS] = 0;
404
405     if (ll_string(&authedcells, ll_s_check, cell_to_use)) {
406         if (dflag) {
407             printf("Already authenticated to %s (or tried to)\n", 
408                    cell_to_use);
409         }
410         return(AKLOG_SUCCESS);
411     }
412
413     /* 
414      * Record that we have attempted to log to this cell.  We do this
415      * before we try rather than after so that we will not try
416      * and fail repeatedly for one cell.
417      */
418     (void)ll_string(&authedcells, ll_s_add, cell_to_use);
419
420     /* 
421      * Record this cell in the list of zephyr subscriptions.  We may
422      * want zephyr subscriptions even if authentication fails.
423      * If this is done after we attempt to get tokens, aklog -zsubs
424      * can return something different depending on whether or not we
425      * are in -noauth mode.
426      */
427     if (ll_string(&zsublist, ll_s_add, cell_to_use) == LL_FAILURE) {
428         fprintf(stderr, 
429                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
430                 progname, cell_to_use);
431         exit(AKLOG_MISC);
432     }
433     if (ll_string(&zsublist, ll_s_add, local_cell) == LL_FAILURE) {
434         fprintf(stderr, 
435                 "%s: failure adding cell %s to zephyr subscriptions list.\n",
436                 progname, local_cell);
437         exit(AKLOG_MISC);
438     }
439
440     if (!noauth) {
441         if (dflag) {
442             printf("Authenticating to cell %s (server %s).\n",
443                    cell_to_use, ak_cellconfig.hostName[0]);
444         }
445
446         if ((status = get_user_realm(context, realm_of_user))) {
447             fprintf(stderr, "%s: Couldn't determine realm of user:)",
448                     progname);
449             afs_com_err(progname, status, " while getting realm");
450             return(AKLOG_KERBEROS);
451         }
452
453         retry = 1;
454         
455         while(retry) {
456             
457             /* Cell on command line - use that one */
458             if (realm && realm[0]) {
459                 realm_of_cell = realm;
460                 status = AKLOG_TRYAGAIN;
461                 if (dflag) {
462                     printf("We were told to authenticate to realm %s.\n", 
463                            realm);
464                 }
465             } else {
466                 /* Initially, try using afs/cell@USERREALM */
467                 if (dflag) {
468                     printf("Trying to authenticate to user's realm %s.\n",
469                            realm_of_user);
470                 }
471                 
472                 realm_of_cell = realm_of_user;
473                 status = get_credv5(context, AFSKEY, cell_to_use, 
474                                     realm_of_cell, &v5cred);
475             
476                 /* If that failed, try to determine the realm from the name of 
477                  * one of the DB servers */
478                 if (TRYAGAIN(status)) {
479                     realm_of_cell = afs_realm_of_cell(context, &ak_cellconfig, 
480                                                       FALSE);
481                     if (!realm_of_cell) {
482                         fprintf(stderr, 
483                                 "%s: Couldn't figure out realm for cell %s.\n",
484                                 progname, cell_to_use);
485                         exit(AKLOG_MISC);
486                     }
487
488                     if (dflag) {
489                         if (realm_of_cell[0])
490                             printf("We've deduced that we need to authenticate"
491                                    " to realm %s.\n", realm_of_cell);
492                     else
493                         printf("We've deduced that we need to authenticate "
494                                "using referrals.\n");
495                     }
496                 }
497             }
498         
499             if (TRYAGAIN(status)) {
500                 /* If we've got the full-princ-first option, or we're in a
501                  * different realm from the cell - use the cell name as the
502                  * instance */
503                 if (AFS_TRY_FULL_PRINC || 
504                     strcasecmp(cell_to_use, realm_of_cell)!=0) {
505                     status = get_credv5(context, AFSKEY, cell_to_use, 
506                                         realm_of_cell, &v5cred);
507
508                     /* If we failed & we've got an empty realm, then try 
509                      * calling afs_realm_for_cell again. */
510                     if (TRYAGAIN(status) && !realm_of_cell[0]) {
511                         /* This time, get the realm by taking the domain 
512                          * component of the db server and make it upper case */
513                         realm_of_cell = afs_realm_of_cell(context, 
514                                                           &ak_cellconfig, TRUE);
515                         if (!realm_of_cell) {
516                             fprintf(stderr,
517                                     "%s: Couldn't figure out realm for cell "
518                                     "%s.\n", progname, cell_to_use);
519                             exit(AKLOG_MISC);
520                         }
521                         printf("We've deduced that we need to authenticate to"
522                                " realm %s.\n", realm_of_cell);
523                     }
524                     status = get_credv5(context, AFSKEY, cell_to_use, 
525                                         realm_of_cell, &v5cred);
526                 }
527            
528                 /* If the realm and cell name match, then try without an 
529                  * instance, but only if realm is non-empty */
530                 
531                 if (TRYAGAIN(status) && 
532                     strcasecmp(cell_to_use, realm_of_cell) == 0) {
533                     status = get_credv5(context, AFSKEY, NULL, 
534                                         realm_of_cell, &v5cred);
535                     if (!AFS_TRY_FULL_PRINC && TRYAGAIN(status)) {
536                         status = get_credv5(context, AFSKEY, cell_to_use,
537                                             realm_of_cell, &v5cred);
538                     }
539                 }
540             }
541
542             /* Try to find a service principal for this cell.
543              * Some broken MIT libraries return KRB5KRB_AP_ERR_MSG_TYPE upon 
544              * the first attempt, so we try twice to be sure */
545
546             if (status == KRB5KRB_AP_ERR_MSG_TYPE && retry == 1)
547                 retry++;
548             else
549                 retry = 0;
550         } 
551         
552         if (status != 0) {
553             if (dflag) {
554                 printf("Kerberos error code returned by get_cred : %d\n",
555                        status);
556             }
557             fprintf(stderr, "%s: Couldn't get %s AFS tickets:\n",
558                     progname, cell_to_use);
559             afs_com_err(progname, status, "while getting AFS tickets");
560             return(AKLOG_KERBEROS);
561         }
562         
563         /* If we've got a valid ticket, and we still don't know the realm name
564          * try to figure it out from the contents of the ticket
565          */
566 #if !defined(USING_HEIMDAL) && defined(HAVE_KRB5_DECODE_TICKET)
567         if (strcmp(realm_of_cell, "") == 0) {
568             krb5_error_code code;
569             krb5_ticket *ticket;
570
571             code = krb5_decode_ticket(&v5cred->ticket, &ticket);
572
573             if (code != 0) {
574                 fprintf(stderr,
575                         "%s: Couldn't decode ticket to determine realm for "
576                         "cell %s.\n",
577                         progname, cell_to_use);
578             } else {
579                 int len = realm_len(context, ticket->server);
580                 /* This really shouldn't happen. */
581                 if (len > REALM_SZ-1)
582                     len = REALM_SZ-1;
583
584                 realm_from_princ = (char *) malloc(sizeof(char) * (len+1));
585                 
586                 strncpy(realm_from_princ, realm_data(context, ticket->server), 
587                         len);
588                 realm_from_princ[len] = 0;
589                 realm_of_cell = realm_from_princ;
590                 
591                 krb5_free_ticket(context, ticket);
592             }
593         }
594 #endif
595
596         strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
597         strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
598         strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
599
600         /*
601          * The default is to use rxkad2b, which means we put in a full
602          * V5 ticket.  If the user specifies -524, we talk to the
603          * 524 ticket converter.
604          */
605
606         if (! do524) {
607             char *p;
608             int len;
609
610             if (dflag)
611                 printf("Using Kerberos V5 ticket natively\n");
612
613             len = min(get_princ_len(context, v5cred->client, 0),
614                       second_comp(context, v5cred->client) ?
615                                         MAXKTCNAMELEN - 2 : MAXKTCNAMELEN - 1);
616             strncpy(username, get_princ_str(context, v5cred->client, 0), len);
617             username[len] = '\0';
618
619             if (second_comp(context, v5cred->client)) {
620                 strcat(username, ".");
621                 p = username + strlen(username);
622                 len = min(get_princ_len(context, v5cred->client, 1),
623                           MAXKTCNAMELEN - strlen(username) - 1);
624                 strncpy(p, get_princ_str(context, v5cred->client, 1), len);
625                 p[len] = '\0';
626             }
627
628             memset(&atoken, 0, sizeof(atoken));
629             atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
630             atoken.startTime = v5cred->times.starttime;;
631             atoken.endTime = v5cred->times.endtime;
632             memcpy(&atoken.sessionKey, get_cred_keydata(v5cred),
633                    get_cred_keylen(v5cred));
634             atoken.ticketLen = v5cred->ticket.length;
635             memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
636 #ifndef HAVE_NO_KRB5_524
637         } else {
638             CREDENTIALS cred;
639
640             if (dflag)
641                 printf("Using Kerberos 524 translator service\n");
642
643             status = krb5_524_convert_creds(context, v5cred, &cred);
644
645             if (status) {
646                 afs_com_err(progname, status, "while converting tickets "
647                         "to Kerberos V4 format");
648                 return(AKLOG_KERBEROS);
649             }
650
651             strcpy (username, cred.pname);
652             if (cred.pinst[0]) {
653                 strcat (username, ".");
654                 strcat (username, cred.pinst);
655             }
656
657             atoken.kvno = cred.kvno;
658             atoken.startTime = cred.issue_date;
659             /*
660              * It seems silly to go through a bunch of contortions to
661              * extract the expiration time, when the v5 credentials already
662              * has the exact time!  Let's use that instead.
663              *
664              * Note that this isn't a security hole, as the expiration time
665              * is also contained in the encrypted token
666              */
667             atoken.endTime = v5cred->times.endtime;
668             memcpy(&atoken.sessionKey, cred.session, 8);
669             atoken.ticketLen = cred.ticket_st.length;
670             memcpy(atoken.ticket, cred.ticket_st.dat, atoken.ticketLen);
671 #endif /* HAVE_NO_KRB5_524 */
672         }
673         
674         if (!force &&
675             !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
676             atoken.kvno == btoken.kvno &&
677             atoken.ticketLen == btoken.ticketLen &&
678             !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
679             !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen)) {
680
681             if (dflag) {
682                 printf("Identical tokens already exist; skipping.\n");
683             }
684             return 0;
685         }
686
687 #ifdef FORCE_NOPRDB
688         noprdb = 1;
689 #endif
690
691         if (noprdb) {
692             if (dflag) {
693                 printf("Not resolving name %s to id (-noprdb set)\n",
694                         username);
695             }
696         }
697         else {
698             if (strcmp(realm_of_user, realm_of_cell)) {
699                 strcat(username, "@");
700                 strcat(username, realm_of_user);
701             }
702
703             if (dflag) {
704                 printf("About to resolve name %s to id in cell %s.\n", 
705                         username, aserver.cell);
706             }
707
708             strcpy(lastcell, aserver.cell);
709
710             if (!pr_Initialize (0, confname, aserver.cell))
711                     status = pr_SNameToId (username, &viceId);
712             
713             if (dflag) {
714                 if (status) 
715                     printf("Error %d\n", status);
716                 else
717                     printf("Id %d\n", (int) viceId);
718             }
719             
720                 /*
721                  * This is a crock, but it is Transarc's crock, so
722                  * we have to play along in order to get the
723                  * functionality.  The way the afs id is stored is
724                  * as a string in the username field of the token.
725                  * Contrary to what you may think by looking at
726                  * the code for tokens, this hack (AFS ID %d) will
727                  * not work if you change %d to something else.
728                  */
729
730                 /*
731                  * This code is taken from cklog -- it lets people
732                  * automatically register with the ptserver in foreign cells
733                  */
734
735 #ifdef ALLOW_REGISTER
736             if ((status == 0) && (viceId == ANONYMOUSID) &&
737                 (strcmp(realm_of_user, realm_of_cell) != 0)) {
738                 if (dflag) {
739                     printf("doing first-time registration of %s "
740                             "at %s\n", username, cell_to_use);
741                 }
742                 viceId = 0;
743                 strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
744                 strcpy(aclient.instance, "");
745                 strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
746                 if ((status = ktc_SetToken(&aserver, &atoken, &aclient, 0))) {
747                     fprintf(stderr, "%s: unable to obtain tokens for cell %s "
748                             "(status: %d).\n", progname, cell_to_use, status);
749                     status = AKLOG_TOKEN;
750                 }
751
752                 /*
753                  * In case you're wondering, we don't need to change the
754                  * filename here because we're still connecting to the
755                  * same cell -- we're just using a different authentication
756                  * level
757                  */
758
759                 if ((status = pr_Initialize(1L, confname, aserver.cell))) {
760                     printf("Error %d\n", status);
761                 }
762
763                 if ((status = pr_CreateUser(username, &viceId))) {
764                     fprintf(stderr, "%s: %s so unable to create remote PTS "
765                             "user %s in cell %s (status: %d).\n", progname,
766                             afs_error_message(status), username, cell_to_use,
767                             status);
768                     viceId = ANONYMOUSID;
769                 } else {
770                     printf("created cross-cell entry for %s (Id %d) at %s\n",
771                            username, viceId, cell_to_use);
772                 }
773             }
774 #endif /* ALLOW_REGISTER */
775
776             if ((status == 0) && (viceId != ANONYMOUSID)) {
777                 sprintf(username, "AFS ID %d", (int) viceId);
778             }
779         }
780
781         if (dflag) {
782             fprintf(stdout, "Set username to %s\n", username);
783         }
784
785         /* Reset the "aclient" structure before we call ktc_SetToken.
786          * This structure was first set by the ktc_GetToken call when
787          * we were comparing whether identical tokens already existed.
788          */
789         strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
790         strcpy(aclient.instance, "");
791         strncpy(aclient.cell, realm_of_user, MAXKTCREALMLEN - 1);
792
793         if (dflag) {
794             printf("Setting tokens. %s / %s @ %s \n",
795                     aclient.name, aclient.instance, aclient.cell );
796         }
797 #ifndef AFS_AIX51_ENV
798         /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before 
799          * this routine, it will not add the token. It is not clear what 
800          * is going on here! So we will do the following operation.
801          * On AIX 5, it causes the parent program to die, so we won't.
802          */
803         write(2,"",0); /* dummy write */
804 #endif
805         if ((status = ktc_SetToken(&aserver, &atoken, &aclient, afssetpag))) {
806             fprintf(stderr, 
807                     "%s: unable to obtain tokens for cell %s (status: %d).\n",
808                     progname, cell_to_use, status);
809             status = AKLOG_TOKEN;
810         }
811     }
812     else
813         if (dflag) {
814             printf("Noauth mode; not authenticating.\n");
815         }
816         
817     return(status);
818 }
819
820 static int get_afs_mountpoint(char *file, char *mountpoint, int size)
821 {
822 #ifdef AFS_SUN_ENV
823         char V ='V'; /* AFS has problem on Sun with pioctl */
824 #endif
825     char our_file[MAXPATHLEN + 1];
826     char *parent_dir;
827     char *last_component;
828     struct ViceIoctl vio;
829     char cellname[BUFSIZ];
830
831     memset(our_file, 0, sizeof(our_file));
832     strcpy(our_file, file);
833
834     if ((last_component = strrchr(our_file, DIR))) {
835         *last_component++ = 0;
836         parent_dir = our_file;
837     }
838     else {
839         last_component = our_file;
840         parent_dir = ".";
841     }    
842     
843     memset(cellname, 0, sizeof(cellname));
844
845     vio.in = last_component;
846     vio.in_size = strlen(last_component)+1;
847     vio.out_size = size;
848     vio.out = mountpoint;
849
850     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0)) {
851         if (strchr(mountpoint, VOLMARKER) == NULL) {
852             vio.in = file;
853             vio.in_size = strlen(file) + 1;
854             vio.out_size = sizeof(cellname);
855             vio.out = cellname;
856             
857             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
858                 strcat(cellname, VOLMARKERSTRING);
859                 strcat(cellname, mountpoint + 1);
860                 memset(mountpoint + 1, 0, size - 1);
861                 strcpy(mountpoint + 1, cellname);
862             }
863         }
864         return(TRUE);
865     }
866     else
867         return(FALSE);
868 }
869
870 /* 
871  * This routine each time it is called returns the next directory 
872  * down a pathname.  It resolves all symbolic links.  The first time
873  * it is called, it should be called with the name of the path
874  * to be descended.  After that, it should be called with the arguemnt
875  * NULL.
876  */
877 static char *next_path(char *origpath)
878 {
879     static char path[MAXPATHLEN + 1];
880     static char pathtocheck[MAXPATHLEN + 1];
881
882     int link = FALSE;           /* Is this a symbolic link? */
883     char linkbuf[MAXPATHLEN + 1];
884     char tmpbuf[MAXPATHLEN + 1];
885
886     static char *last_comp;     /* last component of directory name */
887     static char *elast_comp;    /* End of last component */
888     char *t;
889     int len;
890     
891     static int symlinkcount = 0; /* We can't exceed MAXSYMLINKS */
892     
893     /* If we are given something for origpath, we are initializing only. */
894     if (origpath) {
895         memset(path, 0, sizeof(path));
896         memset(pathtocheck, 0, sizeof(pathtocheck));
897         strcpy(path, origpath);
898         last_comp = path;
899         symlinkcount = 0;
900         return(NULL);
901     }
902
903     /* We were not given origpath; find then next path to check */
904     
905     /* If we've gotten all the way through already, return NULL */
906     if (last_comp == NULL)
907         return(NULL);
908
909     do {
910         while (*last_comp == DIR)
911             strncat(pathtocheck, last_comp++, 1);
912         len = (elast_comp = strchr(last_comp, DIR)) 
913             ? elast_comp - last_comp : strlen(last_comp);
914         strncat(pathtocheck, last_comp, len);
915         memset(linkbuf, 0, sizeof(linkbuf));
916         if ((link = (readlink(pathtocheck, linkbuf, 
917                                     sizeof(linkbuf)) > 0))) {
918             if (++symlinkcount > MAXSYMLINKS) {
919                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
920                 exit(AKLOG_BADPATH);
921             }
922             memset(tmpbuf, 0, sizeof(tmpbuf));
923             if (elast_comp)
924                 strcpy(tmpbuf, elast_comp);
925             if (linkbuf[0] == DIR) {
926                 /* 
927                  * If this is a symbolic link to an absolute path, 
928                  * replace what we have by the absolute path.
929                  */
930                 memset(path, 0, strlen(path));
931                 memcpy(path, linkbuf, sizeof(linkbuf));
932                 strcat(path, tmpbuf);
933                 last_comp = path;
934                 elast_comp = NULL;
935                 memset(pathtocheck, 0, sizeof(pathtocheck));
936             }
937             else {
938                 /* 
939                  * If this is a symbolic link to a relative path, 
940                  * replace only the last component with the link name.
941                  */
942                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
943                 strcat(path, tmpbuf);
944                 elast_comp = NULL;
945                 if ((t = strrchr(pathtocheck, DIR))) {
946                     t++;
947                     memset(t, 0, strlen(t));
948                 }
949                 else
950                     memset(pathtocheck, 0, sizeof(pathtocheck));
951             }
952         }
953         else
954             last_comp = elast_comp;
955     }
956     while(link);
957
958     return(pathtocheck);
959 }
960
961 #if 0
962 /*****************************************/
963 int dee_gettokens()
964 {
965 #ifdef AFS_SUN_ENV
966         char V = 'V'; /* AFS has problem on SunOS */
967 #endif
968    struct ViceIoctl vio;
969    char outbuf[BUFSIZ];
970    long ind;
971    int fd;
972
973    memset(outbuf, 0, sizeof(outbuf));
974
975    vio.out_size = sizeof(outbuf);
976    vio.in_size = sizeof(ind);
977    vio.out = outbuf;
978    vio.in = &ind;
979
980    ind = 0;
981    fd = open("dee.tok",O_WRONLY);
982    while(!pioctl(0,VIOCGETTOK,&vio,0)) {
983         write(fd,&outbuf,sizeof(outbuf)); 
984        ind++;
985    }
986    close(fd);
987 }
988 /*****************************************/
989 #endif
990
991 static void add_hosts(char *file)
992 {
993 #ifdef AFS_SUN_ENV
994         char V = 'V'; /* AFS has problem on SunOS */
995 #endif
996     struct ViceIoctl vio;
997     char outbuf[BUFSIZ];
998     long *phosts;
999     int i;
1000     struct hostent *hp;
1001     struct in_addr in;
1002     
1003     memset(outbuf, 0, sizeof(outbuf));
1004
1005     vio.out_size = sizeof(outbuf);
1006     vio.in_size = 0;
1007     vio.out = outbuf;
1008
1009     if (dflag) {
1010         printf("Getting list of hosts for %s\n", file);
1011     }
1012     /* Don't worry about errors. */
1013     if (!pioctl(file, VIOCWHEREIS, &vio, 1)) {
1014         phosts = (long *) outbuf;
1015
1016         /*
1017          * Lists hosts that we care about.  If ALLHOSTS is defined,
1018          * then all hosts that you ever may possible go through are
1019          * included in this list.  If not, then only hosts that are
1020          * the only ones appear.  That is, if a volume you must use
1021          * is replaced on only one server, that server is included.
1022          * If it is replicated on many servers, then none are included.
1023          * This is not perfect, but the result is that people don't
1024          * get subscribed to a lot of instances of FILSRV that they
1025          * probably won't need which reduces the instances of 
1026          * people getting messages that don't apply to them.
1027          */
1028 #ifndef ALLHOSTS
1029         if (phosts[1] != '\0')
1030             return;
1031 #endif
1032         for (i = 0; phosts[i]; i++) {
1033             if (hosts) {
1034                 in.s_addr = phosts[i];
1035                 if (dflag) {
1036                     printf("Got host %s\n", inet_ntoa(in));
1037                 }
1038                 ll_string(&hostlist, ll_s_add, (char *)inet_ntoa(in));
1039             }
1040             if (zsubs && (hp=gethostbyaddr((char *) &phosts[i],sizeof(long),AF_INET))) {
1041                 if (dflag) {
1042                     printf("Got host %s\n", hp->h_name);
1043                 }
1044                 ll_string(&zsublist, ll_s_add, hp->h_name);
1045             }
1046         }
1047     }
1048 }
1049
1050 /*
1051  * This routine descends through a path to a directory, logging to 
1052  * every cell it encounters along the way.
1053  */
1054 static int auth_to_path(krb5_context context, char *path)
1055 {
1056     int status = AKLOG_SUCCESS;
1057     int auth_to_cell_status = AKLOG_SUCCESS;
1058
1059     char *nextpath;
1060     char pathtocheck[MAXPATHLEN + 1];
1061     char mountpoint[MAXPATHLEN + 1];
1062
1063     char *cell;
1064     char *endofcell;
1065
1066     u_char isdirectory;
1067
1068     /* Initialize */
1069     if (path[0] == DIR)
1070         strcpy(pathtocheck, path);
1071     else {
1072         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
1073             fprintf(stderr, "Unable to find current working directory:\n");
1074             fprintf(stderr, "%s\n", pathtocheck);
1075             fprintf(stderr, "Try an absolute pathname.\n");
1076             exit(AKLOG_BADPATH);
1077         }
1078         else {
1079             strcat(pathtocheck, DIRSTRING);
1080             strcat(pathtocheck, path);
1081         }
1082     }
1083     next_path(pathtocheck);
1084
1085     /* Go on to the next level down the path */
1086     while ((nextpath = next_path(NULL))) {
1087         strcpy(pathtocheck, nextpath);
1088         if (dflag) {
1089             printf("Checking directory %s\n", pathtocheck);
1090         }
1091         /* 
1092          * If this is an afs mountpoint, determine what cell from 
1093          * the mountpoint name which is of the form 
1094          * #cellname:volumename or %cellname:volumename.
1095          */
1096         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint))) {
1097             /* skip over the '#' or '%' */
1098             cell = mountpoint + 1;
1099             /* Add this (cell:volumename) to the list of zsubs */
1100             if (zsubs)
1101                 ll_string(&zsublist, ll_s_add, cell);
1102             if (zsubs || hosts)
1103                 add_hosts(pathtocheck);
1104             if ((endofcell = strchr(mountpoint, VOLMARKER))) {
1105                 *endofcell = '\0';
1106                 if ((auth_to_cell_status = auth_to_cell(context, cell, NULL))) {
1107                     if (status == AKLOG_SUCCESS)
1108                         status = auth_to_cell_status;
1109                     else if (status != auth_to_cell_status)
1110                         status = AKLOG_SOMETHINGSWRONG;
1111                 }
1112             }
1113         }
1114         else {
1115             if (isdir(pathtocheck, &isdirectory) < 0) {
1116                 /*
1117                  * If we've logged and still can't stat, there's
1118                  * a problem... 
1119                  */
1120                 fprintf(stderr, "%s: stat(%s): %s\n", progname, 
1121                         pathtocheck, strerror(errno));
1122                 return(AKLOG_BADPATH);
1123             }
1124             else if (! isdirectory) {
1125                 /* Allow only directories */
1126                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1127                         strerror(ENOTDIR));
1128                 return(AKLOG_BADPATH);
1129             }
1130         }
1131     }
1132     
1133
1134     return(status);
1135 }
1136
1137
1138 /* Print usage message and exit */
1139 static void usage(void)
1140 {
1141     fprintf(stderr, "\nUsage: %s %s%s%s\n", progname,
1142             "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1143             "[[-p | -path] pathname]\n",
1144             "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
1145                 "    [-linked]"
1146 #ifndef HAVE_NO_KRB5_524
1147                 " [-524]"
1148 #endif
1149                 "\n");
1150     fprintf(stderr, "    -d gives debugging information.\n");
1151     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1152     fprintf(stderr, "    pathname is the name of a directory to which ");
1153     fprintf(stderr, "you wish to authenticate.\n");
1154     fprintf(stderr, "    -zsubs gives zephyr subscription information.\n");
1155     fprintf(stderr, "    -hosts gives host address information.\n");
1156     fprintf(stderr, "    -noauth does not attempt to get tokens.\n");
1157     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1158     fprintf(stderr, "    -force means replace identical tickets. \n");
1159     fprintf(stderr, "    -linked means if AFS node is linked, try both. \n");
1160     fprintf(stderr, "    -setpag set the AFS process authentication group.\n");
1161 #ifndef HAVE_NO_KRB5_524
1162     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
1163 #endif
1164     fprintf(stderr, "    No commandline arguments means ");
1165     fprintf(stderr, "authenticate to the local cell.\n");
1166     fprintf(stderr, "\n");
1167     exit(AKLOG_USAGE);
1168 }
1169
1170 void aklog(int argc, char *argv[])
1171 {
1172         krb5_context context;
1173     int status = AKLOG_SUCCESS;
1174     int i;
1175     int somethingswrong = FALSE;
1176
1177     cellinfo_t cellinfo;
1178
1179     extern char *progname;      /* Name of this program */
1180
1181     extern int dflag;           /* Debug mode */
1182
1183     int cmode = FALSE;          /* Cellname mode */
1184     int pmode = FALSE;          /* Path name mode */
1185
1186     char realm[REALM_SZ];       /* Kerberos realm of afs server */
1187     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1188     char path[MAXPATHLEN + 1];          /* Path length for path mode */
1189
1190     linked_list cells;          /* List of cells to log to */
1191     linked_list paths;          /* List of paths to log to */
1192     ll_node *cur_node;
1193
1194     memset(&cellinfo, 0, sizeof(cellinfo));
1195
1196     memset(realm, 0, sizeof(realm));
1197     memset(cell, 0, sizeof(cell));
1198     memset(path, 0, sizeof(path));
1199
1200     ll_init(&cells);
1201     ll_init(&paths);
1202
1203     ll_init(&zsublist);
1204     ll_init(&hostlist);
1205
1206     /* Store the program name here for error messages */
1207     if ((progname = strrchr(argv[0], DIR)))
1208         progname++;
1209     else
1210         progname = argv[0];
1211
1212     krb5_init_context(&context);
1213     initialize_ktc_error_table ();
1214
1215     /* Initialize list of cells to which we have authenticated */
1216     (void)ll_init(&authedcells);
1217
1218     /* Parse commandline arguments and make list of what to do. */
1219     for (i = 1; i < argc; i++) {
1220         if (strcmp(argv[i], "-d") == 0)
1221             dflag++;
1222         else if (strcmp(argv[i], "-noauth") == 0) 
1223             noauth++;
1224         else if (strcmp(argv[i], "-zsubs") == 0)
1225             zsubs++;
1226         else if (strcmp(argv[i], "-hosts") == 0)
1227             hosts++;
1228         else if (strcmp(argv[i], "-noprdb") == 0)
1229             noprdb++;
1230         else if (strcmp(argv[i], "-linked") == 0)
1231                 linked++;
1232         else if (strcmp(argv[i], "-force") == 0)
1233             force++;
1234 #ifndef HAVE_NO_KRB5_524
1235         else if (strcmp(argv[i], "-524") == 0)
1236             do524++;
1237 #endif
1238     else if (strcmp(argv[i], "-setpag") == 0)
1239             afssetpag++;
1240         else if (((strcmp(argv[i], "-cell") == 0) ||
1241                   (strcmp(argv[i], "-c") == 0)) && !pmode)
1242             if (++i < argc) {
1243                 cmode++;
1244                 strcpy(cell, argv[i]);
1245             }
1246             else
1247                 usage();
1248         else if ((strcmp(argv[i], "-keytab") == 0))
1249             if (++i < argc) {
1250                 keytab = argv[i];
1251             }
1252             else
1253                 usage();
1254         else if ((strcmp(argv[i], "-principal") == 0))
1255             if (++i < argc) {
1256                 client = argv[i];
1257             }
1258             else
1259                 usage();
1260         else if (((strcmp(argv[i], "-path") == 0) ||
1261                   (strcmp(argv[i], "-p") == 0)) && !cmode)
1262             if (++i < argc) {
1263                 pmode++;
1264                 strcpy(path, argv[i]);
1265             }
1266             else
1267                 usage();
1268             
1269         else if (argv[i][0] == '-')
1270             usage();
1271         else if (!pmode && !cmode) {
1272             if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
1273                 (strcmp(argv[i], "..") == 0)) {
1274                 pmode++;
1275                 strcpy(path, argv[i]);
1276             }
1277             else { 
1278                 cmode++;
1279                 strcpy(cell, argv[i]);
1280             }
1281         }
1282         else
1283             usage();
1284
1285         if (cmode) {
1286             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
1287                 i+=2;
1288                 if (i < argc)
1289                     strcpy(realm, argv[i]);
1290                 else
1291                     usage();
1292             }
1293             /* Add this cell to list of cells */
1294             strcpy(cellinfo.cell, cell);
1295             strcpy(cellinfo.realm, realm);
1296             if ((cur_node = ll_add_node(&cells, ll_tail))) {
1297                 char *new_cellinfo;
1298                 if ((new_cellinfo = copy_cellinfo(&cellinfo)))
1299                     ll_add_data(cur_node, new_cellinfo);
1300                 else {
1301                     fprintf(stderr, 
1302                             "%s: failure copying cellinfo.\n", progname);
1303                     exit(AKLOG_MISC);
1304                 }
1305             }
1306             else {
1307                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1308                         progname);
1309                 exit(AKLOG_MISC);
1310             }
1311             memset(&cellinfo, 0, sizeof(cellinfo));
1312             cmode = FALSE;
1313             memset(cell, 0, sizeof(cell));
1314             memset(realm, 0, sizeof(realm));
1315         }
1316         else if (pmode) {
1317             /* Add this path to list of paths */
1318             if ((cur_node = ll_add_node(&paths, ll_tail))) {
1319                 char *new_path;
1320                 if ((new_path = strdup(path)))
1321                     ll_add_data(cur_node, new_path);
1322                 else {
1323                     fprintf(stderr, "%s: failure copying path name.\n",
1324                             progname);
1325                     exit(AKLOG_MISC);
1326                 }
1327             }
1328             else {
1329                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1330                         progname);
1331                 exit(AKLOG_MISC);
1332             }
1333             pmode = FALSE;
1334             memset(path, 0, sizeof(path));
1335         }
1336     }
1337
1338     /*
1339      * The code that _used_ to be here called setpag().  When you think
1340      * about this, doing this makes no sense!  setpag() allocates a PAG
1341      * only for the current process, so the token installed would have
1342      * not be usable in the parent!  Since ktc_SetToken() now takes a
1343      * 4th argument to control whether or not we're going to allocate
1344      * a PAG (and since when you do it _that_ way, it modifies the cred
1345      * structure of your parent)), why don't we use that instead?
1346      */
1347
1348 #if 0
1349     if (afssetpag) {
1350            status = setpag();
1351            if (dflag) { 
1352              int i,j;
1353                  int gidsetlen = 50;
1354          int gidset[50];
1355
1356                  printf("setpag %d\n",status);
1357              j = getgroups(gidsetlen,gidset);
1358          printf("Groups(%d):",j);
1359          for (i = 0; i<j; i++) {
1360            printf("%d",gidset[i]);
1361            if((i+1)<j) printf(",");
1362          }
1363          printf("\n");
1364            }
1365         }
1366 #endif
1367     /* If nothing was given, log to the local cell. */
1368     if ((cells.nelements + paths.nelements) == 0) {
1369                 struct passwd *pwd;
1370
1371                 status = auth_to_cell(context, NULL, NULL);
1372         
1373                 /* If this cell is linked to a DCE cell, and user 
1374                  * requested -linked, get tokens for both 
1375                  * This is very usefull when the AFS cell is linked to a DFS 
1376                  * cell and this system does not also have DFS. 
1377                  */
1378
1379                 if (!status && linked && linkedcell[0]) {
1380                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1381                             if (dflag) {
1382                                 printf("Linked cell: %s\n", linkedcell);
1383                             }
1384                                 status = auth_to_cell(context, linkedcell2, NULL);
1385                 }
1386
1387                 /*
1388                  * Local hack - if the person has a file in their home
1389                  * directory called ".xlog", read that for a list of
1390                  * extra cells to authenticate to
1391                  */
1392
1393                 if ((pwd = getpwuid(getuid())) != NULL) {
1394                     struct stat sbuf;
1395                     FILE *f;
1396                     char fcell[100], xlog_path[512];
1397
1398                     strcpy(xlog_path, pwd->pw_dir);
1399                     strcat(xlog_path, "/.xlog");
1400
1401                     if ((stat(xlog_path, &sbuf) == 0) &&
1402                         ((f = fopen(xlog_path, "r")) != NULL)) {
1403
1404                         if (dflag) {
1405                             printf("Reading %s for cells to "
1406                                     "authenticate to.\n", xlog_path);
1407                         }
1408
1409                         while (fgets(fcell, 100, f) != NULL) {
1410                             int auth_status;
1411
1412                             fcell[strlen(fcell) - 1] = '\0';
1413
1414                             if (dflag) {
1415                                 printf("Found cell %s in %s.\n",
1416                                         fcell, xlog_path);
1417                             }
1418
1419                             auth_status = auth_to_cell(context, fcell, NULL);
1420                             if (status == AKLOG_SUCCESS)
1421                                 status = auth_status;
1422                             else
1423                                 status = AKLOG_SOMETHINGSWRONG;
1424                         }
1425                     }
1426                 }
1427         }
1428     else {
1429         /* Log to all cells in the cells list first */
1430         for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
1431             memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
1432             if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm)))
1433                 somethingswrong++;
1434                 else {
1435                         if (linked && linkedcell[0]) {
1436                                 strncpy(linkedcell2,linkedcell,MAXCELLCHARS);
1437                 if (dflag) {
1438                     printf("Linked cell: %s\n",
1439                         linkedcell);
1440                 }
1441                                 if ((status = auth_to_cell(context,linkedcell2,
1442                                                          cellinfo.realm)))
1443                                 somethingswrong++;
1444                         }
1445                 }
1446         }
1447         
1448         /* Then, log to all paths in the paths list */
1449         for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
1450             if ((status = auth_to_path(context, cur_node->data)))
1451                 somethingswrong++;
1452         }
1453         
1454         /* 
1455          * If only one thing was logged to, we'll return the status 
1456          * of the single call.  Otherwise, we'll return a generic
1457          * something failed status.
1458          */
1459         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1460             status = AKLOG_SOMETHINGSWRONG;
1461     }
1462
1463     /* If we are keeping track of zephyr subscriptions, print them. */
1464     if (zsubs) 
1465         for (cur_node = zsublist.first; cur_node; cur_node = cur_node->next) {
1466             printf("zsub: %s\n", cur_node->data);
1467         }
1468
1469     /* If we are keeping track of host information, print it. */
1470     if (hosts)
1471         for (cur_node = hostlist.first; cur_node; cur_node = cur_node->next) {
1472             printf("host: %s\n", cur_node->data);
1473         }
1474
1475     exit(status);
1476 }
1477
1478 static int isdir(char *path, unsigned char *val)
1479 {
1480     struct stat statbuf;
1481
1482     if (lstat(path, &statbuf) < 0)
1483         return (-1);
1484     else {
1485         if ((statbuf.st_mode & S_IFMT) == S_IFDIR) 
1486             *val = TRUE;
1487         else
1488             *val = FALSE;
1489         return (0);
1490     }  
1491 }
1492
1493 static krb5_error_code get_credv5_akimpersonate(krb5_context context,
1494                                                 char* keytab,
1495                                                 krb5_principal service_principal,
1496                                                 krb5_principal client_principal,
1497                                                 time_t starttime,
1498                                                 time_t endtime,
1499                                                 int *allowed_enctypes,
1500                                                 int *paddress,
1501                                                 krb5_creds** out_creds /* out */ )
1502 {
1503 #if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
1504     krb5_error_code code;
1505     krb5_keytab kt = 0;
1506     krb5_kt_cursor cursor[1];
1507     krb5_keytab_entry entry[1];
1508     krb5_ccache cc = 0;
1509     krb5_creds *creds = 0;
1510     krb5_enctype enctype;
1511     krb5_kvno kvno;
1512     krb5_keyblock session_key[1];
1513 #if USING_HEIMDAL
1514     Ticket ticket_reply[1];
1515     EncTicketPart enc_tkt_reply[1];
1516     krb5_address address[30];
1517     krb5_addresses faddr[1];
1518     int temp_vno[1];
1519     time_t temp_time[2];
1520 #else
1521     krb5_ticket ticket_reply[1];
1522     krb5_enc_tkt_part enc_tkt_reply[1];
1523     krb5_address address[30], *faddr[30];
1524 #endif
1525     krb5_data * temp;
1526     int i;
1527     static int any_enctype[] = {0};
1528     *out_creds = 0;
1529     if (!(creds = malloc(sizeof *creds))) {
1530         code = ENOMEM;
1531         goto cleanup;
1532     }
1533     if (!allowed_enctypes)
1534         allowed_enctypes = any_enctype;
1535
1536     cc = 0;
1537     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
1538     kvno = 0; /* AKIMPERSONATE_IGNORE_VNO */
1539     memset((char*)creds, 0, sizeof *creds);
1540     memset((char*)entry, 0, sizeof *entry);
1541     memset((char*)session_key, 0, sizeof *session_key);
1542     memset((char*)ticket_reply, 0, sizeof *ticket_reply);
1543     memset((char*)enc_tkt_reply, 0, sizeof *enc_tkt_reply);
1544     code = krb5_kt_resolve(context, keytab, &kt);
1545     if (code) {
1546         if (keytab)
1547             afs_com_err(progname, code, "while resolving keytab %s", keytab);
1548         else
1549             afs_com_err(progname, code, "while resolving default keytab");
1550         goto cleanup;
1551     }
1552
1553     if (service_principal) {
1554         for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
1555             code = krb5_kt_get_entry(context,
1556                                      kt,
1557                                      service_principal,
1558                                      kvno,
1559                                      enctype,
1560                                      entry);
1561             if (!code) {
1562                 if (allowed_enctypes[i])
1563                     deref_keyblock_enctype(session_key) = allowed_enctypes[i];
1564                 break;
1565             }
1566         }
1567         if (code) {
1568             afs_com_err(progname, code,"while scanning keytab entries");
1569             goto cleanup;
1570         }
1571     } else {
1572         krb5_keytab_entry new[1];
1573         int best = -1;
1574         memset(new, 0, sizeof *new);
1575         if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
1576             afs_com_err(progname, code, "while starting keytab scan");
1577             goto cleanup;
1578         }
1579         while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
1580             for (i = 0;
1581                     allowed_enctypes[i] && allowed_enctypes[i]
1582                      != deref_entry_enctype(new); ++i)
1583                 ;
1584             if ((!i || allowed_enctypes[i]) &&
1585                 (best < 0 || best > i)) {
1586                 krb5_free_keytab_entry_contents(context, entry);
1587                 *entry = *new;
1588                 memset(new, 0, sizeof *new);
1589             } else krb5_free_keytab_entry_contents(context, new);
1590         }
1591         if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
1592             afs_com_err(progname, i, "while ending keytab scan");
1593             code = i;
1594             goto cleanup;
1595         }
1596         if (best < 0) {
1597             afs_com_err(progname, code, "while scanning keytab");
1598             goto cleanup;
1599         }
1600         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
1601     }
1602
1603     /* Make Ticket */
1604
1605 #if USING_HEIMDAL
1606     if ((code = krb5_generate_random_keyblock(context,
1607                                               deref_keyblock_enctype(session_key), session_key))) {
1608         afs_com_err(progname, code, "while making session key");
1609         goto cleanup;
1610     }
1611     enc_tkt_reply->flags.initial = 1;
1612     enc_tkt_reply->transited.tr_type = DOMAIN_X500_COMPRESS;
1613     enc_tkt_reply->cname = client_principal->name;
1614     enc_tkt_reply->crealm = client_principal->realm;
1615     enc_tkt_reply->key = *session_key;
1616     {
1617         static krb5_data empty_string;
1618         enc_tkt_reply->transited.contents = empty_string;
1619     }
1620     enc_tkt_reply->authtime = starttime;
1621     enc_tkt_reply->starttime = temp_time;
1622     *enc_tkt_reply->starttime = starttime;
1623 #if 0
1624     enc_tkt_reply->renew_till = temp_time + 1;
1625     *enc_tkt_reply->renew_till = endtime;
1626 #endif
1627     enc_tkt_reply->endtime = endtime;
1628 #else
1629     if ((code = krb5_c_make_random_key(context,
1630                                        deref_keyblock_enctype(session_key), session_key))) {
1631         afs_com_err(progname, code, "while making session key");
1632         goto cleanup;
1633     }
1634     enc_tkt_reply->magic = KV5M_ENC_TKT_PART;
1635 #define DATACAST        (unsigned char *)
1636     enc_tkt_reply->flags |= TKT_FLG_INITIAL;
1637     enc_tkt_reply->transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
1638     enc_tkt_reply->session = session_key;
1639     enc_tkt_reply->client = client_principal;
1640     {
1641         static krb5_data empty_string;
1642         enc_tkt_reply->transited.tr_contents = empty_string;
1643     }
1644     enc_tkt_reply->times.authtime = starttime;
1645     enc_tkt_reply->times.starttime = starttime; /* krb524init needs this */
1646     enc_tkt_reply->times.endtime = endtime;
1647 #endif  /* USING_HEIMDAL */
1648     /* NB:  We will discard address for now--ignoring caddr field               
1649        in any case.  MIT branch does what it always did. */
1650
1651     if (paddress && *paddress) {
1652         deref_enc_tkt_addrs(enc_tkt_reply) = faddr;
1653 #if USING_HEIMDAL
1654         faddr->len = 0;
1655         faddr->val = address;
1656 #endif
1657         for (i = 0; paddress[i]; ++i) {
1658 #if USING_HEIMDAL
1659             address[i].addr_type = KRB5_ADDRESS_INET;
1660             address[i].address.data = (void*)(paddress+i);
1661             address[i].address.length = sizeof(paddress[i]);
1662 #else
1663 #if !USING_SSL
1664             address[i].magic = KV5M_ADDRESS;
1665             address[i].addrtype = ADDRTYPE_INET;
1666 #else
1667             address[i].addrtype = AF_INET;
1668 #endif
1669             address[i].contents = (void*)(paddress+i);
1670             address[i].length = sizeof(int);
1671             faddr[i] = address+i;
1672 #endif
1673         }
1674 #if USING_HEIMDAL
1675         faddr->len = i;
1676 #else
1677         faddr[i] = 0;
1678 #endif
1679     }
1680
1681 #if USING_HEIMDAL
1682     ticket_reply->sname = service_principal->name;
1683     ticket_reply->realm = service_principal->realm;
1684
1685     { /* crypto block */
1686         krb5_crypto crypto = 0;
1687         unsigned char *buf = 0;
1688         size_t buf_size, buf_len;
1689         char *what;
1690
1691         ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size,
1692                            enc_tkt_reply, &buf_len, code);
1693         if(code) {
1694             afs_com_err(progname, code, "while encoding ticket");
1695             goto cleanup;
1696         }
1697
1698         if(buf_len != buf_size) {
1699             afs_com_err(progname, code,
1700                     "%d != %d while encoding ticket (internal ASN.1 encoder error",
1701                     buf_len, buf_size);
1702             goto cleanup;
1703         }
1704         what = "krb5_crypto_init";
1705         code = krb5_crypto_init(context,
1706                                 &deref_entry_keyblock(entry),
1707                                 deref_entry_enctype(entry),
1708                                 &crypto);
1709         if(!code) {
1710             what = "krb5_encrypt";
1711             code = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_TICKET,
1712                                               buf, buf_len, entry->vno, &(ticket_reply->enc_part));
1713         }
1714         if (buf) free(buf);
1715         if (crypto) krb5_crypto_destroy(context, crypto);
1716         if(code) {
1717             afs_com_err(progname, code, "while %s", what);
1718             goto cleanup;
1719         }
1720     } /* crypto block */
1721     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
1722     ticket_reply->enc_part.kvno = temp_vno;
1723     *ticket_reply->enc_part.kvno = entry->vno;
1724     ticket_reply->tkt_vno = 5;
1725 #else
1726     ticket_reply->server = service_principal;
1727     ticket_reply->enc_part2 = enc_tkt_reply;
1728     if ((code = krb5_encrypt_tkt_part(context, &deref_entry_keyblock(entry), ticket_reply))) {
1729         afs_com_err(progname, code, "while making ticket");
1730         goto cleanup;
1731     }
1732     ticket_reply->enc_part.kvno = entry->vno;
1733 #endif
1734
1735     /* Construct Creds */
1736
1737     if ((code = krb5_copy_principal(context, service_principal,
1738                                     &creds->server))) {
1739         afs_com_err(progname, code, "while copying service principal");
1740         goto cleanup;
1741     }
1742     if ((code = krb5_copy_principal(context, client_principal,
1743                                     &creds->client))) {
1744         afs_com_err(progname, code, "while copying client principal");
1745         goto cleanup;
1746     }
1747     if ((code = krb5_copy_keyblock_contents(context, session_key,
1748                                             &deref_session_key(creds)))) {
1749         afs_com_err(progname, code, "while copying session key");
1750         goto cleanup;
1751     }
1752
1753 #if USING_HEIMDAL
1754     creds->times.authtime = enc_tkt_reply->authtime;
1755     creds->times.starttime = *(enc_tkt_reply->starttime);
1756     creds->times.endtime = enc_tkt_reply->endtime;
1757     creds->times.renew_till = 0; /* *(enc_tkt_reply->renew_till) */
1758     creds->flags.b = enc_tkt_reply->flags;
1759 #else
1760     creds->times = enc_tkt_reply->times;
1761     creds->ticket_flags = enc_tkt_reply->flags;
1762 #endif
1763     if (!deref_enc_tkt_addrs(enc_tkt_reply))
1764         ;
1765     else if ((code = krb5_copy_addresses(context,
1766                                          deref_enc_tkt_addrs(enc_tkt_reply), &creds->addresses))) {
1767         afs_com_err(progname, code, "while copying addresses");
1768         goto cleanup;
1769     }
1770
1771 #if USING_HEIMDAL
1772     {
1773         size_t creds_tkt_len;
1774         ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
1775                            ticket_reply, &creds_tkt_len, code);
1776         if(code) {
1777             afs_com_err(progname, code, "while encoding ticket");
1778             goto cleanup;
1779         }
1780     }
1781 #else
1782     if ((code = encode_krb5_ticket(ticket_reply, &temp))) {
1783         afs_com_err(progname, code, "while encoding ticket");
1784         goto cleanup;
1785     }
1786     creds->ticket = *temp;
1787     free(temp);
1788 #endif
1789     /* return creds */
1790     *out_creds = creds;
1791     creds = 0;
1792 cleanup:
1793     if (deref_enc_data(&ticket_reply->enc_part))
1794         free(deref_enc_data(&ticket_reply->enc_part));
1795     krb5_free_keytab_entry_contents(context, entry);
1796     if (client_principal)
1797         krb5_free_principal(context, client_principal);
1798     if (service_principal)
1799         krb5_free_principal(context, service_principal);
1800     if (cc)
1801         krb5_cc_close(context, cc);
1802     if (kt)
1803         krb5_kt_close(context, kt);
1804     if (creds) krb5_free_creds(context, creds);
1805     krb5_free_keyblock_contents(context, session_key);
1806 out:
1807     return code;
1808 #else
1809     return -1;
1810 #endif
1811 }
1812
1813
1814 static krb5_error_code get_credv5(krb5_context context, 
1815                                   char *name, char *inst, char *realm,
1816                                   krb5_creds **creds)
1817 {
1818     krb5_creds increds;
1819     krb5_error_code r;
1820     static krb5_principal client_principal = 0;
1821
1822     if (dflag) {
1823         printf("Getting tickets: %s%s%s@%s\n", name, inst[0] ? "/" : "",
1824                inst, realm);
1825     }
1826     
1827     memset((char *)&increds, 0, sizeof(increds));
1828 /* ANL - instance may be ptr to a null string. Pass null then */
1829     if ((r = krb5_build_principal(context, &increds.server,
1830                                   strlen(realm), realm,
1831                                   name,
1832                                   (inst && strlen(inst)) ? inst : (void *) NULL,
1833                                   (void *) NULL))) {
1834         return r;
1835     }
1836     
1837
1838     if (!_krb425_ccache) {
1839         r = krb5_cc_default(context, &_krb425_ccache);
1840         if (r)
1841             return r;
1842     }
1843     if (!client_principal) {
1844         if (client) {
1845             r = krb5_parse_name(context, client,  &client_principal);
1846         } else {
1847             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
1848         }
1849         if (r)
1850             return r;
1851     }
1852     
1853     increds.client = client_principal;
1854     increds.times.endtime = 0;
1855     /* Ask for DES since that is what V4 understands */
1856     get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
1857     
1858     if (keytab) {
1859         int allowed_enctypes[] = {
1860             ENCTYPE_DES_CBC_CRC, 0
1861         };
1862
1863         r = get_credv5_akimpersonate(context,
1864                                      keytab,
1865                                      increds.server,
1866                                      increds.client,
1867                                      300, ((~0U)>>1),
1868                                      allowed_enctypes,
1869                                      0 /* paddress */,
1870                                      creds /* out */);
1871     } else {
1872         r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
1873     }    
1874     return r;
1875 }
1876
1877
1878 static int get_user_realm(krb5_context context, char *realm)
1879 {
1880     static krb5_principal client_principal = 0;
1881     int i;
1882     krb5_error_code r = 0;
1883
1884     if (!_krb425_ccache)
1885         krb5_cc_default(context, &_krb425_ccache);
1886     if (!client_principal) {
1887         if (client) {
1888             r = krb5_parse_name(context, client,  &client_principal);
1889         } else {
1890             r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
1891         }
1892         if (r)
1893             return r;
1894     }
1895
1896     i = realm_len(context, client_principal);
1897     if (i > REALM_SZ-1) i = REALM_SZ-1;
1898     strncpy(realm,realm_data(context, client_principal), i);
1899     realm[i] = 0;
1900
1901     return(r);
1902 }