s3:utils: let smbstatus report anonymous signing/encryption explicitly
[samba.git] / source4 / auth / kerberos / kerberos_util.c
index 631cc2d11ff9420b6ac9d1281e7d5ced00546691..cc1bfc7ca16dfce7e9d12108f27b5d5879d34a35 100644 (file)
@@ -1,24 +1,23 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
 
    Kerberos utility functions for GENSEC
-   
+
    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
-   
+
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
 #include "auth/kerberos/kerberos.h"
 #include "auth/credentials/credentials.h"
 #include "auth/credentials/credentials_krb5.h"
+#include "auth/kerberos/kerberos_credentials.h"
+#include "auth/kerberos/kerberos_util.h"
 
 struct principal_container {
        struct smb_krb5_context *smb_krb5_context;
        krb5_principal principal;
+       const char *string_form; /* Optional */
 };
 
-static int free_principal(struct principal_container *pc)
+static krb5_error_code free_principal(struct principal_container *pc)
 {
        /* current heimdal - 0.6.3, which we need anyway, fixes segfaults here */
        krb5_free_principal(pc->smb_krb5_context->krb5_context, pc->principal);
@@ -40,61 +42,54 @@ static int free_principal(struct principal_container *pc)
        return 0;
 }
 
-static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx, 
-                                                      struct cli_credentials *machine_account, 
-                                                      struct smb_krb5_context *smb_krb5_context,
-                                                      krb5_principal *salt_princ)
+
+static krb5_error_code parse_principal(TALLOC_CTX *parent_ctx,
+                                      const char *princ_string,
+                                      struct smb_krb5_context *smb_krb5_context,
+                                      krb5_principal *princ,
+                                      const char **error_string)
 {
-       krb5_error_code ret;
-       char *machine_username;
-       char *salt_body;
-       char *lower_realm;
-       const char *salt_principal;
-       struct principal_container *mem_ctx = talloc(parent_ctx, struct principal_container);
+       int ret;
+       struct principal_container *mem_ctx;
+       if (princ_string == NULL) {
+                *princ = NULL;
+                return 0;
+       }
+
+       /*
+        * Start with talloc(), talloc_reference() and only then call
+        * krb5_parse_name(). If any of them fails, the cleanup code is simpler.
+        */
+       mem_ctx = talloc(parent_ctx, struct principal_container);
        if (!mem_ctx) {
+               (*error_string) = error_message(ENOMEM);
                return ENOMEM;
        }
 
-       salt_principal = cli_credentials_get_salt_principal(machine_account);
-       if (salt_principal) {
-               ret = krb5_parse_name(smb_krb5_context->krb5_context, salt_principal, salt_princ); 
-       } else {
-               machine_username = talloc_strdup(mem_ctx, cli_credentials_get_username(machine_account));
-               
-               if (!machine_username) {
-                       talloc_free(mem_ctx);
-                       return ENOMEM;
-               }
-               
-               if (machine_username[strlen(machine_username)-1] == '$') {
-                       machine_username[strlen(machine_username)-1] = '\0';
-               }
-               lower_realm = strlower_talloc(mem_ctx, cli_credentials_get_realm(machine_account));
-               if (!lower_realm) {
-                       talloc_free(mem_ctx);
-                       return ENOMEM;
-               }
-               
-               salt_body = talloc_asprintf(mem_ctx, "%s.%s", machine_username, 
-                                           lower_realm);
-               if (!salt_body) {
-                       talloc_free(mem_ctx);
+       mem_ctx->smb_krb5_context = talloc_reference(mem_ctx,
+                                                    smb_krb5_context);
+       if (mem_ctx->smb_krb5_context == NULL) {
+               (*error_string) = error_message(ENOMEM);
+               talloc_free(mem_ctx);
                return ENOMEM;
-               }
-               
-               ret = krb5_make_principal(smb_krb5_context->krb5_context, salt_princ, 
-                                         cli_credentials_get_realm(machine_account), 
-                                         "host", salt_body, NULL);
-       } 
-
-       if (ret == 0) {
-               /* This song-and-dance effectivly puts the principal
-                * into talloc, so we can't loose it. */
-               mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context);
-               mem_ctx->principal = *salt_princ;
-               talloc_set_destructor(mem_ctx, free_principal);
        }
-       return ret;
+
+       ret = krb5_parse_name(smb_krb5_context->krb5_context,
+                             princ_string, princ);
+
+       if (ret) {
+               (*error_string) = smb_get_krb5_error_message(
+                                               smb_krb5_context->krb5_context,
+                                               ret, parent_ctx);
+               talloc_free(mem_ctx);
+               return ret;
+       }
+
+       /* This song-and-dance effectively puts the principal
+        * into talloc, so we can't lose it. */
+       mem_ctx->principal = *princ;
+       talloc_set_destructor(mem_ctx, free_principal);
+       return 0;
 }
 
 /* Obtain the principal set on this context.  Requires a
@@ -102,100 +97,359 @@ static krb5_error_code salt_principal_from_credentials(TALLOC_CTX *parent_ctx,
  * the library routines.  The returned princ is placed in the talloc
  * system by means of a destructor (do *not* free). */
 
-krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx, 
-                                          struct cli_credentials *credentials, 
-                                          struct smb_krb5_context *smb_krb5_context,
-                                          krb5_principal *princ)
+krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx,
+                               struct cli_credentials *credentials,
+                               struct smb_krb5_context *smb_krb5_context,
+                               krb5_principal *princ,
+                               enum credentials_obtained *obtained,
+                               const char **error_string)
 {
        krb5_error_code ret;
        const char *princ_string;
-       struct principal_container *mem_ctx = talloc(parent_ctx, struct principal_container);
+       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
+       *obtained = CRED_UNINITIALISED;
+
        if (!mem_ctx) {
+               (*error_string) = error_message(ENOMEM);
                return ENOMEM;
        }
-       
-       princ_string = cli_credentials_get_principal(credentials, mem_ctx);
-
-       /* A NULL here has meaning, as the gssapi server case will
-        * then use the principal from the client */
+       princ_string = cli_credentials_get_principal_and_obtained(credentials,
+                                                                 mem_ctx,
+                                                                 obtained);
        if (!princ_string) {
-               talloc_free(mem_ctx);
-               princ = NULL;
+               *princ = NULL;
                return 0;
        }
 
-       ret = krb5_parse_name(smb_krb5_context->krb5_context,
-                             princ_string, princ);
+       ret = parse_principal(parent_ctx, princ_string,
+                             smb_krb5_context, princ, error_string);
+       talloc_free(mem_ctx);
+       return ret;
+}
+
+/* Obtain the principal set on this context.  Requires a
+ * smb_krb5_context because we are doing krb5 principal parsing with
+ * the library routines.  The returned princ is placed in the talloc
+ * system by means of a destructor (do *not* free). */
 
-       if (ret == 0) {
-               /* This song-and-dance effectivly puts the principal
-                * into talloc, so we can't loose it. */
-               mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context);
-               mem_ctx->principal = *princ;
-               talloc_set_destructor(mem_ctx, free_principal);
+static krb5_error_code impersonate_principal_from_credentials(
+                               TALLOC_CTX *parent_ctx,
+                               struct cli_credentials *credentials,
+                               struct smb_krb5_context *smb_krb5_context,
+                               krb5_principal *princ,
+                               const char **error_string)
+{
+       return parse_principal(parent_ctx,
+                       cli_credentials_get_impersonate_principal(credentials),
+                       smb_krb5_context, princ, error_string);
+}
+
+krb5_error_code smb_krb5_create_principals_array(TALLOC_CTX *mem_ctx,
+                                                krb5_context context,
+                                                const char *account_name,
+                                                const char *realm,
+                                                uint32_t num_spns,
+                                                const char *spns[],
+                                                uint32_t *pnum_principals,
+                                                krb5_principal **pprincipals,
+                                                const char **error_string)
+{
+       krb5_error_code code;
+       TALLOC_CTX *tmp_ctx;
+       uint32_t num_principals = 0;
+       krb5_principal *principals;
+       uint32_t i;
+
+       tmp_ctx = talloc_new(mem_ctx);
+       if (tmp_ctx == NULL) {
+               *error_string = "Cannot allocate tmp_ctx";
+               return ENOMEM;
        }
-       return ret;
+
+       if (realm == NULL) {
+               *error_string = "Cannot create principal without a realm";
+               code = EINVAL;
+               goto done;
+       }
+
+       if (account_name == NULL && (num_spns == 0 || spns == NULL)) {
+               *error_string = "Cannot create principal without an account or SPN";
+               code = EINVAL;
+               goto done;
+       }
+
+       if (account_name != NULL && account_name[0] != '\0') {
+               num_principals++;
+       }
+       num_principals += num_spns;
+
+       principals = talloc_zero_array(tmp_ctx,
+                                      krb5_principal,
+                                      num_principals);
+       if (principals == NULL) {
+               *error_string = "Cannot allocate principals";
+               code = ENOMEM;
+               goto done;
+       }
+
+       for (i = 0; i < num_spns; i++) {
+               code = krb5_parse_name(context, spns[i], &(principals[i]));
+               if (code != 0) {
+                       *error_string = smb_get_krb5_error_message(context,
+                                                                  code,
+                                                                  mem_ctx);
+                       goto done;
+               }
+       }
+
+       if (account_name != NULL && account_name[0] != '\0') {
+               code = smb_krb5_make_principal(context,
+                                              &(principals[i]),
+                                              realm,
+                                              account_name,
+                                              NULL);
+               if (code != 0) {
+                       *error_string = smb_get_krb5_error_message(context,
+                                                                  code,
+                                                                  mem_ctx);
+                       goto done;
+               }
+       }
+
+       if (pnum_principals != NULL) {
+               *pnum_principals = num_principals;
+
+               if (pprincipals != NULL) {
+                       *pprincipals = talloc_steal(mem_ctx, principals);
+               }
+       }
+
+       code = 0;
+done:
+       talloc_free(tmp_ctx);
+       return code;
 }
 
 /**
  * Return a freshly allocated ccache (destroyed by destructor on child
- * of parent_ctx), for a given set of client credentials 
+ * of parent_ctx), for a given set of client credentials
  */
 
  krb5_error_code kinit_to_ccache(TALLOC_CTX *parent_ctx,
                                 struct cli_credentials *credentials,
                                 struct smb_krb5_context *smb_krb5_context,
-                                krb5_ccache ccache) 
+                                struct loadparm_context *lp_ctx,
+                                struct tevent_context *event_ctx,
+                                krb5_ccache ccache,
+                                enum credentials_obtained *obtained,
+                                const char **error_string)
 {
        krb5_error_code ret;
        const char *password;
+       const char *self_service;
+       const char *target_service;
        time_t kdc_time = 0;
        krb5_principal princ;
+       krb5_principal impersonate_principal;
        int tries;
        TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
+       krb5_get_init_creds_opt *krb_options;
+       struct cli_credentials *fast_creds;
 
        if (!mem_ctx) {
+               (*error_string) = strerror(ENOMEM);
                return ENOMEM;
        }
 
-       ret = principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &princ);
+       ret = principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &princ, obtained, error_string);
        if (ret) {
                talloc_free(mem_ctx);
                return ret;
        }
 
