7bb7e7e813c02ec02a9b76c53eb863504cf98d16
[samba.git] / source3 / libads / kerberos_keytab.c
1 /*
2    Unix SMB/CIFS implementation.
3    kerberos keytab utility library
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Remus Koos 2001
6    Copyright (C) Luke Howard 2003
7    Copyright (C) Jim McDonough (jmcd@us.ibm.com) 2003
8    Copyright (C) Guenther Deschner 2003
9    Copyright (C) Rakesh Patel 2004
10    Copyright (C) Dan Perry 2004
11    Copyright (C) Jeremy Allison 2004
12    Copyright (C) Gerald Carter 2006
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.
26 */
27
28 #include "includes.h"
29 #include "smb_krb5.h"
30 #include "ads.h"
31 #include "secrets.h"
32
33 #ifdef HAVE_KRB5
34
35 #ifdef HAVE_ADS
36
37 /* This MAX_NAME_LEN is a constant defined in krb5.h */
38 #ifndef MAX_KEYTAB_NAME_LEN
39 #define MAX_KEYTAB_NAME_LEN 1100
40 #endif
41
42 static krb5_error_code ads_keytab_open(krb5_context context,
43                                        krb5_keytab *keytab)
44 {
45         char keytab_str[MAX_KEYTAB_NAME_LEN] = {0};
46         const char *keytab_name = NULL;
47         krb5_error_code ret = 0;
48
49         switch (lp_kerberos_method()) {
50         case KERBEROS_VERIFY_SYSTEM_KEYTAB:
51         case KERBEROS_VERIFY_SECRETS_AND_KEYTAB:
52                 ret = krb5_kt_default_name(context,
53                                            keytab_str,
54                                            sizeof(keytab_str) - 2);
55                 if (ret != 0) {
56                         DBG_WARNING("Failed to get default keytab name");
57                         goto out;
58                 }
59                 keytab_name = keytab_str;
60                 break;
61         case KERBEROS_VERIFY_DEDICATED_KEYTAB:
62                 keytab_name = lp_dedicated_keytab_file();
63                 break;
64         default:
65                 DBG_ERR("Invalid kerberos method set (%d)\n",
66                         lp_kerberos_method());
67                 ret = KRB5_KT_BADNAME;
68                 goto out;
69         }
70
71         if (keytab_name == NULL || keytab_name[0] == '\0') {
72                 DBG_ERR("Invalid keytab name\n");
73                 ret = KRB5_KT_BADNAME;
74                 goto out;
75         }
76
77         ret = smb_krb5_kt_open(context, keytab_name, true, keytab);
78         if (ret != 0) {
79                 DBG_WARNING("smb_krb5_kt_open failed (%s)\n",
80                             error_message(ret));
81                 goto out;
82         }
83
84 out:
85         return ret;
86 }
87
88 static bool fill_default_spns(TALLOC_CTX *ctx, const char *machine_name,
89                                           const char *my_fqdn, const char *spn,
90                                           const char ***spns)
91 {
92         char *psp1, *psp2;
93
94         if (*spns == NULL) {
95                 *spns = talloc_zero_array(ctx, const char*, 3);
96                 if (*spns == NULL) {
97                         return false;
98                 }
99         }
100
101         psp1 = talloc_asprintf(ctx,
102                                "%s/%s",
103                                spn,
104                                machine_name);
105         if (psp1 == NULL) {
106                 return false;
107         }
108
109         if (!strlower_m(&psp1[strlen(spn) + 1])) {
110                 return false;
111         }
112         (*spns)[0] = psp1;
113
114         psp2 = talloc_asprintf(ctx,
115                                "%s/%s",
116                                spn,
117                                my_fqdn);
118         if (psp2 == NULL) {
119                 return false;
120         }
121
122         if (!strlower_m(&psp2[strlen(spn) + 1])) {
123                 return false;
124         }
125
126         (*spns)[1] = psp2;
127
128         return true;
129 }
130
131 static bool ads_set_machine_account_spns(TALLOC_CTX *ctx,
132                                          ADS_STRUCT *ads,
133                                          const char *service_or_spn,
134                                          const char *my_fqdn)
135 {
136         const char **spn_names = NULL;
137         ADS_STATUS aderr;
138         struct spn_struct* spn_struct = NULL;
139         char *tmp = NULL;
140
141         /* SPN should have '/' */
142         tmp = strchr_m(service_or_spn, '/');
143         if (tmp != NULL) {
144                 spn_struct = parse_spn(ctx, service_or_spn);
145                 if (spn_struct == NULL) {
146                         return false;
147                 }
148         }
149
150         DBG_INFO("Attempting to add/update '%s'\n", service_or_spn);
151
152         if (spn_struct != NULL) {
153                 spn_names = talloc_zero_array(ctx, const char*, 2);
154                 spn_names[0] = service_or_spn;
155         } else {
156                 bool ok;
157
158                 ok = fill_default_spns(ctx,
159                                        lp_netbios_name(),
160                                        my_fqdn,
161                                        service_or_spn,
162                                        &spn_names);
163                 if (!ok) {
164                         return false;
165                 }
166         }
167         aderr = ads_add_service_principal_names(ads,
168                                                 lp_netbios_name(),
169                                                 spn_names);
170         if (!ADS_ERR_OK(aderr)) {
171                 DBG_WARNING("Failed to add service principal name.\n");
172                 return false;
173         }
174
175         return true;
176 }
177
178 /*
179  * Create kerberos principal(s) from SPN or service name.
180  */
181 static bool service_or_spn_to_kerberos_princ(TALLOC_CTX *ctx,
182                                              const char *service_or_spn,
183                                              const char *my_fqdn,
184                                              char **p_princ_s,
185                                              char **p_short_princ_s)
186 {
187         char *princ_s = NULL;
188         char *short_princ_s = NULL;
189         const char *service = service_or_spn;
190         const char *host = my_fqdn;
191         struct spn_struct* spn_struct = NULL;
192         char *tmp = NULL;
193         bool ok = true;
194
195         /* SPN should have '/' */
196         tmp = strchr_m(service_or_spn, '/');
197         if (tmp != NULL) {
198                 spn_struct = parse_spn(ctx, service_or_spn);
199                 if (spn_struct == NULL) {
200                         ok = false;
201                         goto out;
202                 }
203         }
204         if (spn_struct != NULL) {
205                 service = spn_struct->serviceclass;
206                 host = spn_struct->host;
207         }
208         princ_s = talloc_asprintf(ctx, "%s/%s@%s",
209                                   service,
210                                   host, lp_realm());
211         if (princ_s == NULL) {
212                 ok = false;
213                 goto out;
214         }
215
216         if (spn_struct == NULL) {
217                 short_princ_s = talloc_asprintf(ctx, "%s/%s@%s",
218                                         service, lp_netbios_name(),
219                                         lp_realm());
220                 if (short_princ_s == NULL) {
221                         ok = false;
222                         goto out;
223                 }
224         }
225         *p_princ_s = princ_s;
226         *p_short_princ_s = short_princ_s;
227 out:
228         return ok;
229 }
230
231 static int add_kt_entry_etypes(krb5_context context, TALLOC_CTX *tmpctx,
232                                ADS_STRUCT *ads, const char *salt_princ_s,
233                                krb5_keytab keytab, krb5_kvno kvno,
234                                const char *srvPrinc, const char *my_fqdn,
235                                krb5_data *password, bool update_ads)
236 {
237         krb5_error_code ret = 0;
238         char *princ_s = NULL;
239         char *short_princ_s = NULL;
240         krb5_enctype enctypes[4] = {
241 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
242                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
243 #endif
244 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
245                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
246 #endif
247                 ENCTYPE_ARCFOUR_HMAC,
248                 0
249         };
250         size_t i;
251
252         /* Construct our principal */
253         if (strchr_m(srvPrinc, '@')) {
254                 /* It's a fully-named principal. */
255                 princ_s = talloc_asprintf(tmpctx, "%s", srvPrinc);
256                 if (!princ_s) {
257                         ret = -1;
258                         goto out;
259                 }
260         } else if (srvPrinc[strlen(srvPrinc)-1] == '$') {
261                 /* It's the machine account, as used by smbclient clients. */
262                 princ_s = talloc_asprintf(tmpctx, "%s@%s",
263                                           srvPrinc, lp_realm());
264                 if (!princ_s) {
265                         ret = -1;
266                         goto out;
267                 }
268         } else {
269                 /* It's a normal service principal.  Add the SPN now so that we
270                  * can obtain credentials for it and double-check the salt value
271                  * used to generate the service's keys. */
272
273                 if (!service_or_spn_to_kerberos_princ(tmpctx,
274                                                       srvPrinc,
275                                                       my_fqdn,
276                                                       &princ_s,
277                                                       &short_princ_s)) {
278                         ret = -1;
279                         goto out;
280                 }
281
282                 /* According to http://support.microsoft.com/kb/326985/en-us,
283                    certain principal names are automatically mapped to the
284                    host/... principal in the AD account.
285                    So only create these in the keytab, not in AD.  --jerry */
286
287                 if (update_ads && !strequal(srvPrinc, "cifs") &&
288                     !strequal(srvPrinc, "host")) {
289                         if (!ads_set_machine_account_spns(tmpctx,
290                                                           ads,
291                                                           srvPrinc,
292                                                           my_fqdn)) {
293                                 ret = -1;
294                                 goto out;
295                         }
296                 }
297         }
298
299         for (i = 0; enctypes[i]; i++) {
300
301                 /* add the fqdn principal to the keytab */
302                 ret = smb_krb5_kt_add_entry(context,
303                                             keytab,
304                                             kvno,
305                                             princ_s,
306                                             salt_princ_s,
307                                             enctypes[i],
308                                             password,
309                                             false); /* no_salt */
310                 if (ret) {
311                         DBG_WARNING("Failed to add entry to keytab\n");
312                         goto out;
313                 }
314
315                 /* add the short principal name if we have one */
316                 if (short_princ_s) {
317                         ret = smb_krb5_kt_add_entry(context,
318                                                     keytab,
319                                                     kvno,
320                                                     short_princ_s,
321                                                     salt_princ_s,
322                                                     enctypes[i],
323                                                     password,
324                                                     false); /* no_salt */
325                         if (ret) {
326                                 DBG_WARNING("Failed to add short entry to keytab\n");
327                                 goto out;
328                         }
329                 }
330         }
331 out:
332         return ret;
333 }
334
335 /**********************************************************************
336  Adds a single service principal, i.e. 'host' to the system keytab
337 ***********************************************************************/
338
339 int ads_keytab_add_entry(ADS_STRUCT *ads, const char *srvPrinc, bool update_ads)
340 {
341         krb5_error_code ret = 0;
342         krb5_context context = NULL;
343         krb5_keytab keytab = NULL;
344         krb5_data password;
345         krb5_kvno kvno;
346         char *salt_princ_s = NULL;
347         char *password_s = NULL;
348         char *my_fqdn;
349         TALLOC_CTX *tmpctx = NULL;
350         char **hostnames_array = NULL;
351         size_t num_hostnames = 0;
352
353         ret = smb_krb5_init_context_common(&context);
354         if (ret) {
355                 DBG_ERR("kerberos init context failed (%s)\n",
356                         error_message(ret));
357                 return -1;
358         }
359
360         ret = ads_keytab_open(context, &keytab);
361         if (ret != 0) {
362                 goto out;
363         }
364
365         /* retrieve the password */
366         if (!secrets_init()) {
367                 DBG_WARNING("secrets_init failed\n");
368                 ret = -1;
369                 goto out;
370         }
371         password_s = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
372         if (!password_s) {
373                 DBG_WARNING("failed to fetch machine password\n");
374                 ret = -1;
375                 goto out;
376         }
377         ZERO_STRUCT(password);
378         password.data = password_s;
379         password.length = strlen(password_s);
380
381         /* we need the dNSHostName value here */
382         tmpctx = talloc_init(__location__);
383         if (!tmpctx) {
384                 DBG_ERR("talloc_init() failed!\n");
385                 ret = -1;
386                 goto out;
387         }
388
389         my_fqdn = ads_get_dnshostname(ads, tmpctx, lp_netbios_name());
390         if (!my_fqdn) {
391                 DBG_ERR("unable to determine machine account's dns name in "
392                         "AD!\n");
393                 ret = -1;
394                 goto out;
395         }
396
397         /* make sure we have a single instance of a the computer account */
398         if (!ads_has_samaccountname(ads, tmpctx, lp_netbios_name())) {
399                 DBG_ERR("unable to determine machine account's short name in "
400                         "AD!\n");
401                 ret = -1;
402                 goto out;
403         }
404
405         kvno = (krb5_kvno)ads_get_machine_kvno(ads, lp_netbios_name());
406         if (kvno == -1) {
407                 /* -1 indicates failure, everything else is OK */
408                 DBG_WARNING("ads_get_machine_kvno failed to determine the "
409                             "system's kvno.\n");
410                 ret = -1;
411                 goto out;
412         }
413
414         salt_princ_s = kerberos_secrets_fetch_salt_princ();
415         if (salt_princ_s == NULL) {
416                 DBG_WARNING("kerberos_secrets_fetch_salt_princ() failed\n");
417                 ret = -1;
418                 goto out;
419         }
420
421         ret = add_kt_entry_etypes(context, tmpctx, ads, salt_princ_s, keytab,
422                                   kvno, srvPrinc, my_fqdn, &password,
423                                   update_ads);
424         if (ret != 0) {
425                 goto out;
426         }
427
428         if (ADS_ERR_OK(ads_get_additional_dns_hostnames(tmpctx, ads,
429                                                         lp_netbios_name(),
430                                                         &hostnames_array,
431                                                         &num_hostnames))) {
432                 size_t i;
433
434                 for (i = 0; i < num_hostnames; i++) {
435
436                         ret = add_kt_entry_etypes(context, tmpctx, ads,
437                                                   salt_princ_s, keytab,
438                                                   kvno, srvPrinc,
439                                                   hostnames_array[i],
440                                                   &password, update_ads);
441                         if (ret != 0) {
442                                 goto out;
443                         }
444                 }
445         }
446
447 out:
448         SAFE_FREE(salt_princ_s);
449         TALLOC_FREE(tmpctx);
450
451         if (keytab) {
452                 krb5_kt_close(context, keytab);
453         }
454         if (context) {
455                 krb5_free_context(context);
456         }
457         return (int)ret;
458 }
459
460 /**********************************************************************
461  Flushes all entries from the system keytab.
462 ***********************************************************************/
463
464 int ads_keytab_flush(ADS_STRUCT *ads)
465 {
466         krb5_error_code ret = 0;
467         krb5_context context = NULL;
468         krb5_keytab keytab = NULL;
469         krb5_kvno kvno;
470         ADS_STATUS aderr;
471
472         ret = smb_krb5_init_context_common(&context);
473         if (ret) {
474                 DBG_ERR("kerberos init context failed (%s)\n",
475                         error_message(ret));
476                 return ret;
477         }
478
479         ret = ads_keytab_open(context, &keytab);
480         if (ret != 0) {
481                 goto out;
482         }
483
484         kvno = (krb5_kvno)ads_get_machine_kvno(ads, lp_netbios_name());
485         if (kvno == -1) {
486                 /* -1 indicates a failure */
487                 DEBUG(1, (__location__ ": Error determining the kvno.\n"));
488                 ret = -1;
489                 goto out;
490         }
491
492         /* Seek and delete old keytab entries */
493         ret = smb_krb5_kt_seek_and_delete_old_entries(context,
494                                                       keytab,
495                                                       kvno,
496                                                       ENCTYPE_NULL,
497                                                       NULL,
498                                                       NULL,
499                                                       true); /* flush */
500         if (ret) {
501                 goto out;
502         }
503
504         aderr = ads_clear_service_principal_names(ads, lp_netbios_name());
505         if (!ADS_ERR_OK(aderr)) {
506                 DEBUG(1, (__location__ ": Error while clearing service "
507                           "principal listings in LDAP.\n"));
508                 ret = -1;
509                 goto out;
510         }
511
512 out:
513         if (keytab) {
514                 krb5_kt_close(context, keytab);
515         }
516         if (context) {
517                 krb5_free_context(context);
518         }
519         return ret;
520 }
521
522 /**********************************************************************
523  Adds all the required service principals to the system keytab.
524 ***********************************************************************/
525
526 int ads_keytab_create_default(ADS_STRUCT *ads)
527 {
528         krb5_error_code ret = 0;
529         krb5_context context = NULL;
530         krb5_keytab keytab = NULL;
531         krb5_kt_cursor cursor = {0};
532         krb5_keytab_entry kt_entry = {0};
533         krb5_kvno kvno;
534         size_t found = 0;
535         char *sam_account_name, *upn;
536         char **oldEntries = NULL, *princ_s[26];
537         TALLOC_CTX *frame;
538         char *machine_name;
539         char **spn_array;
540         size_t num_spns;
541         size_t i;
542         bool ok = false;
543         ADS_STATUS status;
544
545         ZERO_STRUCT(kt_entry);
546         ZERO_STRUCT(cursor);
547
548         frame = talloc_stackframe();
549         if (frame == NULL) {
550                 ret = -1;
551                 goto done;
552         }
553
554         status = ads_get_service_principal_names(frame,
555                                                  ads,
556                                                  lp_netbios_name(),
557                                                  &spn_array,
558                                                  &num_spns);
559         if (!ADS_ERR_OK(status)) {
560                 ret = -1;
561                 goto done;
562         }
563
564         for (i = 0; i < num_spns; i++) {
565                 char *srv_princ;
566                 char *p;
567
568                 srv_princ = strlower_talloc(frame, spn_array[i]);
569                 if (srv_princ == NULL) {
570                         ret = -1;
571                         goto done;
572                 }
573
574                 p = strchr_m(srv_princ, '/');
575                 if (p == NULL) {
576                         continue;
577                 }
578                 p[0] = '\0';
579
580                 /* Add the SPNs found on the DC */
581                 ret = ads_keytab_add_entry(ads, srv_princ, false);
582                 if (ret != 0) {
583                         DEBUG(1, ("ads_keytab_add_entry failed while "
584                                   "adding '%s' principal.\n",
585                                   spn_array[i]));
586                         goto done;
587                 }
588         }
589
590 #if 0   /* don't create the CIFS/... keytab entries since no one except smbd
591            really needs them and we will fall back to verifying against
592            secrets.tdb */
593
594         ret = ads_keytab_add_entry(ads, "cifs", false));
595         if (ret != 0 ) {
596                 DEBUG(1, (__location__ ": ads_keytab_add_entry failed while "
597                           "adding 'cifs'.\n"));
598                 return ret;
599         }
600 #endif
601
602         memset(princ_s, '\0', sizeof(princ_s));
603
604         ret = smb_krb5_init_context_common(&context);
605         if (ret) {
606                 DBG_ERR("kerberos init context failed (%s)\n",
607                         error_message(ret));
608                 goto done;
609         }
610
611         machine_name = talloc_strdup(frame, lp_netbios_name());
612         if (!machine_name) {
613                 ret = -1;
614                 goto done;
615         }
616
617         /* now add the userPrincipalName and sAMAccountName entries */
618         ok = ads_has_samaccountname(ads, frame, machine_name);
619         if (!ok) {
620                 DEBUG(0, (__location__ ": unable to determine machine "
621                           "account's name in AD!\n"));
622                 ret = -1;
623                 goto done;
624         }
625
626         /*
627          * append '$' to netbios name so 'ads_keytab_add_entry' recognises
628          * it as a machine account rather than a service or Windows SPN.
629          */
630         sam_account_name = talloc_asprintf(frame, "%s$",machine_name);
631         if (sam_account_name == NULL) {
632                 ret = -1;
633                 goto done;
634         }
635         /* upper case the sAMAccountName to make it easier for apps to
636            know what case to use in the keytab file */
637         if (!strupper_m(sam_account_name)) {
638                 ret = -1;
639                 goto done;
640         }
641
642         ret = ads_keytab_add_entry(ads, sam_account_name, false);
643         if (ret != 0) {
644                 DEBUG(1, (__location__ ": ads_keytab_add_entry() failed "
645                           "while adding sAMAccountName (%s)\n",
646                           sam_account_name));
647                 goto done;
648         }
649
650         /* remember that not every machine account will have a upn */
651         upn = ads_get_upn(ads, frame, machine_name);
652         if (upn) {
653                 ret = ads_keytab_add_entry(ads, upn, false);
654                 if (ret != 0) {
655                         DEBUG(1, (__location__ ": ads_keytab_add_entry() "
656                                   "failed while adding UPN (%s)\n", upn));
657                         goto done;
658                 }
659         }
660
661         /* Now loop through the keytab and update any other existing entries */
662         kvno = (krb5_kvno)ads_get_machine_kvno(ads, machine_name);
663         if (kvno == (krb5_kvno)-1) {
664                 DEBUG(1, (__location__ ": ads_get_machine_kvno() failed to "
665                           "determine the system's kvno.\n"));
666                 goto done;
667         }
668
669         DEBUG(3, (__location__ ": Searching for keytab entries to preserve "
670                   "and update.\n"));
671
672         ret = ads_keytab_open(context, &keytab);
673         if (ret != 0) {
674                 goto done;
675         }
676
677         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
678         if (ret != KRB5_KT_END && ret != ENOENT ) {
679                 while ((ret = krb5_kt_next_entry(context, keytab,
680                                                  &kt_entry, &cursor)) == 0) {
681                         smb_krb5_kt_free_entry(context, &kt_entry);
682                         ZERO_STRUCT(kt_entry);
683                         found++;
684                 }
685         }
686         krb5_kt_end_seq_get(context, keytab, &cursor);
687         ZERO_STRUCT(cursor);
688
689         /*
690          * Hmmm. There is no "rewind" function for the keytab. This means we
691          * have a race condition where someone else could add entries after
692          * we've counted them. Re-open asap to minimise the race. JRA.
693          */
694         DEBUG(3, (__location__ ": Found %zd entries in the keytab.\n", found));
695         if (!found) {
696                 goto done;
697         }
698
699         oldEntries = talloc_zero_array(frame, char *, found + 1);
700         if (!oldEntries) {
701                 DEBUG(1, (__location__ ": Failed to allocate space to store "
702                           "the old keytab entries (talloc failed?).\n"));
703                 ret = -1;
704                 goto done;
705         }
706
707         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
708         if (ret == KRB5_KT_END || ret == ENOENT) {
709                 krb5_kt_end_seq_get(context, keytab, &cursor);
710                 ZERO_STRUCT(cursor);
711                 goto done;
712         }
713
714         while (krb5_kt_next_entry(context, keytab, &kt_entry, &cursor) == 0) {
715                 if (kt_entry.vno != kvno) {
716                         char *ktprinc = NULL;
717                         char *p;
718
719                         /* This returns a malloc'ed string in ktprinc. */
720                         ret = smb_krb5_unparse_name(oldEntries, context,
721                                                     kt_entry.principal,
722                                                     &ktprinc);
723                         if (ret) {
724                                 DEBUG(1, (__location__
725                                          ": smb_krb5_unparse_name failed "
726                                          "(%s)\n", error_message(ret)));
727                                 goto done;
728                         }
729                         /*
730                          * From looking at the krb5 source they don't seem to
731                          * take locale or mb strings into account.
732                          * Maybe this is because they assume utf8 ?
733                          * In this case we may need to convert from utf8 to
734                          * mb charset here ? JRA.
735                          */
736                         p = strchr_m(ktprinc, '@');
737                         if (p) {
738                                 *p = '\0';
739                         }
740
741                         p = strchr_m(ktprinc, '/');
742                         if (p) {
743                                 *p = '\0';
744                         }
745                         for (i = 0; i < found; i++) {
746                                 if (!oldEntries[i]) {
747                                         oldEntries[i] = ktprinc;
748                                         break;
749                                 }
750                                 if (!strcmp(oldEntries[i], ktprinc)) {
751                                         TALLOC_FREE(ktprinc);
752                                         break;
753                                 }
754                         }
755                         if (i == found) {
756                                 TALLOC_FREE(ktprinc);
757                         }
758                 }
759                 smb_krb5_kt_free_entry(context, &kt_entry);
760                 ZERO_STRUCT(kt_entry);
761         }
762         krb5_kt_end_seq_get(context, keytab, &cursor);
763         ZERO_STRUCT(cursor);
764
765         ret = 0;
766         for (i = 0; oldEntries[i]; i++) {
767                 ret |= ads_keytab_add_entry(ads, oldEntries[i], false);
768                 TALLOC_FREE(oldEntries[i]);
769         }
770
771 done:
772         TALLOC_FREE(oldEntries);
773         TALLOC_FREE(frame);
774
775         if (context) {
776                 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
777                         smb_krb5_kt_free_entry(context, &kt_entry);
778                 }
779                 if (!all_zero((uint8_t *)&cursor, sizeof(cursor)) && keytab) {
780                         krb5_kt_end_seq_get(context, keytab, &cursor);
781                 }
782                 if (keytab) {
783                         krb5_kt_close(context, keytab);
784                 }
785                 krb5_free_context(context);
786         }
787         return ret;
788 }
789
790 #endif /* HAVE_ADS */
791
792 /**********************************************************************
793  List system keytab.
794 ***********************************************************************/
795
796 int ads_keytab_list(const char *keytab_name)
797 {
798         krb5_error_code ret = 0;
799         krb5_context context = NULL;
800         krb5_keytab keytab = NULL;
801         krb5_kt_cursor cursor;
802         krb5_keytab_entry kt_entry;
803
804         ZERO_STRUCT(kt_entry);
805         ZERO_STRUCT(cursor);
806
807         ret = smb_krb5_init_context_common(&context);
808         if (ret) {
809                 DBG_ERR("kerberos init context failed (%s)\n",
810                         error_message(ret));
811                 return ret;
812         }
813
814         if (keytab_name == NULL) {
815 #ifdef HAVE_ADS
816                 ret = ads_keytab_open(context, &keytab);
817 #else
818                 ret = ENOENT;
819 #endif
820         } else {
821                 ret = smb_krb5_kt_open(context, keytab_name, False, &keytab);
822         }
823         if (ret) {
824                 DEBUG(1, ("smb_krb5_kt_open failed (%s)\n",
825                           error_message(ret)));
826                 goto out;
827         }
828
829         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
830         if (ret) {
831                 ZERO_STRUCT(cursor);
832                 goto out;
833         }
834
835         printf("Vno  Type                                        Principal\n");
836
837         while (krb5_kt_next_entry(context, keytab, &kt_entry, &cursor) == 0) {
838
839                 char *princ_s = NULL;
840                 char *etype_s = NULL;
841                 krb5_enctype enctype = 0;
842
843                 ret = smb_krb5_unparse_name(talloc_tos(), context,
844                                             kt_entry.principal, &princ_s);
845                 if (ret) {
846                         goto out;
847                 }
848
849                 enctype = smb_krb5_kt_get_enctype_from_entry(&kt_entry);
850
851                 ret = smb_krb5_enctype_to_string(context, enctype, &etype_s);
852                 if (ret &&
853                     (asprintf(&etype_s, "UNKNOWN: %d", enctype) == -1)) {
854                         TALLOC_FREE(princ_s);
855                         goto out;
856                 }
857
858                 printf("%3d  %-43s %s\n", kt_entry.vno, etype_s, princ_s);
859
860                 TALLOC_FREE(princ_s);
861                 SAFE_FREE(etype_s);
862
863                 ret = smb_krb5_kt_free_entry(context, &kt_entry);
864                 if (ret) {
865                         goto out;
866                 }
867         }
868
869         ret = krb5_kt_end_seq_get(context, keytab, &cursor);
870         if (ret) {
871                 goto out;
872         }
873
874         /* Ensure we don't double free. */
875         ZERO_STRUCT(kt_entry);
876         ZERO_STRUCT(cursor);
877 out:
878
879         if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
880                 smb_krb5_kt_free_entry(context, &kt_entry);
881         }
882         if (!all_zero((uint8_t *)&cursor, sizeof(cursor)) && keytab) {
883                 krb5_kt_end_seq_get(context, keytab, &cursor);
884         }
885
886         if (keytab) {
887                 krb5_kt_close(context, keytab);
888         }
889         if (context) {
890                 krb5_free_context(context);
891         }
892         return ret;
893 }
894
895 #endif /* HAVE_KRB5 */