venus: Remove dedebug
[openafs.git] / src / aklog / aklog.c
index e052d9b..3dba5f4 100644 (file)
 #include <afs/ktc.h>
 #include <afs/token.h>
 
+#define KERBEROS_APPLE_DEPRECATED(x)
 #include <krb5.h>
-#if defined(HAVE_ET_COM_ERR_H)
-#include <et/com_err.h>
+#ifdef HAVE_COM_ERR_H
+# include <com_err.h>
+#elif HAVE_ET_COM_ERR_H
+# include <et/com_err.h>
+#elif HAVE_KRB5_COM_ERR_H
+# include <krb5/com_err.h>
 #else
-#include <com_err.h>
+# error No com_err.h? We need some kind of com_err.h
 #endif
 
 #ifndef HAVE_KERBEROSV_HEIM_ERR_H
 #define DIRSTRING "/"          /* String form of above */
 #define VOLMARKER ':'          /* Character separating cellname from mntpt */
 #define VOLMARKERSTRING ":"    /* String form of above */
+#define AKIMP_LIFETIME_MAX 720  /* Max token lifetime for akimpersonate in hours (30 days) */
 
 typedef struct {
     char cell[BUFSIZ];
@@ -140,6 +146,7 @@ static int get_user_realm(krb5_context, char **);
 
 #define TRYAGAIN(x) (x == AKLOG_TRYAGAIN || \
                     x == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN || \
+                    x == KRB5_KT_NOTFOUND || \
                     x == KRB5KRB_ERR_GENERIC)
 
 #if defined(HAVE_KRB5_PRINC_SIZE) || defined(krb5_princ_size)
@@ -162,6 +169,11 @@ static int get_user_realm(krb5_context, char **);
 #error "Must have either krb5_princ_size or krb5_principal_get_comp_string"
 #endif
 
+#if defined(HAVE_ENCODE_KRB5_TICKET)
+extern krb5_error_code encode_krb5_ticket (const krb5_ticket *rep,
+                                          krb5_data **code);
+#endif
+
 #if !defined(HAVE_KRB5_ENCRYPT_TKT_PART) && defined(HAVE_ENCODE_KRB5_ENC_TKT_PART) && defined(HAVE_KRB5_C_ENCRYPT)
 extern krb5_error_code encode_krb5_enc_tkt_part (const krb5_enc_tkt_part *rep,
                                                 krb5_data **code);
@@ -216,12 +228,11 @@ Done:
 #error "Must have either keyblock or session member of krb5_creds"
 #endif
 
-#ifdef AFS_DARWIN110_ENV
-#define HAVE_NO_KRB5_524 /* MITKerberosShim logs but returns success */
+/* MITKerberosShim logs but returns success */
+#if !defined(HAVE_KRB5_524_CONV_PRINCIPAL) || defined(AFS_DARWIN110_ENV) || (!defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC))
+#define HAVE_NO_KRB5_524
 #elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && defined(HAVE_KRB524_CONVERT_CREDS_KDC)
 #define krb5_524_convert_creds krb524_convert_creds_kdc
-#elif !defined(HAVE_KRB5_524_CONVERT_CREDS) && !defined(HAVE_KRB524_CONVERT_CREDS_KDC)
-#define HAVE_NO_KRB5_524
 #endif
 
 #if USING_HEIMDAL
@@ -293,6 +304,8 @@ static char *client = NULL;     /* client principal for akimpersonate */
 static linked_list zsublist;   /* List of zephyr subscriptions */
 static linked_list hostlist;   /* List of host addresses */
 static linked_list authedcells;        /* List of cells already logged to */
+static int akimp_lifetime = 36000;  /* Lifetime for akimpersonate tokens. Default 10 hrs */ 
+static int akimplifetime_present = 0; /* Whether a lifetime was specified for akimpersonate */
 
 /* A com_error bodge. The idea here is that this routine lets us lookup
  * things in the system com_err, if the AFS one just tells us the error
@@ -311,8 +324,12 @@ redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
        if (strncmp(str, "unknown", strlen("unknown")) == 0) {
 #ifdef HAVE_KRB5_SVC_GET_MSG
            krb5_svc_get_msg(code,&str);
-#elif defined(HAVE_ERROR_MESSAGE)
-           str = error_message(code);
+#elif defined(HAVE_KRB5_GET_ERROR_MESSAGE)
+           krb5_context context;
+           if (krb5_init_context(&context) == 0) {
+                str = krb5_get_error_message(context, code);
+                krb5_free_context(context);
+            }
 #else
            ; /* IRIX apparently has neither: use the string we have */
 #endif
@@ -345,7 +362,7 @@ copy_cellinfo(cellinfo_t *cellinfo)
 {
     cellinfo_t *new_cellinfo;
 
-    if ((new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t))))
+    if ((new_cellinfo = malloc(sizeof(cellinfo_t))))
        memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
 
     return ((char *)new_cellinfo);
@@ -353,7 +370,8 @@ copy_cellinfo(cellinfo_t *cellinfo)
 
 
 static int
-get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char **local_cell)
+get_cellconfig(const char *config, char *cell,
+              struct afsconf_cell *cellconfig, char **local_cell)
 {
     int status = AKLOG_SUCCESS;
     struct afsconf_dir *configdir;
@@ -367,26 +385,31 @@ get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char **local_cell)
        exit(AKLOG_AFS);
     }
 
-    if (!(configdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))) {
+    if (!(configdir = afsconf_Open(config))) {
        fprintf(stderr,
                "%s: can't get afs configuration (afsconf_Open(%s))\n",
-               progname, AFSDIR_CLIENT_ETC_DIRPATH);
+               progname, config);
        exit(AKLOG_AFS);
     }
 
