s4-auth-krb: Fix talloc access after free in smb_krb5_update_keytab
[samba.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 = talloc_strdup(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 = create_kerberos_key_from_string_direct(context,
214                                                 salt_princ, &password,
215                                                 KRB5_KT_KEY(&entry),
216                                                 enctypes[i]);
217                 if (ret != 0) {
218                         return ret;
219                 }
220
221                 entry.vno = kvno;
222
223                 for (p = 0; principals[p]; p++) {
224                         unparsed = NULL;
225                         entry.principal = principals[p];
226                         ret = krb5_kt_add_entry(context, keytab, &entry);
227                         if (ret != 0) {
228                                 char *k5_error_string =
229                                         smb_get_krb5_error_message(context,
230                                                                    ret, NULL);
231                                 krb5_unparse_name(context,
232                                                 principals[p], &unparsed);
233                                 *error_string = talloc_asprintf(parent_ctx,
234                                         "Failed to add enctype %d entry for "
235                                         "%s(kvno %d) to keytab: %s\n",
236                                         (int)enctypes[i], unparsed,
237                                         kvno, k5_error_string);
238
239                                 free(unparsed);
240                                 talloc_free(k5_error_string);
241                                 krb5_free_keyblock_contents(context,
242                                                             KRB5_KT_KEY(&entry));
243                                 return ret;
244                         }
245
246                         DEBUG(5, ("Added key (kvno %d) to keytab (enctype %d)\n",
247                                   kvno, (int)enctypes[i]));
248                 }
249                 krb5_free_keyblock_contents(context, KRB5_KT_KEY(&entry));
250         }
251         return 0;
252 }
253
254 static krb5_error_code create_keytab(TALLOC_CTX *parent_ctx,
255                                      const char *samAccountName,
256                                      const char *realm,
257                                      const char *saltPrincipal,
258                                      int kvno,
259                                      const char *new_secret,
260                                      const char *old_secret,
261                                      uint32_t supp_enctypes,
262                                      krb5_principal *principals,
263                                      krb5_context context,
264                                      krb5_keytab keytab,
265                                      bool add_old,
266                                      const char **error_string)
267 {
268         krb5_error_code ret;
269         krb5_principal salt_princ = NULL;
270         krb5_enctype *enctypes;
271         TALLOC_CTX *mem_ctx;
272
273         if (!new_secret) {
274                 /* There is no password here, so nothing to do */
275                 return 0;
276         }
277
278         mem_ctx = talloc_new(parent_ctx);
279         if (!mem_ctx) {
280                 *error_string = talloc_strdup(parent_ctx,
281                         "unable to allocate tmp_ctx for create_keytab");
282                 return ENOMEM;
283         }
284
285         /* The salt used to generate these entries may be different however,
286          * fetch that */
287         ret = salt_principal(mem_ctx, samAccountName, realm, saltPrincipal,
288                              context, &salt_princ, error_string);
289         if (ret) {
290                 talloc_free(mem_ctx);
291                 return ret;
292         }
293
294         ret = ms_suptypes_to_ietf_enctypes(mem_ctx, supp_enctypes, &enctypes);
295         if (ret) {
296                 *error_string = talloc_asprintf(parent_ctx,
297                                         "create_keytab: generating list of "
298                                         "encryption types failed (%s)\n",
299                                         smb_get_krb5_error_message(context,
300                                                                 ret, mem_ctx));
301                 goto done;
302         }
303
304         ret = keytab_add_keys(mem_ctx, principals,
305                               salt_princ, kvno, new_secret,
306                               context, enctypes, keytab, error_string);
307         if (ret) {
308                 talloc_steal(parent_ctx, *error_string);
309                 goto done;
310         }
311
312         if (old_secret && add_old && kvno != 0) {
313                 ret = keytab_add_keys(mem_ctx, principals,
314                                       salt_princ, kvno - 1, old_secret,
315                                       context, enctypes, keytab, error_string);
316                 if (ret) {
317                         talloc_steal(parent_ctx, *error_string);
318                 }
319         }
320
321 done:
322         krb5_free_principal(context, salt_princ);
323         talloc_free(mem_ctx);
324         return ret;
325 }
326
327 /*
328  * Walk the keytab, looking for entries of this principal name,
329  * with KVNO other than current kvno -1.
330  *
331  * These entries are now stale,
332  * we only keep the current and previous entries around.
333  *
334  * Inspired by the code in Samba3 for 'use kerberos keytab'.
335  */
336
337 static krb5_error_code remove_old_entries(TALLOC_CTX *parent_ctx,
338                                           int kvno,
339                                           krb5_principal *principals,
340                                           bool delete_all_kvno,
341                                           krb5_context context,
342                                           krb5_keytab keytab,
343                                           bool *found_previous,
344                                           const char **error_string)
345 {
346         krb5_error_code ret, ret2;
347         krb5_kt_cursor cursor;
348         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
349
350         if (!mem_ctx) {
351                 return ENOMEM;
352         }
353
354         *found_previous = false;
355
356         /* for each entry in the keytab */
357         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
358         switch (ret) {
359         case 0:
360                 break;
361 #ifdef HEIM_ERR_OPNOTSUPP
362         case HEIM_ERR_OPNOTSUPP:
363 #endif
364         case ENOENT:
365         case KRB5_KT_END:
366                 /* no point enumerating if there isn't anything here */
367                 talloc_free(mem_ctx);
368                 return 0;
369         default:
370                 *error_string = talloc_asprintf(parent_ctx,
371                         "failed to open keytab for read of old entries: %s\n",
372                         smb_get_krb5_error_message(context, ret, mem_ctx));
373                 talloc_free(mem_ctx);
374                 return ret;
375         }
376
377         while (!ret) {
378                 unsigned int i;
379                 bool matched = false;
380                 krb5_keytab_entry entry;
381                 ret = krb5_kt_next_entry(context, keytab, &entry, &cursor);
382                 if (ret) {
383                         break;
384                 }
385                 for (i = 0; principals[i]; i++) {
386                         /* if it matches our principal */
387                         if (smb_krb5_kt_compare(context, &entry,
388                                                 principals[i], 0, 0)) {
389                                 matched = true;
390                                 break;
391                         }
392                 }
393
394                 if (!matched) {
395                         /* Free the entry,
396                          * it wasn't the one we were looking for anyway */
397                         krb5_kt_free_entry(context, &entry);
398                         continue;
399                 }
400
401                 /* delete it, if it is not kvno -1 */
402                 if (entry.vno != (kvno - 1 )) {
403                         /* Release the enumeration.  We are going to
404                          * have to start this from the top again,
405                          * because deletes during enumeration may not
406                          * always be consistent.
407                          *
408                          * Also, the enumeration locks a FILE: keytab
409                          */
410
411                         krb5_kt_end_seq_get(context, keytab, &cursor);
412
413                         ret = krb5_kt_remove_entry(context, keytab, &entry);
414                         krb5_kt_free_entry(context, &entry);
415
416                         /* Deleted: Restart from the top */
417                         ret2 = krb5_kt_start_seq_get(context, keytab, &cursor);
418                         if (ret2) {
419                                 krb5_kt_free_entry(context, &entry);
420                                 DEBUG(1, ("failed to restart enumeration of keytab: %s\n",
421                                           smb_get_krb5_error_message(context,
422                                                                 ret, mem_ctx)));
423
424                                 talloc_free(mem_ctx);
425                                 return ret2;
426                         }
427
428                         if (ret) {
429                                 break;
430                         }
431
432                 } else {
433                         *found_previous = true;
434                 }
435
436                 /* Free the entry, we don't need it any more */
437                 krb5_kt_free_entry(context, &entry);
438         }
439         krb5_kt_end_seq_get(context, keytab, &cursor);
440
441         switch (ret) {
442         case 0:
443                 break;
444         case ENOENT:
445         case KRB5_KT_END:
446                 ret = 0;
447                 break;
448         default:
449                 *error_string = talloc_asprintf(parent_ctx,
450                         "failed in deleting old entries for principal: %s\n",
451                         smb_get_krb5_error_message(context, ret, mem_ctx));
452         }
453         talloc_free(mem_ctx);
454         return ret;
455 }
456
457 krb5_error_code smb_krb5_update_keytab(TALLOC_CTX *parent_ctx,
458                                 krb5_context context,
459                                 const char *keytab_name,
460                                 const char *samAccountName,
461                                 const char *realm,
462                                 const char **SPNs,
463                                 int num_SPNs,
464                                 const char *saltPrincipal,
465                                 const char *new_secret,
466                                 const char *old_secret,
467                                 int kvno,
468                                 uint32_t supp_enctypes,
469                                 bool delete_all_kvno,
470                                 krb5_keytab *_keytab,
471                                 const char **error_string)
472 {
473         krb5_keytab keytab;
474         krb5_error_code ret;
475         bool found_previous;
476         TALLOC_CTX *tmp_ctx;
477         krb5_principal *principals = NULL;
478
479         if (keytab_name == NULL) {
480                 return ENOENT;
481         }
482
483         ret = krb5_kt_resolve(context, keytab_name, &keytab);
484         if (ret) {
485                 *error_string = smb_get_krb5_error_message(context,
486                                                            ret, parent_ctx);
487                 return ret;
488         }
489
490         DEBUG(5, ("Opened keytab %s\n", keytab_name));
491
492         tmp_ctx = talloc_new(parent_ctx);
493         if (!tmp_ctx) {
494                 return ENOMEM;
495         }
496
497         /* Get the principal we will store the new keytab entries under */
498         ret = principals_from_list(tmp_ctx,
499                                   samAccountName, realm, SPNs, num_SPNs,
500                                   context, &principals, error_string);
501
502         if (ret != 0) {
503                 *error_string = talloc_asprintf(parent_ctx,
504                         "Failed to load principals from ldb message: %s\n",
505                         *error_string);
506                 goto done;
507         }
508
509         ret = remove_old_entries(tmp_ctx, kvno, principals, delete_all_kvno,
510                                  context, keytab, &found_previous, error_string);
511         if (ret != 0) {
512                 *error_string = talloc_asprintf(parent_ctx,
513                         "Failed to remove old principals from keytab: %s\n",
514                         *error_string);
515                 goto done;
516         }
517
518         if (!delete_all_kvno) {
519                 /* Create a new keytab.  If during the cleanout we found
520                  * entires for kvno -1, then don't try and duplicate them.
521                  * Otherwise, add kvno, and kvno -1 */
522
523                 ret = create_keytab(tmp_ctx,
524                                     samAccountName, realm, saltPrincipal,
525                                     kvno, new_secret, old_secret,
526                                     supp_enctypes, principals,
527                                     context, keytab,
528                                     found_previous ? false : true,
529                                     error_string);
530                 if (ret) {
531                         talloc_steal(parent_ctx, *error_string);
532                 }
533         }
534
535         if (ret == 0 && _keytab != NULL) {
536                 /* caller wants the keytab handle back */
537                 *_keytab = keytab;
538         }
539
540 done:
541         keytab_principals_free(context, principals);
542         if (ret != 0 || _keytab == NULL) {
543                 krb5_kt_close(context, keytab);
544         }
545         talloc_free(tmp_ctx);
546         return ret;
547 }
548
549 krb5_error_code smb_krb5_create_memory_keytab(TALLOC_CTX *parent_ctx,
550                                 krb5_context context,
551                                 const char *new_secret,
552                                 const char *samAccountName,
553                                 const char *realm,
554                                 int kvno,
555                                 krb5_keytab *keytab,
556                                 const char **keytab_name)
557 {
558         krb5_error_code ret;
559         TALLOC_CTX *mem_ctx = talloc_new(parent_ctx);
560         const char *rand_string;
561         const char *error_string;
562         if (!mem_ctx) {
563                 return ENOMEM;
564         }
565
566         rand_string = generate_random_str(mem_ctx, 16);
567         if (!rand_string) {
568                 talloc_free(mem_ctx);
569                 return ENOMEM;
570         }
571
572         *keytab_name = talloc_asprintf(mem_ctx, "MEMORY:%s", rand_string);
573         if (*keytab_name == NULL) {
574                 talloc_free(mem_ctx);
575                 return ENOMEM;
576         }
577
578
579         ret = smb_krb5_update_keytab(mem_ctx, context,
580                                      *keytab_name, samAccountName, realm,
581                                      NULL, 0, NULL, new_secret, NULL,
582                                      kvno, ENC_ALL_TYPES,
583                                      false, keytab, &error_string);
584         if (ret == 0) {
585                 talloc_steal(parent_ctx, *keytab_name);
586         } else {
587                 DEBUG(0, ("Failed to create in-memory keytab: %s\n",
588                           error_string));
589                 *keytab_name = NULL;
590         }
591         talloc_free(mem_ctx);
592         return ret;
593 }