+       if (princ == NULL) {
+               (*error_string) = talloc_asprintf(credentials, "principal, username or realm was not specified in the credentials");
+               talloc_free(mem_ctx);
+               return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
+       }
+
+       ret = impersonate_principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &impersonate_principal, error_string);
+       if (ret) {
+               talloc_free(mem_ctx);
+               return ret;
+       }
+
+       self_service = cli_credentials_get_self_service(credentials);
+       target_service = cli_credentials_get_target_service(credentials);
+
        password = cli_credentials_get_password(credentials);
 
+       /* setup the krb5 options we want */
+       if ((ret = krb5_get_init_creds_opt_alloc(smb_krb5_context->krb5_context, &krb_options))) {
+               (*error_string) = talloc_asprintf(credentials, "krb5_get_init_creds_opt_alloc failed (%s)\n",
+                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
+                                                                            ret, mem_ctx));
+               talloc_free(mem_ctx);
+               return ret;
+       }
+
+#ifdef SAMBA4_USES_HEIMDAL /* Disable for now MIT reads defaults when needed */
+       /* get the defaults */
+       krb5_get_init_creds_opt_set_default_flags(smb_krb5_context->krb5_context, NULL, NULL, krb_options);
+#endif
+       /* set if we want a forwardable ticket */
+       switch (cli_credentials_get_krb_forwardable(credentials)) {
+       case CRED_AUTO_KRB_FORWARDABLE:
+               break;
+       case CRED_NO_KRB_FORWARDABLE:
+               krb5_get_init_creds_opt_set_forwardable(krb_options, FALSE);
+               break;
+       case CRED_FORCE_KRB_FORWARDABLE:
+               krb5_get_init_creds_opt_set_forwardable(krb_options, TRUE);
+               break;
+       }
+
+#ifdef SAMBA4_USES_HEIMDAL /* FIXME: MIT does not have this yet */
+       /*
+        * In order to work against windows KDCs even if we use
+        * the netbios domain name as realm, we need to add the following
+        * flags:
+        * KRB5_INIT_CREDS_NO_C_CANON_CHECK;
+        * KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK;
+        *
+        * On MIT: Set pkinit_eku_checking to none
+        */
+       krb5_get_init_creds_opt_set_win2k(smb_krb5_context->krb5_context,
+                                         krb_options, true);
+       krb5_get_init_creds_opt_set_canonicalize(smb_krb5_context->krb5_context,
+                                                krb_options, true);
+#else /* MIT */
+       krb5_get_init_creds_opt_set_canonicalize(krb_options, true);
+#endif
+
+       fast_creds = cli_credentials_get_krb5_fast_armor_credentials(credentials);
+
+       if (fast_creds != NULL) {
+#ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_SET_FAST_CCACHE
+               struct ccache_container *fast_ccc = NULL;
+               const char *fast_error_string = NULL;
+               ret = cli_credentials_get_ccache(fast_creds, event_ctx, lp_ctx, &fast_ccc, &fast_error_string);
+               if (ret != 0) {
+                       (*error_string) = talloc_asprintf(credentials,
+                                                         "Obtaining the Kerberos FAST armor credentials failed: %s\n",
+                                                         fast_error_string);
+                       return ret;
+               }
+               krb5_get_init_creds_opt_set_fast_ccache(smb_krb5_context->krb5_context,
+                                                       krb_options,
+                                                       fast_ccc->ccache);
+#else
+               *error_string = talloc_strdup(credentials,
+                                             "Using Kerberos FAST "
+                                             "armor credentials not possible "
+                                             "with this Kerberos library.  "
+                                             "Modern MIT or Samba's embedded "
+                                             "Heimdal required");
+               return EINVAL;
+#endif
+       }
+
+#ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_SET_FAST_FLAGS
+       {
+               bool require_fast;
+               /*
+                * This ensures that if FAST was required, but no armor
+                * credentials cache was specified, we proceed with (eg)
+                * anonymous PKINIT
+                */
+               require_fast = cli_credentials_get_krb5_require_fast_armor(credentials);
+               if (require_fast) {
+                       krb5_get_init_creds_opt_set_fast_flags(smb_krb5_context->krb5_context,
+                                                              krb_options,
+                                                              KRB5_FAST_REQUIRED);
+               }
+       }
+#endif
+
        tries = 2;
        while (tries--) {
+#ifdef SAMBA4_USES_HEIMDAL
+               struct tevent_context *previous_ev;
+               /* Do this every time, in case we have weird recursive issues here */
+               ret = smb_krb5_context_set_event_ctx(smb_krb5_context, event_ctx, &previous_ev);
+               if (ret) {
+                       talloc_free(mem_ctx);
+                       krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
+                       return ret;
+               }
+#endif
                if (password) {
-                       ret = kerberos_kinit_password_cc(smb_krb5_context->krb5_context, ccache, 
-                                                        princ, 
-                                                        password, NULL, &kdc_time);
+                       if (impersonate_principal) {
+                               ret = smb_krb5_kinit_s4u2_ccache(smb_krb5_context->krb5_context,
+                                                                ccache,
+                                                                princ,
+                                                                password,
+                                                                impersonate_principal,
+                                                                self_service,
+                                                                target_service,
+                                                                krb_options,
+                                                                NULL,
+                                                                &kdc_time);
+                       } else {
+                               ret = smb_krb5_kinit_password_ccache(smb_krb5_context->krb5_context,
+                                                                    ccache,
+                                                                    princ,
+                                                                    password,
+                                                                    target_service,
+                                                                    krb_options,
+                                                                    NULL,
+                                                                    &kdc_time);
+                       }
+               } else if (impersonate_principal) {
+                       talloc_free(mem_ctx);
+                       (*error_string) = "INTERNAL error: Cannot impersonate principal with just a keyblock.  A password must be specified in the credentials";
+                       krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
+#ifdef SAMBA4_USES_HEIMDAL
+                       smb_krb5_context_remove_event_ctx(smb_krb5_context, previous_ev, event_ctx);
+#endif
+                       return EINVAL;
                } else {
                        /* No password available, try to use a keyblock instead */
-                       
+
                        krb5_keyblock keyblock;
                        const struct samr_Password *mach_pwd;
                        mach_pwd = cli_credentials_get_nt_hash(credentials, mem_ctx);
                        if (!mach_pwd) {
                                talloc_free(mem_ctx);
-                               DEBUG(1, ("kinit_to_ccache: No password available for kinit\n"));
+                               (*error_string) = "kinit_to_ccache: No password available for kinit\n";
+                               krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
+#ifdef SAMBA4_USES_HEIMDAL
+                               smb_krb5_context_remove_event_ctx(smb_krb5_context, previous_ev, event_ctx);
+#endif
                                return EINVAL;
                        }
-                       ret = krb5_keyblock_init(smb_krb5_context->krb5_context,
-                                                ETYPE_ARCFOUR_HMAC_MD5,
-                                                mach_pwd->hash, sizeof(mach_pwd->hash), 
+                       ret = smb_krb5_keyblock_init_contents(smb_krb5_context->krb5_context,
+                                                ENCTYPE_ARCFOUR_HMAC,
+                                                mach_pwd->hash, sizeof(mach_pwd->hash),
                                                 &keyblock);
-                       
+
                        if (ret == 0) {
-                               ret = kerberos_kinit_keyblock_cc(smb_krb5_context->krb5_context, ccache, 
-                                                                princ,
-                                                                &keyblock, NULL, &kdc_time);
+                               ret = smb_krb5_kinit_keyblock_ccache(smb_krb5_context->krb5_context,
+                                                                    ccache,
+                                                                    princ,
+                                                                    &keyblock,
+                                                                    target_service,
+                                                                    krb_options,
+                                                                    NULL,
+                                                                    &kdc_time);
                                krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &keyblock);
                        }
                }
 
+#ifdef SAMBA4_USES_HEIMDAL
+               smb_krb5_context_remove_event_ctx(smb_krb5_context, previous_ev, event_ctx);
+#endif
+
                if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) {
                        /* Perhaps we have been given an invalid skew, so try again without it */
                        time_t t = time(NULL);
@@ -206,11 +460,13 @@ krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx,
                }
        }
 