-    if (afsconf_GetLocalCell(configdir, *local_cell, MAXCELLCHARS)) {
-       fprintf(stderr, "%s: can't determine local cell.\n", progname);
-       exit(AKLOG_AFS);
+    if (cell != NULL && cell[0] == '\0') {
+       /* Use the local cell */
+       cell = NULL;
     }
 
-    if ((cell == NULL) || (cell[0] == 0))
-       cell = *local_cell;
-
     /* XXX - This function modifies 'cell' by passing it through lcstring */
     if (afsconf_GetCellInfo(configdir, cell, NULL, cellconfig)) {
-       fprintf(stderr, "%s: Can't get information about cell %s.\n",
-               progname, cell);
+       if (cell != NULL) {
+           fprintf(stderr, "%s: Can't get information about cell %s.\n",
+                   progname, cell);
+       } else {
+           fprintf(stderr, "%s: Can't get information about the local cell.\n",
+                   progname);
+       }
        status = AKLOG_AFS;
+    } else if (afsconf_GetLocalCell(configdir, *local_cell, MAXCELLCHARS)) {
+       fprintf(stderr, "%s: can't determine local cell.\n", progname);
+       exit(AKLOG_AFS);
     }
 
     afsconf_Close(configdir);
@@ -561,9 +584,9 @@ rxkad_get_ticket(krb5_context context, char *realm,
                    }
                    afs_dprintf("We've deduced that we need to authenticate"
                            " to realm %s.\n", realm_of_cell);
+                   status = get_credv5(context, AFSKEY, cell->name,
+                                       realm_of_cell, v5cred);
                }
-               status = get_credv5(context, AFSKEY, cell->name,
-                                   realm_of_cell, v5cred);
            }
 
            /* If the realm and cell name match, then try without an
@@ -597,7 +620,7 @@ rxkad_get_ticket(krb5_context context, char *realm,
        afs_com_err(progname, status, "while getting AFS tickets");
 #ifdef KRB5_CC_NOT_KTYPE
        if (status == KRB5_CC_NOT_KTYPE) {
-           fprintf(stderr, "allow_weak_enctypes may be required in the Kerberos configuration\n");
+           fprintf(stderr, "allow_weak_crypto may be required in the Kerberos configuration\n");
        }
 #endif
        status = AKLOG_KERBEROS;
@@ -647,7 +670,8 @@ out:
  *     structure which should be freed by the caller.
  * @param[out[ userPtr
  *     A string containing the principal of the user to whom the token was
- *     issued. This is a malloc'd block which should be freed by the caller.
+ *     issued. This is a malloc'd block which should be freed by the caller,
+ *      if set.
  *
  * @returns
  *     0 on success, an error value upon failure
@@ -655,18 +679,19 @@ out:
 static int
 rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
                         struct ktc_tokenUnion **tokenPtr, char **userPtr) {
-    char username[BUFSIZ];
-    struct ktc_tokenUnion *token;
-    struct token_rxkad *rxkadToken;
+    char username[BUFSIZ]="";
+    struct ktc_token token;
+    int status;
 #ifdef HAVE_NO_KRB5_524
     char *p;
     int len;
 #else
-    int status;
     char k4name[ANAME_SZ];
     char k4inst[INST_SZ];
     char k4realm[REALM_SZ];
 #endif
+    void *inkey = get_cred_keydata(v5cred);
+    size_t inkey_sz = get_cred_keylen(v5cred);
 
     afs_dprintf("Using Kerberos V5 ticket natively\n");
 
@@ -679,14 +704,15 @@ rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
                                      (char *) &k4inst,
                                      (char *) &k4realm);
     if (status) {
-       afs_com_err(progname, status, "while converting principal "
-                   "to Kerberos V4 format");
-       return AKLOG_KERBEROS;
-    }
-    strcpy (username, k4name);
-    if (k4inst[0]) {
-       strcat (username, ".");
-       strcat (username, k4inst);
+       if (!noprdb)
+           afs_com_err(progname, status,
+                       "while converting principal to Kerberos V4 format");
+    } else {
+       strcpy (username, k4name);
+       if (k4inst[0]) {
+           strcat (username, ".");
+           strcat (username, k4inst);
+       }
     }
 #else
     len = min(get_princ_len(context, v5cred->client, 0),
@@ -705,31 +731,25 @@ rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
     }
 #endif
 
-    token = malloc(sizeof(struct ktc_tokenUnion));
-    if (token == NULL)
-       return ENOMEM;
-
-    memset(token, 0, sizeof(struct ktc_tokenUnion));
+    memset(&token, 0, sizeof(struct ktc_token));
 
-    token->at_type = AFSTOKEN_UNION_KAD;
-    rxkadToken = &token->ktc_tokenUnion_u.at_kad;
+    token.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
+    token.startTime = v5cred->times.starttime;;
+    token.endTime = v5cred->times.endtime;
+    if (tkt_DeriveDesKey(get_creds_enctype(v5cred), inkey, inkey_sz,
+                        &token.sessionKey) != 0) {
+       return RXKADBADKEY;
+    }
+    token.ticketLen = v5cred->ticket.length;
+    memcpy(token.ticket, v5cred->ticket.data, token.ticketLen);
 
-    rxkadToken->rk_kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
-    rxkadToken->rk_begintime = v5cred->times.starttime;;
-    rxkadToken->rk_endtime = v5cred->times.endtime;
-    memcpy(&rxkadToken->rk_key, get_cred_keydata(v5cred),
-          get_cred_keylen(v5cred));
-    rxkadToken->rk_ticket.rk_ticket_len = v5cred->ticket.length;
-    rxkadToken->rk_ticket.rk_ticket_val = malloc(v5cred->ticket.length);
-    if (rxkadToken->rk_ticket.rk_ticket_val == NULL) {
-       free(token);
-       return ENOMEM;
+    status = token_importRxkadViceId(tokenPtr, &token, 0);
+    if (status) {
+       return status;
     }
-    memcpy(rxkadToken->rk_ticket.rk_ticket_val, v5cred->ticket.data,
-          rxkadToken->rk_ticket.rk_ticket_len);
 
-    *tokenPtr = token;
-    *userPtr = strdup(username);
+    if (username[0] != '\0')
+       *userPtr = strdup(username);
 
     return 0;
 }
@@ -749,7 +769,8 @@ rxkad_build_native_token(krb5_context context, krb5_creds *v5cred,
  *     structure which should be freed by the caller.
  * @param[out[ userPtr
  *     A string containing the principal of the user to whom the token was
- *     issued. This is a malloc'd block which should be freed by the caller.
+ *     issued. This is a malloc'd block which should be freed by the caller,
+ *      if set.
  *
  * @returns
  *     0 on success, an error value upon failure
@@ -770,8 +791,7 @@ rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
                          struct ktc_tokenUnion **tokenPtr, char **userPtr) {
     CREDENTIALS cred;
     char username[BUFSIZ];
-    struct ktc_tokenUnion *token;
-    struct token_rxkad *rxkadToken;
+    struct ktc_token token;
     int status;
 
     *tokenPtr = NULL;
@@ -793,16 +813,10 @@ rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
        strcat (username, cred.pinst);
     }
 
-    token = malloc(sizeof(struct ktc_tokenUnion));
-    if (token == NULL)
-       return ENOMEM;
-    memset(token, 0, sizeof(struct ktc_tokenUnion));
-
-    token->at_type = AFSTOKEN_UNION_KAD;
+    memset(&token, 0, sizeof(struct ktc_token));
 
-    rxkadToken = &token->ktc_tokenUnion_u.at_kad;
-    rxkadToken->rk_kvno = cred.kvno;
-    rxkadToken->rk_begintime = cred.issue_date;
+    token.kvno = cred.kvno;
+    token.startTime = cred.issue_date;
     /*
      * It seems silly to go through a bunch of contortions to
      * extract the expiration time, when the v5 credentials already
@@ -811,18 +825,16 @@ rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
      * Note that this isn't a security hole, as the expiration time
      * is also contained in the encrypted token
      */
