s4-auth: avoid double free of krb5 kt_entries when compiling with MIT kerberos library.
[kai/samba-autobuild/.git] / source4 / auth / kerberos / srv_keytab.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Kerberos utility functions
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
24 #include "includes.h"
25 #include "system/kerberos.h"
26 #include "auth/kerberos/kerberos.h"
27 #include "auth/kerberos/kerberos_srv_keytab.h"
28
29 static void keytab_principals_free(krb5_context context, krb5_principal *set)
30 {
31         int i;
32         for (i = 0; set[i] != NULL; i++) {
33                 krb5_free_principal(context, set[i]);
34         }
35 }
36
37 static krb5_error_code principals_from_list(TALLOC_CTX *parent_ctx,
38                                         const char *samAccountName,
39                                         const char *realm,
40                                         const char **SPNs, int num_SPNs,
41                                         krb5_context context,
42                                         krb5_principal **principals_out,
43                                         const char **error_string)
44 {
45         unsigned int i;
46         krb5_error_code ret;
47         char *upper_realm;
48         TALLOC_CTX *tmp_ctx;
49         krb5_principal *principals = NULL;
50         tmp_ctx = talloc_new(parent_ctx);
51         if (!tmp_ctx) {
52                 *error_string = "Cannot allocate tmp_ctx";
53                 return ENOMEM;
54         }
55
56         if (!realm) {
57                 *error_string = "Cannot make principal without a realm";
58                 ret = EINVAL;
59                 goto done;
60         }
61
62         upper_realm = strupper_talloc(tmp_ctx, realm);
63         if (!upper_realm) {
64                 *error_string = "Cannot allocate full upper case realm";
65                 ret = ENOMEM;
66                 goto done;
67         }
68
69         principals = talloc_zero_array(tmp_ctx, krb5_principal,
70                                         num_SPNs ? (num_SPNs + 2) : 2);
71
72         for (i = 0; num_SPNs && i < num_SPNs; i++) {
73                 ret = krb5_parse_name(context, SPNs[i], &principals[i]);
74
75                 if (ret) {
76                         *error_string = smb_get_krb5_error_message(context, ret,
77                                                                    parent_ctx);
78                         goto done;
79                 }
80         }
81
82         if (samAccountName) {
83                 ret = smb_krb5_make_principal(context, &principals[i],
84                                           upper_realm, samAccountName,
85                                           NULL);
86                 if (ret) {
87                         *error_string = smb_get_krb5_error_message(context, ret,
88                                                                    parent_ctx);
89                         goto done;
90                 }
91         }
92
93 done:
94         if (ret) {
95                 keytab_principals_free(context, principals);
96         } else {
97                 *principals_out = talloc_steal(parent_ctx, principals);
98         }
99         talloc_free(tmp_ctx);
100         return ret;
101 }
102
103 static krb5_error_code salt_principal(TALLOC_CTX *parent_ctx,
104                                 const char *samAccountName,
105                                 const char *realm,
106                                 const char *saltPrincipal,
107                                 krb5_context context,
108                                 krb5_principal *salt_princ,
109                                 const char **error_string)
110 {
111
112         krb5_error_code ret;
113         char *machine_username;
114         char *salt_body;
115         char *lower_realm;
116         char *upper_realm;
117
118         TALLOC_CTX *tmp_ctx;
119
120         if (saltPrincipal) {
121                 ret = krb5_parse_name(context, saltPrincipal, salt_princ);
122                 if (ret) {
123                         *error_string = smb_get_krb5_error_message(
124                                                 context, ret, parent_ctx);
125                 }
126                 return ret;
127         }
128
129         if (!samAccountName) {
130                 (*error_string) = "Cannot determine salt principal, no "
131                                 "saltPrincipal or samAccountName specified";
132                 return EINVAL;
133         }
134
135         if (!realm) {
136                 *error_string = "Cannot make principal without a realm";
137                 return EINVAL;
138         }
139
140         tmp_ctx = talloc_new(parent_ctx);
141         if (!tmp_ctx) {
142                 *error_string = "Cannot allocate tmp_ctx";
143                 return ENOMEM;
144         }
145
146         machine_username = strlower_talloc(tmp_ctx, samAccountName);
147         if (!machine_username) {
148                 *error_string = "Cannot duplicate samAccountName";
149                 talloc_free(tmp_ctx);
150                 return ENOMEM;
151         }
152
153         if (machine_username[strlen(machine_username)-1] == '$') {
154                 machine_username[strlen(machine_username)-1] = '\0';
155         }
156
157         lower_realm = strlower_talloc(tmp_ctx, realm);
158         if (!lower_realm) {
159                 *error_string = "Cannot allocate to lower case realm";
160                 talloc_free(tmp_ctx);
161                 return ENOMEM;
162         }
163
164         upper_realm = strupper_talloc(tmp_ctx, realm);
165         if (!upper_realm) {
166                 *error_string = "Cannot allocate to upper case realm";
167                 talloc_free(tmp_ctx);
168                 return ENOMEM;
169         }
170
171         salt_body = talloc_asprintf(tmp_ctx, "%s.%s",
172                                     machine_username, lower_realm);
173         if (!salt_body) {
174                 *error_string = "Cannot form salt principal body";
175                 talloc_free(tmp_ctx);
176                 return ENOMEM;
177         }
178
179         ret = smb_krb5_make_principal(context, salt_princ, upper_realm,
180                                                 "host", salt_body, NULL);
181         if (ret) {
182                 *error_string = smb_get_krb5_error_message(context,
183                                                            ret, parent_ctx);
184         }
185
186         talloc_free(tmp_ctx);
187         return ret;
188 }
189
190 static krb5_error_code keytab_add_keys(TALLOC_CTX *parent_ctx,
191                                        krb5_principal *principals,
192                                        krb5_principal salt_princ,
193                                        int kvno,
194                                        const char *password_s,
195                                        krb5_context context,
196                                        krb5_enctype *enctypes,
197                                        krb5_keytab keytab,
198                                        const char **error_string)
199 {
200         unsigned int i, p;
201         krb5_error_code ret;
202         krb5_data password;
203         char *unparsed;
204
205         password.data = discard_const_p(char, password_s);
206         password.length = strlen(password_s);
207
208         for (i = 0; enctypes[i]; i++) {
209                 krb5_keytab_entry entry;
210
211                 ZERO_STRUCT(entry);
212
213                 ret = smb_krb5_create_key_from_string(context,
214                                                       &salt_princ,
215                                                       NULL,
216                                                       &password,
217                                                       enctypes[i],
218                                                       KRB5_KT_KEY(&entry));
219                 if (ret != 0) {
220                         return ret;
221                 }
222
223                 entry.vno = kvno;
224
225                 for (p = 0; principals[p]; p++) {
226                         unparsed = NULL;
227                         entry.principal = principals[p];
228                         ret = krb5_kt_add_entry(context, keytab, &entry);
229                         if (ret != 0) {
230                                 char *k5_error_string =
231                                         smb_get_krb5_error_message(context,
232                                                                    ret, NULL);
233                                 krb5_unparse_name(context,
234                                                 principals[p], &unparsed);
235                                 *error_string = talloc_asprintf(parent_ctx,
236                                         "Failed to add enctype %d entry for "
237                                         "%s(kvno %d) to keytab: %s\n",
238                                         (int)enctypes[i], unparsed,
239                                         kvno, k5_error_string);
240
241                                 free(unparsed);
242                                 talloc_free(k5_error_string);
243                                 krb5_free_keyblock_contents(context,
244                                                             KRB5_KT_KEY(&entry));
245                                 return ret;
246                         }
247
248                         DEBUG(5, ("Added key (kvno %d) to keytab (enctype %d)\n",
249                                   kvno, (int)enctypes[i]));
250                 }
251                 krb5_free_keyblock_contents(context, KRB5_KT_KEY(&entry));
252         }
253         return 0;
254 }
255
256 static krb5_error_code create_keytab(TALLOC_CTX *parent_ctx,
257                                      const char *samAccountName,
258                                      const char *realm,
259                                      const char *saltPrincipal,
260                                      int kvno,
261                                      const char *new_secret,
262                                      const char *old_secret,
263                                      uint32_t supp_enctypes,
264                                      krb5_principal *principals,
265                                      krb5_context context,
266                                      krb5_keytab keytab,
267                                      bool add_old,
268                                      const char **error_string)
269 {
270         krb5_error_code ret;
271         krb5_principal salt_princ = NULL;
272         krb5_enctype *enctypes;
273         TALLOC_CTX *mem_ctx;
274
275         if (!new_secret) {
276                 /* There is no password here, so nothing to do */
277                 return 0;
278         }
279
280         mem_ctx = talloc_new(parent_ctx);
281         if (!mem_ctx) {
282                 *error_string = talloc_strdup(parent_ctx,
283                         "unable to allocate tmp_ctx for create_keytab");
284                 return ENOMEM;
285         }
286
287         /* The salt used to generate these entries may be different however,
288          * fetch that */
289         ret = salt_principal(mem_ctx, samAccountName, realm, saltPrincipal,
290                              context, &salt_princ, error_string);
291         if (ret) {
292                 talloc_free(mem_ctx);
293                 return ret;
294         }
295
296         ret = ms_suptypes_to_ietf_enctypes(mem_ctx, supp_enctypes, &enctypes);
297         if (ret) {
298                 *error_string = talloc_asprintf(parent_ctx,
299                                         "create_keytab: generating list of "
300                                         "encryption types failed (%s)\n",
301                                         smb_get_krb5_error_message(context,
302                                                                 ret, mem_ctx));
303                 goto done;
304         }
305
306         ret = keytab_add_keys(mem_ctx, principals,
307                               salt_princ, kvno, new_secret,
308                               context, enctypes, keytab, error_string);
309         if (ret) {
310                 talloc_steal(parent_ctx, *error_string);
311                 goto done;
312         }
313
314         if (old_secret && add_old && kvno != 0) {
315                 ret = keytab_add_keys(mem_ctx, principals,
316                                       salt_princ, kvno - 1, old_secret,
317                                       context, enctypes, keytab, error_string);
318                 if (ret) {
319                         talloc_steal(parent_ctx, *error_string);
320                 }
321         }
322
323 done:
324         krb5_free_principal(context, salt_princ);
325         talloc_free(mem_ctx);
326         return ret;
327 }
328
329 /*
330  * Walk the keytab, looking for entries of this principal name,
331  * with KVNO other than current kvno -1.
332  *
333  * These entries are now stale,
334  * we only keep the current and previous entries around.
335  *
336  * Inspired by the code in Samba3 for 'use kerberos keytab'.
337  */
338
339 static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
340                                           int kvno,
341                                           krb5_principal *principals,
342                                           bool delete_all_kvno,
343                                           krb5_context context,
344                                           krb5_keytab keytab,
345                                           bool *found_previous,
346                                           const char **error_string)
347 {
348         krb5_error_code ret, ret2;
349         krb5_kt_cursor cursor;
350         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
351
352         if (!mem_ctx) {
353                 return ENOMEM;
354         }
355
356         *found_previous = false;
357
358         /* for each entry in the keytab */
359         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
360         switch (ret) {
361         case 0:
362                 break;
363 #ifdef HEIM_ERR_OPNOTSUPP
364         case HEIM_ERR_OPNOTSUPP:
365 #endif
366         case ENOENT:
367         case KRB5_KT_END:
368                 /* no point enumerating if there isn't anything here */
369                 talloc_free(mem_ctx);
370                 return 0;
371         default:
372                 *error_string = talloc_asprintf(parent_ctx,
373                         "failed to open keytab for read of old entries: %s\n",
374                         smb_get_krb5_error_message(context, ret, mem_ctx));
375                 talloc_free(mem_ctx);
376                 return ret;
377         }
378
379         while (!ret) {
380                 unsigned int i;
381                 bool matched = false;
382                 krb5_keytab_entry entry;
383
384                 ret = krb5_kt_next_entry(context, keytab, &entry, &cursor);
385                 if (ret) {
386                         break;
387                 }
388                 for (i = 0; principals[i]; i++) {
389                         /* if it matches our principal */
390                         if (smb_krb5_kt_compare(context, &entry,
391                                                 principals[i], 0, 0)) {
392                                 matched = true;
393                                 break;
394                         }
395                 }
396
397                 if (!matched) {
398                         /* Free the entry,
399                          * it wasn't the one we were looking for anyway */
400                         krb5_kt_free_entry(context, &entry);
401                         /* Make sure we do not double free */
402                         ZERO_STRUCT(entry);
403                         continue;
404                 }
405
406                 /* delete it, if it is not kvno -1 */
407                 if (entry.vno != (kvno - 1 )) {
408                         /* Release the enumeration.  We are going to
409                          * have to start this from the top again,
410                          * because deletes during enumeration may not
411                          * always be consistent.
412                          *
413                          * Also, the enumeration locks a FILE: keytab
414                          */
415
416                         krb5_kt_end_seq_get(context, keytab, &cursor);
417
418                         ret = krb5_kt_remove_entry(context, keytab, &entry);
419                         krb5_kt_free_entry(context, &entry);
420                         /* Make sure we do not double free */
421                         ZERO_STRUCT(entry);
422
423                         /* Deleted: Restart from the top */
424                         ret2 = krb5_kt_start_seq_get(context, keytab, &cursor);
425                         if (ret2) {
426                                 krb5_kt_free_entry(context, &entry);
427                                 /* Make sure we do not double free */
428                                 ZERO_STRUCT(entry);
429                                 DEBUG(1, ("failed to restart enumeration of keytab: %s\n",
430                                           smb_get_krb5_error_message(context,
431                                                                 ret, mem_ctx)));
432
433                                 talloc_free(mem_ctx);
434                                 return ret2;
435                         }
436
437                         if (ret) {
438                                 break;
439                         }
440
441                 } else {
442                         *found_previous = true;
443                 }
444
445                 /* Free the entry, we don't need it any more */
446                 krb5_kt_free_entry(context, &entry);
447                 /* Make sure we do not double free */
448                 ZERO_STRUCT(entry);
449         }
450         krb5_kt_end_seq_get(context, keytab, &cursor);
451
452         switch (ret) {
453         case 0:
454                 break;
455         case ENOENT:
456         case KRB5_KT_END:
457                 ret = 0;
458                 break;
459         default:
460                 *error_string = talloc_asprintf(parent_ctx,
461                         "failed in deleting old entries for principal: %s\n",
462                         smb_get_krb5_error_message(context, ret, mem_ctx));
463         }
464         talloc_free(mem_ctx);
465         return ret;
466 }
467
468 krb5_error_code smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
469                                 krb5_context context,
470                                 const char *keytab_name,
471                                 const char *samAccountName,
472                                 const char *realm,
473                                 const char **SPNs,
474                                 int num_SPNs,
475                                 const char *saltPrincipal,
476                                 const char *new_secret,
477                                 const char *old_secret,
478                                 int kvno,
479                                 uint32_t supp_enctypes,
480                                 bool delete_all_kvno,
481                                 krb5_keytab *_keytab,
482                                 const char **error_string)
483 {
484         krb5_keytab keytab;
485         krb5_error_code ret;
486         bool found_previous;
487         TALLOC_CTX *tmp_ctx;
488         krb5_principal *principals = NULL;
489
490         if (keytab_name == NULL) {
491                 return ENOENT;
492         }
493
494         ret = krb5_kt_resolve(context, keytab_name, &keytab);
495         if (ret) {
496                 *error_string = smb_get_krb5_error_message(context,
497                                                            ret, parent_ctx);
498                 return ret;
499         }
500
501         DEBUG(5, ("Opened keytab %s\n", keytab_name));
502
503         tmp_ctx = talloc_new(parent_ctx);
504         if (!tmp_ctx) {
505                 return ENOMEM;
506         }
507
508         /* Get the principal we will store the new keytab entries under */
509         ret = principals_from_list(tmp_ctx,
510                                   samAccountName, realm, SPNs, num_SPNs,
511                                   context, &principals, error_string);
512
513         if (ret != 0) {
514                 *error_string = talloc_asprintf(parent_ctx,
515                         "Failed to load principals from ldb message: %s\n",
516                         *error_string);
517                 goto done;
518         }
519
520         ret = remove_old_entries(tmp_ctx, kvno, principals, delete_all_kvno,
521                                  context, keytab, &found_previous, error_string);
522         if (ret != 0) {
523                 *error_string = talloc_asprintf(parent_ctx,
524                         "Failed to remove old principals from keytab: %s\n",
525                         *error_string);
526                 goto done;
527         }
528
529         if (!delete_all_kvno) {
530                 /* Create a new keytab.  If during the cleanout we found
531                  * entires for kvno -1, then don't try and duplicate them.
532                  * Otherwise, add kvno, and kvno -1 */
533
534                 ret = create_keytab(tmp_ctx,
535                                     samAccountName, realm, saltPrincipal,
536                                     kvno, new_secret, old_secret,
537                                     supp_enctypes, principals,
538                                     context, keytab,
539                                     found_previous ? false : true,
540                                     error_string);
541                 if (ret) {
542                         talloc_steal(parent_ctx, *error_string);
543                 }
544         }
545
546         if (ret == 0 && _keytab != NULL) {
547                 /* caller wants the keytab handle back */
548                 *_keytab = keytab;
549         }
550
551 done:
552         keytab_principals_free(context, principals);
553         if (ret != 0 || _keytab == NULL) {
554                 krb5_kt_close(context, keytab);
555         }
556         talloc_free(tmp_ctx);
557         return ret;
558 }
559
560 krb5_error_code smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
561                                 krb5_context context,
562                                 const char *new_secret,
563                                 const char *samAccountName,
564                                 const char *realm,
565                                 int kvno,
566                                 krb5_keytab *keytab,
567                                 const char **keytab_name)
568 {
569         krb5_error_code ret;
570         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
571         const char *rand_string;
572         const char *error_string;
573         if (!mem_ctx) {
574                 return ENOMEM;
575         }
576
577         rand_string = generate_random_str(mem_ctx, 16);
578         if (!rand_string) {
579                 talloc_free(mem_ctx);
580                 return ENOMEM;
581         }
582
583         *keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", rand_string);
584         if (*keytab_name == NULL) {
585                 talloc_free(mem_ctx);
586                 return ENOMEM;
587         }
588
589
590         ret = smb_krb5_update_keytab(mem_ctx, context,
591                                      *keytab_name, samAccountName, realm,
592                                      NULL, 0, NULL, new_secret, NULL,
593                                      kvno, ENC_ALL_TYPES,
594                                      false, keytab, &error_string);
595         if (ret == 0) {
596                 talloc_steal(parent_ctx, *keytab_name);
597         } else {
598                 DEBUG(0, ("Failed to create in-memory keytab: %s\n",
599                           error_string));
600                 *keytab_name = NULL;
601         }
602         talloc_free(mem_ctx);
603         return ret;
604 }