+       krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
+
        if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) {
-               DEBUG(1,("kinit for %s failed (%s)\n", 
-                        cli_credentials_get_principal(credentials, mem_ctx), 
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
+               (*error_string) = talloc_asprintf(credentials, "kinit for %s failed (%s)\n",
+                                                 cli_credentials_get_principal(credentials, mem_ctx),
+                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
+                                                                            ret, mem_ctx));
                talloc_free(mem_ctx);
                return ret;
        }
@@ -222,459 +478,348 @@ krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx,
                DEBUG(4,("Advancing clock by %d seconds to cope with clock skew\n", time_offset));
                krb5_set_real_time(smb_krb5_context->krb5_context, t + time_offset + 1, 0);
        }
-       
+
        if (ret == KRB5KDC_ERR_PREAUTH_FAILED && cli_credentials_wrong_password(credentials)) {
                ret = kinit_to_ccache(parent_ctx,
                                      credentials,
                                      smb_krb5_context,
-                                     ccache); 
+                                     lp_ctx,
+                                     event_ctx,
+                                     ccache, obtained,
+                                     error_string);
        }
-       if (ret) {
-               DEBUG(1,("kinit for %s failed (%s)\n", 
-                        cli_credentials_get_principal(credentials, mem_ctx), 
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-               talloc_free(mem_ctx);
-               return ret;
-       } 
-       return 0;
-}
-
-static int free_keytab(struct keytab_container *ktc)
-{
-       krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab);
 
-       return 0;
-}
-
-int smb_krb5_open_keytab(TALLOC_CTX *mem_ctx,
-                        struct smb_krb5_context *smb_krb5_context, 
-                        const char *keytab_name, struct keytab_container **ktc) 
-{
-       krb5_keytab keytab;
-       int ret;
-       ret = krb5_kt_resolve(smb_krb5_context->krb5_context, keytab_name, &keytab);
        if (ret) {
-               DEBUG(1,("failed to open krb5 keytab: %s\n", 
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
+               (*error_string) = talloc_asprintf(credentials, "kinit for %s failed (%s)\n",
+                                                 cli_credentials_get_principal(credentials, mem_ctx),
+                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
+                                                                            ret, mem_ctx));
+               talloc_free(mem_ctx);
                return ret;
        }
 
-       *ktc = talloc(mem_ctx, struct keytab_container);
-       if (!*ktc) {
-               return ENOMEM;
-       }
+       DEBUG(10,("kinit for %s succeeded\n",
+               cli_credentials_get_principal(credentials, mem_ctx)));
 
-       (*ktc)->smb_krb5_context = talloc_reference(*ktc, smb_krb5_context);
-       (*ktc)->keytab = keytab;
-       talloc_set_destructor(*ktc, free_keytab);
 
+       talloc_free(mem_ctx);
        return 0;
 }
 
-static krb5_error_code keytab_add_keys(TALLOC_CTX *parent_ctx,
-                                      const char *princ_string,
-                                      krb5_principal princ,
-                                      krb5_principal salt_princ,
-                                      int kvno,
-                                      const char *password_s,
-                                      struct smb_krb5_context *smb_krb5_context,
-                                      const char **enctype_strings,
-                                      krb5_keytab keytab)
+static krb5_error_code free_keytab_container(struct keytab_container *ktc)
 {
-       int i;
-       krb5_error_code ret;
-       krb5_data password;
-       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
-       if (!mem_ctx) {
-               return ENOMEM;
-       }
-
-       password.data = discard_const_p(char *, password_s);
-       password.length = strlen(password_s);
-
-       for (i=0; enctype_strings[i]; i++) {
-               krb5_keytab_entry entry;
-               krb5_enctype enctype;
-               ret = krb5_string_to_enctype(smb_krb5_context->krb5_context, enctype_strings[i], &enctype);
-               if (ret != 0) {
-                       DEBUG(1, ("Failed to interpret %s as a krb5 encryption type: %s\n",                               
-                                 enctype_strings[i],
-                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                            ret, mem_ctx)));
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
-               ret = create_kerberos_key_from_string(smb_krb5_context->krb5_context, 
-                                                     salt_princ, &password, &entry.keyblock, enctype);
-               if (ret != 0) {
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
-
-                entry.principal = princ;
-                entry.vno       = kvno;
-               ret = krb5_kt_add_entry(smb_krb5_context->krb5_context, keytab, &entry);
-               if (ret != 0) {
-                       DEBUG(1, ("Failed to add %s entry for %s(kvno %d) to keytab: %s\n",
-                                 enctype_strings[i],
-                                 princ_string,
-                                 kvno,
-                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                            ret, mem_ctx)));
-                       talloc_free(mem_ctx);
-                       krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
-                       return ret;
-               }
-
-               DEBUG(5, ("Added %s(kvno %d) to keytab (%s)\n", 
-                         princ_string, kvno,
-                         enctype_strings[i]));
-               
-               krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
-       }
-       talloc_free(mem_ctx);
-       return 0;
+       return krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab);
 }
 
