s4-kerberos Don't segfault if the password isn't specified in keytab generation
[samba.git] / source4 / auth / kerberos / kerberos_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Kerberos utility functions for GENSEC
5    
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "system/kerberos.h"
25 #include "auth/kerberos/kerberos.h"
26 #include "auth/credentials/credentials.h"
27 #include "auth/credentials/credentials_proto.h"
28 #include "auth/credentials/credentials_krb5.h"
29 #include "auth/kerberos/kerberos_credentials.h"
30 #include "ldb.h"
31 #include "param/secrets.h"
32
33 struct principal_container {
34         struct smb_krb5_context *smb_krb5_context;
35         krb5_principal principal;
36         const char *string_form; /* Optional */
37 };
38
39 static krb5_error_code free_principal(struct principal_container *pc)
40 {
41         /* current heimdal - 0.6.3, which we need anyway, fixes segfaults here */
42         krb5_free_principal(pc->smb_krb5_context->krb5_context, pc->principal);
43
44         return 0;
45 }
46
47
48 static krb5_error_code parse_principal(TALLOC_CTX *parent_ctx,
49                                        const char *princ_string,
50                                        struct smb_krb5_context *smb_krb5_context,
51                                        krb5_principal *princ,
52                                        const char **error_string)
53 {
54         int ret;
55         struct principal_container *mem_ctx;
56         if (princ_string == NULL) {
57                  *princ = NULL;
58                  return 0;
59         }
60
61         ret = krb5_parse_name(smb_krb5_context->krb5_context,
62                               princ_string, princ);
63
64         if (ret) {
65                 (*error_string) = smb_get_krb5_error_message(smb_krb5_context->krb5_context, ret, parent_ctx);
66                 return ret;
67         }
68
69         mem_ctx = talloc(parent_ctx, struct principal_container);
70         if (!mem_ctx) {
71                 (*error_string) = error_message(ENOMEM);
72                 return ENOMEM;
73         }
74
75         /* This song-and-dance effectivly puts the principal
76          * into talloc, so we can't loose it. */
77         mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context);
78         mem_ctx->principal = *princ;
79         talloc_set_destructor(mem_ctx, free_principal);
80         return 0;
81 }
82
83 static krb5_error_code principals_from_msg(TALLOC_CTX *parent_ctx,
84                                            struct ldb_message *msg,
85                                            struct smb_krb5_context *smb_krb5_context,
86                                            struct principal_container ***principals_out,
87                                            const char **error_string)
88 {
89         unsigned int i;
90         krb5_error_code ret;
91         char *upper_realm;
92         const char *realm = ldb_msg_find_attr_as_string(msg, "realm", NULL);
93         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
94         struct ldb_message_element *spn_el = ldb_msg_find_element(msg, "servicePrincipalName");
95         TALLOC_CTX *tmp_ctx;
96         struct principal_container **principals;
97         tmp_ctx = talloc_new(parent_ctx);
98         if (!tmp_ctx) {
99                 *error_string = "Cannot allocate tmp_ctx";
100                 return ENOMEM;
101         }
102
103         if (!realm) {
104                 *error_string = "Cannot have a kerberos secret in secrets.ldb without a realm";
105                 return EINVAL;
106         }
107
108         upper_realm = strupper_talloc(tmp_ctx, realm);
109         if (!upper_realm) {
110                 talloc_free(tmp_ctx);
111                 *error_string = "Cannot allocate full upper case realm";
112                 return ENOMEM;
113         }
114
115         principals = talloc_array(tmp_ctx, struct principal_container *, spn_el ? (spn_el->num_values + 2) : 2);
116
117         spn_el = ldb_msg_find_element(msg, "servicePrincipalName");
118         for (i=0; spn_el && i < spn_el->num_values; i++) {
119                 principals[i] = talloc(principals, struct principal_container);
120                 if (!principals[i]) {
121                         talloc_free(tmp_ctx);
122                         *error_string = "Cannot allocate mem_ctx";
123                         return ENOMEM;
124                 }
125
126                 principals[i]->smb_krb5_context = talloc_reference(principals[i], smb_krb5_context);
127                 principals[i]->string_form = talloc_asprintf(principals[i], "%*.*s@%s",
128                                                              (int)spn_el->values[i].length,
129                                                              (int)spn_el->values[i].length,
130                                                              (const char *)spn_el->values[i].data, upper_realm);
131                 if (!principals[i]->string_form) {
132                         talloc_free(tmp_ctx);
133                         *error_string = "Cannot allocate full samAccountName";
134                         return ENOMEM;
135                 }
136
137                 ret = krb5_parse_name(smb_krb5_context->krb5_context,
138                                       principals[i]->string_form, &principals[i]->principal);
139                 
140                 if (ret) {
141                         talloc_free(tmp_ctx);
142                         (*error_string) = smb_get_krb5_error_message(smb_krb5_context->krb5_context, ret, parent_ctx);
143                         return ret;
144                 }
145
146                 /* This song-and-dance effectivly puts the principal
147                  * into talloc, so we can't loose it. */
148                 talloc_set_destructor(principals[i], free_principal);
149         }
150
151         if (samAccountName) {
152                 principals[i] = talloc(principals, struct principal_container);
153                 if (!principals[i]) {
154                         talloc_free(tmp_ctx);
155                         *error_string = "Cannot allocate mem_ctx";
156                         return ENOMEM;
157                 }
158
159                 principals[i]->smb_krb5_context = talloc_reference(principals[i], smb_krb5_context);
160                 principals[i]->string_form = talloc_asprintf(parent_ctx, "%s@%s", samAccountName, upper_realm);
161                 if (!principals[i]->string_form) {
162                         talloc_free(tmp_ctx);
163                         *error_string = "Cannot allocate full samAccountName";
164                         return ENOMEM;
165                 }
166                 
167                 ret = krb5_make_principal(smb_krb5_context->krb5_context, &principals[i]->principal, upper_realm, samAccountName,
168                                           NULL);
169                 if (ret) {
170                         talloc_free(tmp_ctx);
171                         (*error_string) = smb_get_krb5_error_message(smb_krb5_context->krb5_context, ret, parent_ctx);
172                         return ret;
173                 }
174                 
175                 /* This song-and-dance effectivly puts the principal
176                  * into talloc, so we can't loose it. */
177                 talloc_set_destructor(principals[i], free_principal);
178                 i++;
179         }
180
181         principals[i] = NULL;
182         *principals_out = talloc_steal(parent_ctx, principals);
183
184         talloc_free(tmp_ctx);
185         return ret;
186 }
187
188 static krb5_error_code salt_principal_from_msg(TALLOC_CTX *parent_ctx, 
189                                                struct ldb_message *msg, 
190                                                struct smb_krb5_context *smb_krb5_context,
191                                                krb5_principal *salt_princ,
192                                                const char **error_string)
193 {
194         const char *salt_principal = ldb_msg_find_attr_as_string(msg, "saltPrincipal", NULL);
195         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
196         const char *realm = ldb_msg_find_attr_as_string(msg, "realm", NULL);
197         if (salt_principal) {
198                 return parse_principal(parent_ctx, salt_principal, smb_krb5_context, salt_princ, error_string);
199         } else if (samAccountName) {
200                 krb5_error_code ret;
201                 char *machine_username;
202                 char *salt_body;
203                 char *lower_realm;
204                 char *upper_realm;
205
206                 TALLOC_CTX *tmp_ctx;
207                 struct principal_container *mem_ctx = talloc(parent_ctx, struct principal_container);
208                 if (!mem_ctx) {
209                         *error_string = "Cannot allocate mem_ctx";
210                         return ENOMEM;
211                 }
212
213                 tmp_ctx = talloc_new(mem_ctx);
214                 if (!tmp_ctx) {
215                         talloc_free(mem_ctx);
216                         *error_string = "Cannot allocate tmp_ctx";
217                         return ENOMEM;
218                 }
219
220                 if (!realm) {
221                         *error_string = "Cannot have a kerberos secret in secrets.ldb without a realm";
222                         return EINVAL;
223                 }
224                 
225                 machine_username = talloc_strdup(tmp_ctx, samAccountName);
226                 if (!machine_username) {
227                         talloc_free(mem_ctx);
228                         *error_string = "Cannot duplicate samAccountName";
229                         return ENOMEM;
230                 }
231                 
232                 if (machine_username[strlen(machine_username)-1] == '$') {
233                         machine_username[strlen(machine_username)-1] = '\0';
234                 }
235
236                 lower_realm = strlower_talloc(tmp_ctx, realm);
237                 if (!lower_realm) {
238                         talloc_free(mem_ctx);
239                         *error_string = "Cannot allocate to lower case realm";
240                         return ENOMEM;
241                 }
242                 
243                 upper_realm = strupper_talloc(tmp_ctx, realm);
244                 if (!upper_realm) {
245                         talloc_free(mem_ctx);
246                         *error_string = "Cannot allocate to upper case realm";
247                         return ENOMEM;
248                 }
249                 
250                 salt_body = talloc_asprintf(tmp_ctx, "%s.%s", machine_username, 
251                                             lower_realm);
252                 talloc_free(lower_realm);
253                 talloc_free(machine_username);
254                 if (!salt_body) {
255                         talloc_free(mem_ctx);
256                         *error_string = "Cannot form salt principal body";
257                         return ENOMEM;
258                 }
259                 
260                 ret = krb5_make_principal(smb_krb5_context->krb5_context, salt_princ, 
261                                           upper_realm,
262                                           "host", salt_body, NULL);
263                 if (ret == 0) {
264                         /* This song-and-dance effectivly puts the principal
265                          * into talloc, so we can't loose it. */
266                         mem_ctx->smb_krb5_context = talloc_reference(mem_ctx, smb_krb5_context);
267                         mem_ctx->principal = *salt_princ;
268                         talloc_set_destructor(mem_ctx, free_principal);
269                 } else {
270                         (*error_string) = smb_get_krb5_error_message(smb_krb5_context->krb5_context, ret, parent_ctx);
271                 }
272                 talloc_free(tmp_ctx);
273                 return ret;
274         } else {
275                 (*error_string) = "Cannot determine salt principal, no saltPrincipal or samAccountName specified";
276                 return EINVAL;
277         }
278 }
279
280 /* Obtain the principal set on this context.  Requires a
281  * smb_krb5_context because we are doing krb5 principal parsing with
282  * the library routines.  The returned princ is placed in the talloc
283  * system by means of a destructor (do *not* free). */
284
285 krb5_error_code principal_from_credentials(TALLOC_CTX *parent_ctx, 
286                                             struct cli_credentials *credentials, 
287                                             struct smb_krb5_context *smb_krb5_context,
288                                             krb5_principal *princ,
289                                             enum credentials_obtained *obtained,
290                                             const char **error_string)
291 {
292         krb5_error_code ret;
293         const char *princ_string;
294         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
295         if (!mem_ctx) {
296                 (*error_string) = error_message(ENOMEM);
297                 return ENOMEM;
298         }
299         princ_string = cli_credentials_get_principal_and_obtained(credentials, mem_ctx, obtained);
300         if (!princ_string) {
301                 (*error_string) = error_message(ENOMEM);
302                 return ENOMEM;
303         }
304
305         ret = parse_principal(parent_ctx, princ_string,
306                               smb_krb5_context, princ, error_string);
307         talloc_free(mem_ctx);
308         return ret;
309 }
310
311 /* Obtain the principal set on this context.  Requires a
312  * smb_krb5_context because we are doing krb5 principal parsing with
313  * the library routines.  The returned princ is placed in the talloc
314  * system by means of a destructor (do *not* free). */
315
316  krb5_error_code impersonate_principal_from_credentials(TALLOC_CTX *parent_ctx,
317                                                         struct cli_credentials *credentials,
318                                                         struct smb_krb5_context *smb_krb5_context,
319                                                         krb5_principal *princ,
320                                                         const char **error_string)
321 {
322         return parse_principal(parent_ctx, cli_credentials_get_impersonate_principal(credentials),
323                                smb_krb5_context, princ, error_string);
324 }
325
326 /**
327  * Return a freshly allocated ccache (destroyed by destructor on child
328  * of parent_ctx), for a given set of client credentials 
329  */
330
331  krb5_error_code kinit_to_ccache(TALLOC_CTX *parent_ctx,
332                                  struct cli_credentials *credentials,
333                                  struct smb_krb5_context *smb_krb5_context,
334                                  krb5_ccache ccache,
335                                  enum credentials_obtained *obtained,
336                                  const char **error_string)
337 {
338         krb5_error_code ret;
339         const char *password, *target_service;
340         time_t kdc_time = 0;
341         krb5_principal princ;
342         krb5_principal impersonate_principal;
343         int tries;
344         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
345         krb5_get_init_creds_opt *krb_options;
346
347         if (!mem_ctx) {
348                 (*error_string) = strerror(ENOMEM);
349                 return ENOMEM;
350         }
351
352         ret = principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &princ, obtained, error_string);
353         if (ret) {
354                 talloc_free(mem_ctx);
355                 return ret;
356         }
357
358         ret = impersonate_principal_from_credentials(mem_ctx, credentials, smb_krb5_context, &impersonate_principal, error_string);
359         if (ret) {
360                 talloc_free(mem_ctx);
361                 return ret;
362         }
363
364         target_service = cli_credentials_get_target_service(credentials);
365
366         password = cli_credentials_get_password(credentials);
367
368         /* setup the krb5 options we want */
369         if ((ret = krb5_get_init_creds_opt_alloc(smb_krb5_context->krb5_context, &krb_options))) {
370                 (*error_string) = talloc_asprintf(credentials, "krb5_get_init_creds_opt_alloc failed (%s)\n",
371                                                   smb_get_krb5_error_message(smb_krb5_context->krb5_context,
372                                                                              ret, mem_ctx));
373                 talloc_free(mem_ctx);
374                 return ret;
375         }
376
377         /* get the defaults */
378         krb5_get_init_creds_opt_set_default_flags(smb_krb5_context->krb5_context, NULL, NULL, krb_options);
379
380         /* set if we want a forwardable ticket */
381         switch (cli_credentials_get_krb_forwardable(credentials)) {
382         case CRED_AUTO_KRB_FORWARDABLE:
383                 break;
384         case CRED_NO_KRB_FORWARDABLE:
385                 krb5_get_init_creds_opt_set_forwardable(krb_options, FALSE);
386                 break;
387         case CRED_FORCE_KRB_FORWARDABLE:
388                 krb5_get_init_creds_opt_set_forwardable(krb_options, TRUE);
389                 break;
390         }
391
392         tries = 2;
393         while (tries--) {
394                 if (password) {
395                         ret = kerberos_kinit_password_cc(smb_krb5_context->krb5_context, ccache, 
396                                                          princ, password,
397                                                          impersonate_principal, target_service,
398                                                          krb_options,
399                                                          NULL, &kdc_time);
400                 } else if (impersonate_principal) {
401                         (*error_string) = "INTERNAL error: Cannot impersonate principal with just a keyblock.  A password must be specified in the credentials";
402                         return EINVAL;
403                 } else {
404                         /* No password available, try to use a keyblock instead */
405                         
406                         krb5_keyblock keyblock;
407                         const struct samr_Password *mach_pwd;
408                         mach_pwd = cli_credentials_get_nt_hash(credentials, mem_ctx);
409                         if (!mach_pwd) {
410                                 talloc_free(mem_ctx);
411                                 (*error_string) = "kinit_to_ccache: No password available for kinit\n";
412                                 krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
413                                 return EINVAL;
414                         }
415                         ret = krb5_keyblock_init(smb_krb5_context->krb5_context,
416                                                  ENCTYPE_ARCFOUR_HMAC,
417                                                  mach_pwd->hash, sizeof(mach_pwd->hash), 
418                                                  &keyblock);
419                         
420                         if (ret == 0) {
421                                 ret = kerberos_kinit_keyblock_cc(smb_krb5_context->krb5_context, ccache, 
422                                                                  princ, &keyblock,
423                                                                  target_service, krb_options,
424                                                                  NULL, &kdc_time);
425                                 krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &keyblock);
426                         }
427                 }
428
429                 if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) {
430                         /* Perhaps we have been given an invalid skew, so try again without it */
431                         time_t t = time(NULL);
432                         krb5_set_real_time(smb_krb5_context->krb5_context, t, 0);
433                 } else {
434                         /* not a skew problem */
435                         break;
436                 }
437         }
438
439         krb5_get_init_creds_opt_free(smb_krb5_context->krb5_context, krb_options);
440
441         if (ret == KRB5KRB_AP_ERR_SKEW || ret == KRB5_KDCREP_SKEW) {
442                 (*error_string) = talloc_asprintf(credentials, "kinit for %s failed (%s)\n",
443                                                   cli_credentials_get_principal(credentials, mem_ctx),
444                                                   smb_get_krb5_error_message(smb_krb5_context->krb5_context,
445                                                                              ret, mem_ctx));
446                 talloc_free(mem_ctx);
447                 return ret;
448         }
449
450         /* cope with ticket being in the future due to clock skew */
451         if ((unsigned)kdc_time > time(NULL)) {
452                 time_t t = time(NULL);
453                 int time_offset =(unsigned)kdc_time-t;
454                 DEBUG(4,("Advancing clock by %d seconds to cope with clock skew\n", time_offset));
455                 krb5_set_real_time(smb_krb5_context->krb5_context, t + time_offset + 1, 0);
456         }
457         
458         if (ret == KRB5KDC_ERR_PREAUTH_FAILED && cli_credentials_wrong_password(credentials)) {
459                 ret = kinit_to_ccache(parent_ctx,
460                                       credentials,
461                                       smb_krb5_context,
462                                       ccache, obtained,
463                                       error_string);
464         }
465
466         if (ret) {
467                 (*error_string) = talloc_asprintf(credentials, "kinit for %s failed (%s)\n",
468                                                   cli_credentials_get_principal(credentials, mem_ctx),
469                                                   smb_get_krb5_error_message(smb_krb5_context->krb5_context,
470                                                                              ret, mem_ctx));
471                 talloc_free(mem_ctx);
472                 return ret;
473         } 
474         talloc_free(mem_ctx);
475         return 0;
476 }
477
478 static krb5_error_code free_keytab(struct keytab_container *ktc)
479 {
480         return krb5_kt_close(ktc->smb_krb5_context->krb5_context, ktc->keytab);
481 }
482
483 krb5_error_code smb_krb5_open_keytab(TALLOC_CTX *mem_ctx,
484                          struct smb_krb5_context *smb_krb5_context, 
485                          const char *keytab_name, struct keytab_container **ktc) 
486 {
487         krb5_keytab keytab;
488         krb5_error_code ret;
489         ret = krb5_kt_resolve(smb_krb5_context->krb5_context, keytab_name, &keytab);
490         if (ret) {
491                 DEBUG(1,("failed to open krb5 keytab: %s\n", 
492                          smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
493                                                     ret, mem_ctx)));
494                 return ret;
495         }
496
497         *ktc = talloc(mem_ctx, struct keytab_container);
498         if (!*ktc) {
499                 return ENOMEM;
500         }
501
502         (*ktc)->smb_krb5_context = talloc_reference(*ktc, smb_krb5_context);
503         (*ktc)->keytab = keytab;
504         talloc_set_destructor(*ktc, free_keytab);
505
506         return 0;
507 }
508
509 static krb5_error_code keytab_add_keys(TALLOC_CTX *parent_ctx,
510                                        const char *princ_string,
511                                        krb5_principal princ,
512                                        krb5_principal salt_princ,
513                                        int kvno,
514                                        const char *password_s,
515                                        struct smb_krb5_context *smb_krb5_context,
516                                        krb5_enctype *enctypes,
517                                        krb5_keytab keytab,
518                                        const char **error_string)
519 {
520         int i;
521         krb5_error_code ret;
522         krb5_data password;
523         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
524         if (!mem_ctx) {
525                 return ENOMEM;
526         }
527
528         password.data = discard_const_p(char *, password_s);
529         password.length = strlen(password_s);
530
531         for (i=0; enctypes[i]; i++) {
532                 krb5_keytab_entry entry;
533                 ret = create_kerberos_key_from_string(smb_krb5_context->krb5_context, 
534                                                       salt_princ, &password, &entry.keyblock, enctypes[i]);
535                 if (ret != 0) {
536                         talloc_free(mem_ctx);
537                         return ret;
538                 }
539
540                 entry.principal = princ;
541                 entry.vno       = kvno;
542                 ret = krb5_kt_add_entry(smb_krb5_context->krb5_context, keytab, &entry);
543                 if (ret != 0) {
544                         *error_string = talloc_asprintf(parent_ctx, "Failed to add enctype %d entry for %s(kvno %d) to keytab: %s\n",
545                                                         (int)enctypes[i],
546                                                         princ_string,
547                                                         kvno,
548                                                         smb_get_krb5_error_message(smb_krb5_context->krb5_context,
549                                                                                    ret, mem_ctx));
550                         talloc_free(mem_ctx);
551                         krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
552                         return ret;
553                 }
554
555                 DEBUG(5, ("Added %s(kvno %d) to keytab (enctype %d)\n", 
556                           princ_string, kvno,
557                           (int)enctypes[i]));
558                 
559                 krb5_free_keyblock_contents(smb_krb5_context->krb5_context, &entry.keyblock);
560         }
561         talloc_free(mem_ctx);
562         return 0;
563 }
564
565 static krb5_error_code create_keytab(TALLOC_CTX *parent_ctx,
566                                      struct ldb_message *msg,
567                                      struct principal_container **principals,
568                                      struct smb_krb5_context *smb_krb5_context,
569                                      krb5_keytab keytab,
570                                      bool add_old,
571                                      const char **error_string)
572 {
573         unsigned int i;
574         krb5_error_code ret;
575         const char *password_s;
576         const char *old_secret;
577         int kvno;
578         uint32_t enctype_bitmap;
579         krb5_principal salt_princ;
580         krb5_enctype *enctypes;
581         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
582         if (!mem_ctx) {
583                 *error_string = "unable to allocate tmp_ctx for create_keytab";
584                 return ENOMEM;
585         }
586
587         /* The salt used to generate these entries may be different however, fetch that */
588         ret = salt_principal_from_msg(mem_ctx, msg,
589                                       smb_krb5_context, 
590                                       &salt_princ, error_string);
591         if (ret) {
592                 talloc_free(mem_ctx);
593                 return ret;
594         }
595
596         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
597
598         /* Finally, do the dance to get the password to put in the entry */
599         password_s =  ldb_msg_find_attr_as_string(msg, "secret", NULL);
600
601         if (!password_s) {
602                 /* There is no password here, so nothing to do */
603                 talloc_free(mem_ctx);
604                 return 0;
605         }
606
607         if (add_old && kvno != 0) {
608                 old_secret = ldb_msg_find_attr_as_string(msg, "priorSecret", NULL);
609         } else {
610                 old_secret = NULL;
611         }
612
613         enctype_bitmap = (uint32_t)ldb_msg_find_attr_as_int(msg, "msDS-SupportedEncryptionTypes", ENC_ALL_TYPES);
614         
615         ret = kerberos_enctype_bitmap_to_enctypes(mem_ctx, enctype_bitmap, &enctypes);
616         if (ret) {
617                 *error_string = talloc_asprintf(parent_ctx, "create_keytab: generating list of encryption types failed (%s)\n",
618                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
619                                                                            ret, mem_ctx));
620                 talloc_free(mem_ctx);
621                 return ret;
622         }
623
624         /* Walk over the principals */
625         for (i=0; principals[i]; i++) {
626                 ret = keytab_add_keys(mem_ctx, principals[i]->string_form, principals[i]->principal,
627                                       salt_princ,
628                                       kvno, password_s, smb_krb5_context,
629                                       enctypes, keytab, error_string);
630                 if (ret) {
631                         talloc_free(mem_ctx);
632                         return ret;
633                 }
634
635                 if (old_secret) {
636                         ret = keytab_add_keys(mem_ctx, principals[i]->string_form, principals[i]->principal,
637                                               salt_princ,
638                                               kvno - 1, old_secret, smb_krb5_context,
639                                               enctypes, keytab, error_string);
640                         if (ret) {
641                                 talloc_free(mem_ctx);
642                                 return ret;
643                         }
644                 }
645         }
646
647         talloc_free(mem_ctx);
648         return ret;
649 }
650
651 /*
652  * Walk the keytab, looking for entries of this principal name, with KVNO other than current kvno -1.
653  *
654  * These entries are now stale, we only keep the current, and previous entries around.
655  *
656  * Inspired by the code in Samba3 for 'use kerberos keytab'.
657  *
658  */
659
660 static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
661                                           struct ldb_message *msg,
662                                           struct principal_container **principals,
663                                           bool delete_all_kvno,
664                                           struct smb_krb5_context *smb_krb5_context,
665                                           krb5_keytab keytab, bool *found_previous,
666                                           const char **error_string)
667 {
668         krb5_error_code ret, ret2;
669         krb5_kt_cursor cursor;
670         int kvno;
671         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
672
673         if (!mem_ctx) {
674                 return ENOMEM;
675         }
676
677         *found_previous = false;
678
679         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
680
681         /* for each entry in the keytab */
682         ret = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
683         switch (ret) {
684         case 0:
685                 break;
686         case HEIM_ERR_OPNOTSUPP:
687         case ENOENT:
688         case KRB5_KT_END:
689                 /* no point enumerating if there isn't anything here */
690                 talloc_free(mem_ctx);
691                 return 0;
692         default:
693                 *error_string = talloc_asprintf(parent_ctx, "failed to open keytab for read of old entries: %s\n",
694                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
695                                                                            ret, mem_ctx));
696                 talloc_free(mem_ctx);
697                 return ret;
698         }
699
700         while (!ret) {
701                 unsigned int i;
702                 bool matched = false;
703                 krb5_keytab_entry entry;
704                 ret = krb5_kt_next_entry(smb_krb5_context->krb5_context, keytab, &entry, &cursor);
705                 if (ret) {
706                         break;
707                 }
708                 for (i = 0; principals[i]; i++) {
709                         /* if it matches our principal */
710                         if (krb5_kt_compare(smb_krb5_context->krb5_context, &entry, principals[i]->principal, 0, 0)) {
711                                 matched = true;
712                                 break;
713                         }
714                 }
715
716                 if (!matched) {
717                         /* Free the entry, it wasn't the one we were looking for anyway */
718                         krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
719                         continue;
720                 }
721
722                 /* delete it, if it is not kvno -1 */
723                 if (entry.vno != (kvno - 1 )) {
724                         /* Release the enumeration.  We are going to
725                          * have to start this from the top again,
726                          * because deletes during enumeration may not
727                          * always be consistant.
728                          *
729                          * Also, the enumeration locks a FILE: keytab
730                          */
731                 
732                         krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
733
734                         ret = krb5_kt_remove_entry(smb_krb5_context->krb5_context, keytab, &entry);
735                         krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
736
737                         /* Deleted: Restart from the top */
738                         ret2 = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
739                         if (ret2) {
740                                 krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
741                                 DEBUG(1,("failed to restart enumeration of keytab: %s\n",
742                                          smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
743                                                                     ret, mem_ctx)));
744                                 
745                                 talloc_free(mem_ctx);
746                                 return ret2;
747                         }
748
749                         if (ret) {
750                                 break;
751                         }
752                         
753                 } else {
754                         *found_previous = true;
755                 }
756                 
757                 /* Free the entry, we don't need it any more */
758                 krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
759                 
760                 
761         }
762         krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
763
764         switch (ret) {
765         case 0:
766                 break;
767         case ENOENT:
768         case KRB5_KT_END:
769                 ret = 0;
770                 break;
771         default:
772                 *error_string = talloc_asprintf(parent_ctx, "failed in deleting old entries for principal: %s\n",
773                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
774                                                                            ret, mem_ctx));
775         }
776         talloc_free(mem_ctx);
777         return ret;
778 }
779
780 krb5_error_code smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
781                                        struct smb_krb5_context *smb_krb5_context,
782                                        struct ldb_context *ldb, 
783                                        struct ldb_message *msg,
784                                        bool delete_all_kvno,
785                                        const char **error_string)
786 {
787         krb5_error_code ret;
788         bool found_previous;
789         TALLOC_CTX *mem_ctx = talloc_new(NULL);
790         struct keytab_container *keytab_container;
791         struct principal_container **principals;
792         const char *keytab_name;
793
794         if (!mem_ctx) {
795                 return ENOMEM;
796         }
797
798         keytab_name = keytab_name_from_msg(mem_ctx, ldb, msg);
799         if (!keytab_name) {
800                 return ENOENT;
801         }
802
803         ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, &keytab_container);
804
805         if (ret != 0) {
806                 talloc_free(mem_ctx);
807                 return ret;
808         }
809
810         DEBUG(5, ("Opened keytab %s\n", keytab_name));
811
812         /* Get the principal we will store the new keytab entries under */
813         ret = principals_from_msg(mem_ctx, msg, smb_krb5_context, &principals, error_string);
814
815         if (ret != 0) {
816                 *error_string = talloc_asprintf(parent_ctx, "Failed to load principals from ldb message: %s\n", *error_string);
817                 talloc_free(mem_ctx);
818                 return ret;
819         }
820
821         ret = remove_old_entries(mem_ctx, msg, principals, delete_all_kvno,
822                                  smb_krb5_context, keytab_container->keytab, &found_previous, error_string);
823         if (ret != 0) {
824                 *error_string = talloc_asprintf(parent_ctx, "Failed to remove old principals from keytab: %s\n", *error_string);
825                 talloc_free(mem_ctx);
826                 return ret;
827         }
828         
829         if (!delete_all_kvno) {
830                 /* Create a new keytab.  If during the cleanout we found
831                  * entires for kvno -1, then don't try and duplicate them.
832                  * Otherwise, add kvno, and kvno -1 */
833                 
834                 ret = create_keytab(mem_ctx, msg, principals,
835                                     smb_krb5_context,
836                                     keytab_container->keytab, 
837                                     found_previous ? false : true, error_string);
838         }
839         talloc_free(mem_ctx);
840         return ret;
841 }
842
843 krb5_error_code smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
844                                            struct cli_credentials *machine_account,
845                                            struct smb_krb5_context *smb_krb5_context,
846                                            struct keytab_container **keytab_container) 
847 {
848         krb5_error_code ret;
849         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
850         const char *rand_string;
851         const char *keytab_name;
852         struct ldb_message *msg;
853         const char *error_string;
854         if (!mem_ctx) {
855                 return ENOMEM;
856         }
857         
858         *keytab_container = talloc(mem_ctx, struct keytab_container);
859
860         rand_string = generate_random_str(mem_ctx, 16);
861         if (!rand_string) {
862                 talloc_free(mem_ctx);
863                 return ENOMEM;
864         }
865
866         keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", 
867                                       rand_string);
868         if (!keytab_name) {
869                 talloc_free(mem_ctx);
870                 return ENOMEM;
871         }
872
873         ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, keytab_container);
874         if (ret) {
875                 return ret;
876         }
877
878         msg = ldb_msg_new(mem_ctx);
879         if (!msg) {
880                 talloc_free(mem_ctx);
881                 return ENOMEM;
882         }
883         ldb_msg_add_string(msg, "krb5Keytab", keytab_name);
884         ldb_msg_add_string(msg, "secret", cli_credentials_get_password(machine_account));
885         ldb_msg_add_string(msg, "samAccountName", cli_credentials_get_username(machine_account));
886         ldb_msg_add_string(msg, "realm", cli_credentials_get_realm(machine_account));
887         ldb_msg_add_fmt(msg, "msDS-KeyVersionNumber", "%d", (int)cli_credentials_get_kvno(machine_account));
888
889         ret = smb_krb5_update_keytab(mem_ctx, smb_krb5_context, NULL, msg, false, &error_string);
890         if (ret == 0) {
891                 talloc_steal(parent_ctx, *keytab_container);
892         } else {
893                 DEBUG(0, ("Failed to create in-memory keytab: %s\n", error_string));
894                 *keytab_container = NULL;
895         }
896         talloc_free(mem_ctx);
897         return ret;
898 }
899 /* Translate between the IETF encryption type values and the Microsoft msDS-SupportedEncryptionTypes values */
900 uint32_t kerberos_enctype_to_bitmap(krb5_enctype enc_type_enum)
901 {
902         switch (enc_type_enum) {
903         case ENCTYPE_DES_CBC_CRC:
904                 return ENC_CRC32;
905         case ENCTYPE_DES_CBC_MD5:
906                 return ENC_RSA_MD5;
907         case ENCTYPE_ARCFOUR_HMAC_MD5:
908                 return ENC_RC4_HMAC_MD5;
909         case ENCTYPE_AES128_CTS_HMAC_SHA1_96:
910                 return ENC_HMAC_SHA1_96_AES128;
911         case ENCTYPE_AES256_CTS_HMAC_SHA1_96:
912                 return ENC_HMAC_SHA1_96_AES256;
913         default:
914                 return 0;
915         }
916 }
917
918 /* Translate between the Microsoft msDS-SupportedEncryptionTypes values and the IETF encryption type values */
919 krb5_enctype kerberos_enctype_bitmap_to_enctype(uint32_t enctype_bitmap)
920 {
921         switch (enctype_bitmap) {
922         case ENC_CRC32:
923                 return ENCTYPE_DES_CBC_CRC;
924         case ENC_RSA_MD5:
925                 return ENCTYPE_DES_CBC_MD5;
926         case ENC_RC4_HMAC_MD5:
927                 return ENCTYPE_ARCFOUR_HMAC_MD5;
928         case ENC_HMAC_SHA1_96_AES128:
929                 return ENCTYPE_AES128_CTS_HMAC_SHA1_96;
930         case ENC_HMAC_SHA1_96_AES256:
931                 return ENCTYPE_AES256_CTS_HMAC_SHA1_96;
932         default:
933                 return 0;
934         }
935 }
936
937 /* Return an array of krb5_enctype values */
938 krb5_error_code kerberos_enctype_bitmap_to_enctypes(TALLOC_CTX *mem_ctx, uint32_t enctype_bitmap, krb5_enctype **enctypes)
939 {
940         unsigned int i, j = 0;
941         *enctypes = talloc_zero_array(mem_ctx, krb5_enctype, (8*sizeof(enctype_bitmap))+1);
942         if (!*enctypes) {
943                 return ENOMEM;
944         }
945         for (i=0; i<(8*sizeof(enctype_bitmap)); i++) {
946                 uint32_t bit_value = (1 << i) & enctype_bitmap;
947                 if (bit_value & enctype_bitmap) {
948                         (*enctypes)[j] = kerberos_enctype_bitmap_to_enctype(bit_value);
949                         if (!(*enctypes)[j]) {
950                                 continue;
951                         }
952                         j++;
953                 }
954         }
955         (*enctypes)[j] = 0;
956         return 0;
957 }