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