-static int create_keytab(TALLOC_CTX *parent_ctx,
-                        struct cli_credentials *machine_account,
-                        struct smb_krb5_context *smb_krb5_context,
-                        const char **enctype_strings,
-                        krb5_keytab keytab,
-                        BOOL add_old) 
+krb5_error_code smb_krb5_get_keytab_container(TALLOC_CTX *mem_ctx,
+                               struct smb_krb5_context *smb_krb5_context,
+                               krb5_keytab opt_keytab,
+                               const char *keytab_name,
+                               struct keytab_container **ktc)
 {
+       krb5_keytab keytab;
        krb5_error_code ret;
-       const char *password_s;
-       const char *old_secret;
-       int kvno;
-       krb5_principal salt_princ;
-       krb5_principal princ;
-       const char *princ_string;
 
-       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
-       if (!mem_ctx) {
+       /*
+        * Start with talloc(), talloc_reference() and only then call
+        * krb5_kt_resolve(). If any of them fails, the cleanup code is simpler.
+        */
+       *ktc = talloc(mem_ctx, struct keytab_container);
+       if (!*ktc) {
                return ENOMEM;
        }
 
-       princ_string = cli_credentials_get_principal(machine_account, mem_ctx);
-       /* Get the principal we will store the new keytab entries under */
-       ret = principal_from_credentials(mem_ctx, machine_account, smb_krb5_context, &princ);
-       if (ret) {
-               DEBUG(1,("create_keytab: makeing krb5 principal failed (%s)\n",
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-               talloc_free(mem_ctx);
-               return ret;
-       }
-
-       /* The salt used to generate these entries may be different however, fetch that */
-       ret = salt_principal_from_credentials(mem_ctx, machine_account, 
-                                             smb_krb5_context, 
-                                             &salt_princ);
-       if (ret) {
-               DEBUG(1,("create_keytab: makeing salt principal failed (%s)\n",
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-               talloc_free(mem_ctx);
-               return ret;
+       (*ktc)->smb_krb5_context = talloc_reference(*ktc, smb_krb5_context);
+       if ((*ktc)->smb_krb5_context == NULL) {
+               TALLOC_FREE(*ktc);
+               return ENOMEM;
        }
 
-       /* Finally, do the dance to get the password to put in the entry */
-       password_s = cli_credentials_get_password(machine_account);
-       if (!password_s) {
-               krb5_keytab_entry entry;
-               const struct samr_Password *mach_pwd;
-
-               if (!str_list_check(enctype_strings, "arcfour-hmac-md5")) {
-                       DEBUG(1, ("Asked to create keytab, but with only an NT hash supplied, "
-                                 "but not listing arcfour-hmac-md5 as an enc type to include in the keytab!\n"));
-                       talloc_free(mem_ctx);
-                       return EINVAL;
-               }
-
-               /* If we don't have the plaintext password, try for
-                * the MD4 password hash */
-               mach_pwd = cli_credentials_get_nt_hash(machine_account, mem_ctx);
-               if (!mach_pwd) {
-                       /* OK, nothing to do here */
-                       talloc_free(mem_ctx);
-                       return 0;
-               }
-               ret = krb5_keyblock_init(smb_krb5_context->krb5_context,
-                                        ETYPE_ARCFOUR_HMAC_MD5,
-                                        mach_pwd->hash, sizeof(mach_pwd->hash), 
-                                        &entry.keyblock);
-               if (ret) {
-                       DEBUG(1, ("create_keytab: krb5_keyblock_init failed: %s\n",
-                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                            ret, mem_ctx)));
-                       talloc_free(mem_ctx);
-                       return ret;
-               }
-
-               entry.principal = princ;
-               entry.vno       = cli_credentials_get_kvno(machine_account);
-               ret = krb5_kt_add_entry(smb_krb5_context->krb5_context, keytab, &entry);
+       if (opt_keytab) {
+               keytab = opt_keytab;
+       } else {
+               ret = krb5_kt_resolve(smb_krb5_context->krb5_context,
+                                               keytab_name, &keytab);
                if (ret) {
-                       DEBUG(1, ("Failed to add ARCFOUR_HMAC (only) entry for %s to keytab: %s",
-                                 cli_credentials_get_principal(machine_account, mem_ctx), 
-                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                            ret, mem_ctx)));
-                       talloc_free(mem_ctx);
-                       krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
+                       DEBUG(1,("failed to open krb5 keytab: %s\n",
+                                smb_get_krb5_error_message(
+                                       smb_krb5_context->krb5_context,
+                                       ret, mem_ctx)));
+                       TALLOC_FREE(*ktc);
                        return ret;
                }
-               
-               DEBUG(5, ("Added %s(kvno %d) to keytab (arcfour-hmac-md5)\n", 
-                         cli_credentials_get_principal(machine_account, mem_ctx),
-                         cli_credentials_get_kvno(machine_account)));
-
-               krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
-
-               /* Can't go any further, we only have this one key */
-               talloc_free(mem_ctx);
-               return 0;
-       }
-       
-       kvno = cli_credentials_get_kvno(machine_account);
-       /* good, we actually have the real plaintext */
-       ret = keytab_add_keys(mem_ctx, princ_string, princ, salt_princ, 
-                             kvno, password_s, smb_krb5_context, 
-                             enctype_strings, keytab);
-       if (!ret) {
-               talloc_free(mem_ctx);
-               return ret;
-       }
-
-       if (!add_old || kvno == 0) {
-               talloc_free(mem_ctx);
-               return 0;
        }
 
-       old_secret = cli_credentials_get_old_password(machine_account);
-       if (!old_secret) {
-               talloc_free(mem_ctx);
-               return 0;
-       }
-       
-       ret = keytab_add_keys(mem_ctx, princ_string, princ, salt_princ, 
-                             kvno - 1, old_secret, smb_krb5_context, 
-                             enctype_strings, keytab);
-       if (!ret) {
-               talloc_free(mem_ctx);
-               return ret;
-       }
+       (*ktc)->keytab = keytab;
+       (*ktc)->password_based = false;
+       talloc_set_destructor(*ktc, free_keytab_container);
 
-       talloc_free(mem_ctx);
        return 0;
 }
 
-
 /*
- * Walk the keytab, looking for entries of this principal name, with KVNO other than current kvno -1.
+ * Walk the keytab, looking for entries of this principal name,
+ * with KVNO other than current kvno -1.
  *
- * These entries are now stale, we only keep the current, and previous entries around.
+ * These entries are now stale,
+ * we only keep the current and previous entries around.
  *
  * Inspired by the code in Samba3 for 'use kerberos keytab'.
- *
  */
-
-static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
-                                         struct cli_credentials *machine_account,
-                                         struct smb_krb5_context *smb_krb5_context,
-                                         krb5_keytab keytab, BOOL *found_previous)
+krb5_error_code smb_krb5_remove_obsolete_keytab_entries(TALLOC_CTX *mem_ctx,
+                                                       krb5_context context,
+                                                       krb5_keytab keytab,
+                                                       uint32_t num_principals,
+                                                       krb5_principal *principals,
+                                                       krb5_kvno kvno,
+                                                       bool *found_previous,
+                                                       const char **error_string)
 {
-       krb5_error_code ret, ret2;
+       TALLOC_CTX *tmp_ctx;
+       krb5_error_code code;
        krb5_kt_cursor cursor;
-       krb5_principal princ;
-       int kvno;
-       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
-       const char *princ_string;
-       if (!mem_ctx) {
-               return ENOMEM;
-       }
-
-       *found_previous = False;
-       princ_string = cli_credentials_get_principal(machine_account, mem_ctx);
 
-       /* Get the principal we will store the new keytab entries under */
-       ret = principal_from_credentials(mem_ctx, machine_account, smb_krb5_context, &princ);
-       if (ret) {
-               DEBUG(1,("update_keytab: makeing krb5 principal failed (%s)\n",
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-               talloc_free(mem_ctx);
-               return ret;
+       tmp_ctx = talloc_new(mem_ctx);
+       if (tmp_ctx == NULL) {
+               *error_string = "Cannot allocate tmp_ctx";
+               return ENOMEM;
        }
 
-       kvno = cli_credentials_get_kvno(machine_account);
+       *found_previous = true;
 
-       /* for each entry in the keytab */
-       ret = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
-       switch (ret) {
+       code = krb5_kt_start_seq_get(context, keytab, &cursor);
+       switch (code) {
        case 0:
                break;
+#ifdef HEIM_ERR_OPNOTSUPP
        case HEIM_ERR_OPNOTSUPP:
+#endif
        case ENOENT:
        case KRB5_KT_END:
                /* no point enumerating if there isn't anything here */
-               talloc_free(mem_ctx);
-               return 0;
+               code = 0;
+               goto done;
        default:
-               DEBUG(1,("failed to open keytab for read of old entries: %s\n",
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-               talloc_free(mem_ctx);
-               return ret;
+               *error_string = talloc_asprintf(mem_ctx,
+                                               "failed to open keytab for read of old entries: %s\n",
+                                               smb_get_krb5_error_message(context, code, tmp_ctx));
+               goto done;
        }
 
-       while (!ret) {
+       do {
+               krb5_kvno old_kvno = kvno - 1;
                krb5_keytab_entry entry;
-               ret = krb5_kt_next_entry(smb_krb5_context->krb5_context, keytab, &entry, &cursor);
-               if (ret) {
+               bool matched = false;
+               uint32_t i;
+
+               code = krb5_kt_next_entry(context, keytab, &entry, &cursor);
+               if (code) {
                        break;
                }
-               /* if it matches our principal */
-               if (!krb5_kt_compare(smb_krb5_context->krb5_context, &entry, princ, 0, 0)) {
-                       /* Free the entry, it wasn't the one we were looking for anyway */
-                       krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
+
+               for (i = 0; i < num_principals; i++) {
+                       krb5_boolean ok;
+
+                       ok = smb_krb5_kt_compare(context,
+                                               &entry,
+                                               principals[i],
+                                               0,
+                                               0);
+                       if (ok) {
+                               matched = true;
+                               break;
+                       }
+               }
+
+               if (!matched) {
+                       /*
+                        * Free the entry, it wasn't the one we were looking
+                        * for anyway
+                        */
+                       krb5_kt_free_entry(context, &entry);
+                       /* Make sure we do not double free */
+                       ZERO_STRUCT(entry);
                        continue;
                }
 
-               /* delete it, if it is not kvno -1 */
-               if (entry.vno != (kvno - 1 )) {
+               /*
+                * Delete it, if it is not kvno - 1.
+                *
+                * Some keytab files store the kvno only in 8bits. Limit the
+                * compare to 8bits, so that we don't miss old keys and delete
+                * them.
+                */
+               if ((entry.vno & 0xff) != (old_kvno & 0xff)) {
+                       krb5_error_code rc;
+
                        /* Release the enumeration.  We are going to
                         * have to start this from the top again,
                         * because deletes during enumeration may not
-                        * always be consistant.
+                        * always be consistent.
                         *
                         * Also, the enumeration locks a FILE: keytab
                         */
-               
-                       krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
+                       krb5_kt_end_seq_get(context, keytab, &cursor);
+
+                       code = krb5_kt_remove_entry(context, keytab, &entry);
+                       krb5_kt_free_entry(context, &entry);
 
-                       ret = krb5_kt_remove_entry(smb_krb5_context->krb5_context, keytab, &entry);
-                       krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
+                       /* Make sure we do not double free */
+                       ZERO_STRUCT(entry);
 
                        /* Deleted: Restart from the top */
-                       ret2 = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
-                       if (ret2) {
-                               krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
-                               DEBUG(1,("failed to restart enumeration of keytab: %s\n",
-                                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                                   ret, mem_ctx)));
-                               
-                               talloc_free(mem_ctx);
-                               return ret2;
+                       rc = krb5_kt_start_seq_get(context, keytab, &cursor);
+                       if (rc != 0) {
+                               krb5_kt_free_entry(context, &entry);
+
+                               /* Make sure we do not double free */
+                               ZERO_STRUCT(entry);
+
+                               DEBUG(1, ("failed to restart enumeration of keytab: %s\n",
+                                         smb_get_krb5_error_message(context,
+                                                                    code,
+                                                                    tmp_ctx)));
+
+                               talloc_free(tmp_ctx);
+                               return rc;
                        }
 
-                       if (ret) {
+                       if (code != 0) {
                                break;
                        }
-                       
+
                } else {
-                       *found_previous = True;
+                       *found_previous = true;
                }
-               
+
                /* Free the entry, we don't need it any more */
-               krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
-               
-               
-       }
-       krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
+               krb5_kt_free_entry(context, &entry);
+               /* Make sure we do not double free */
+               ZERO_STRUCT(entry);
+       } while (code == 0);
+
+       krb5_kt_end_seq_get(context, keytab, &cursor);
 
-       switch (ret) {
+       switch (code) {
        case 0:
                break;
        case ENOENT:
        case KRB5_KT_END:
-               ret = 0;
                break;
        default:
-               DEBUG(1,("failed in deleting old entries for principal: %s: %s\n",
-                        princ_string, 
-                        smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
-                                                   ret, mem_ctx)));
-       }
-       talloc_free(mem_ctx);
-       return ret;
+               *error_string = talloc_asprintf(mem_ctx,
+                                               "failed in deleting old entries for principal: %s\n",
+                                               smb_get_krb5_error_message(context,
+                                                                          code,
+                                                                          tmp_ctx));
+               goto done;
+       }
+
+       code = 0;
+done:
+       talloc_free(tmp_ctx);
+       return code;
 }
 
-int smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
-                          struct cli_credentials *machine_account,
-                          struct smb_krb5_context *smb_krb5_context,
-                          const char **enctype_strings,
-                          struct keytab_container *keytab_container) 
+/*
+ * Walk the keytab, looking for entries of this principal name,
+ * with KVNO and key equal
+ *
+ * These entries do not need to be replaced, so we want to tell the caller not to add them again
+ *
+ * Inspired by the code in Samba3 for 'use kerberos keytab'.
+ */
+krb5_error_code smb_krb5_is_exact_entry_in_keytab(TALLOC_CTX *mem_ctx,
+                                                 krb5_context context,
+                                                 krb5_keytab keytab,
+                                                 krb5_keytab_entry *to_match,
+                                                 bool *found,
+                                                 const char **error_string)
 {
-       krb5_error_code ret;
-       BOOL found_previous;
-       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
-       if (!mem_ctx) {
+       TALLOC_CTX *tmp_ctx;
+       krb5_error_code code;
+       krb5_kt_cursor cursor;
+
+       tmp_ctx = talloc_new(mem_ctx);
+       if (tmp_ctx == NULL) {
+               *error_string = "Cannot allocate tmp_ctx";
                return ENOMEM;
        }
 
-       ret = remove_old_entries(mem_ctx, machine_account, 
-                                smb_krb5_context, keytab_container->keytab, &found_previous);
-       if (ret != 0) {
-               talloc_free(mem_ctx);
-               return ret;
-       }
-       
-       /* Create a new keytab.  If during the cleanout we found
-        * entires for kvno -1, then don't try and duplicate them.
-        * Otherwise, add kvno, and kvno -1 */
-       
-       ret = create_keytab(mem_ctx, machine_account, smb_krb5_context, 
-                           enctype_strings, 
-                           keytab_container->keytab, 
-                           found_previous ? False : True);
-       talloc_free(mem_ctx);
-       return ret;
-}
+       *found = false;
 
-_PUBLIC_ int smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
-                                          struct cli_credentials *machine_account,
-                                          struct smb_krb5_context *smb_krb5_context,
-                                          const char **enctype_strings,
-                                          struct keytab_container **keytab_container) 
-{
-       krb5_error_code ret;
-       TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
-       const char *rand_string;
-       const char *keytab_name;
-       if (!mem_ctx) {
-               return ENOMEM;
+       code = krb5_kt_start_seq_get(context, keytab, &cursor);
+       switch (code) {
+       case 0:
+               break;
+#ifdef HEIM_ERR_OPNOTSUPP
+       case HEIM_ERR_OPNOTSUPP:
+#endif
+       case ENOENT:
+       case KRB5_KT_END:
+               /* no point enumerating if there isn't anything here */
+               code = 0;
+               goto done;
+       default:
+               *error_string = talloc_asprintf(mem_ctx,
+                                               "failed to open keytab for read of existing entries: %s\n",
+                                               smb_get_krb5_error_message(context, code, tmp_ctx));
+               goto done;
        }
-       
-       *keytab_container = talloc(mem_ctx, struct keytab_container);
 
-       rand_string = generate_random_str(mem_ctx, 16);
-       if (!rand_string) {
-               talloc_free(mem_ctx);
-               return ENOMEM;
-       }
+       do {
+               krb5_keytab_entry entry;
+               bool matched = false;
+               krb5_boolean ok;
 
-       keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", 
-                                     rand_string);
-       if (!keytab_name) {
-               talloc_free(mem_ctx);
-               return ENOMEM;
-       }
+               code = krb5_kt_next_entry(context, keytab, &entry, &cursor);
+               if (code) {
+                       break;
+               }
 
-       ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, keytab_container);
-       if (ret) {
-               return ret;
-       }
+               ok = smb_krb5_kt_compare(context,
+                                        &entry,
+                                        to_match->principal,
+                                        to_match->vno,
+                                        KRB5_KEY_TYPE(KRB5_KT_KEY(to_match)));
+               if (ok) {
+                       /* This is not a security check, constant time is not required */
+                       if ((KRB5_KEY_LENGTH(KRB5_KT_KEY(&entry)) == KRB5_KEY_LENGTH(KRB5_KT_KEY(to_match)))
+                           && memcmp(KRB5_KEY_DATA(KRB5_KT_KEY(&entry)), KRB5_KEY_DATA(KRB5_KT_KEY(to_match)),
+                                     KRB5_KEY_LENGTH(KRB5_KT_KEY(&entry))) == 0) {
+                               matched = true;
+                       }
+               }
 
-       ret = smb_krb5_update_keytab(mem_ctx, machine_account, smb_krb5_context, enctype_strings, *keytab_container);
-       if (ret == 0) {
-               talloc_steal(parent_ctx, *keytab_container);
-       } else {
-               *keytab_container = NULL;
-       }
-       talloc_free(mem_ctx);
-       return ret;
-}
+               /* Free the entry, we don't need it any more */
+               krb5_kt_free_entry(context, &entry);
+               /* Make sure we do not double free */
+               ZERO_STRUCT(entry);
+               if (matched) {
+                       *found = true;
+                       break;
+               }
+       } while (code == 0);
+
+       krb5_kt_end_seq_get(context, keytab, &cursor);
 
+       switch (code) {
+       case 0:
+               break;
+       case ENOENT:
+       case KRB5_KT_END:
+               break;
+       default:
+               *error_string = talloc_asprintf(mem_ctx,
+                                               "failed in checking old entries for principal: %s\n",
+                                               smb_get_krb5_error_message(context,
+                                                                          code,
+                                                                          tmp_ctx));
+               goto done;
+       }
+
+       code = 0;
+done:
+       talloc_free(tmp_ctx);
+       return code;
+}