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