s3:libads: let kerberos_kinit_password_ext() return the canonicalized principal/realm
[samba.git] / source3 / libads / kerberos.c
1 /* 
2    Unix SMB/CIFS implementation.
3    kerberos utility library
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Remus Koos 2001
6    Copyright (C) Nalin Dahyabhai <nalin@redhat.com> 2004.
7    Copyright (C) Jeremy Allison 2004.
8    Copyright (C) Gerald Carter 2006.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "libsmb/namequery.h"
26 #include "system/filesys.h"
27 #include "smb_krb5.h"
28 #include "../librpc/gen_ndr/ndr_misc.h"
29 #include "libads/kerberos_proto.h"
30 #include "libads/cldap.h"
31 #include "secrets.h"
32 #include "../lib/tsocket/tsocket.h"
33 #include "lib/util/asn1.h"
34 #include "krb5_errs.h"
35
36 #ifdef HAVE_KRB5
37
38 #define LIBADS_CCACHE_NAME "MEMORY:libads"
39
40 /*
41   we use a prompter to avoid a crash bug in the kerberos libs when 
42   dealing with empty passwords
43   this prompter is just a string copy ...
44 */
45 static krb5_error_code 
46 kerb_prompter(krb5_context ctx, void *data,
47                const char *name,
48                const char *banner,
49                int num_prompts,
50                krb5_prompt prompts[])
51 {
52         if (num_prompts == 0) return 0;
53         if (num_prompts == 2) {
54                 /*
55                  * only heimdal has a prompt type and we need to deal with it here to
56                  * avoid loops.
57                  *
58                  * removing the prompter completely is not an option as at least these
59                  * versions would crash: heimdal-1.0.2 and heimdal-1.1. Later heimdal
60                  * version have looping detection and return with a proper error code.
61                  */
62
63 #if defined(HAVE_KRB5_PROMPT_TYPE) /* Heimdal */
64                  if (prompts[0].type == KRB5_PROMPT_TYPE_NEW_PASSWORD &&
65                      prompts[1].type == KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN) {
66                         /*
67                          * We don't want to change passwords here. We're
68                          * called from heimal when the KDC returns
69                          * KRB5KDC_ERR_KEY_EXPIRED, but at this point we don't
70                          * have the chance to ask the user for a new
71                          * password. If we return 0 (i.e. success), we will be
72                          * spinning in the endless for-loop in
73                          * change_password() in
74                          * source4/heimdal/lib/krb5/init_creds_pw.c:526ff
75                          */
76                         return KRB5KDC_ERR_KEY_EXPIRED;
77                 }
78 #elif defined(HAVE_KRB5_GET_PROMPT_TYPES) /* MIT */
79                 krb5_prompt_type *prompt_types = NULL;
80
81                 prompt_types = krb5_get_prompt_types(ctx);
82                 if (prompt_types != NULL) {
83                         if (prompt_types[0] == KRB5_PROMPT_TYPE_NEW_PASSWORD &&
84                             prompt_types[1] == KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN) {
85                                 return KRB5KDC_ERR_KEY_EXP;
86                         }
87                 }
88 #endif
89         }
90
91         memset(prompts[0].reply->data, '\0', prompts[0].reply->length);
92         if (prompts[0].reply->length > 0) {
93                 if (data) {
94                         strncpy((char *)prompts[0].reply->data, (const char *)data,
95                                 prompts[0].reply->length-1);
96                         prompts[0].reply->length = strlen((const char *)prompts[0].reply->data);
97                 } else {
98                         prompts[0].reply->length = 0;
99                 }
100         }
101         return 0;
102 }
103
104 /*
105   simulate a kinit, putting the tgt in the given cache location. If cache_name == NULL
106   place in default cache location.
107   remus@snapserver.com
108 */
109 int kerberos_kinit_password_ext(const char *given_principal,
110                                 const char *password,
111                                 int time_offset,
112                                 time_t *expire_time,
113                                 time_t *renew_till_time,
114                                 const char *cache_name,
115                                 bool request_pac,
116                                 bool add_netbios_addr,
117                                 time_t renewable_time,
118                                 TALLOC_CTX *mem_ctx,
119                                 char **_canon_principal,
120                                 char **_canon_realm,
121                                 NTSTATUS *ntstatus)
122 {
123         TALLOC_CTX *frame = talloc_stackframe();
124         krb5_context ctx = NULL;
125         krb5_error_code code = 0;
126         krb5_ccache cc = NULL;
127         krb5_principal me = NULL;
128         krb5_principal canon_princ = NULL;
129         krb5_creds my_creds;
130         krb5_get_init_creds_opt *opt = NULL;
131         smb_krb5_addresses *addr = NULL;
132         char *canon_principal = NULL;
133         char *canon_realm = NULL;
134
135         ZERO_STRUCT(my_creds);
136
137         code = smb_krb5_init_context_common(&ctx);
138         if (code != 0) {
139                 DBG_ERR("kerberos init context failed (%s)\n",
140                         error_message(code));
141                 TALLOC_FREE(frame);
142                 return code;
143         }
144
145         if (time_offset != 0) {
146                 krb5_set_real_time(ctx, time(NULL) + time_offset, 0);
147         }
148
149         DBG_DEBUG("as %s using [%s] as ccache and config [%s]\n",
150                   given_principal,
151                   cache_name ? cache_name: krb5_cc_default_name(ctx),
152                   getenv("KRB5_CONFIG"));
153
154         if ((code = krb5_cc_resolve(ctx, cache_name ? cache_name : krb5_cc_default_name(ctx), &cc))) {
155                 goto out;
156         }
157
158         if ((code = smb_krb5_parse_name(ctx, given_principal, &me))) {
159                 goto out;
160         }
161
162         if ((code = krb5_get_init_creds_opt_alloc(ctx, &opt))) {
163                 goto out;
164         }
165
166         krb5_get_init_creds_opt_set_renew_life(opt, renewable_time);
167         krb5_get_init_creds_opt_set_forwardable(opt, True);
168
169         /* Turn on canonicalization for lower case realm support */
170 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
171         krb5_get_init_creds_opt_set_canonicalize(opt, true);
172 #endif /* MIT */
173 #if 0
174         /* insane testing */
175         krb5_get_init_creds_opt_set_tkt_life(opt, 60);
176 #endif
177
178 #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_SET_PAC_REQUEST
179         if (request_pac) {
180                 if ((code = krb5_get_init_creds_opt_set_pac_request(ctx, opt, (krb5_boolean)request_pac))) {
181                         goto out;
182                 }
183         }
184 #endif
185         if (add_netbios_addr) {
186                 if ((code = smb_krb5_gen_netbios_krb5_address(&addr,
187                                                         lp_netbios_name()))) {
188                         goto out;
189                 }
190                 krb5_get_init_creds_opt_set_address_list(opt, addr->addrs);
191         }
192
193         if ((code = krb5_get_init_creds_password(ctx, &my_creds, me, discard_const_p(char,password), 
194                                                  kerb_prompter, discard_const_p(char, password),
195                                                  0, NULL, opt))) {
196                 goto out;
197         }
198
199 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
200         canon_princ = my_creds.client;
201 #else
202         canon_princ = me;
203 #endif /* MIT */
204
205         code = smb_krb5_unparse_name(frame,
206                                      ctx,
207                                      canon_princ,
208                                      &canon_principal);
209         if (code != 0) {
210                 goto out;
211         }
212
213         DBG_DEBUG("%s mapped to %s\n", given_principal, canon_principal);
214
215         canon_realm = smb_krb5_principal_get_realm(frame, ctx, canon_princ);
216         if (canon_realm == NULL) {
217                 code = ENOMEM;
218                 goto out;
219         }
220
221         if ((code = krb5_cc_initialize(ctx, cc, canon_princ))) {
222                 goto out;
223         }
224
225         if ((code = krb5_cc_store_cred(ctx, cc, &my_creds))) {
226                 goto out;
227         }
228
229         if (expire_time) {
230                 *expire_time = (time_t) my_creds.times.endtime;
231         }
232
233         if (renew_till_time) {
234                 *renew_till_time = (time_t) my_creds.times.renew_till;
235         }
236
237         if (_canon_principal != NULL) {
238                 *_canon_principal = talloc_move(mem_ctx, &canon_principal);
239         }
240         if (_canon_realm != NULL) {
241                 *_canon_realm = talloc_move(mem_ctx, &canon_realm);
242         }
243  out:
244         if (ntstatus) {
245                 /* fast path */
246                 if (code == 0) {
247                         *ntstatus = NT_STATUS_OK;
248                         goto cleanup;
249                 }
250
251                 /* fall back to self-made-mapping */
252                 *ntstatus = krb5_to_nt_status(code);
253         }
254
255  cleanup:
256         krb5_free_cred_contents(ctx, &my_creds);
257         if (me) {
258                 krb5_free_principal(ctx, me);
259         }
260         if (addr) {
261                 smb_krb5_free_addresses(ctx, addr);
262         }
263         if (opt) {
264                 krb5_get_init_creds_opt_free(ctx, opt);
265         }
266         if (cc) {
267                 krb5_cc_close(ctx, cc);
268         }
269         if (ctx) {
270                 krb5_free_context(ctx);
271         }
272         TALLOC_FREE(frame);
273         return code;
274 }
275
276 int ads_kdestroy(const char *cc_name)
277 {
278         krb5_error_code code;
279         krb5_context ctx = NULL;
280         krb5_ccache cc = NULL;
281
282         code = smb_krb5_init_context_common(&ctx);
283         if (code != 0) {
284                 DBG_ERR("kerberos init context failed (%s)\n",
285                         error_message(code));
286                 return code;
287         }
288
289         if (!cc_name) {
290                 if ((code = krb5_cc_default(ctx, &cc))) {
291                         krb5_free_context(ctx);
292                         return code;
293                 }
294         } else {
295                 if ((code = krb5_cc_resolve(ctx, cc_name, &cc))) {
296                         DEBUG(3, ("ads_kdestroy: krb5_cc_resolve failed: %s\n",
297                                   error_message(code)));
298                         krb5_free_context(ctx);
299                         return code;
300                 }
301         }
302
303         if ((code = krb5_cc_destroy (ctx, cc))) {
304                 DEBUG(3, ("ads_kdestroy: krb5_cc_destroy failed: %s\n", 
305                         error_message(code)));
306         }
307
308         krb5_free_context (ctx);
309         return code;
310 }
311
312 int create_kerberos_key_from_string(krb5_context context,
313                                         krb5_principal host_princ,
314                                         krb5_principal salt_princ,
315                                         krb5_data *password,
316                                         krb5_keyblock *key,
317                                         krb5_enctype enctype,
318                                         bool no_salt)
319 {
320         int ret;
321         /*
322          * Check if we've determined that the KDC is salting keys for this
323          * principal/enctype in a non-obvious way.  If it is, try to match
324          * its behavior.
325          */
326         if (no_salt) {
327                 KRB5_KEY_DATA(key) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
328                 if (!KRB5_KEY_DATA(key)) {
329                         return ENOMEM;
330                 }
331                 memcpy(KRB5_KEY_DATA(key), password->data, password->length);
332                 KRB5_KEY_LENGTH(key) = password->length;
333                 KRB5_KEY_TYPE(key) = enctype;
334                 return 0;
335         }
336         ret = smb_krb5_create_key_from_string(context,
337                                               salt_princ ? salt_princ : host_princ,
338                                               NULL,
339                                               password,
340                                               enctype,
341                                               key);
342         return ret;
343 }
344
345 /************************************************************************
346 ************************************************************************/
347
348 int kerberos_kinit_password(const char *principal,
349                             const char *password,
350                             int time_offset,
351                             const char *cache_name)
352 {
353         return kerberos_kinit_password_ext(principal, 
354                                            password, 
355                                            time_offset, 
356                                            0, 
357                                            0,
358                                            cache_name,
359                                            False,
360                                            False,
361                                            0,
362                                            NULL,
363                                            NULL,
364                                            NULL,
365                                            NULL);
366 }
367
368 /************************************************************************
369 ************************************************************************/
370
371 /************************************************************************
372  Create a string list of available kdc's, possibly searching by sitename.
373  Does DNS queries.
374
375  If "sitename" is given, the DC's in that site are listed first.
376
377 ************************************************************************/
378
379 static void add_sockaddr_unique(struct sockaddr_storage *addrs, size_t *num_addrs,
380                                 const struct sockaddr_storage *addr)
381 {
382         size_t i;
383
384         for (i=0; i<*num_addrs; i++) {
385                 if (sockaddr_equal((const struct sockaddr *)&addrs[i],
386                                    (const struct sockaddr *)addr)) {
387                         return;
388                 }
389         }
390         addrs[i] = *addr;
391         *num_addrs += 1;
392 }
393
394 /* print_canonical_sockaddr prints an ipv6 addr in the form of
395 * [ipv6.addr]. This string, when put in a generated krb5.conf file is not
396 * always properly dealt with by some older krb5 libraries. Adding the hard-coded
397 * portnumber workarounds the issue. - gd */
398
399 static char *print_canonical_sockaddr_with_port(TALLOC_CTX *mem_ctx,
400                                                 const struct sockaddr_storage *pss)
401 {
402         char *str = NULL;
403
404         str = print_canonical_sockaddr(mem_ctx, pss);
405         if (str == NULL) {
406                 return NULL;
407         }
408
409         if (pss->ss_family != AF_INET6) {
410                 return str;
411         }
412
413 #if defined(HAVE_IPV6)
414         str = talloc_asprintf_append(str, ":88");
415 #endif
416         return str;
417 }
418
419 static char *get_kdc_ip_string(char *mem_ctx,
420                 const char *realm,
421                 const char *sitename,
422                 const struct sockaddr_storage *pss)
423 {
424         TALLOC_CTX *frame = talloc_stackframe();
425         size_t i;
426         struct ip_service *ip_srv_site = NULL;
427         struct ip_service *ip_srv_nonsite = NULL;
428         int count_site = 0;
429         int count_nonsite;
430         size_t num_dcs;
431         struct sockaddr_storage *dc_addrs;
432         struct tsocket_address **dc_addrs2 = NULL;
433         const struct tsocket_address * const *dc_addrs3 = NULL;
434         char *result = NULL;
435         struct netlogon_samlogon_response **responses = NULL;
436         NTSTATUS status;
437         char *kdc_str = talloc_asprintf(mem_ctx, "%s\t\tkdc = %s\n", "",
438                                         print_canonical_sockaddr_with_port(mem_ctx, pss));
439
440         if (kdc_str == NULL) {
441                 TALLOC_FREE(frame);
442                 return NULL;
443         }
444
445         /*
446          * First get the KDC's only in this site, the rest will be
447          * appended later
448          */
449
450         if (sitename) {
451                 get_kdc_list(realm, sitename, &ip_srv_site, &count_site);
452                 DEBUG(10, ("got %d addresses from site %s search\n", count_site,
453                            sitename));
454         }
455
456         /* Get all KDC's. */
457
458         get_kdc_list(realm, NULL, &ip_srv_nonsite, &count_nonsite);
459         DEBUG(10, ("got %d addresses from site-less search\n", count_nonsite));
460
461         dc_addrs = talloc_array(talloc_tos(), struct sockaddr_storage,
462                                 count_site + count_nonsite);
463         if (dc_addrs == NULL) {
464                 goto out;
465         }
466
467         num_dcs = 0;
468
469         for (i = 0; i < count_site; i++) {
470                 if (!sockaddr_equal(
471                         (const struct sockaddr *)pss,
472                         (const struct sockaddr *)&ip_srv_site[i].ss)) {
473                         add_sockaddr_unique(dc_addrs, &num_dcs,
474                                             &ip_srv_site[i].ss);
475                 }
476         }
477
478         for (i = 0; i < count_nonsite; i++) {
479                 if (!sockaddr_equal(
480                         (const struct sockaddr *)pss,
481                         (const struct sockaddr *)&ip_srv_nonsite[i].ss)) {
482                         add_sockaddr_unique(dc_addrs, &num_dcs,
483                                             &ip_srv_nonsite[i].ss);
484                 }
485         }
486
487         dc_addrs2 = talloc_zero_array(talloc_tos(),
488                                       struct tsocket_address *,
489                                       num_dcs);
490
491         DBG_DEBUG("%zu additional KDCs to test\n", num_dcs);
492         if (num_dcs == 0) {
493                 goto out;
494         }
495         if (dc_addrs2 == NULL) {
496                 goto out;
497         }
498
499         for (i=0; i<num_dcs; i++) {
500                 char addr[INET6_ADDRSTRLEN];
501                 int ret;
502
503                 print_sockaddr(addr, sizeof(addr), &dc_addrs[i]);
504
505                 ret = tsocket_address_inet_from_strings(dc_addrs2, "ip",
506                                                         addr, LDAP_PORT,
507                                                         &dc_addrs2[i]);
508                 if (ret != 0) {
509                         status = map_nt_error_from_unix(errno);
510                         DEBUG(2,("Failed to create tsocket_address for %s - %s\n",
511                                  addr, nt_errstr(status)));
512                         goto out;
513                 }
514         }
515
516         dc_addrs3 = (const struct tsocket_address * const *)dc_addrs2;
517
518         status = cldap_multi_netlogon(talloc_tos(),
519                         dc_addrs3, num_dcs,
520                         realm, lp_netbios_name(),
521                         NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX,
522                         MIN(num_dcs, 3), timeval_current_ofs(3, 0), &responses);
523         TALLOC_FREE(dc_addrs2);
524         dc_addrs3 = NULL;
525
526         if (!NT_STATUS_IS_OK(status)) {
527                 DEBUG(10,("get_kdc_ip_string: cldap_multi_netlogon failed: "
528                           "%s\n", nt_errstr(status)));
529                 goto out;
530         }
531
532         for (i=0; i<num_dcs; i++) {
533                 char *new_kdc_str;
534
535                 if (responses[i] == NULL) {
536                         continue;
537                 }
538
539                 /* Append to the string - inefficient but not done often. */
540                 new_kdc_str = talloc_asprintf(mem_ctx, "%s\t\tkdc = %s\n",
541                                               kdc_str,
542                                               print_canonical_sockaddr_with_port(mem_ctx, &dc_addrs[i]));
543                 if (new_kdc_str == NULL) {
544                         goto out;
545                 }
546                 TALLOC_FREE(kdc_str);
547                 kdc_str = new_kdc_str;
548         }
549
550 out:
551         DEBUG(10, ("get_kdc_ip_string: Returning %s\n", kdc_str));
552
553         result = kdc_str;
554         SAFE_FREE(ip_srv_site);
555         SAFE_FREE(ip_srv_nonsite);
556         TALLOC_FREE(frame);
557         return result;
558 }
559
560 /************************************************************************
561  Create  a specific krb5.conf file in the private directory pointing
562  at a specific kdc for a realm. Keyed off domain name. Sets
563  KRB5_CONFIG environment variable to point to this file. Must be
564  run as root or will fail (which is a good thing :-).
565 ************************************************************************/
566
567 #if !defined(SAMBA4_USES_HEIMDAL) /* MIT version */
568 static char *get_enctypes(TALLOC_CTX *mem_ctx)
569 {
570         char *aes_enctypes = NULL;
571         const char *legacy_enctypes = "";
572         char *enctypes = NULL;
573
574         aes_enctypes = talloc_strdup(mem_ctx, "");
575         if (aes_enctypes == NULL) {
576                 goto done;
577         }
578
579         if (lp_kerberos_encryption_types() == KERBEROS_ETYPES_ALL ||
580             lp_kerberos_encryption_types() == KERBEROS_ETYPES_STRONG) {
581 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
582                 aes_enctypes = talloc_asprintf_append(
583                     aes_enctypes, "%s", "aes256-cts-hmac-sha1-96 ");
584                 if (aes_enctypes == NULL) {
585                         goto done;
586                 }
587 #endif
588 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
589                 aes_enctypes = talloc_asprintf_append(
590                     aes_enctypes, "%s", "aes128-cts-hmac-sha1-96");
591                 if (aes_enctypes == NULL) {
592                         goto done;
593                 }
594 #endif
595         }
596
597         if (lp_kerberos_encryption_types() == KERBEROS_ETYPES_ALL ||
598             lp_kerberos_encryption_types() == KERBEROS_ETYPES_LEGACY) {
599                 legacy_enctypes = "RC4-HMAC DES-CBC-CRC DES-CBC-MD5";
600         }
601
602         enctypes =
603             talloc_asprintf(mem_ctx, "\tdefault_tgs_enctypes = %s %s\n"
604                                      "\tdefault_tkt_enctypes = %s %s\n"
605                                      "\tpreferred_enctypes = %s %s\n",
606                             aes_enctypes, legacy_enctypes, aes_enctypes,
607                             legacy_enctypes, aes_enctypes, legacy_enctypes);
608 done:
609         TALLOC_FREE(aes_enctypes);
610         return enctypes;
611 }
612 #else /* Heimdal version */
613 static char *get_enctypes(TALLOC_CTX *mem_ctx)
614 {
615         const char *aes_enctypes = "";
616         const char *legacy_enctypes = "";
617         char *enctypes = NULL;
618
619         if (lp_kerberos_encryption_types() == KERBEROS_ETYPES_ALL ||
620             lp_kerberos_encryption_types() == KERBEROS_ETYPES_STRONG) {
621                 aes_enctypes =
622                     "aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96";
623         }
624
625         if (lp_kerberos_encryption_types() == KERBEROS_ETYPES_ALL ||
626             lp_kerberos_encryption_types() == KERBEROS_ETYPES_LEGACY) {
627                 legacy_enctypes = "arcfour-hmac-md5 des-cbc-crc des-cbc-md5";
628         }
629
630         enctypes = talloc_asprintf(mem_ctx, "\tdefault_etypes = %s %s\n",
631                                    aes_enctypes, legacy_enctypes);
632
633         return enctypes;
634 }
635 #endif
636
637 bool create_local_private_krb5_conf_for_domain(const char *realm,
638                                                 const char *domain,
639                                                 const char *sitename,
640                                                 const struct sockaddr_storage *pss)
641 {
642         char *dname;
643         char *tmpname = NULL;
644         char *fname = NULL;
645         char *file_contents = NULL;
646         char *kdc_ip_string = NULL;
647         size_t flen = 0;
648         ssize_t ret;
649         int fd;
650         char *realm_upper = NULL;
651         bool result = false;
652         char *enctypes = NULL;
653         const char *include_system_krb5 = "";
654         mode_t mask;
655
656         if (!lp_create_krb5_conf()) {
657                 return false;
658         }
659
660         if (realm == NULL) {
661                 DEBUG(0, ("No realm has been specified! Do you really want to "
662                           "join an Active Directory server?\n"));
663                 return false;
664         }
665
666         if (domain == NULL || pss == NULL) {
667                 return false;
668         }
669
670         dname = lock_path(talloc_tos(), "smb_krb5");
671         if (!dname) {
672                 return false;
673         }
674         if ((mkdir(dname, 0755)==-1) && (errno != EEXIST)) {
675                 DEBUG(0,("create_local_private_krb5_conf_for_domain: "
676                         "failed to create directory %s. Error was %s\n",
677                         dname, strerror(errno) ));
678                 goto done;
679         }
680
681         tmpname = lock_path(talloc_tos(), "smb_tmp_krb5.XXXXXX");
682         if (!tmpname) {
683                 goto done;
684         }
685
686         fname = talloc_asprintf(dname, "%s/krb5.conf.%s", dname, domain);
687         if (!fname) {
688                 goto done;
689         }
690
691         DEBUG(10,("create_local_private_krb5_conf_for_domain: fname = %s, realm = %s, domain = %s\n",
692                 fname, realm, domain ));
693
694         realm_upper = talloc_strdup(fname, realm);
695         if (!strupper_m(realm_upper)) {
696                 goto done;
697         }
698
699         kdc_ip_string = get_kdc_ip_string(dname, realm, sitename, pss);
700         if (!kdc_ip_string) {
701                 goto done;
702         }
703
704         enctypes = get_enctypes(fname);
705         if (enctypes == NULL) {
706                 goto done;
707         }
708
709 #if !defined(SAMBA4_USES_HEIMDAL)
710         if (lp_include_system_krb5_conf()) {
711                 include_system_krb5 = "include /etc/krb5.conf";
712         }
713 #endif
714
715         /*
716          * We are setting 'dns_lookup_kdc' to true, because we want to lookup
717          * KDCs which are not configured via DNS SRV records, eg. if we do:
718          *
719          *     net ads join -Uadmin@otherdomain
720          */
721         file_contents =
722             talloc_asprintf(fname,
723                             "[libdefaults]\n"
724                             "\tdefault_realm = %s\n"
725                             "%s"
726                             "\tdns_lookup_realm = false\n"
727                             "\tdns_lookup_kdc = true\n\n"
728                             "[realms]\n\t%s = {\n"
729                             "%s\t}\n"
730                             "%s\n",
731                             realm_upper,
732                             enctypes,
733                             realm_upper,
734                             kdc_ip_string,
735                             include_system_krb5);
736
737         if (!file_contents) {
738                 goto done;
739         }
740
741         flen = strlen(file_contents);
742
743         mask = umask(S_IRWXO | S_IRWXG);
744         fd = mkstemp(tmpname);
745         umask(mask);
746         if (fd == -1) {
747                 DEBUG(0,("create_local_private_krb5_conf_for_domain: smb_mkstemp failed,"
748                         " for file %s. Errno %s\n",
749                         tmpname, strerror(errno) ));
750                 goto done;
751         }
752
753         if (fchmod(fd, 0644)==-1) {
754                 DEBUG(0,("create_local_private_krb5_conf_for_domain: fchmod failed for %s."
755                         " Errno %s\n",
756                         tmpname, strerror(errno) ));
757                 unlink(tmpname);
758                 close(fd);
759                 goto done;
760         }
761
762         ret = write(fd, file_contents, flen);
763         if (flen != ret) {
764                 DEBUG(0,("create_local_private_krb5_conf_for_domain: write failed,"
765                         " returned %d (should be %u). Errno %s\n",
766                         (int)ret, (unsigned int)flen, strerror(errno) ));
767                 unlink(tmpname);
768                 close(fd);
769                 goto done;
770         }
771         if (close(fd)==-1) {
772                 DEBUG(0,("create_local_private_krb5_conf_for_domain: close failed."
773                         " Errno %s\n", strerror(errno) ));
774                 unlink(tmpname);
775                 goto done;
776         }
777
778         if (rename(tmpname, fname) == -1) {
779                 DEBUG(0,("create_local_private_krb5_conf_for_domain: rename "
780                         "of %s to %s failed. Errno %s\n",
781                         tmpname, fname, strerror(errno) ));
782                 unlink(tmpname);
783                 goto done;
784         }
785
786         DEBUG(5,("create_local_private_krb5_conf_for_domain: wrote "
787                 "file %s with realm %s KDC list = %s\n",
788                 fname, realm_upper, kdc_ip_string));
789
790         /* Set the environment variable to this file. */
791         setenv("KRB5_CONFIG", fname, 1);
792
793         result = true;
794
795 #if defined(OVERWRITE_SYSTEM_KRB5_CONF)
796
797 #define SYSTEM_KRB5_CONF_PATH "/etc/krb5.conf"
798         /* Insanity, sheer insanity..... */
799
800         if (strequal(realm, lp_realm())) {
801                 SMB_STRUCT_STAT sbuf;
802
803                 if (sys_lstat(SYSTEM_KRB5_CONF_PATH, &sbuf, false) == 0) {
804                         if (S_ISLNK(sbuf.st_ex_mode) && sbuf.st_ex_size) {
805                                 int lret;
806                                 size_t alloc_size = sbuf.st_ex_size + 1;
807                                 char *linkpath = talloc_array(talloc_tos(), char,
808                                                 alloc_size);
809                                 if (!linkpath) {
810                                         goto done;
811                                 }
812                                 lret = readlink(SYSTEM_KRB5_CONF_PATH, linkpath,
813                                                 alloc_size - 1);
814                                 if (lret == -1) {
815                                         TALLOC_FREE(linkpath);
816                                         goto done;
817                                 }
818                                 linkpath[lret] = '\0';
819
820                                 if (strcmp(linkpath, fname) == 0) {
821                                         /* Symlink already exists. */
822                                         TALLOC_FREE(linkpath);
823                                         goto done;
824                                 }
825                                 TALLOC_FREE(linkpath);
826                         }
827                 }
828
829                 /* Try and replace with a symlink. */
830                 if (symlink(fname, SYSTEM_KRB5_CONF_PATH) == -1) {
831                         const char *newpath = SYSTEM_KRB5_CONF_PATH ".saved";
832                         if (errno != EEXIST) {
833                                 DEBUG(0,("create_local_private_krb5_conf_for_domain: symlink "
834                                         "of %s to %s failed. Errno %s\n",
835                                         fname, SYSTEM_KRB5_CONF_PATH, strerror(errno) ));
836                                 goto done; /* Not a fatal error. */
837                         }
838
839                         /* Yes, this is a race conditon... too bad. */
840                         if (rename(SYSTEM_KRB5_CONF_PATH, newpath) == -1) {
841                                 DEBUG(0,("create_local_private_krb5_conf_for_domain: rename "
842                                         "of %s to %s failed. Errno %s\n",
843                                         SYSTEM_KRB5_CONF_PATH, newpath,
844                                         strerror(errno) ));
845                                 goto done; /* Not a fatal error. */
846                         }
847
848                         if (symlink(fname, SYSTEM_KRB5_CONF_PATH) == -1) {
849                                 DEBUG(0,("create_local_private_krb5_conf_for_domain: "
850                                         "forced symlink of %s to /etc/krb5.conf failed. Errno %s\n",
851                                         fname, strerror(errno) ));
852                                 goto done; /* Not a fatal error. */
853                         }
854                 }
855         }
856 #endif
857
858 done:
859         TALLOC_FREE(tmpname);
860         TALLOC_FREE(dname);
861
862         return result;
863 }
864 #endif