NO_DES_H_INCLUDE is no longer necessary
[openafs.git] / src / WINNT / afsd / afskfw.c
index d646899..4a6a892 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2005, 2006 Secure Endpoints Inc.
+ * Copyright (c) 2004, 2005, 2006, 2007, 2008 Secure Endpoints Inc.
  * Copyright (c) 2003 SkyRope, LLC
  * All rights reserved.
  * 
  */
 
 
-#define USE_MS2MIT
 #undef  USE_KRB4
-#include "afskfw-int.h"
-#include "afskfw.h"
-#include <userenv.h>
+#ifndef _WIN64
+#define USE_KRB524 1
+#endif
+#define USE_MS2MIT 1
+#define USE_LEASH 1
 
-#include <Sddl.h>
-#include <Aclapi.h>
+#include <afsconfig.h>
+#include <afs/param.h>
+#include <roken.h>
 
 #include <osilog.h>
 #include <afs/ptserver.h>
 #include <afs/ptuser.h>
 #include <rx/rxkad.h>
-
 #include <WINNT\afsreg.h>
+#include "cm.h"
+
+#include "afskfw.h"
+#include "afskfw-int.h"
+#include <userenv.h>
+#include "strsafe.h"
+
+#include <Sddl.h>
+#include <Aclapi.h>
 
 /*
  * TIMING _____________________________________________________________________
@@ -94,6 +104,7 @@ DECL_FUNC_PTR(cc_shutdown);
 DECL_FUNC_PTR(cc_get_NC_info);
 DECL_FUNC_PTR(cc_free_NC_info);
 
+#ifdef USE_LEASH
 // leash functions
 DECL_FUNC_PTR(Leash_get_default_lifetime);
 DECL_FUNC_PTR(Leash_get_default_forwardable);
@@ -108,6 +119,7 @@ DECL_FUNC_PTR(Leash_get_default_renew_min);
 DECL_FUNC_PTR(Leash_get_default_renew_max);
 DECL_FUNC_PTR(Leash_get_default_renewable);
 DECL_FUNC_PTR(Leash_get_default_mslsa_import);
+#endif 
 
 // krb5 functions
 DECL_FUNC_PTR(krb5_change_password);
@@ -170,15 +182,23 @@ DECL_FUNC_PTR(krb5_free_host_realm);
 DECL_FUNC_PTR(krb5_free_addresses);
 DECL_FUNC_PTR(krb5_c_random_make_octets);
 
+// Krb5 KFW 3.2 functions
+DECL_FUNC_PTR(krb5_get_error_message);
+DECL_FUNC_PTR(krb5_free_error_message);
+
+#ifdef USE_KRB524
 // Krb524 functions
 DECL_FUNC_PTR(krb524_init_ets);
 DECL_FUNC_PTR(krb524_convert_creds_kdc);
+#endif
 
+#ifdef USE_KRB4
 // krb4 functions
 DECL_FUNC_PTR(krb_get_cred);
 DECL_FUNC_PTR(tkt_string);
 DECL_FUNC_PTR(krb_get_tf_realm);
 DECL_FUNC_PTR(krb_mk_req);
+#endif
 
 // ComErr functions
 DECL_FUNC_PTR(com_err);
@@ -219,6 +239,7 @@ FUNC_INFO ccapi_fi[] = {
     END_FUNC_INFO
 };
 
+#ifdef USE_LEASH
 FUNC_INFO leash_fi[] = {
     MAKE_FUNC_INFO(Leash_get_default_lifetime),
     MAKE_FUNC_INFO(Leash_get_default_renew_till),
@@ -239,6 +260,7 @@ FUNC_INFO leash_opt_fi[] = {
     MAKE_FUNC_INFO(Leash_get_default_mslsa_import),
     END_FUNC_INFO
 };
+#endif
 
 FUNC_INFO k5_fi[] = {
     MAKE_FUNC_INFO(krb5_change_password),
@@ -304,6 +326,12 @@ FUNC_INFO k5_fi[] = {
     END_FUNC_INFO
 };
 
+FUNC_INFO k5_kfw_32_fi[] = {
+    MAKE_FUNC_INFO(krb5_get_error_message),
+    MAKE_FUNC_INFO(krb5_free_error_message),
+    END_FUNC_INFO
+};
+
 #ifdef USE_KRB4
 FUNC_INFO k4_fi[] = {
     MAKE_FUNC_INFO(krb_get_cred),
@@ -314,11 +342,13 @@ FUNC_INFO k4_fi[] = {
 };
 #endif
 
+#ifdef USE_KRB524
 FUNC_INFO k524_fi[] = {
     MAKE_FUNC_INFO(krb524_init_ets),
     MAKE_FUNC_INFO(krb524_convert_creds_kdc),
     END_FUNC_INFO
 };
+#endif
 
 FUNC_INFO profile_fi[] = {
         MAKE_FUNC_INFO(profile_init),
@@ -360,7 +390,7 @@ FUNC_INFO lsa_fi[] = {
 
 /* Static Prototypes */
 char *afs_realm_of_cell(krb5_context, struct afsconf_cell *);