-    rxkadToken->rk_endtime = v5cred->times.endtime;
-    memcpy(&rxkadToken->rk_key, cred.session, 8);
-    rxkadToken->rk_ticket.rk_ticket_len = cred.ticket_st.length;
-    rxkadToken->rk_ticket.rk_ticket_val = malloc(cred.ticket_st.length);
-    if (rxkadToken->rk_ticket.rk_ticket_val == NULL) {
-       free(token);
-       return ENOMEM;
+    token.endTime = v5cred->times.endtime;
+    memcpy(&token.sessionKey, cred.session, 8);
+    token.ticketLen = cred.ticket_st.length;
+    memcpy(token.ticket, cred.ticket_st.dat, token.ticketLen);
+
+    status = token_importRxkadViceId(tokenPtr, &token, 0);
+    if (status) {
+       return status;
     }
-    memcpy(rxkadToken->rk_ticket.rk_ticket_val, cred.ticket_st.dat,
-          rxkadToken->rk_ticket.rk_ticket_len);
 
-    *tokenPtr = token;
     *userPtr = strdup(username);
 
     return 0;
@@ -845,7 +857,8 @@ rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
  *     be freed by the caller.
  * @parma[out] authuser
  *     A string containing the principal of the user to whom the token was
- *     issued. This is a malloc'd block which should be freed by the caller.
+ *     issued. This is a malloc'd block which should be freed by the caller,
+ *      if set.
  * @param[out] foreign
  *     Whether the user is considered as 'foreign' to the realm of the cell.
  *
@@ -855,11 +868,10 @@ rxkad_get_converted_token(krb5_context context, krb5_creds *v5cred,
 static int
 rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
                struct ktc_tokenUnion **token, char **authuser, int *foreign) {
-    krb5_creds *v5cred;
+    krb5_creds *v5cred = NULL;
     char *realmUsed = NULL;
     char *username = NULL;
     int status;
-    size_t len;
 
     *token = NULL;
     *authuser = NULL;
@@ -867,7 +879,7 @@ rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
 
     status = rxkad_get_ticket(context, realm, cell, &v5cred, &realmUsed);
     if (status)
-       return status;
+       goto out;
 
     if (do524)
        status = rxkad_get_converted_token(context, v5cred, token, &username);
@@ -879,14 +891,17 @@ rxkad_get_token(krb5_context context, struct afsconf_cell *cell, char *realm,
 
     /* We now have the username, plus the realm name, so stitch them together
      * to give us the name that the ptserver will know the user by */
-    if (realmUsed == NULL) {
+    if (realmUsed == NULL || username == NULL) {
        *authuser = username;
        username = NULL;
        *foreign = 0;
     } else {
-       len = strlen(username)+strlen(realmUsed)+2;
-       *authuser = malloc(len);
-       snprintf(*authuser, len, "%s@%s", username, realmUsed);
+       if (asprintf(authuser, "%s@%s", username, realmUsed) < 0) {
+           fprintf(stderr, "%s: Out of memory building PTS name\n", progname);
+           *authuser = NULL;
+           status = AKLOG_MISC;
+           goto out;
+       }
        *foreign = 1;
     }
 
@@ -895,6 +910,8 @@ out:
        free(realmUsed);
     if (username)
        free(username);
+    if (v5cred)
+        krb5_free_creds(context, v5cred);
 
     return status;
 }
@@ -905,7 +922,8 @@ out:
  * to.
  */
 static int
-auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
+auth_to_cell(krb5_context context, const char *config, 
+            char *cell, char *realm, char **linkedcell)
 {
     int status = AKLOG_SUCCESS;
     int isForeign = 0;
@@ -919,7 +937,7 @@ auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
     struct afsconf_cell cellconf;
 
     /* NULL or empty cell returns information on local cell */
-    if ((status = get_cellconfig(cell, &cellconf, &local_cell)))
+    if ((status = get_cellconfig(config, cell, &cellconf, &local_cell)))
        return(status);
 
     if (linkedcell != NULL) {
@@ -1007,7 +1025,10 @@ auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
        noprdb = 1;
 #endif
 
-       if (noprdb) {
+       if (username == NULL) {
+           afs_dprintf("Not resolving name to id\n");
+       }
+       else if (noprdb) {
            afs_dprintf("Not resolving name %s to id (-noprdb set)\n", username);
        }
        else {
@@ -1068,20 +1089,34 @@ auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
 #endif /* ALLOW_REGISTER */
 
            if ((status == 0) && (viceId != ANONYMOUSID)) {
-               rxkadToken->ktc_tokenUnion_u.at_kad.rk_viceid = viceId;
-               token_replaceToken(token, rxkadToken);
+               status = token_setRxkadViceId(rxkadToken, viceId);
+               if (status) {
+                   fprintf(stderr, "Error %d setting rxkad ViceId\n", status);
+                   status = AKLOG_SUCCESS;
+               } else {
+                   token_replaceToken(token, rxkadToken);
+               }
            }
        }
 
-       afs_dprintf("Setting tokens. %s @ %s \n", username, cellconf.name);
+       if (username) {
+           afs_dprintf("Setting tokens. %s @ %s\n",
+                       username, cellconf.name);
+       } else {
+           afs_dprintf("Setting tokens for cell %s\n", cellconf.name);
+       }
 
-#ifndef AFS_AIX51_ENV
+#if defined(AFS_AIX_ENV) && !defined(AFS_AIX51_ENV)
        /* on AIX 4.1.4 with AFS 3.4a+ if a write is not done before
         * this routine, it will not add the token. It is not clear what
         * is going on here! So we will do the following operation.
         * On AIX 5, it causes the parent program to die, so we won't.
+        * We don't care about the return value, but need to collect it
+        * to avoid compiler warnings.
         */
-       write(2,"",0); /* dummy write */
+       if (write(2,"",0) < 0) {
+           /* dummy write, don't care */
+       }
 #endif
        token_setPag(token, afssetpag);
        status = ktc_SetTokenEx(token);
@@ -1096,8 +1131,7 @@ auth_to_cell(krb5_context context, char *cell, char *realm, char **linkedcell)
 
 out:
     if (rxkadToken) {
-       free(rxkadToken->ktc_tokenUnion_u.at_kad.rk_ticket.rk_ticket_val);
-       free(rxkadToken);
+       token_freeToken(&rxkadToken);
     }
 
     if (local_cell)
@@ -1120,8 +1154,7 @@ get_afs_mountpoint(char *file, char *mountpoint, int size)
     struct ViceIoctl vio;
     char cellname[BUFSIZ];
 
-    memset(our_file, 0, sizeof(our_file));
-    strcpy(our_file, file);
+    strlcpy(our_file, file, sizeof(our_file));
 
     if ((last_component = strrchr(our_file, DIR))) {
        *last_component++ = 0;
@@ -1147,8 +1180,8 @@ get_afs_mountpoint(char *file, char *mountpoint, int size)
            vio.out = cellname;
 
            if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1)) {
-               strcat(cellname, VOLMARKERSTRING);
-               strcat(cellname, mountpoint + 1);
+               strlcat(cellname, VOLMARKERSTRING, sizeof(cellname));
+               strlcat(cellname, mountpoint + 1, sizeof(cellname));
                memset(mountpoint + 1, 0, size - 1);
                strcpy(mountpoint + 1, cellname);
            }
@@ -1172,7 +1205,7 @@ next_path(char *origpath)
     static char path[MAXPATHLEN + 1];
     static char pathtocheck[MAXPATHLEN + 1];
 
-    int link = FALSE;          /* Is this a symbolic link? */
+    ssize_t link;              /* Return value from readlink */
     char linkbuf[MAXPATHLEN + 1];
     char tmpbuf[MAXPATHLEN + 1];
 
@@ -1187,7 +1220,7 @@ next_path(char *origpath)
     if (origpath) {
        memset(path, 0, sizeof(path));
        memset(pathtocheck, 0, sizeof(pathtocheck));
-       strcpy(path, origpath);
+       strlcpy(path, origpath, sizeof(path));
        last_comp = path;
        symlinkcount = 0;
        return(NULL);
@@ -1206,15 +1239,19 @@ next_path(char *origpath)
            ? elast_comp - last_comp : strlen(last_comp);
        strncat(pathtocheck, last_comp, len);
        memset(linkbuf, 0, sizeof(linkbuf));
-       if ((link = (readlink(pathtocheck, linkbuf,
-                                   sizeof(linkbuf)) > 0))) {
+       link = readlink(pathtocheck, linkbuf, sizeof(linkbuf)-1);
+
+       if (link > 0) {
+           linkbuf[link] = '\0'; /* NUL terminate string */
+
            if (++symlinkcount > MAXSYMLINKS) {
                fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
                exit(AKLOG_BADPATH);
            }
+
            memset(tmpbuf, 0, sizeof(tmpbuf));
            if (elast_comp)
-               strcpy(tmpbuf, elast_comp);
+               strlcpy(tmpbuf, elast_comp, sizeof(tmpbuf));
            if (linkbuf[0] == DIR) {
                /*
                 * If this is a symbolic link to an absolute path,
@@ -1246,7 +1283,7 @@ next_path(char *origpath)
        else
            last_comp = elast_comp;
     }
-    while(link);
+    while(link > 0);
 
     return(pathtocheck);
 }
@@ -1311,7 +1348,7 @@ add_hosts(char *file)
  * every cell it encounters along the way.
  */
 static int
-auth_to_path(krb5_context context, char *path)
+auth_to_path(krb5_context context, const char *config, char *path)
 {
     int status = AKLOG_SUCCESS;
     int auth_status = AKLOG_SUCCESS;
@@ -1327,7 +1364,7 @@ auth_to_path(krb5_context context, char *path)
 
     /* Initialize */
     if (path[0] == DIR)
-       strcpy(pathtocheck, path);
+       strlcpy(pathtocheck, path, sizeof(pathtocheck));
     else {
        if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL) {
            fprintf(stderr, "Unable to find current working directory:\n");
@@ -1336,15 +1373,15 @@ auth_to_path(krb5_context context, char *path)
            exit(AKLOG_BADPATH);
        }
        else {
-           strcat(pathtocheck, DIRSTRING);
-           strcat(pathtocheck, path);
+           strlcat(pathtocheck, DIRSTRING, sizeof(pathtocheck));
+           strlcat(pathtocheck, path, sizeof(pathtocheck));
        }
     }
     next_path(pathtocheck);
 
     /* Go on to the next level down the path */
     while ((nextpath = next_path(NULL))) {
-       strcpy(pathtocheck, nextpath);
+       strlcpy(pathtocheck, nextpath, sizeof(pathtocheck));
        afs_dprintf("Checking directory %s\n", pathtocheck);
        /*
         * If this is an afs mountpoint, determine what cell from
@@ -1361,7 +1398,8 @@ auth_to_path(krb5_context context, char *path)
                add_hosts(pathtocheck);
            if ((endofcell = strchr(mountpoint, VOLMARKER))) {
                *endofcell = '\0';
-               if ((auth_status = auth_to_cell(context, cell, NULL, NULL))) {
+               auth_status = auth_to_cell(context, config, cell, NULL, NULL);
+               if (auth_status) {
                    if (status == AKLOG_SUCCESS)
                        status = auth_status;
                    else if (status != auth_status)
@@ -1401,7 +1439,7 @@ usage(void)
            "[-d] [[-cell | -c] cell [-k krb_realm]] ",
            "[[-p | -path] pathname]\n",
            "    [-zsubs] [-hosts] [-noauth] [-noprdb] [-force] [-setpag] \n"
-               "    [-linked]"
+               "    [-linked] [-insecure_des]"
 #ifndef HAVE_NO_KRB5_524
                " [-524]"
 #endif
@@ -1420,6 +1458,7 @@ usage(void)
 #ifndef HAVE_NO_KRB5_524
     fprintf(stderr, "    -524 means use the 524 converter instead of V5 directly\n");
 #endif
+    fprintf(stderr, "    -insecure_des enables insecure single-DES for krb5.\n");
     fprintf(stderr, "    No commandline arguments means ");
     fprintf(stderr, "authenticate to the local cell.\n");
     fprintf(stderr, "\n");
@@ -1433,6 +1472,7 @@ main(int argc, char *argv[])
     int status = AKLOG_SUCCESS;
     int i;
     int somethingswrong = FALSE;
+    int insecure_des = 0;
 
     cellinfo_t cellinfo;
 
@@ -1449,6 +1489,7 @@ main(int argc, char *argv[])
     linked_list paths;         /* List of paths to log to */
     ll_node *cur_node;
     char *linkedcell;
+    const char *config = AFSDIR_CLIENT_ETC_DIRPATH;
 
     memset(&cellinfo, 0, sizeof(cellinfo));
 
@@ -1468,7 +1509,42 @@ main(int argc, char *argv[])
     else
        progname = argv[0];
 
-    krb5_init_context(&context);
+#if defined(KRB5_PROG_ETYPE_NOSUPP) && !(defined(HAVE_KRB5_ENCTYPE_ENABLE) || defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO))
+    {
+       char *filepath = NULL, *newpath = NULL;
+#ifndef AFS_DARWIN_ENV
+       char *defaultpath = "/etc/krb5.conf:/etc/krb5/krb5.conf";
+#else
+       char *defaultpath = "~/Library/Preferences/edu.mit.Kerberos:/Library/Preferences/edu.mit.Kerberos";
+#endif
+       filepath = getenv("KRB5_CONFIG");
+
+       /* only fiddle with KRB5_CONFIG if krb5-weak.conf actually exists */
+       if (asprintf(&newpath, "%s/krb5-weak.conf",
+                    AFSDIR_CLIENT_ETC_DIRPATH) < 0)
+           newpath = NULL;
+       if (newpath != NULL && access(newpath, R_OK) == 0) {
+           free(newpath);
+           newpath = NULL;
+           if (asprintf(&newpath, "%s:%s/krb5-weak.conf",
+                        filepath ? filepath : defaultpath,
+                        AFSDIR_CLIENT_ETC_DIRPATH) < 0)
+               newpath = NULL;
+           else
+               setenv("KRB5_CONFIG", newpath, 1);
+       }
+#endif
+       krb5_init_context(&context);
+
+#if defined(KRB5_PROG_ETYPE_NOSUPP) && !(defined(HAVE_KRB5_ENCTYPE_ENABLE) || defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO))
+       if (newpath)
+           free(newpath);
+       if (filepath)
+           setenv("KRB5_CONFIG", filepath, 1);
+       else
+           unsetenv("KRB5_CONFIG");
+    }
+#endif
     initialize_KTC_error_table ();
     initialize_U_error_table();
     initialize_RXK_error_table();
@@ -1476,19 +1552,6 @@ main(int argc, char *argv[])
     initialize_PT_error_table();
     afs_set_com_err_hook(redirect_errors);
 
-    /*
-     * Enable DES enctypes, which are currently still required for AFS.
-     * krb5_allow_weak_crypto is MIT Kerberos 1.8.  krb5_enctype_enable is
-     * Heimdal.
-     */
-#if defined(HAVE_KRB5_ENCTYPE_ENABLE)
-    i = krb5_enctype_valid(context, ETYPE_DES_CBC_CRC);
-    if (i)
-        krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
-#elif defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO)
-    krb5_allow_weak_crypto(context, 1);
-#endif
-
     /* Initialize list of cells to which we have authenticated */
     ll_init(&authedcells);
 
@@ -1518,7 +1581,7 @@ main(int argc, char *argv[])
                  (strcmp(argv[i], "-c") == 0)) && !pmode)
            if (++i < argc) {
                cmode++;
-               strcpy(cell, argv[i]);
+               strlcpy(cell, argv[i], sizeof(cell));
            }
            else
                usage();
@@ -1528,6 +1591,28 @@ main(int argc, char *argv[])
            }
            else
                usage();
+        else if ((strcmp(argv[i], "-token-lifetime") == 0))
+           if (++i < argc) {
+               status = util_GetInt32(argv[i], &akimp_lifetime);
+               if (status) {
+                   fprintf(stderr,
+                           "%s: invalid value specified for token-lifetime.\n",
+                           progname);
+                   exit(AKLOG_MISC);
+               }
+
+               if (akimp_lifetime < 0 || akimp_lifetime > AKIMP_LIFETIME_MAX) {
+                   fprintf(stderr,
+                            "%s: token-lifetime must be within 0 and %d hrs.\n",
+                           progname, AKIMP_LIFETIME_MAX);
+                   exit(AKLOG_MISC);
+               }
+
+               akimp_lifetime = akimp_lifetime * 60 * 60;
+               akimplifetime_present = TRUE;
+           }
+           else
+               usage();
        else if ((strcmp(argv[i], "-principal") == 0))
            if (++i < argc) {
                client = argv[i];
@@ -1538,32 +1623,59 @@ main(int argc, char *argv[])
                  (strcmp(argv[i], "-p") == 0)) && !cmode)
            if (++i < argc) {
                pmode++;
-               strcpy(path, argv[i]);
+               strlcpy(path, argv[i], sizeof(path));
            }
            else
                usage();
-
+       else if (strcmp(argv[i], "-config") == 0)
+           if (++i < argc) {
+               config = argv[i];
+           }
+           else
+               usage();
+       else if (strcmp(argv[i], "-insecure_des") == 0)
+           insecure_des = 1;
        else if (argv[i][0] == '-')
            usage();
        else if (!pmode && !cmode) {
            if (strchr(argv[i], DIR) || (strcmp(argv[i], ".") == 0) ||
                (strcmp(argv[i], "..") == 0)) {
                pmode++;
-               strcpy(path, argv[i]);
+               strlcpy(path, argv[i], sizeof(path));
            }
            else {
                cmode++;
-               strcpy(cell, argv[i]);
+               strlcpy(cell, argv[i], sizeof(cell));
            }
        }
        else
            usage();
 
+    /*
+     * Enable DES enctypes if requested.  This is not required when rxkad-k5
+     * is used, but some sites may not have updated.
+     * krb5_allow_weak_crypto is MIT Kerberos 1.8.  krb5_enctype_enable is
+     * Heimdal.
+     */
+    if (insecure_des) {
+#if defined(HAVE_KRB5_ENCTYPE_ENABLE)
+       i = krb5_enctype_valid(context, ETYPE_DES_CBC_CRC);
+       if (i)
+           krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
+#elif defined(HAVE_KRB5_ALLOW_WEAK_CRYPTO)
+       krb5_allow_weak_crypto(context, 1);
+#else
+       fprintf(stderr,
+           "%s: -insecure_des is not supported by this libkrb5\n", progname);
+       exit(AKLOG_MISC);
+#endif
+    }
+
        if (cmode) {
            if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0)) {
                i+=2;
                if (i < argc)
-                   strcpy(realm, argv[i]);
+                   strlcpy(realm, argv[i], sizeof(realm));
                else
                    usage();
            }
@@ -1612,11 +1724,18 @@ main(int argc, char *argv[])
        }
     }
 
+    if (akimplifetime_present && !keytab) {
+       fprintf(stderr,
+               "%s: -token-lifetime is valid only if -keytab is specified.\n",
+               progname);
+       exit(AKLOG_MISC);
+    }
+
     /* If nothing was given, log to the local cell. */
     if ((cells.nelements + paths.nelements) == 0) {
        struct passwd *pwd;
 
-       status = auth_to_cell(context, NULL, NULL, &linkedcell);
+       status = auth_to_cell(context, config, NULL, NULL, &linkedcell);
 
        /* If this cell is linked to a DCE cell, and user requested -linked,
         * get tokens for both. This is very useful when the AFS cell is
@@ -1625,7 +1744,7 @@ main(int argc, char *argv[])
 
        if (!status && linked && linkedcell != NULL) {
            afs_dprintf("Linked cell: %s\n", linkedcell);
-           status = auth_to_cell(context, linkedcell, NULL, NULL);
+           status = auth_to_cell(context, config, linkedcell, NULL, NULL);
        }
        if (linkedcell) {
            free(linkedcell);
@@ -1643,8 +1762,8 @@ main(int argc, char *argv[])
            FILE *f;
            char fcell[100], xlog_path[512];
 
-           strcpy(xlog_path, pwd->pw_dir);
-           strcat(xlog_path, "/.xlog");
+           strlcpy(xlog_path, pwd->pw_dir, sizeof(xlog_path));
+           strlcat(xlog_path, "/.xlog", sizeof(xlog_path));
 
            if ((stat(xlog_path, &sbuf) == 0) &&
                ((f = fopen(xlog_path, "r")) != NULL)) {
@@ -1659,7 +1778,7 @@ main(int argc, char *argv[])
 
                    afs_dprintf("Found cell %s in %s.\n", fcell, xlog_path);
 
-                   auth_status = auth_to_cell(context, fcell, NULL, NULL);
+                   auth_status = auth_to_cell(context, config, fcell, NULL, NULL);
                    if (status == AKLOG_SUCCESS)
                        status = auth_status;
                    else
@@ -1672,14 +1791,16 @@ main(int argc, char *argv[])
        /* Log to all cells in the cells list first */
        for (cur_node = cells.first; cur_node; cur_node = cur_node->next) {
            memcpy((char *)&cellinfo, cur_node->data, sizeof(cellinfo));
-           if ((status = auth_to_cell(context, cellinfo.cell, cellinfo.realm,
-                                      &linkedcell)))
+           status = auth_to_cell(context, config, cellinfo.cell,
+                                 cellinfo.realm, &linkedcell);
+           if (status) {
                somethingswrong++;
-           else {
+           } else {
                if (linked && linkedcell != NULL) {
                    afs_dprintf("Linked cell: %s\n", linkedcell);
-                   if ((status = auth_to_cell(context, linkedcell,
-                                              cellinfo.realm, NULL)))
+                   status = auth_to_cell(context, config, linkedcell,
+                                         cellinfo.realm, NULL);
+                   if (status)
                        somethingswrong++;
                }
                if (linkedcell != NULL) {
@@ -1691,7 +1812,8 @@ main(int argc, char *argv[])
 
        /* Then, log to all paths in the paths list */
        for (cur_node = paths.first; cur_node; cur_node = cur_node->next) {
-           if ((status = auth_to_path(context, cur_node->data)))
+           status = auth_to_path(context, config, cur_node->data);
+           if (status)
                somethingswrong++;
        }
 
@@ -1742,14 +1864,12 @@ get_credv5_akimpersonate(krb5_context context,
                         krb5_principal client_principal,
                         time_t starttime,
                         time_t endtime,
-                        int *allowed_enctypes,
                         int *paddress,
                         krb5_creds** out_creds /* out */ )
 {
-#if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
+#if defined(USING_HEIMDAL) || (defined(HAVE_ENCODE_KRB5_ENC_TKT_PART) && defined(HAVE_ENCODE_KRB5_TICKET) && defined(HAVE_KRB5_C_ENCRYPT))
     krb5_error_code code;
     krb5_keytab kt = 0;
-    krb5_kt_cursor cursor[1];
     krb5_keytab_entry entry[1];
     krb5_ccache cc = 0;
     krb5_creds *creds = 0;
@@ -1761,7 +1881,7 @@ get_credv5_akimpersonate(krb5_context context,
     EncTicketPart enc_tkt_reply[1];
     krb5_address address[30];
     krb5_addresses faddr[1];
-    int temp_vno[1];
+    unsigned int temp_vno[1];
     time_t temp_time[2];
 #else
     krb5_ticket ticket_reply[1];
@@ -1770,14 +1890,11 @@ get_credv5_akimpersonate(krb5_context context,
     krb5_data * temp;
 #endif
     int i;
-    static int any_enctype[] = {0};
     *out_creds = 0;
     if (!(creds = malloc(sizeof *creds))) {
         code = ENOMEM;
         goto cleanup;
     }
-    if (!allowed_enctypes)
-        allowed_enctypes = any_enctype;
 
     cc = 0;
     enctype = 0; /* AKIMPERSONATE_IGNORE_ENCTYPE */
@@ -1796,54 +1913,17 @@ get_credv5_akimpersonate(krb5_context context,
         goto cleanup;
     }
 
-    if (service_principal) {
-        for (i = 0; (enctype = allowed_enctypes[i]) || !i; ++i) {
-           code = krb5_kt_get_entry(context,
-                                    kt,
-                                    service_principal,
-                                    kvno,
-                                    enctype,
-                                    entry);
-           if (!code) {
-               if (allowed_enctypes[i])
-                   deref_keyblock_enctype(session_key) = allowed_enctypes[i];
-               break;
-           }
-        }
-        if (code) {
-           afs_com_err(progname, code,"while scanning keytab entries");
-           goto cleanup;
-        }
-    } else {
-        krb5_keytab_entry new[1];
-        int best = -1;
-        memset(new, 0, sizeof *new);
-        if ((code == krb5_kt_start_seq_get(context, kt, cursor))) {
-            afs_com_err(progname, code, "while starting keytab scan");
-            goto cleanup;
-        }
-        while (!(code = krb5_kt_next_entry(context, kt, new, cursor))) {
-            for (i = 0;
-                    allowed_enctypes[i] && allowed_enctypes[i]
-                    != deref_entry_enctype(new); ++i)
-                ;
-            if ((!i || allowed_enctypes[i]) &&
-               (best < 0 || best > i)) {
-                krb5_free_keytab_entry_contents(context, entry);
-                *entry = *new;
-                memset(new, 0, sizeof *new);
-            } else krb5_free_keytab_entry_contents(context, new);
-        }
-        if ((i = krb5_kt_end_seq_get(context, kt, cursor))) {
-            afs_com_err(progname, i, "while ending keytab scan");
-            code = i;
-            goto cleanup;
-        }
-        if (best < 0) {
-            afs_com_err(progname, code, "while scanning keytab");
-            goto cleanup;
-        }
+    code = krb5_kt_get_entry(context,
+                            kt,
+                            service_principal,
+                            kvno,
+                            enctype,
+                            entry);
+    if (!code)
         deref_keyblock_enctype(session_key) = deref_entry_enctype(entry);
+    else {
+        afs_com_err(progname, code, "while scanning keytab entries");
+        goto cleanup;
     }
 
     /* Make Ticket */
@@ -1866,10 +1946,6 @@ get_credv5_akimpersonate(krb5_context context,
     enc_tkt_reply->authtime = starttime;
     enc_tkt_reply->starttime = temp_time;
     *enc_tkt_reply->starttime = starttime;
-#if 0
-    enc_tkt_reply->renew_till = temp_time + 1;
-    *enc_tkt_reply->renew_till = endtime;
-#endif
     enc_tkt_reply->endtime = endtime;
 #else
     if ((code = krb5_c_make_random_key(context,
@@ -1965,7 +2041,7 @@ get_credv5_akimpersonate(krb5_context context,
         }
     } /* crypto block */
     ticket_reply->enc_part.etype = deref_entry_enctype(entry);
-    ticket_reply->enc_part.kvno = temp_vno;
+    ticket_reply->enc_part.kvno = (void *)temp_vno;
     *ticket_reply->enc_part.kvno = entry->vno;
     ticket_reply->tkt_vno = 5;
 #else
@@ -2039,10 +2115,6 @@ cleanup:
     if (deref_enc_data(&ticket_reply->enc_part))
         free(deref_enc_data(&ticket_reply->enc_part));
     krb5_free_keytab_entry_contents(context, entry);
-    if (client_principal)
-        krb5_free_principal(context, client_principal);
-    if (service_principal)
-        krb5_free_principal(context, service_principal);
     if (cc)
         krb5_cc_close(context, cc);
     if (kt)
@@ -2062,7 +2134,6 @@ get_credv5(krb5_context context, char *name, char *inst, char *realm,
 {
     krb5_creds increds;
     krb5_error_code r;
-    static krb5_principal client_principal = 0;
 
     afs_dprintf("Getting tickets: %s%s%s@%s\n", name,
            (inst && inst[0]) ? "/" : "", inst ? inst : "", realm);
@@ -2072,51 +2143,65 @@ get_credv5(krb5_context context, char *name, char *inst, char *realm,
     if ((r = krb5_build_principal(context, &increds.server,
                                  strlen(realm), realm,
                                  name,
-                                 (inst && strlen(inst)) ? inst : (void *) NULL,
-                                 (void *) NULL))) {
-        return r;
+                                 (inst && strlen(inst)) ? inst : NULL,
+                                 NULL))) {
+        goto out;
     }
 
 
     if (!_krb425_ccache) {
         r = krb5_cc_default(context, &_krb425_ccache);
        if (r)
-           return r;
+           goto out;
     }
-    if (!client_principal) {
-       if (client) {
-           r = krb5_parse_name(context, client,  &client_principal);
-       } else {
-           r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
-       }
-       if (r)
-           return r;
+
+    if (client) {
+        r = krb5_parse_name(context, client,  &increds.client);
+    } else {
+        r = krb5_cc_get_principal(context, _krb425_ccache, &increds.client);
     }
 
-    increds.client = client_principal;
+    if (r)
+       goto out;
+
     increds.times.endtime = 0;
-    /* Ask for DES since that is what V4 understands */
-    get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
+    if (do524)
+       /* Ask for DES since that is what V4 understands */
+       get_creds_enctype((&increds)) = ENCTYPE_DES_CBC_CRC;
 
     if (keytab) {
-       int allowed_enctypes[] = {
-           ENCTYPE_DES_CBC_CRC, 0
-       };
+       afs_int32 start, end;
+       start = time(NULL);
+
+       if (akimp_lifetime == 0) {
+           end = MAX_AFS_INT32;
+       } else {
+           end = start + akimp_lifetime;
+       }
 
        r = get_credv5_akimpersonate(context,
                                     keytab,
                                     increds.server,
                                     increds.client,
-                                    300, ((~0U)>>1),
-                                    allowed_enctypes,
+                                    start, end,
                                     0 /* paddress */,
                                     creds /* out */);
     } else {
        r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
     }
-    return r;
-}
 
+ out:
+
+   if (increds.server) {
+       krb5_free_principal(context, increds.server);
+   }
+
+   if (increds.client) {
+       krb5_free_principal(context, increds.client);
+   }
+
+   return r;
+}
 
 static int
 get_user_realm(krb5_context context, char **realm)
@@ -2126,8 +2211,11 @@ get_user_realm(krb5_context context, char **realm)
 
     *realm = NULL;
 
-    if (!_krb425_ccache)
-        krb5_cc_default(context, &_krb425_ccache);
+    if (!_krb425_ccache) {
+       r = krb5_cc_default(context, &_krb425_ccache);
+       if (r)
+           return r;
+    }
     if (!client_principal) {
        if (client) {
            r = krb5_parse_name(context, client,  &client_principal);