37a5ae6f39058f5fc85b3e5748c490a334e98553
[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         if (add_old && kvno != 0) {
601                 old_secret = ldb_msg_find_attr_as_string(msg, "priorSecret", NULL);
602         } else {
603                 old_secret = NULL;
604         }
605
606         enctype_bitmap = (uint32_t)ldb_msg_find_attr_as_int(msg, "msDS-SupportedEncryptionTypes", ENC_ALL_TYPES);
607         
608         ret = kerberos_enctype_bitmap_to_enctypes(mem_ctx, enctype_bitmap, &enctypes);
609         if (ret) {
610                 *error_string = talloc_asprintf(parent_ctx, "create_keytab: generating list of encryption types failed (%s)\n",
611                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
612                                                                            ret, mem_ctx));
613                 talloc_free(mem_ctx);
614                 return ret;
615         }
616
617         /* Walk over the principals */
618         for (i=0; principals[i]; i++) {
619                 ret = keytab_add_keys(mem_ctx, principals[i]->string_form, principals[i]->principal,
620                                       salt_princ,
621                                       kvno, password_s, smb_krb5_context,
622                                       enctypes, keytab, error_string);
623                 if (ret) {
624                         talloc_free(mem_ctx);
625                         return ret;
626                 }
627
628                 if (old_secret) {
629                         ret = keytab_add_keys(mem_ctx, principals[i]->string_form, principals[i]->principal,
630                                               salt_princ,
631                                               kvno - 1, old_secret, smb_krb5_context,
632                                               enctypes, keytab, error_string);
633                         if (ret) {
634                                 talloc_free(mem_ctx);
635                                 return ret;
636                         }
637                 }
638         }
639
640         talloc_free(mem_ctx);
641         return ret;
642 }
643
644 /*
645  * Walk the keytab, looking for entries of this principal name, with KVNO other than current kvno -1.
646  *
647  * These entries are now stale, we only keep the current, and previous entries around.
648  *
649  * Inspired by the code in Samba3 for 'use kerberos keytab'.
650  *
651  */
652
653 static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
654                                           struct ldb_message *msg,
655                                           struct principal_container **principals,
656                                           bool delete_all_kvno,
657                                           struct smb_krb5_context *smb_krb5_context,
658                                           krb5_keytab keytab, bool *found_previous,
659                                           const char **error_string)
660 {
661         krb5_error_code ret, ret2;
662         krb5_kt_cursor cursor;
663         int kvno;
664         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
665
666         if (!mem_ctx) {
667                 return ENOMEM;
668         }
669
670         *found_previous = false;
671
672         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
673
674         /* for each entry in the keytab */
675         ret = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
676         switch (ret) {
677         case 0:
678                 break;
679         case HEIM_ERR_OPNOTSUPP:
680         case ENOENT:
681         case KRB5_KT_END:
682                 /* no point enumerating if there isn't anything here */
683                 talloc_free(mem_ctx);
684                 return 0;
685         default:
686                 *error_string = talloc_asprintf(parent_ctx, "failed to open keytab for read of old entries: %s\n",
687                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
688                                                                            ret, mem_ctx));
689                 talloc_free(mem_ctx);
690                 return ret;
691         }
692
693         while (!ret) {
694                 unsigned int i;
695                 bool matched = false;
696                 krb5_keytab_entry entry;
697                 ret = krb5_kt_next_entry(smb_krb5_context->krb5_context, keytab, &entry, &cursor);
698                 if (ret) {
699                         break;
700                 }
701                 for (i = 0; principals[i]; i++) {
702                         /* if it matches our principal */
703                         if (krb5_kt_compare(smb_krb5_context->krb5_context, &entry, principals[i]->principal, 0, 0)) {
704                                 matched = true;
705                                 break;
706                         }
707                 }
708
709                 if (!matched) {
710                         /* Free the entry, it wasn't the one we were looking for anyway */
711                         krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
712                         continue;
713                 }
714
715                 /* delete it, if it is not kvno -1 */
716                 if (entry.vno != (kvno - 1 )) {
717                         /* Release the enumeration.  We are going to
718                          * have to start this from the top again,
719                          * because deletes during enumeration may not
720                          * always be consistant.
721                          *
722                          * Also, the enumeration locks a FILE: keytab
723                          */
724                 
725                         krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
726
727                         ret = krb5_kt_remove_entry(smb_krb5_context->krb5_context, keytab, &entry);
728                         krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
729
730                         /* Deleted: Restart from the top */
731                         ret2 = krb5_kt_start_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
732                         if (ret2) {
733                                 krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
734                                 DEBUG(1,("failed to restart enumeration of keytab: %s\n",
735                                          smb_get_krb5_error_message(smb_krb5_context->krb5_context, 
736                                                                     ret, mem_ctx)));
737                                 
738                                 talloc_free(mem_ctx);
739                                 return ret2;
740                         }
741
742                         if (ret) {
743                                 break;
744                         }
745                         
746                 } else {
747                         *found_previous = true;
748                 }
749                 
750                 /* Free the entry, we don't need it any more */
751                 krb5_kt_free_entry(smb_krb5_context->krb5_context, &entry);
752                 
753                 
754         }
755         krb5_kt_end_seq_get(smb_krb5_context->krb5_context, keytab, &cursor);
756
757         switch (ret) {
758         case 0:
759                 break;
760         case ENOENT:
761         case KRB5_KT_END:
762                 ret = 0;
763                 break;
764         default:
765                 *error_string = talloc_asprintf(parent_ctx, "failed in deleting old entries for principal: %s\n",
766                                                 smb_get_krb5_error_message(smb_krb5_context->krb5_context,
767                                                                            ret, mem_ctx));
768         }
769         talloc_free(mem_ctx);
770         return ret;
771 }
772
773 krb5_error_code smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
774                                        struct smb_krb5_context *smb_krb5_context,
775                                        struct ldb_context *ldb, 
776                                        struct ldb_message *msg,
777                                        bool delete_all_kvno,
778                                        const char **error_string)
779 {
780         krb5_error_code ret;
781         bool found_previous;
782         TALLOC_CTX *mem_ctx = talloc_new(NULL);
783         struct keytab_container *keytab_container;
784         struct principal_container **principals;
785         const char *keytab_name;
786
787         if (!mem_ctx) {
788                 return ENOMEM;
789         }
790
791         keytab_name = keytab_name_from_msg(mem_ctx, ldb, msg);
792         if (!keytab_name) {
793                 return ENOENT;
794         }
795
796         ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, &keytab_container);
797
798         if (ret != 0) {
799                 talloc_free(mem_ctx);
800                 return ret;
801         }
802
803         DEBUG(5, ("Opened keytab %s\n", keytab_name));
804
805         /* Get the principal we will store the new keytab entries under */
806         ret = principals_from_msg(mem_ctx, msg, smb_krb5_context, &principals, error_string);
807
808         if (ret != 0) {
809                 *error_string = talloc_asprintf(parent_ctx, "Failed to load principals from ldb message: %s\n", *error_string);
810                 talloc_free(mem_ctx);
811                 return ret;
812         }
813
814         ret = remove_old_entries(mem_ctx, msg, principals, delete_all_kvno,
815                                  smb_krb5_context, keytab_container->keytab, &found_previous, error_string);
816         if (ret != 0) {
817                 *error_string = talloc_asprintf(parent_ctx, "Failed to remove old principals from keytab: %s\n", *error_string);
818                 talloc_free(mem_ctx);
819                 return ret;
820         }
821         
822         if (!delete_all_kvno) {
823                 /* Create a new keytab.  If during the cleanout we found
824                  * entires for kvno -1, then don't try and duplicate them.
825                  * Otherwise, add kvno, and kvno -1 */
826                 
827                 ret = create_keytab(mem_ctx, msg, principals,
828                                     smb_krb5_context,
829                                     keytab_container->keytab, 
830                                     found_previous ? false : true, error_string);
831         }
832         talloc_free(mem_ctx);
833         return ret;
834 }
835
836 krb5_error_code smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
837                                            struct cli_credentials *machine_account,
838                                            struct smb_krb5_context *smb_krb5_context,
839                                            struct keytab_container **keytab_container) 
840 {
841         krb5_error_code ret;
842         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
843         const char *rand_string;
844         const char *keytab_name;
845         struct ldb_message *msg;
846         const char *error_string;
847         if (!mem_ctx) {
848                 return ENOMEM;
849         }
850         
851         *keytab_container = talloc(mem_ctx, struct keytab_container);
852
853         rand_string = generate_random_str(mem_ctx, 16);
854         if (!rand_string) {
855                 talloc_free(mem_ctx);
856                 return ENOMEM;
857         }
858
859         keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", 
860                                       rand_string);
861         if (!keytab_name) {
862                 talloc_free(mem_ctx);
863                 return ENOMEM;
864         }
865
866         ret = smb_krb5_open_keytab(mem_ctx, smb_krb5_context, keytab_name, keytab_container);
867         if (ret) {
868                 return ret;
869         }
870
871         msg = ldb_msg_new(mem_ctx);
872         if (!msg) {
873                 talloc_free(mem_ctx);
874                 return ENOMEM;
875         }
876         ldb_msg_add_string(msg, "krb5Keytab", keytab_name);
877         ldb_msg_add_string(msg, "secret", cli_credentials_get_password(machine_account));
878         ldb_msg_add_string(msg, "samAccountName", cli_credentials_get_username(machine_account));
879         ldb_msg_add_string(msg, "realm", cli_credentials_get_realm(machine_account));
880         ldb_msg_add_fmt(msg, "msDS-KeyVersionNumber", "%d", (int)cli_credentials_get_kvno(machine_account));
881
882         ret = smb_krb5_update_keytab(mem_ctx, smb_krb5_context, NULL, msg, false, &error_string);
883         if (ret == 0) {
884                 talloc_steal(parent_ctx, *keytab_container);
885         } else {
886                 DEBUG(0, ("Failed to create in-memory keytab: %s\n", error_string));
887                 *keytab_container = NULL;
888         }
889         talloc_free(mem_ctx);
890         return ret;
891 }
892 /* Translate between the IETF encryption type values and the Microsoft msDS-SupportedEncryptionTypes values */
893 uint32_t kerberos_enctype_to_bitmap(krb5_enctype enc_type_enum)
894 {
895         switch (enc_type_enum) {
896         case ENCTYPE_DES_CBC_CRC:
897                 return ENC_CRC32;
898         case ENCTYPE_DES_CBC_MD5:
899                 return ENC_RSA_MD5;
900         case ENCTYPE_ARCFOUR_HMAC_MD5:
901                 return ENC_RC4_HMAC_MD5;
902         case ENCTYPE_AES128_CTS_HMAC_SHA1_96:
903                 return ENC_HMAC_SHA1_96_AES128;
904         case ENCTYPE_AES256_CTS_HMAC_SHA1_96:
905                 return ENC_HMAC_SHA1_96_AES256;
906         default:
907                 return 0;
908         }
909 }
910
911 /* Translate between the Microsoft msDS-SupportedEncryptionTypes values and the IETF encryption type values */
912 krb5_enctype kerberos_enctype_bitmap_to_enctype(uint32_t enctype_bitmap)
913 {
914         switch (enctype_bitmap) {
915         case ENC_CRC32:
916                 return ENCTYPE_DES_CBC_CRC;
917         case ENC_RSA_MD5:
918                 return ENCTYPE_DES_CBC_MD5;
919         case ENC_RC4_HMAC_MD5:
920                 return ENCTYPE_ARCFOUR_HMAC_MD5;
921         case ENC_HMAC_SHA1_96_AES128:
922                 return ENCTYPE_AES128_CTS_HMAC_SHA1_96;
923         case ENC_HMAC_SHA1_96_AES256:
924                 return ENCTYPE_AES256_CTS_HMAC_SHA1_96;
925         default:
926                 return 0;
927         }
928 }
929
930 /* Return an array of krb5_enctype values */
931 krb5_error_code kerberos_enctype_bitmap_to_enctypes(TALLOC_CTX *mem_ctx, uint32_t enctype_bitmap, krb5_enctype **enctypes)
932 {
933         unsigned int i, j = 0;
934         *enctypes = talloc_zero_array(mem_ctx, krb5_enctype, (8*sizeof(enctype_bitmap))+1);
935         if (!*enctypes) {
936                 return ENOMEM;
937         }
938         for (i=0; i<(8*sizeof(enctype_bitmap)); i++) {
939                 uint32_t bit_value = (1 << i) & enctype_bitmap;
940                 if (bit_value & enctype_bitmap) {
941                         (*enctypes)[j] = kerberos_enctype_bitmap_to_enctype(bit_value);
942                         if (!(*enctypes)[j]) {
943                                 continue;
944                         }
945                         j++;
946                 }
947         }
948         (*enctypes)[j] = 0;
949         return 0;
950 }