-static long get_cellconfig_callback(void *, struct sockaddr_in *, char *);
+static long get_cellconfig_callback(void *, struct sockaddr_in *, char *, unsigned short);
 int KFW_AFS_get_cellconfig(char *, struct afsconf_cell *, char *);
 static krb5_error_code KRB5_CALLCONV KRB5_prompter( krb5_context context,
            void *data, const char *name, const char *banner, int num_prompts,
@@ -372,10 +402,13 @@ static int                inited = 0;
 static int                mid_cnt = 0;
 static struct textField * mid_tb = NULL;
 static HINSTANCE hKrb5 = 0;
+static HINSTANCE hKrb5_kfw_32 = 0;
 #ifdef USE_KRB4
 static HINSTANCE hKrb4 = 0;
 #endif /* USE_KRB4 */
+#ifdef USE_KRB524
 static HINSTANCE hKrb524 = 0;
+#endif
 #ifdef USE_MS2MIT
 static HINSTANCE hSecur32 = 0;
 #endif /* USE_MS2MIT */
@@ -383,8 +416,10 @@ static HINSTANCE hAdvApi32 = 0;
 static HINSTANCE hComErr = 0;
 static HINSTANCE hService = 0;
 static HINSTANCE hProfile = 0;
+#ifdef USE_LEASH
 static HINSTANCE hLeash = 0;
 static HINSTANCE hLeashOpt = 0;
+#endif
 static HINSTANCE hCCAPI = 0;
 static struct principal_ccache_data * princ_cc_data = NULL;
 static struct cell_principal_map    * cell_princ_map = NULL;
@@ -398,7 +433,7 @@ KFW_initialize(void)
         char mutexName[MAX_PATH];
         HANDLE hMutex = NULL;
 
-        sprintf(mutexName, "AFS KFW Init pid=%d", getpid());
+        StringCbPrintf( mutexName, sizeof(mutexName), "AFS KFW Init pid=%d", getpid());
         
         hMutex = CreateMutex( NULL, TRUE, mutexName );
         if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
@@ -409,22 +444,27 @@ KFW_initialize(void)
         if ( !inited ) {
             inited = 1;
             LoadFuncs(KRB5_DLL, k5_fi, &hKrb5, 0, 1, 0, 0);
+            LoadFuncs(KRB5_DLL, k5_kfw_32_fi, &hKrb5_kfw_32, 0, 1, 0, 0);
+            LoadFuncs(COMERR_DLL, ce_fi, &hComErr, 0, 0, 1, 0);
+            LoadFuncs(PROFILE_DLL, profile_fi, &hProfile, 0, 1, 0, 0);
 #ifdef USE_KRB4
             LoadFuncs(KRB4_DLL, k4_fi, &hKrb4, 0, 1, 0, 0);
 #endif /* USE_KRB4 */
-            LoadFuncs(COMERR_DLL, ce_fi, &hComErr, 0, 0, 1, 0);
             LoadFuncs(SERVICE_DLL, service_fi, &hService, 0, 1, 0, 0);
 #ifdef USE_MS2MIT
             LoadFuncs(SECUR32_DLL, lsa_fi, &hSecur32, 0, 1, 1, 1);
 #endif /* USE_MS2MIT */
+#ifdef USE_KRB524
             LoadFuncs(KRB524_DLL, k524_fi, &hKrb524, 0, 1, 1, 1);
-            LoadFuncs(PROFILE_DLL, profile_fi, &hProfile, 0, 1, 0, 0);
+#endif
+#ifdef USE_LEASH
             LoadFuncs(LEASH_DLL, leash_fi, &hLeash, 0, 1, 0, 0);
-            LoadFuncs(CCAPI_DLL, ccapi_fi, &hCCAPI, 0, 1, 0, 0);
             LoadFuncs(LEASH_DLL, leash_opt_fi, &hLeashOpt, 0, 1, 0, 0);
+#endif
+            LoadFuncs(CCAPI_DLL, ccapi_fi, &hCCAPI, 0, 1, 0, 0);
 
             if ( KFW_is_available() ) {
-                char rootcell[MAXCELLCHARS+1];
+                char rootcell[CELL_MAXNAMELEN+1];
 #ifdef USE_MS2MIT
                 KFW_import_windows_lsa();
 #endif /* USE_MS2MIT */
@@ -444,14 +484,18 @@ KFW_initialize(void)
 void
 KFW_cleanup(void)
 {
+#ifdef USE_LEASH
     if (hLeashOpt)
         FreeLibrary(hLeashOpt);
-    if (hCCAPI)
-        FreeLibrary(hCCAPI);
     if (hLeash)
         FreeLibrary(hLeash);
+#endif
+#ifdef USE_KRB524
     if (hKrb524)
         FreeLibrary(hKrb524);
+#endif
+    if (hCCAPI)
+        FreeLibrary(hCCAPI);
 #ifdef USE_MS2MIT
     if (hSecur32)
         FreeLibrary(hSecur32);
@@ -468,8 +512,68 @@ KFW_cleanup(void)
 #endif /* USE_KRB4 */
     if (hKrb5)
         FreeLibrary(hKrb5);
+    if (hKrb5_kfw_32)
+        FreeLibrary(hKrb5_kfw_32);
+}
+
+typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
+static int IsWow64()
+{
+    static int init = TRUE;
+    static int bIsWow64 = FALSE;
+
+    if (init) {
+        HMODULE hModule;
+        LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
+
+        hModule = GetModuleHandle(TEXT("kernel32"));
+        if (hModule) {
+            fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process");
+  
+            if (NULL != fnIsWow64Process)
+            {
+                if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
+                {
+                    // on error, assume FALSE.
+                    // in other words, do nothing.
+                }
+            }
+            FreeLibrary(hModule);
+        }
+        init = FALSE;
+    }
+    return bIsWow64;
+}
+
+int
+KFW_accept_dotted_usernames(void)
+{
+    HKEY parmKey;
+    DWORD code, len;
+    DWORD value = 1;
+
+    code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
+                         0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
+    if (code == ERROR_SUCCESS) {
+        len = sizeof(value);
+        code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
+                                (BYTE *) &value, &len);
+        RegCloseKey(parmKey);
+    }
+    if (code != ERROR_SUCCESS) {
+        code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
+                             0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
+        if (code == ERROR_SUCCESS) {
+            len = sizeof(value);
+            code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
+                                    (BYTE *) &value, &len);
+            RegCloseKey (parmKey);
+        }
+    }
+    return value;
 }
 
+
 int
 KFW_use_krb524(void)
 {
@@ -478,7 +582,7 @@ KFW_use_krb524(void)
     DWORD use524 = 0;
 
     code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
-                         0, KEY_QUERY_VALUE, &parmKey);
+                         0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
     if (code == ERROR_SUCCESS) {
         len = sizeof(use524);
         code = RegQueryValueEx(parmKey, "Use524", NULL, NULL,
@@ -487,7 +591,7 @@ KFW_use_krb524(void)
     }
     if (code != ERROR_SUCCESS) {
         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
-                             0, KEY_QUERY_VALUE, &parmKey);
+                             0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
         if (code == ERROR_SUCCESS) {
             len = sizeof(use524);
             code = RegQueryValueEx(parmKey, "Use524", NULL, NULL,
@@ -506,7 +610,7 @@ KFW_is_available(void)
     DWORD enableKFW = 1;
 
     code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
-                         0, KEY_QUERY_VALUE, &parmKey);
+                         0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
     if (code == ERROR_SUCCESS) {
         len = sizeof(enableKFW);
         code = RegQueryValueEx(parmKey, "EnableKFW", NULL, NULL,
@@ -516,7 +620,7 @@ KFW_is_available(void)
     
     if (code != ERROR_SUCCESS) {
         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
-                             0, KEY_QUERY_VALUE, &parmKey);
+                             0, (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
         if (code == ERROR_SUCCESS) {
             len = sizeof(enableKFW);
             code = RegQueryValueEx(parmKey, "EnableKFW", NULL, NULL,
@@ -533,8 +637,13 @@ KFW_is_available(void)
 #ifdef USE_MS2MIT
          hSecur32 && 
 #endif /* USE_MS2MIT */
+#ifdef USE_KRB524
          hKrb524 &&
-         hProfile && hLeash && hCCAPI )
+#endif
+#ifdef USE_LEASH
+         hLeash &&
+#endif
+         hProfile && hCCAPI )
         return TRUE;
     return FALSE;
 }
@@ -558,12 +667,17 @@ KRB5_error(krb5_error_code rc, LPCSTR FailedFunctionName,
     }
     */
         
-    errText = perror_message(rc);   
-    _snprintf(message, sizeof(message), 
-              "%s\n(Kerberos error %ld)\n\n%s failed", 
+    if (pkrb5_get_error_message)
+        errText = pkrb5_get_error_message(ctx, rc);
+    else
+        errText = perror_message(rc);
+    StringCbPrintf(message, sizeof(message), 
+              "%s\n(Kerberos error %ld)\n\n%s failed",
               errText, 
               krb5Error, 
               FailedFunctionName);
+    if (pkrb5_free_error_message)
+        pkrb5_free_error_message(ctx, (char *)errText);
 
     if ( IsDebuggerPresent() )
         OutputDebugString(message);
@@ -577,11 +691,11 @@ KRB5_error(krb5_error_code rc, LPCSTR FailedFunctionName,
         {
             if (cache && *cache != NULL) {
                 pkrb5_cc_close(*ctx, *cache);
-                               *cache = NULL;
-                       }
+                *cache = NULL;
+            }
        
             pkrb5_free_context(*ctx);
-                       *ctx = NULL;
+            *ctx = NULL;
         }
     }
 
@@ -595,6 +709,8 @@ KFW_AFS_update_princ_ccache_data(krb5_context ctx, krb5_ccache cc, int lsa)
     krb5_principal principal = 0;
     char * pname = NULL;
     const char * ccname = NULL;
+    const char * cctype = NULL;
+    char * ccfullname = NULL;
     krb5_error_code code = 0;
     krb5_error_code cc_code = 0;
     krb5_cc_cursor cur;
@@ -614,10 +730,18 @@ KFW_AFS_update_princ_ccache_data(krb5_context ctx, krb5_ccache cc, int lsa)
     ccname = pkrb5_cc_get_name(ctx, cc);
     if (!ccname) goto cleanup;
 
+    cctype = pkrb5_cc_get_type(ctx, cc);
+    if (!cctype) goto cleanup;
+
+    ccfullname = malloc(strlen(ccname) + strlen(cctype) + 2);
+    if (!ccfullname) goto cleanup;
+       
+    StringCbPrintf(ccfullname, sizeof(ccfullname), "%s:%s", cctype, ccname);
+
     // Search the existing list to see if we have a match 
     if ( next ) {
         for ( ; next ; next = next->next ) {
-            if ( !strcmp(next->principal,pname) && !strcmp(next->ccache_name, ccname) )
+            if ( !strcmp(next->principal,pname) && !strcmp(next->ccache_name, ccfullname) )
                 break;
         }
     } 
@@ -628,7 +752,8 @@ KFW_AFS_update_princ_ccache_data(krb5_context ctx, krb5_ccache cc, int lsa)
         next->next = princ_cc_data;
         princ_cc_data = next;
         next->principal = _strdup(pname);
-        next->ccache_name = _strdup(ccname);
+        next->ccache_name = ccfullname;
+        ccfullname = NULL;
         next->from_lsa = lsa;
         next->expired = 1;
         next->expiration_time = 0;
@@ -687,6 +812,8 @@ KFW_AFS_update_princ_ccache_data(krb5_context ctx, krb5_ccache cc, int lsa)
     flags = KRB5_TC_OPENCLOSE;  //turn on OPENCLOSE
     code = pkrb5_cc_set_flags(ctx, cc, flags);
 
+    if ( ccfullname)
+        free(ccfullname);
     if ( pname )
         pkrb5_free_unparsed_name(ctx,pname);
     if ( principal )
@@ -892,8 +1019,9 @@ KFW_get_ccache(krb5_context alt_ctx, krb5_principal principal, krb5_ccache * cc)
 
         if ( !KFW_AFS_find_ccache_for_principal(ctx,pname,&ccname,TRUE) &&
              !KFW_AFS_find_ccache_for_principal(ctx,pname,&ccname,FALSE)) {
-            ccname = (char *)malloc(strlen(pname) + 5);
-            sprintf(ccname,"API:%s",pname);
+            size_t len = strlen(pname) + 5;
+            ccname = (char *)malloc(len);
+            StringCbPrintf(ccname, len, "API:%s", pname);
         }
         code = pkrb5_cc_resolve(ctx, ccname, cc);
     } else {
@@ -923,17 +1051,12 @@ KFW_import_windows_lsa(void)
     krb5_data *  princ_realm;
     krb5_error_code code;
     char cell[128]="", realm[128]="", *def_realm = 0;
-    int i;
+    unsigned int i;
     DWORD dwMsLsaImport;
          
     if (!pkrb5_init_context)
         return;
 
-#ifdef COMMENT
-    if ( !MSLSA_IsKerberosLogon() )
-        return;
-#endif
-
     code = pkrb5_init_context(&ctx);
     if (code) goto cleanup;
 
@@ -953,10 +1076,10 @@ KFW_import_windows_lsa(void)
         break;
     case 2: { /* matching realm */
         char ms_realm[128] = "", *r;
-        int i;
+        unsigned int j;
 
-        for ( r=ms_realm, i=0; i<krb5_princ_realm(ctx, princ)->length; r++, i++ ) {
-            *r = krb5_princ_realm(ctx, princ)->data[i];
+        for ( r=ms_realm, j=0; j<krb5_princ_realm(ctx, princ)->length; r++, j++ ) {
+            *r = krb5_princ_realm(ctx, princ)->data[j];
         }
         *r = '\0';
 
@@ -985,7 +1108,7 @@ KFW_import_windows_lsa(void)
     code = KFW_AFS_klog(ctx, cc, "afs", cell, realm, pLeash_get_default_lifetime(),NULL);
     if ( IsDebuggerPresent() ) {
         char message[256];
-        sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+        StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
         OutputDebugString(message);
     }
     if ( code ) goto cleanup;
@@ -1127,8 +1250,10 @@ KFW_import_ccache_data(void)
                 }
 
                 memset(&aserver, '\0', sizeof(aserver));
-                strcpy(aserver.name, sname->data);
-                strcpy(aserver.cell, cell->data);
+                StringCbCopyN( aserver.name, sizeof(aserver.name),
+                               sname->data, sizeof(aserver.name) - 1);
+                StringCbCopyN( aserver.cell, sizeof(aserver.cell),
+                               cell->data, sizeof(aserver.cell) - 1);
 
                 code = ktc_GetToken(&aserver, &atoken, sizeof(atoken), &aclient);
                 if (!code) {
@@ -1157,10 +1282,16 @@ KFW_import_ccache_data(void)
                         OutputDebugString("Calling KFW_AFS_klog() to obtain token\n");
                     }
 
-                    code = KFW_AFS_klog(ctx, cc, "afs", cell->data, realm->data, pLeash_get_default_lifetime(),NULL);
+                    code = KFW_AFS_klog(ctx, cc, "afs", cell->data, realm->data, 
+#ifndef USE_LEASH
+                                        600,
+#else
+                                        pLeash_get_default_lifetime(),
+#endif /* USE_LEASH */
+                                        NULL);
                     if ( IsDebuggerPresent() ) {
                         char message[256];
-                        sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+                        StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
                         OutputDebugString(message);
                     }
                 }
@@ -1214,19 +1345,19 @@ KFW_AFS_get_cred( char * username,
                   char * smbname,
                   char ** reasonP )
 {
+    static char reason[1024]="";
     krb5_context ctx = NULL;
     krb5_ccache cc = NULL;
     char * realm = NULL, * userrealm = NULL;
     krb5_principal principal = NULL;
     char * pname = NULL;
     krb5_error_code code;
-    char local_cell[MAXCELLCHARS+1];
+    char local_cell[CELL_MAXNAMELEN+1];
     char **cells = NULL;
     int  cell_count=0;
     struct afsconf_cell cellconfig;
     char * dot;
 
-
     if (!pkrb5_init_context)
         return 0;
 
@@ -1238,6 +1369,8 @@ KFW_AFS_get_cred( char * username,
         OutputDebugString("\n");
     }
 
+    memset(&cellconfig, 0, sizeof(cellconfig));
+
     code = pkrb5_init_context(&ctx);
     if ( code ) goto cleanup;
 
@@ -1249,26 +1382,33 @@ KFW_AFS_get_cred( char * username,
     userrealm = strchr(username,'@');
     if ( userrealm ) {
         pname = strdup(username);
-        userrealm = strchr(pname, '@');
-        *userrealm = '\0';
+        if (!KFW_accept_dotted_usernames()) {
+            userrealm = strchr(pname, '@');
+            *userrealm = '\0';
 
-        /* handle kerberos iv notation */
-        while ( dot = strchr(pname,'.') ) {
-            *dot = '/';
+            /* handle kerberos iv notation */
+            while ( dot = strchr(pname,'.') ) {
+                *dot = '/';
+            }
+            *userrealm++ = '@';
         }
-        *userrealm++ = '@';
     } else {
-        pname = malloc(strlen(username) + strlen(realm) + 2);
-
-        strcpy(pname, username);
-
-        /* handle kerberos iv notation */
-        while ( dot = strchr(pname,'.') ) {
-            *dot = '/';
+        size_t len = strlen(username) + strlen(realm) + 2;
+        pname = malloc(len);
+        if (pname == NULL) {
+            code = KRB5KRB_ERR_GENERIC;
+            goto cleanup;
         }
+        StringCbCopy(pname, len, username);
 
-        strcat(pname,"@");
-        strcat(pname,realm);
+        if (!KFW_accept_dotted_usernames()) {
+            /* handle kerberos iv notation */
+            while ( dot = strchr(pname,'.') ) {
+                *dot = '/';
+            }
+        }
+        StringCbCat( pname, len, "@");
+        StringCbCat( pname, len, realm);
     }
     if ( IsDebuggerPresent() ) {
         OutputDebugString("Realm: ");
@@ -1283,21 +1423,35 @@ KFW_AFS_get_cred( char * username,
     if ( code ) goto cleanup;
 
     if ( lifetime == 0 )
+#ifndef USE_LEASH
+        lifetime = 600;
+#else
         lifetime = pLeash_get_default_lifetime();
+#endif
 
     if ( password && password[0] ) {
         code = KFW_kinit( ctx, cc, HWND_DESKTOP, 
                           pname, 
                           password,
                           lifetime,
+#ifndef USE_LEASH
+                          1, /* forwardable */
+                          0, /* not proxiable */
+                          1, /* renewable */
+                          1, /* noaddresses */
+                          0  /* no public ip */
+#else
                           pLeash_get_default_forwardable(),
                           pLeash_get_default_proxiable(),
                           pLeash_get_default_renewable() ? pLeash_get_default_renew_till() : 0,
                           pLeash_get_default_noaddresses(),
-                          pLeash_get_default_publicip());
+                          pLeash_get_default_publicip()
+#endif /* USE_LEASH */
+                          );
+
         if ( IsDebuggerPresent() ) {
             char message[256];
-            sprintf(message,"KFW_kinit() returns: %d\n",code);
+            StringCbPrintf(message, sizeof(message), "KFW_kinit() returns: %d\n", code);
             OutputDebugString(message);
         }
         if ( code ) goto cleanup;
@@ -1308,7 +1462,7 @@ KFW_AFS_get_cred( char * username,
     code = KFW_AFS_klog(ctx, cc, "afs", cell, realm, lifetime, smbname);
     if ( IsDebuggerPresent() ) {
         char message[256];
-        sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+        StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
         OutputDebugString(message);
     }
     if ( code ) goto cleanup;
@@ -1323,9 +1477,15 @@ KFW_AFS_get_cred( char * username,
             if ( strcmp(cells[cell_count],cell) ) {
                 if ( IsDebuggerPresent() ) {
                     char message[256];
-                    sprintf(message,"found another cell for the same principal: %s\n",cell);
+                    StringCbPrintf(message, sizeof(message),
+                                   "found another cell for the same principal: %s\n", cell);
                     OutputDebugString(message);
                 }
+
+                if (cellconfig.linkedCell) {
+                    free(cellconfig.linkedCell);
+                    cellconfig.linkedCell = NULL;
+                }
                 code = KFW_AFS_get_cellconfig( cells[cell_count], (void*)&cellconfig, local_cell);
                 if ( code ) continue;
     
@@ -1339,7 +1499,7 @@ KFW_AFS_get_cred( char * username,
                 code = KFW_AFS_klog(ctx, cc, "afs", cells[cell_count], realm, lifetime, smbname);
                 if ( IsDebuggerPresent() ) {
                     char message[256];
-                    sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+                    StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
                     OutputDebugString(message);
                 }
             }
@@ -1356,9 +1516,19 @@ KFW_AFS_get_cred( char * username,
         free(pname);
     if ( cc )
         pkrb5_cc_close(ctx, cc);
+    if ( cellconfig.linkedCell )
+        free(cellconfig.linkedCell);
 
     if ( code && reasonP ) {
-        *reasonP = (char *)perror_message(code);
+        if (pkrb5_get_error_message) {
+            char *msg = pkrb5_get_error_message(ctx, code);
+            StringCbCopyN( reason, sizeof(reason),
+                           msg, sizeof(reason) - 1);
+            *reasonP = reason;
+            pkrb5_free_error_message(ctx, msg);
+        } else {
+            *reasonP = perror_message(code);
+        }
     }
     return(code);
 }
@@ -1423,7 +1593,8 @@ KFW_AFS_destroy_tickets_for_cell(char * cell)
         }
         free(principals);
     }
-    pkrb5_free_context(ctx);
+    if (ctx)
+               pkrb5_free_context(ctx);
     return 0;
 }
 
@@ -1477,7 +1648,8 @@ KFW_AFS_destroy_tickets_for_principal(char * user)
         free(cells);
     }
 
-    pkrb5_free_context(ctx);
+    if (ctx)
+               pkrb5_free_context(ctx);
     return 0;
 }
 
@@ -1492,7 +1664,7 @@ KFW_AFS_renew_expiring_tokens(void)
     int cell_count;
     char ** cells=NULL;
     const char * realm = NULL;
-    char local_cell[MAXCELLCHARS+1]="";
+    char local_cell[CELL_MAXNAMELEN+1]="";
     struct afsconf_cell cellconfig;
 
     if (!pkrb5_init_context)
@@ -1505,6 +1677,8 @@ KFW_AFS_renew_expiring_tokens(void)
         OutputDebugString("KFW_AFS_renew_expiring_tokens\n");
     }
 
+    memset(&cellconfig, 0, sizeof(cellconfig));
+
     code = pkrb5_init_context(&ctx);
     if (code) goto cleanup;
 
@@ -1546,6 +1720,10 @@ KFW_AFS_renew_expiring_tokens(void)
                         OutputDebugString(cells[cell_count]);
                         OutputDebugString("\n");
                     }
+                    if (cellconfig.linkedCell) {
+                        free(cellconfig.linkedCell);
+                        cellconfig.linkedCell = NULL;
+                    }
                     code = KFW_AFS_get_cellconfig( cells[cell_count], (void*)&cellconfig, local_cell);
                     if ( code ) continue;
                     realm = afs_realm_of_cell(ctx, &cellconfig);  // do not free
@@ -1557,7 +1735,7 @@ KFW_AFS_renew_expiring_tokens(void)
                     code = KFW_AFS_klog(ctx, cc, "afs", cells[cell_count], (char *)realm, 0, NULL);
                     if ( IsDebuggerPresent() ) {
                         char message[256];
-                        sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+                        StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
                         OutputDebugString(message);
                     }
                     free(cells[cell_count]);
@@ -1578,6 +1756,8 @@ KFW_AFS_renew_expiring_tokens(void)
         pkrb5_cc_close(ctx,cc);
     if ( ctx )
         pkrb5_free_context(ctx);
+    if (cellconfig.linkedCell)
+        free(cellconfig.linkedCell);
 
     return 0;
 }
@@ -1620,7 +1800,9 @@ KFW_AFS_renew_token_for_cell(char * cell)
         krb5_ccache                    cc  = 0;
         const char * realm = NULL;
         struct afsconf_cell cellconfig;
-        char local_cell[MAXCELLCHARS+1];
+        char local_cell[CELL_MAXNAMELEN+1];
+
+        memset(&cellconfig, 0, sizeof(cellconfig));
 
         while ( count-- ) {
             code = pkrb5_parse_name(ctx, principals[count], &princ);
@@ -1629,6 +1811,10 @@ KFW_AFS_renew_token_for_cell(char * cell)
             code = KFW_get_ccache(ctx, princ, &cc);
             if (code) goto loop_cleanup;
 
+            if (cellconfig.linkedCell) {
+                free(cellconfig.linkedCell);
+                cellconfig.linkedCell = NULL;
+            }
             code = KFW_AFS_get_cellconfig( cell, (void*)&cellconfig, local_cell);
             if ( code ) goto loop_cleanup;
 
@@ -1675,7 +1861,7 @@ KFW_AFS_renew_token_for_cell(char * cell)
             code = KFW_AFS_klog(ctx, cc, "afs", cell, (char *)realm, 0,NULL);
             if ( IsDebuggerPresent() ) {
                 char message[256];
-                sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
+                StringCbPrintf(message, sizeof(message), "KFW_AFS_klog() returns: %d\n", code);
                 OutputDebugString(message);
             }
 
@@ -1692,6 +1878,10 @@ KFW_AFS_renew_token_for_cell(char * cell)
                 pkrb5_free_principal(ctx, service);
                 princ = 0;
             }
+            if (cellconfig.linkedCell) {
+                free(cellconfig.linkedCell);
+                cellconfig.linkedCell = NULL;
+            }
 
             KFW_AFS_update_cell_princ_map(ctx, cell, principals[count], code ? FALSE : TRUE);
             free(principals[count]);
@@ -1701,7 +1891,8 @@ KFW_AFS_renew_token_for_cell(char * cell)
         code = -1;      // we did not renew the tokens 
 
   cleanup:
-    pkrb5_free_context(ctx);
+    if (ctx) 
+        pkrb5_free_context(ctx);
     return (code ? FALSE : TRUE);
 
 }
@@ -1787,7 +1978,7 @@ KFW_renew(krb5_context alt_ctx, krb5_ccache alt_cc)
     if (code) {
         if ( IsDebuggerPresent() ) {
             char message[256];
-            sprintf(message,"krb5_get_renewed_creds() failed: %d\n",code);
+            StringCbPrintf(message, sizeof(message), "krb5_get_renewed_creds() failed: %d\n", code);
             OutputDebugString(message);
         }
         goto cleanup;
@@ -1797,7 +1988,7 @@ KFW_renew(krb5_context alt_ctx, krb5_ccache alt_cc)
     if (code) {
         if ( IsDebuggerPresent() ) {
             char message[256];
-            sprintf(message,"krb5_cc_initialize() failed: %d\n",code);
+            StringCbPrintf(message, sizeof(message), "krb5_cc_initialize() failed: %d\n", code);
             OutputDebugString(message);
         }
         goto cleanup;
@@ -1807,7 +1998,7 @@ KFW_renew(krb5_context alt_ctx, krb5_ccache alt_cc)
     if (code) {
         if ( IsDebuggerPresent() ) {
             char message[256];
-            sprintf(message,"krb5_cc_store_cred() failed: %d\n",code);
+            StringCbPrintf(message, sizeof(message), "krb5_cc_store_cred() failed: %d\n", code);
             OutputDebugString(message);
         }
         goto cleanup;
@@ -1886,7 +2077,11 @@ KFW_kinit( krb5_context alt_ctx,
        goto cleanup;
 
     if (lifetime == 0)
+#ifndef USE_LEASH
+        lifetime = 600;
+#else
         lifetime = pLeash_get_default_lifetime();
+#endif /* USE_LEASH */
     lifetime *= 60;
 
     if (renew_life > 0)
@@ -2103,8 +2298,8 @@ MSLSA_IsKerberosLogon(VOID)
             usLength = (pSessionData->AuthenticationPackage).Length;
             if (usLength < 256)
             {
-                lstrcpynW (buffer, usBuffer, usLength);
-                lstrcatW (buffer,L"");
+                StringCbCopyNW( buffer, sizeof(buffer)/sizeof(WCHAR),
+                                usBuffer, usLength);
                 if ( !lstrcmpW(L"Kerberos",buffer) )
                     Success = TRUE;
             }
@@ -2354,7 +2549,7 @@ MultiInputDialog( HINSTANCE hinst, HWND hwndOwner,
         return 0;
     default: {
         char buf[256];
-        sprintf(buf,"DialogBoxIndirect() failed: %d",GetLastError());
+        StringCbPrintf(buf, sizeof(buf), "DialogBoxIndirect() failed: %d", GetLastError());
         MessageBox(hwndOwner,
                     buf,
                     "GetLastError()",
@@ -2531,8 +2726,8 @@ ViceIDToUsername(char *username,
                  struct ktc_principal *aserver, 
                  struct ktc_token *atoken)
 {
-    static char lastcell[MAXCELLCHARS+1] = { 0 };
-    static char confname[512] = { 0 };
+    static char lastcell[CELL_MAXNAMELEN+1] = { 0 };
+    static char confdir[512] = { 0 };
 #ifdef AFS_ID_TO_NAME
     char username_copy[BUFSIZ];
 #endif /* AFS_ID_TO_NAME */
@@ -2542,17 +2737,16 @@ ViceIDToUsername(char *username,
     afs_int32 id;
 #endif /* ALLOW_REGISTER */
 
-    if (confname[0] == '\0') {
-        strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
-        confname[sizeof(confname) - 2] = '\0';
-    }
+    if (confdir[0] == '\0')
+        cm_GetConfigDir(confdir, sizeof(confdir));
 
-    strcpy(lastcell, aserver->cell);
+    StringCbCopyN( lastcell, sizeof(lastcell),
+                   aserver->cell, sizeof(lastcell) - 1);
 
-    if (!pr_Initialize (0, confname, aserver->cell)) {
+    if (!pr_Initialize (0, confdir, aserver->cell)) {
         char sname[PR_MAXNAMELEN];
-        strncpy(sname, username, PR_MAXNAMELEN);
-        sname[PR_MAXNAMELEN-1] = '\0';    
+        StringCbCopyN( sname, sizeof(sname),
+                       username, sizeof(sname) - 1);
         status = pr_SNameToId (sname, &viceId);
        pr_End();
     }
@@ -2580,26 +2774,30 @@ ViceIDToUsername(char *username,
 #endif /* ALLOW_REGISTER */
             {
 #ifdef AFS_ID_TO_NAME
-                strncpy(username_copy, username, BUFSIZ);
+                StringCbCopyN( username_copy, sizeof(username_copy),
+                               username, sizeof(username_copy) - 1);
                 snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
 #endif /* AFS_ID_TO_NAME */
             }
 #ifdef ALLOW_REGISTER
         } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
             id = 0;
-            strncpy(aclient->name, username, MAXKTCNAMELEN - 1);
-            strcpy(aclient->instance, "");
-            strncpy(aclient->cell, realm_of_user, MAXKTCREALMLEN - 1);
+            StringCbCopyN( aclient->name, sizeof(aclient->name),
+                           username, sizeof(aclient->name) - 1);
+            aclient->instance[0] = '\0';
+            StringCbCopyN( aclient->cell, sizeof(aclient->cell),
+                           realm_of_user, sizeof(aclient->cell) - 1);
             if (status = ktc_SetToken(aserver, atoken, aclient, 0))
                 return status;
-            if (status = pr_Initialize(1L, confname, aserver->cell))
+            if (status = pr_Initialize(1L, confdir, aserver->cell))
                 return status;
             status = pr_CreateUser(username, &id);
            pr_End();
            if (status)
                return status;
 #ifdef AFS_ID_TO_NAME
-            strncpy(username_copy, username, BUFSIZ);
+            StringCbCopyN( username_copy, sizeof(username_copy),
+                           username, sizeof(username_copy) - 1);
             snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
 #endif /* AFS_ID_TO_NAME */
         }
@@ -2609,6 +2807,24 @@ ViceIDToUsername(char *username,
 }
 
 
+static void
+copy_realm_of_ticket(krb5_context context, char * dest, size_t destlen, krb5_creds *v5cred) {
+    krb5_error_code code;
+    krb5_ticket *ticket;
+    size_t len;
+
+    code = pkrb5_decode_ticket(&v5cred->ticket, &ticket);
+    if (code == 0) {
+        len = krb5_princ_realm(context, ticket->server)->length;
+        if (len > destlen - 1)
+            len = destlen - 1;
+
+        StringCbCopyN(dest, destlen, krb5_princ_realm(context, ticket->server)->data, len);
+
+        pkrb5_free_ticket(context, ticket);
+    }
+}
+
 int
 KFW_AFS_klog(
     krb5_context alt_ctx,
@@ -2629,8 +2845,8 @@ KFW_AFS_klog(
     struct ktc_principal       aclient;
     char       realm_of_user[REALM_SZ]; /* Kerberos realm of user */
     char       realm_of_cell[REALM_SZ]; /* Kerberos realm of cell */
-    char       local_cell[MAXCELLCHARS+1];
-    char       Dmycell[MAXCELLCHARS+1];
+    char       local_cell[CELL_MAXNAMELEN+1];
+    char       Dmycell[CELL_MAXNAMELEN+1];
     struct ktc_token   atoken;
     struct ktc_token   btoken;
     struct afsconf_cell        ak_cellconfig; /* General information about the cell */
@@ -2647,7 +2863,7 @@ KFW_AFS_klog(
     krb5_error_code code;
     krb5_principal client_principal = NULL;
     krb5_data * k5data = NULL;
-    int i, retry = 0;
+    unsigned int i, retry = 0;
 
     CurrentState = 0;
     memset(HostName, '\0', sizeof(HostName));
@@ -2666,13 +2882,15 @@ KFW_AFS_klog(
     if (!pkrb5_init_context)
         return 0;
 
+    memset(&ak_cellconfig, 0, sizeof(ak_cellconfig));
     memset(RealmName, '\0', sizeof(RealmName));
     memset(CellName, '\0', sizeof(CellName));
     memset(ServiceName, '\0', sizeof(ServiceName));
     memset(realm_of_user, '\0', sizeof(realm_of_user));
     memset(realm_of_cell, '\0', sizeof(realm_of_cell));
     if (cell && cell[0])
-        strcpy(Dmycell, cell);
+        StringCbCopyN( Dmycell, sizeof(Dmycell),
+                       cell, sizeof(Dmycell) - 1);
     else
         memset(Dmycell, '\0', sizeof(Dmycell));
 
@@ -2697,7 +2915,7 @@ KFW_AFS_klog(
         if (code) goto skip_krb5_init;
     }
 
-    memset((char *)&increds, 0, sizeof(increds));
+    memset(&increds, 0, sizeof(increds));
 
     code = pkrb5_cc_get_principal(ctx, cc, &client_principal);
     if (code) {
@@ -2708,26 +2926,28 @@ KFW_AFS_klog(
         goto skip_krb5_init;
     }
 
-    /* look for client principals which cannot be distinguished 
-     * from Kerberos 4 multi-component principal names
-     */
-    k5data = krb5_princ_component(ctx,client_principal,0);
-    for ( i=0; i<k5data->length; i++ ) {
-        if ( k5data->data[i] == '.' )
-            break;
-    }
-    if (i != k5data->length)
-    {
-        OutputDebugString("Illegal Principal name contains dot in first component\n");
-        rc = KRB5KRB_ERR_GENERIC;
-        goto cleanup;
+    if (!KFW_accept_dotted_usernames()) {
+        /* look for client principals which cannot be distinguished 
+         * from Kerberos 4 multi-component principal names
+         */
+        k5data = krb5_princ_component(ctx,client_principal,0);
+        for ( i=0; i<k5data->length; i++ ) {
+            if ( k5data->data[i] == '.' )
+                break;
+        }
+        if (i != k5data->length)
+        {
+            OutputDebugString("Illegal Principal name contains dot in first component\n");
+            rc = KRB5KRB_ERR_GENERIC;
+            goto cleanup;
+        }
     }
 
     i = krb5_princ_realm(ctx, client_principal)->length;
     if (i > REALM_SZ-1) 
         i = REALM_SZ-1;
-    strncpy(realm_of_user,krb5_princ_realm(ctx, client_principal)->data,i);
-    realm_of_user[i] = 0;
+    StringCbCopyN( realm_of_user, sizeof(realm_of_user),
+                   krb5_princ_realm(ctx, client_principal)->data, i);
     try_krb5 = 1;
 
   skip_krb5_init:
@@ -2742,77 +2962,60 @@ KFW_AFS_klog(
     if (!try_krb5)
         goto cleanup;
 #endif
-    strcpy(realm_of_cell, afs_realm_of_cell(ctx, &ak_cellconfig));
+    StringCbCopyN( realm_of_cell, sizeof(realm_of_cell),
+                   afs_realm_of_cell(ctx, &ak_cellconfig),
+                   sizeof(realm_of_cell) - 1);
 
     if (strlen(service) == 0)
-        strcpy(ServiceName, "afs");
+        StringCbCopy( ServiceName, sizeof(ServiceName), "afs");
     else
-        strcpy(ServiceName, service);
+        StringCbCopyN( ServiceName, sizeof(ServiceName),
+                       service, sizeof(ServiceName) - 1);
 
     if (strlen(cell) == 0)
-        strcpy(CellName, local_cell);
+        StringCbCopyN( CellName, sizeof(CellName),
+                       local_cell, sizeof(CellName) - 1);
     else
-        strcpy(CellName, cell);
+        StringCbCopyN( CellName, sizeof(CellName),
+                       cell, sizeof(CellName) - 1);
 
+    /* This is for Kerberos v4 only */
     if (strlen(realm) == 0)
-        strcpy(RealmName, realm_of_cell);
+        StringCbCopyN( RealmName, sizeof(RealmName),
+                       realm_of_cell, sizeof(RealmName) - 1);
     else
-        strcpy(RealmName, realm);
+        StringCbCopyN( RealmName, sizeof(RealmName),
+                       realm, sizeof(RealmName) - 1);
 
     memset(&creds, '\0', sizeof(creds));
 
     if ( try_krb5 ) {
         int len;
+        code = KRB5KRB_ERR_GENERIC;
 
-        /* First try service/cell@REALM */
-        if (code = pkrb5_build_principal(ctx, &increds.server,
-                                          (int)strlen(RealmName),
-                                          RealmName,
-                                          ServiceName,
-                                          CellName,
-                                          0)) 
-        {
-            goto cleanup;
-        }
 
         increds.client = client_principal;
         increds.times.endtime = 0;
         /* Ask for DES since that is what V4 understands */
         increds.keyblock.enctype = ENCTYPE_DES_CBC_CRC;
 
-
-        if ( IsDebuggerPresent() ) {
-            char * cname, *sname;
-            pkrb5_unparse_name(ctx, increds.client, &cname);
-            pkrb5_unparse_name(ctx, increds.server, &sname);
-            OutputDebugString("Getting tickets for \"");
-            OutputDebugString(cname);
-            OutputDebugString("\" and service \"");
-            OutputDebugString(sname);
-            OutputDebugString("\"\n");
-            pkrb5_free_unparsed_name(ctx,cname);
-            pkrb5_free_unparsed_name(ctx,sname);
-        }
-
-        code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
-        if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
-             code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
-             code == KRB5KRB_AP_ERR_MSG_TYPE) {
-            /* Or service@REALM */
-            pkrb5_free_principal(ctx,increds.server);
+        /* If there was a specific realm we are supposed to try
+         * then use it 
+         */
+        if (strlen(realm) != 0) {
+            /* service/cell@REALM */
             increds.server = 0;
             code = pkrb5_build_principal(ctx, &increds.server,
-                                          (int)strlen(RealmName),
-                                          RealmName,
-                                          ServiceName,
-                                          0);
-
+                                         (int)strlen(realm),
+                                         realm,
+                                         ServiceName,
+                                         CellName,
+                                         0);
             if ( IsDebuggerPresent() ) {
                 char * cname, *sname;
                 pkrb5_unparse_name(ctx, increds.client, &cname);
                 pkrb5_unparse_name(ctx, increds.server, &sname);
-                OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
-                OutputDebugString("Trying again: getting tickets for \"");
+                OutputDebugString("Getting tickets for \"");
                 OutputDebugString(cname);
                 OutputDebugString("\" and service \"");
                 OutputDebugString(sname);
@@ -2823,29 +3026,60 @@ KFW_AFS_klog(
 
             if (!code)
                 code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
-        }
 
-        if ((code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
-              code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
-              code == KRB5KRB_AP_ERR_MSG_TYPE) &&
-             strcmp(RealmName, realm_of_cell)) {
-            /* Or service/cell@REALM_OF_CELL */
-            strcpy(RealmName, realm_of_cell);
-            pkrb5_free_principal(ctx,increds.server);
-            increds.server = 0;
-            code = pkrb5_build_principal(ctx, &increds.server,
-                                         (int)strlen(RealmName),
-                                         RealmName,
-                                         ServiceName,
-                                         CellName,
-                                         0);
+            if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
+                code == KRB5_ERR_HOST_REALM_UNKNOWN ||
+                code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
+                code == KRB5KRB_AP_ERR_MSG_TYPE) {
+                /* Or service@REALM */
+                pkrb5_free_principal(ctx,increds.server);
+                increds.server = 0;
+                code = pkrb5_build_principal(ctx, &increds.server,
+                                              (int)strlen(realm),
+                                              realm,
+                                              ServiceName,
+                                              0);
+
+                if ( IsDebuggerPresent() ) {
+                    char * cname, *sname;
+                    pkrb5_unparse_name(ctx, increds.client, &cname);
+                    pkrb5_unparse_name(ctx, increds.server, &sname);
+                    OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
+                    OutputDebugString("Trying again: getting tickets for \"");
+                    OutputDebugString(cname);
+                    OutputDebugString("\" and service \"");
+                    OutputDebugString(sname);
+                    OutputDebugString("\"\n");
+                    pkrb5_free_unparsed_name(ctx,cname);
+                    pkrb5_free_unparsed_name(ctx,sname);
+                }
+
+                if (!code)
+                    code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
+            }
+
+            if (code == 0) {
+                /* we have a local realm for the cell */
+                StringCbCopyN( realm_of_cell, sizeof(realm_of_cell),
+                               realm, sizeof(realm_of_cell) - 1);
+            }
+        } else {
+            /* Otherwise, first try service/cell@CLIENT_REALM */
+            if (code = pkrb5_build_principal(ctx, &increds.server,
+                                              (int)strlen(realm_of_user),
+                                              realm_of_user,
+                                              ServiceName,
+                                              CellName,
+                                              0)) 
+            {
+                goto cleanup;
+            }
 
             if ( IsDebuggerPresent() ) {
                 char * cname, *sname;
                 pkrb5_unparse_name(ctx, increds.client, &cname);
                 pkrb5_unparse_name(ctx, increds.server, &sname);
-                OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
-                OutputDebugString("Trying again: getting tickets for \"");
+                OutputDebugString("Getting tickets for \"");
                 OutputDebugString(cname);
                 OutputDebugString("\" and service \"");
                 OutputDebugString(sname);
@@ -2854,19 +3088,61 @@ KFW_AFS_klog(
                 pkrb5_free_unparsed_name(ctx,sname);
             }
 
-            if (!code)
-                code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
+            code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
+            if (code == 0) {
+                /* The client's realm is a local realm for the cell.
+                 * Save it so that later the pts registration will not
+                 * be performed.
+                 */
+                StringCbCopyN( realm_of_cell, sizeof(realm_of_cell),
+                               realm_of_user, sizeof(realm_of_cell) - 1);
+            }
 
-        
-            if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
+            if ((code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
+                 code == KRB5_ERR_HOST_REALM_UNKNOWN ||
                  code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
-                                code == KRB5KRB_AP_ERR_MSG_TYPE) {
-                /* Or service@REALM_OF_CELL */
+                 code == KRB5KRB_AP_ERR_MSG_TYPE) && 
+                 strcmp(realm_of_user, realm_of_cell)) {
+                /* Then service/cell@CELL_REALM */
                 pkrb5_free_principal(ctx,increds.server);
                 increds.server = 0;
                 code = pkrb5_build_principal(ctx, &increds.server,
-                                              (int)strlen(RealmName),
-                                              RealmName,
+                                              (int)strlen(realm_of_cell),
+                                              realm_of_cell,
+                                              ServiceName,
+                                              CellName,
+                                              0);
+                if ( IsDebuggerPresent() ) {
+                    char * cname, *sname;
+                    pkrb5_unparse_name(ctx, increds.client, &cname);
+                    pkrb5_unparse_name(ctx, increds.server, &sname);
+                    OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
+                    OutputDebugString("Trying again: getting tickets for \"");
+                    OutputDebugString(cname);
+                    OutputDebugString("\" and service \"");
+                    OutputDebugString(sname);
+                    OutputDebugString("\"\n");
+                    pkrb5_free_unparsed_name(ctx,cname);
+                    pkrb5_free_unparsed_name(ctx,sname);
+                }
+
+                if (!code)
+                    code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
+
+                if (!code && !strlen(realm_of_cell)) 
+                    copy_realm_of_ticket(ctx, realm_of_cell, sizeof(realm_of_cell), k5creds);
+            }
+
+            if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
+                code == KRB5_ERR_HOST_REALM_UNKNOWN ||
+                code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
+                code == KRB5KRB_AP_ERR_MSG_TYPE) {
+                /* Finally service@CELL_REALM */
+                pkrb5_free_principal(ctx,increds.server);
+                increds.server = 0;
+                code = pkrb5_build_principal(ctx, &increds.server,
+                                              (int)strlen(realm_of_cell),
+                                              realm_of_cell,
                                               ServiceName,
                                               0);
 
@@ -2886,13 +3162,15 @@ KFW_AFS_klog(
 
                 if (!code)
                     code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
+                if (!code && !strlen(realm_of_cell)) 
+                    copy_realm_of_ticket(ctx, realm_of_cell, sizeof(realm_of_cell), k5creds);
             }
         }
 
         if (code) {
             if ( IsDebuggerPresent() ) {
                 char message[256];
-                sprintf(message,"krb5_get_credentials returns: %d\n",code);
+                StringCbPrintf(message, sizeof(message), "krb5_get_credentials returns: %d\n", code);
                 OutputDebugString(message);
             }
             try_krb5 = 0;
@@ -2908,8 +3186,10 @@ KFW_AFS_klog(
             goto try_krb524d;
 
         memset(&aserver, '\0', sizeof(aserver));
-        strncpy(aserver.name, ServiceName, MAXKTCNAMELEN - 1);
-        strncpy(aserver.cell, CellName, MAXKTCREALMLEN - 1);
+        StringCbCopyN( aserver.name, sizeof(aserver.name),
+                       ServiceName, sizeof(aserver.name) - 1);
+        StringCbCopyN( aserver.cell, sizeof(aserver.cell),
+                       CellName, sizeof(aserver.cell) - 1);
 
         memset(&atoken, '\0', sizeof(atoken));
         atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
@@ -2927,7 +3207,7 @@ KFW_AFS_klog(
                 retry++;
                 goto retry_gettoken5;
             }
-            goto try_krb524d;
+            goto cleanup;
         }
 
         if (atoken.kvno == btoken.kvno &&
@@ -2943,31 +3223,27 @@ KFW_AFS_klog(
         // * This structure was first set by the ktc_GetToken call when
         // * we were comparing whether identical tokens already existed.
 
-        len = min(k5creds->client->data[0].length,MAXKTCNAMELEN - 1);
-        strncpy(aclient.name, k5creds->client->data[0].data, len);
-        aclient.name[len] = '\0';
+        len = min(k5creds->client->data[0].length, sizeof(aclient.name) - 1);
+        StringCbCopyN( aclient.name, sizeof(aclient.name),
+                       k5creds->client->data[0].data, len);
 
         if ( k5creds->client->length > 1 ) {
-            char * p;
-            strcat(aclient.name, ".");
-            p = aclient.name + strlen(aclient.name);
-            len = min(k5creds->client->data[1].length,MAXKTCNAMELEN - (int)strlen(aclient.name) - 1);
-            strncpy(p, k5creds->client->data[1].data, len);
-            p[len] = '\0';
+            StringCbCat( aclient.name, sizeof(aclient.name), ".");
+            len = min(k5creds->client->data[1].length, (int)(sizeof(aclient.name) - strlen(aclient.name) - 1));
+            StringCbCatN( aclient.name, sizeof(aclient.name),
+                          k5creds->client->data[1].data, len);
         }
         aclient.instance[0] = '\0';
 
-        strcpy(aclient.cell, realm_of_cell);
+        StringCbCopyN( aclient.cell, sizeof(aclient.cell),
+                       realm_of_cell, sizeof(aclient.cell) - 1);
 
         len = min(k5creds->client->realm.length,(int)strlen(realm_of_cell));
         /* For Khimaira, always append the realm name */
         if ( 1 /* strncmp(realm_of_cell, k5creds->client->realm.data, len) */ ) {
-            char * p;
-            strcat(aclient.name, "@");
-            p = aclient.name + strlen(aclient.name);
-            len = min(k5creds->client->realm.length,MAXKTCNAMELEN - (int)strlen(aclient.name) - 1);
-            strncpy(p, k5creds->client->realm.data, len);
-            p[len] = '\0';
+            StringCbCat( aclient.name, sizeof(aclient.name), "@");
+            len = min(k5creds->client->realm.length, (int)(sizeof(aclient.name) - strlen(aclient.name) - 1));
+            StringCbCatN( aclient.name, sizeof(aclient.name), k5creds->client->realm.data, len);
         }
 
        GetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL, 0);
@@ -2976,8 +3252,8 @@ KFW_AFS_klog(
                             &aclient, &aserver, &atoken);
 
         if ( smbname ) {
-            strncpy(aclient.smbname, smbname, sizeof(aclient.smbname));
-            aclient.smbname[sizeof(aclient.smbname)-1] = '\0';
+            StringCbCopyN( aclient.smbname, sizeof(aclient.smbname),
+                           smbname, sizeof(aclient.smbname) - 1);
         } else {
             aclient.smbname[0] = '\0';
         }
@@ -2987,6 +3263,9 @@ KFW_AFS_klog(
             goto cleanup;   /* We have successfully inserted the token */
 
       try_krb524d:
+#ifndef USE_KRB524
+        goto cleanup;
+#else
         /* Otherwise, the ticket could have been too large so try to
          * convert using the krb524d running with the KDC 
          */
@@ -2995,12 +3274,13 @@ KFW_AFS_klog(
         if (code) {
             if ( IsDebuggerPresent() ) {
                 char message[256];
-                sprintf(message,"krb524_convert_creds_kdc returns: %d\n",code);
+                StringCbPrintf(message, sizeof(message), "krb524_convert_creds_kdc returns: %d\n", code);
                 OutputDebugString(message);
             }
             try_krb5 = 0;
             goto use_krb4;
         }
+#endif /* USE_KRB524 */
     } else {
       use_krb4:
 #ifdef USE_KRB4
@@ -3040,8 +3320,8 @@ KFW_AFS_klog(
     }
 
     memset(&aserver, '\0', sizeof(aserver));
-    strncpy(aserver.name, ServiceName, MAXKTCNAMELEN - 1);
-    strncpy(aserver.cell, CellName, MAXKTCREALMLEN - 1);
+    StringCbCopyN( aserver.name, sizeof(aserver.name), ServiceName, sizeof(aserver.name) - 1);
+    StringCbCopyN( aserver.cell, sizeof(aserver.cell), CellName, sizeof(aserver.cell) - 1);
 
     memset(&atoken, '\0', sizeof(atoken));
     atoken.kvno = creds.kvno;
@@ -3076,19 +3356,20 @@ KFW_AFS_klog(
     // * This structure was first set by the ktc_GetToken call when
     // * we were comparing whether identical tokens already existed.
 
-    strncpy(aclient.name, creds.pname, MAXKTCNAMELEN - 1);
+    StringCbCopyN( aclient.name, sizeof(aclient.name), creds.pname, sizeof(aclient.name) - 1);
     if (creds.pinst[0])
     {
         strncat(aclient.name, ".", MAXKTCNAMELEN - 1);
         strncat(aclient.name, creds.pinst, MAXKTCNAMELEN - 1);
     }
-    strcpy(aclient.instance, "");
+    aclient.instance[0] = '\0';
 
     strncat(aclient.name, "@", MAXKTCNAMELEN - 1);
     strncat(aclient.name, creds.realm, MAXKTCREALMLEN - 1);
     aclient.name[MAXKTCREALMLEN-1] = '\0';
 
-    strcpy(aclient.cell, CellName);
+    StringCbCopyN( aclient.cell, sizeof(aclient.cell),
+                   CellName, sizeof(aclient.cell) - 1);
 
     GetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL, 0);
     if (GetLastError() == ERROR_ENVVAR_NOT_FOUND)
@@ -3096,8 +3377,8 @@ KFW_AFS_klog(
                         &aclient, &aserver, &atoken);
 
     if ( smbname ) {
-        strncpy(aclient.smbname, smbname, sizeof(aclient.smbname));
-        aclient.smbname[sizeof(aclient.smbname)-1] = '\0';
+        StringCbCopyN( aclient.smbname, sizeof(aclient.smbname),
+                       smbname, sizeof(aclient.smbname) - 1);
     } else {
         aclient.smbname[0] = '\0';
     }
@@ -3119,6 +3400,8 @@ KFW_AFS_klog(
         pkrb5_cc_close(ctx, cc);
     if (ctx && (ctx != alt_ctx))
         pkrb5_free_context(ctx);
+    if (ak_cellconfig.linkedCell)
+        free(ak_cellconfig.linkedCell);
 
     return(rc? rc : code);
 }
@@ -3138,7 +3421,8 @@ afs_realm_of_cell(krb5_context ctx, struct afsconf_cell *cellconfig)
 
     r = pkrb5_get_host_realm(ctx, cellconfig->hostName[0], &realmlist);
     if ( !r && realmlist && realmlist[0] ) {
-        strcpy(krbrlm, realmlist[0]);
+        StringCbCopyN( krbrlm, sizeof(krbrlm),
+                       realmlist[0], sizeof(krbrlm) - 1);
         pkrb5_free_host_realm(ctx, realmlist);
     }
 
@@ -3161,11 +3445,12 @@ afs_realm_of_cell(krb5_context ctx, struct afsconf_cell *cellconfig)
 /**************************************/
 /* KFW_AFS_get_cellconfig():          */
 /**************************************/
-int 
+int
 KFW_AFS_get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell)
 {
     int        rc;
-    char newcell[MAXCELLCHARS+1];
+    char newcell[CELL_MAXNAMELEN+1];
+    char linkedcell[CELL_MAXNAMELEN+1]="";
 
     local_cell[0] = (char)0;
     memset(cellconfig, 0, sizeof(*cellconfig));
@@ -3179,16 +3464,20 @@ KFW_AFS_get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_
     if (strlen(cell) == 0)
         strcpy(cell, local_cell);
 
-    /* WIN32: cm_SearchCellFile(cell, pcallback, pdata) */
-    strcpy(cellconfig->name, cell);
-
-    rc = cm_SearchCellFile(cell, newcell, get_cellconfig_callback, (void*)cellconfig);
-#ifdef AFS_AFSDB_ENV
+    rc = cm_SearchCellRegistry(1, cell, newcell, linkedcell, get_cellconfig_callback, (void*)cellconfig);
+    if (rc && rc != CM_ERROR_FORCE_DNS_LOOKUP)
+        rc = cm_SearchCellFileEx(cell, newcell, linkedcell, get_cellconfig_callback, (void*)cellconfig);
     if (rc != 0) {
         int ttl;
         rc = cm_SearchCellByDNS(cell, newcell, &ttl, get_cellconfig_callback, (void*)cellconfig);
     }
-#endif
+
+    if (rc == 0) {
+        StringCbCopyN( cellconfig->name, sizeof(cellconfig->name),
+                       newcell, sizeof(cellconfig->name) - 1);
+        if (linkedcell[0])
+            cellconfig->linkedCell = strdup(linkedcell);
+    }
     return rc;
 }
 
@@ -3196,12 +3485,13 @@ KFW_AFS_get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_
 /* get_cellconfig_callback():         */
 /**************************************/
 static long 
-get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep)
+get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep, unsigned short ipRank)
 {
     struct afsconf_cell *cc = (struct afsconf_cell *)cellconfig;
 
     cc->hostAddr[cc->numServers] = *addrp;
-    strcpy(cc->hostName[cc->numServers], namep);
+    StringCbCopyN( cc->hostName[cc->numServers], sizeof(cc->hostName[cc->numServers]),
+                   namep, sizeof(cc->hostName[cc->numServers]) - 1);
     cc->numServers++;
     return(0);
 }
@@ -3238,7 +3528,7 @@ KFW_AFS_error(LONG rc, LPCSTR FailedFunctionName)
     else
       errText = "Unknown error!";
 
-    sprintf(message, "%s (0x%x)\n(%s failed)", errText, rc, FailedFunctionName);
+    StringCbPrintf(message, sizeof(message), "%s (0x%x)\n(%s failed)", errText, rc, FailedFunctionName);
 
     if ( IsDebuggerPresent() ) {
         OutputDebugString(message);
@@ -3475,8 +3765,7 @@ KFW_AFS_get_lsa_principal(char * szUser, DWORD *dwSize)
         goto cleanup;
 
     if ( strlen(pname) < *dwSize ) {
-        strncpy(szUser, pname, *dwSize);
-        szUser[*dwSize-1] = '\0';
+        StringCbCopyN(szUser, *dwSize, pname, (*dwSize) - 1);
         success = 1;
     }
     *dwSize = (DWORD)strlen(pname);
@@ -3606,7 +3895,7 @@ KFW_AFS_obtain_user_temp_directory(HANDLE hUserToken, char *newfilename, int siz
     DWORD dwLen  = 0;
  
     if (!hUserToken || !newfilename || size <= 0)
-       return;
+       return 1;
  
      *newfilename = '\0';
  
@@ -3643,10 +3932,10 @@ KFW_AFS_copy_cache_to_system_file(char * user, char * szLogonId)
     if ( strlen(filename) + strlen(szLogonId) + 2 > sizeof(filename) )
         return;
 
-    strcat(filename, "\\");
-    strcat(filename, szLogonId);    
+    StringCbCat( filename, sizeof(filename), "\\");
+    StringCbCat( filename, sizeof(filename), szLogonId);
 
-    strcat(cachename, filename);
+    StringCbCat( cachename, sizeof(cachename), filename);
 
     DeleteFile(filename);
 
@@ -3708,7 +3997,7 @@ KFW_AFS_copy_file_cache_to_default_cache(char * filename)
     code = pkrb5_init_context(&ctx);
     if (code) return 1;
 
-    strcat(cachename, filename);
+    StringCbCat( cachename, sizeof(cachename), filename);
 
     code = pkrb5_cc_resolve(ctx, cachename, &cc);
     if (code) goto cleanup;