4e555b285331086e515ac564fb906c09a338187e
[idra/samba.git] / lib / krb5_wrap / krb5_samba.c
1 /*
2    Unix SMB/CIFS implementation.
3    simple kerberos5 routines for active directory
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Luke Howard 2002-2003
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
7    Copyright (C) Guenther Deschner 2005-2009
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "krb5_samba.h"
25 #include "librpc/gen_ndr/krb5pac.h"
26 #include "lib/util/asn1.h"
27
28 #ifndef KRB5_AUTHDATA_WIN2K_PAC
29 #define KRB5_AUTHDATA_WIN2K_PAC 128
30 #endif
31
32 #ifndef KRB5_AUTHDATA_IF_RELEVANT
33 #define KRB5_AUTHDATA_IF_RELEVANT 1
34 #endif
35
36 #ifdef HAVE_KRB5
37
38 #define GSSAPI_CHECKSUM      0x8003             /* Checksum type value for Kerberos */
39 #define GSSAPI_BNDLENGTH     16                 /* Bind Length (rfc-1964 pg.3) */
40 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
41                                                         bind field, flags field. */
42
43 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
44    but still has the symbol */
45 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
46 krb5_error_code krb5_auth_con_set_req_cksumtype(
47         krb5_context     context,
48         krb5_auth_context      auth_context,
49         krb5_cksumtype     cksumtype);
50 #endif
51
52 #if !defined(SMB_MALLOC)
53 #undef malloc
54 #define SMB_MALLOC(s) malloc((s))
55 #endif
56
57 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
58
59 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
60
61 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
62  * to krb5_set_default_tgs_ktypes. See
63  *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
64  *
65  * If the MIT libraries are not exporting internal symbols, we will end up in
66  * this branch, which is correct. Otherwise we will continue to use the
67  * internal symbol
68  */
69  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
70 {
71     return krb5_set_default_tgs_enctypes(ctx, enc);
72 }
73
74 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
75
76 /* Heimdal */
77  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
78 {
79         return krb5_set_default_in_tkt_etypes(ctx, enc);
80 }
81
82 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
83
84 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
85
86 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
87 /* HEIMDAL */
88  bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
89 {
90         memset(pkaddr, '\0', sizeof(krb5_address));
91 #if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
92         if (paddr->ss_family == AF_INET6) {
93                 pkaddr->addr_type = KRB5_ADDRESS_INET6;
94                 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
95                 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
96                 return true;
97         }
98 #endif
99         if (paddr->ss_family == AF_INET) {
100                 pkaddr->addr_type = KRB5_ADDRESS_INET;
101                 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
102                 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
103                 return true;
104         }
105         return false;
106 }
107 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
108 /* MIT */
109 bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
110 {
111         memset(pkaddr, '\0', sizeof(krb5_address));
112 #if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
113         if (paddr->ss_family == AF_INET6) {
114                 pkaddr->addrtype = ADDRTYPE_INET6;
115                 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
116                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
117                 return true;
118         }
119 #endif
120         if (paddr->ss_family == AF_INET) {
121                 pkaddr->addrtype = ADDRTYPE_INET;
122                 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
123                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
124                 return true;
125         }
126         return false;
127 }
128 #else
129 #error UNKNOWN_ADDRTYPE
130 #endif
131
132 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
133 /* MIT */
134 int create_kerberos_key_from_string_direct(krb5_context context,
135                                                   krb5_principal host_princ,
136                                                   krb5_data *password,
137                                                   krb5_keyblock *key,
138                                                   krb5_enctype enctype)
139 {
140         int ret = 0;
141         krb5_data salt;
142
143         ret = krb5_principal2salt(context, host_princ, &salt);
144         if (ret) {
145                 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
146                 return ret;
147         }
148         ret = krb5_c_string_to_key(context, enctype, password, &salt, key);
149         SAFE_FREE(salt.data);
150
151         return ret;
152 }
153 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
154 /* Heimdal */
155 int create_kerberos_key_from_string_direct(krb5_context context,
156                                                   krb5_principal host_princ,
157                                                   krb5_data *password,
158                                                   krb5_keyblock *key,
159                                                   krb5_enctype enctype)
160 {
161         int ret;
162         krb5_salt salt;
163
164         ret = krb5_get_pw_salt(context, host_princ, &salt);
165         if (ret) {
166                 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
167                 return ret;
168         }
169
170         ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, salt, key);
171         krb5_free_salt(context, salt);
172
173         return ret;
174 }
175 #else
176 #error UNKNOWN_CREATE_KEY_FUNCTIONS
177 #endif
178
179 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
180  krb5_error_code get_kerberos_allowed_etypes(krb5_context context,
181                                             krb5_enctype **enctypes)
182 {
183         return krb5_get_permitted_enctypes(context, enctypes);
184 }
185 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
186  krb5_error_code get_kerberos_allowed_etypes(krb5_context context,
187                                             krb5_enctype **enctypes)
188 {
189 #ifdef HAVE_KRB5_PDU_NONE_DECL
190         return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
191 #else
192         return krb5_get_default_in_tkt_etypes(context, enctypes);
193 #endif
194 }
195 #else
196 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
197 #endif
198
199 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
200  krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
201                                         krb5_auth_context auth_context,
202                                         krb5_keyblock *keyblock)
203 {
204         return krb5_auth_con_setkey(context, auth_context, keyblock);
205 }
206 #endif
207
208 bool unwrap_edata_ntstatus(TALLOC_CTX *mem_ctx,
209                            DATA_BLOB *edata,
210                            DATA_BLOB *edata_out)
211 {
212         DATA_BLOB edata_contents;
213         ASN1_DATA *data;
214         int edata_type;
215
216         if (!edata->length) {
217                 return false;
218         }
219
220         data = asn1_init(mem_ctx);
221         if (data == NULL) {
222                 return false;
223         }
224
225         asn1_load(data, *edata);
226         asn1_start_tag(data, ASN1_SEQUENCE(0));
227         asn1_start_tag(data, ASN1_CONTEXT(1));
228         asn1_read_Integer(data, &edata_type);
229
230         if (edata_type != KRB5_PADATA_PW_SALT) {
231                 DEBUG(0,("edata is not of required type %d but of type %d\n",
232                         KRB5_PADATA_PW_SALT, edata_type));
233                 asn1_free(data);
234                 return false;
235         }
236
237         asn1_start_tag(data, ASN1_CONTEXT(2));
238         asn1_read_OctetString(data, talloc_tos(), &edata_contents);
239         asn1_end_tag(data);
240         asn1_end_tag(data);
241         asn1_end_tag(data);
242         asn1_free(data);
243
244         *edata_out = data_blob_talloc(mem_ctx, edata_contents.data, edata_contents.length);
245
246         data_blob_free(&edata_contents);
247
248         return true;
249 }
250
251
252 static bool ads_cleanup_expired_creds(krb5_context context,
253                                       krb5_ccache  ccache,
254                                       krb5_creds  *credsp)
255 {
256         krb5_error_code retval;
257         const char *cc_type = krb5_cc_get_type(context, ccache);
258
259         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
260                   cc_type, krb5_cc_get_name(context, ccache),
261                   http_timestring(talloc_tos(), credsp->times.endtime)));
262
263         /* we will probably need new tickets if the current ones
264            will expire within 10 seconds.
265         */
266         if (credsp->times.endtime >= (time(NULL) + 10))
267                 return false;
268
269         /* heimdal won't remove creds from a file ccache, and
270            perhaps we shouldn't anyway, since internally we
271            use memory ccaches, and a FILE one probably means that
272            we're using creds obtained outside of our exectuable
273         */
274         if (strequal(cc_type, "FILE")) {
275                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
276                 return false;
277         }
278
279         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
280         if (retval) {
281                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
282                           error_message(retval)));
283                 /* If we have an error in this, we want to display it,
284                    but continue as though we deleted it */
285         }
286         return true;
287 }
288
289 /* Allocate and setup the auth context into the state we need. */
290
291 static krb5_error_code setup_auth_context(krb5_context context,
292                         krb5_auth_context *auth_context)
293 {
294         krb5_error_code retval;
295
296         retval = krb5_auth_con_init(context, auth_context );
297         if (retval) {
298                 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
299                         error_message(retval)));
300                 return retval;
301         }
302
303         /* Ensure this is an addressless ticket. */
304         retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
305         if (retval) {
306                 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
307                         error_message(retval)));
308         }
309
310         return retval;
311 }
312
313 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
314 static krb5_error_code create_gss_checksum(krb5_data *in_data, /* [inout] */
315                                                 uint32_t gss_flags)
316 {
317         unsigned int orig_length = in_data->length;
318         unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
319         char *gss_cksum = NULL;
320
321         if (orig_length) {
322                 /* Extra length field for delgated ticket. */
323                 base_cksum_size += 4;
324         }
325
326         if ((unsigned int)base_cksum_size + orig_length <
327                         (unsigned int)base_cksum_size) {
328                 return EINVAL;
329         }
330
331         gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
332         if (gss_cksum == NULL) {
333                 return ENOMEM;
334         }
335
336         memset(gss_cksum, '\0', base_cksum_size + orig_length);
337         SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
338
339         /*
340          * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
341          * This matches the behavior of heimdal and mit.
342          *
343          * And it is needed to work against some closed source
344          * SMB servers.
345          *
346          * See bug #7883
347          */
348         memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
349
350         SIVAL(gss_cksum, 20, gss_flags);
351
352         if (orig_length) {
353                 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
354                 SSVAL(gss_cksum, 26, orig_length);
355                 /* Copy the kerberos KRB_CRED data */
356                 memcpy(gss_cksum + 28, in_data->data, orig_length);
357                 free(in_data->data);
358                 in_data->data = NULL;
359                 in_data->length = 0;
360         }
361         in_data->data = gss_cksum;
362         in_data->length = base_cksum_size + orig_length;
363         return 0;
364 }
365 #endif
366
367 /**************************************************************
368  krb5_parse_name that takes a UNIX charset.
369 **************************************************************/
370
371 krb5_error_code smb_krb5_parse_name(krb5_context context,
372                                 const char *name, /* in unix charset */
373                                 krb5_principal *principal)
374 {
375         krb5_error_code ret;
376         char *utf8_name;
377         size_t converted_size;
378         TALLOC_CTX *frame = talloc_stackframe();
379
380         if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
381                 talloc_free(frame);
382                 return ENOMEM;
383         }
384
385         ret = krb5_parse_name(context, utf8_name, principal);
386         TALLOC_FREE(frame);
387         return ret;
388 }
389
390 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
391 void krb5_free_unparsed_name(krb5_context context, char *val)
392 {
393         SAFE_FREE(val);
394 }
395 #endif
396
397 /**************************************************************
398  krb5_parse_name that returns a UNIX charset name. Must
399  be freed with talloc_free() call.
400 **************************************************************/
401
402 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
403                                       krb5_context context,
404                                       krb5_const_principal principal,
405                                       char **unix_name)
406 {
407         krb5_error_code ret;
408         char *utf8_name;
409         size_t converted_size;
410
411         *unix_name = NULL;
412         ret = krb5_unparse_name(context, principal, &utf8_name);
413         if (ret) {
414                 return ret;
415         }
416
417         if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
418                 krb5_free_unparsed_name(context, utf8_name);
419                 return ENOMEM;
420         }
421         krb5_free_unparsed_name(context, utf8_name);
422         return 0;
423 }
424
425 krb5_error_code smb_krb5_parse_name_norealm(krb5_context context, 
426                                             const char *name, 
427                                             krb5_principal *principal)
428 {
429         /* we are cheating here because parse_name will in fact set the realm.
430          * We don't care as the only caller of smb_krb5_parse_name_norealm
431          * ignores the realm anyway when calling
432          * smb_krb5_principal_compare_any_realm later - Guenther */
433
434         return smb_krb5_parse_name(context, name, principal);
435 }
436
437 bool smb_krb5_principal_compare_any_realm(krb5_context context, 
438                                           krb5_const_principal princ1, 
439                                           krb5_const_principal princ2)
440 {
441         return krb5_principal_compare_any_realm(context, princ1, princ2);
442 }
443
444 /*
445   we can't use krb5_mk_req because w2k wants the service to be in a particular format
446 */
447 static krb5_error_code ads_krb5_mk_req(krb5_context context,
448                                        krb5_auth_context *auth_context,
449                                        const krb5_flags ap_req_options,
450                                        const char *principal,
451                                        krb5_ccache ccache,
452                                        krb5_data *outbuf,
453                                        time_t *expire_time,
454                                        const char *impersonate_princ_s)
455 {
456         krb5_error_code           retval;
457         krb5_principal    server;
458         krb5_principal impersonate_princ = NULL;
459         krb5_creds              * credsp;
460         krb5_creds                creds;
461         krb5_data in_data;
462         bool creds_ready = false;
463         int i = 0, maxtries = 3;
464
465         ZERO_STRUCT(in_data);
466
467         retval = smb_krb5_parse_name(context, principal, &server);
468         if (retval) {
469                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
470                 return retval;
471         }
472
473         if (impersonate_princ_s) {
474                 retval = smb_krb5_parse_name(context, impersonate_princ_s,
475                                              &impersonate_princ);
476                 if (retval) {
477                         DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
478                         goto cleanup_princ;
479                 }
480         }
481
482         /* obtain ticket & session key */
483         ZERO_STRUCT(creds);
484         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
485                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
486                          error_message(retval)));
487                 goto cleanup_princ;
488         }
489
490         if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
491                 /* This can commonly fail on smbd startup with no ticket in the cache.
492                  * Report at higher level than 1. */
493                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
494                          error_message(retval)));
495                 goto cleanup_creds;
496         }
497
498         while (!creds_ready && (i < maxtries)) {
499
500                 if ((retval = smb_krb5_get_credentials(context, ccache,
501                                                        creds.client,
502                                                        creds.server,
503                                                        impersonate_princ,
504                                                        &credsp))) {
505                         DEBUG(1,("ads_krb5_mk_req: smb_krb5_get_credentials failed for %s (%s)\n",
506                                 principal, error_message(retval)));
507                         goto cleanup_creds;
508                 }
509
510                 /* cope with ticket being in the future due to clock skew */
511                 if ((unsigned)credsp->times.starttime > time(NULL)) {
512                         time_t t = time(NULL);
513                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
514                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
515                         krb5_set_real_time(context, t + time_offset + 1, 0);
516                 }
517
518                 if (!ads_cleanup_expired_creds(context, ccache, credsp)) {
519                         creds_ready = true;
520                 }
521
522                 i++;
523         }
524
525         DEBUG(10,("ads_krb5_mk_req: Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
526                   principal, krb5_cc_get_type(context, ccache), krb5_cc_get_name(context, ccache),
527                   http_timestring(talloc_tos(), (unsigned)credsp->times.endtime), 
528                   (unsigned)credsp->times.endtime));
529
530         if (expire_time) {
531                 *expire_time = (time_t)credsp->times.endtime;
532         }
533
534         /* Allocate the auth_context. */
535         retval = setup_auth_context(context, auth_context);
536         if (retval) {
537                 DEBUG(1,("setup_auth_context failed (%s)\n",
538                         error_message(retval)));
539                 goto cleanup_creds;
540         }
541
542 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
543         {
544                 uint32_t gss_flags = 0;
545
546                 if( credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE ) {
547                         /* Fetch a forwarded TGT from the KDC so that we can hand off a 2nd ticket
548                          as part of the kerberos exchange. */
549
550                         DEBUG( 3, ("ads_krb5_mk_req: server marked as OK to delegate to, building forwardable TGT\n")  );
551
552                         retval = krb5_auth_con_setuseruserkey(context,
553                                         *auth_context,
554                                         &credsp->keyblock );
555                         if (retval) {
556                                 DEBUG(1,("krb5_auth_con_setuseruserkey failed (%s)\n",
557                                         error_message(retval)));
558                                 goto cleanup_creds;
559                         }
560
561                         /* Must use a subkey for forwarded tickets. */
562                         retval = krb5_auth_con_setflags(context,
563                                 *auth_context,
564                                 KRB5_AUTH_CONTEXT_USE_SUBKEY);
565                         if (retval) {
566                                 DEBUG(1,("krb5_auth_con_setflags failed (%s)\n",
567                                         error_message(retval)));
568                                 goto cleanup_creds;
569                         }
570
571                         retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
572                                 *auth_context,  /* Authentication context [in] */
573                                 discard_const_p(char, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
574                                 credsp->client, /* Client principal for the tgt [in] */
575                                 credsp->server, /* Server principal for the tgt [in] */
576                                 ccache,         /* Credential cache to use for storage [in] */
577                                 1,              /* Turn on for "Forwardable ticket" [in] */
578                                 &in_data );     /* Resulting response [out] */
579
580                         if (retval) {
581                                 DEBUG( 3, ("krb5_fwd_tgt_creds failed (%s)\n",
582                                            error_message( retval ) ) );
583
584                                 /*
585                                  * This is not fatal. Delete the *auth_context and continue
586                                  * with krb5_mk_req_extended to get a non-forwardable ticket.
587                                  */
588
589                                 if (in_data.data) {
590                                         free( in_data.data );
591                                         in_data.data = NULL;
592                                         in_data.length = 0;
593                                 }
594                                 krb5_auth_con_free(context, *auth_context);
595                                 *auth_context = NULL;
596                                 retval = setup_auth_context(context, auth_context);
597                                 if (retval) {
598                                         DEBUG(1,("setup_auth_context failed (%s)\n",
599                                                 error_message(retval)));
600                                         goto cleanup_creds;
601                                 }
602                         } else {
603                                 /* We got a delegated ticket. */
604                                 gss_flags |= GSS_C_DELEG_FLAG;
605                         }
606                 }
607
608                 /* Frees and reallocates in_data into a GSS checksum blob. */
609                 retval = create_gss_checksum(&in_data, gss_flags);
610                 if (retval) {
611                         goto cleanup_data;
612                 }
613
614                 /* We always want GSS-checksum types. */
615                 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
616                 if (retval) {
617                         DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
618                                 error_message(retval)));
619                         goto cleanup_data;
620                 }
621         }
622 #endif
623
624         retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
625                                       &in_data, credsp, outbuf);
626         if (retval) {
627                 DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
628                          error_message(retval)));
629         }
630
631 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
632 cleanup_data:
633 #endif
634
635         if (in_data.data) {
636                 free( in_data.data );
637                 in_data.length = 0;
638         }
639
640         krb5_free_creds(context, credsp);
641
642 cleanup_creds:
643         krb5_free_cred_contents(context, &creds);
644
645 cleanup_princ:
646         krb5_free_principal(context, server);
647         if (impersonate_princ) {
648                 krb5_free_principal(context, impersonate_princ);
649         }
650
651         return retval;
652 }
653
654 void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
655 {
656 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
657         if (pdata->data) {
658                 krb5_free_data_contents(context, pdata);
659         }
660 #elif defined(HAVE_KRB5_DATA_FREE)
661         krb5_data_free(context, pdata);
662 #else
663         SAFE_FREE(pdata->data);
664 #endif
665 }
666
667 /*
668   get a kerberos5 ticket for the given service
669 */
670 int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
671                         const char *principal, time_t time_offset,
672                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
673                         uint32_t extra_ap_opts, const char *ccname,
674                         time_t *tgs_expire,
675                         const char *impersonate_princ_s)
676
677 {
678         krb5_error_code retval;
679         krb5_data packet;
680         krb5_context context = NULL;
681         krb5_ccache ccdef = NULL;
682         krb5_auth_context auth_context = NULL;
683         krb5_enctype enc_types[] = {
684                 ENCTYPE_ARCFOUR_HMAC,
685                 ENCTYPE_DES_CBC_MD5,
686                 ENCTYPE_DES_CBC_CRC,
687                 ENCTYPE_NULL};
688
689         initialize_krb5_error_table();
690         retval = krb5_init_context(&context);
691         if (retval) {
692                 DEBUG(1, ("krb5_init_context failed (%s)\n",
693                          error_message(retval)));
694                 goto failed;
695         }
696
697         if (time_offset != 0) {
698                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
699         }
700
701         if ((retval = krb5_cc_resolve(context, ccname ?
702                         ccname : krb5_cc_default_name(context), &ccdef))) {
703                 DEBUG(1, ("krb5_cc_default failed (%s)\n",
704                          error_message(retval)));
705                 goto failed;
706         }
707
708         if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
709                 DEBUG(1, ("krb5_set_default_tgs_ktypes failed (%s)\n",
710                          error_message(retval)));
711                 goto failed;
712         }
713
714         retval = ads_krb5_mk_req(context, &auth_context,
715                                 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
716                                 principal, ccdef, &packet,
717                                 tgs_expire, impersonate_princ_s);
718         if (retval) {
719                 goto failed;
720         }
721
722         get_krb5_smb_session_key(mem_ctx, context, auth_context,
723                                  session_key_krb5, false);
724
725         *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
726
727         kerberos_free_data_contents(context, &packet);
728
729 failed:
730
731         if (context) {
732                 if (ccdef)
733                         krb5_cc_close(context, ccdef);
734                 if (auth_context)
735                         krb5_auth_con_free(context, auth_context);
736                 krb5_free_context(context);
737         }
738
739         return retval;
740 }
741
742 bool get_krb5_smb_session_key(TALLOC_CTX *mem_ctx,
743                               krb5_context context,
744                               krb5_auth_context auth_context,
745                               DATA_BLOB *session_key, bool remote)
746 {
747         krb5_keyblock *skey = NULL;
748         krb5_error_code err = 0;
749         bool ret = false;
750
751         if (remote) {
752                 err = krb5_auth_con_getremotesubkey(context,
753                                                     auth_context, &skey);
754         } else {
755                 err = krb5_auth_con_getlocalsubkey(context,
756                                                    auth_context, &skey);
757         }
758
759         if (err || skey == NULL) {
760                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
761                 goto done;
762         }
763
764         DEBUG(10, ("Got KRB5 session key of length %d\n",
765                    (int)KRB5_KEY_LENGTH(skey)));
766
767         *session_key = data_blob_talloc(mem_ctx,
768                                          KRB5_KEY_DATA(skey),
769                                          KRB5_KEY_LENGTH(skey));
770         dump_data_pw("KRB5 Session Key:\n",
771                      session_key->data,
772                      session_key->length);
773
774         ret = true;
775
776 done:
777         if (skey) {
778                 krb5_free_keyblock(context, skey);
779         }
780
781         return ret;
782 }
783
784
785 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
786  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
787
788  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
789 {
790         static krb5_data kdata;
791
792         kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
793         kdata.length = strlen((const char *)kdata.data);
794         return &kdata;
795 }
796 #endif
797
798 /* Prototypes */
799
800  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
801                                        const char *client_string,       /* gd@BER.SUSE.DE */
802                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
803                                        time_t *expire_time)
804 {
805         krb5_error_code ret;
806         krb5_context context = NULL;
807         krb5_ccache ccache = NULL;
808         krb5_principal client = NULL;
809         krb5_creds creds, creds_in, *creds_out = NULL;
810
811         ZERO_STRUCT(creds);
812         ZERO_STRUCT(creds_in);
813
814         initialize_krb5_error_table();
815         ret = krb5_init_context(&context);
816         if (ret) {
817                 goto done;
818         }
819
820         if (!ccache_string) {
821                 ccache_string = krb5_cc_default_name(context);
822         }
823
824         if (!ccache_string) {
825                 ret = EINVAL;
826                 goto done;
827         }
828
829         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
830
831         /* FIXME: we should not fall back to defaults */
832         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
833         if (ret) {
834                 goto done;
835         }
836
837         if (client_string) {
838                 ret = smb_krb5_parse_name(context, client_string, &client);
839                 if (ret) {
840                         goto done;
841                 }
842         } else {
843                 ret = krb5_cc_get_principal(context, ccache, &client);
844                 if (ret) {
845                         goto done;
846                 }
847         }
848
849         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
850         if (ret) {
851                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
852                 goto done;
853         }
854
855         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
856         ret = krb5_cc_initialize(context, ccache, client);
857         if (ret) {
858                 goto done;
859         }
860
861         ret = krb5_cc_store_cred(context, ccache, &creds);
862
863         if (expire_time) {
864                 *expire_time = (time_t) creds.times.endtime;
865         }
866
867 done:
868         krb5_free_cred_contents(context, &creds_in);
869
870         if (creds_out) {
871                 krb5_free_creds(context, creds_out);
872         } else {
873                 krb5_free_cred_contents(context, &creds);
874         }
875
876         if (client) {
877                 krb5_free_principal(context, client);
878         }
879         if (ccache) {
880                 krb5_cc_close(context, ccache);
881         }
882         if (context) {
883                 krb5_free_context(context);
884         }
885
886         return ret;
887 }
888
889  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
890 {
891         krb5_error_code ret = 0;
892         if (addr == NULL) {
893                 return ret;
894         }
895 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
896         krb5_free_addresses(context, addr->addrs);
897 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
898         ret = krb5_free_addresses(context, addr->addrs);
899         SAFE_FREE(addr->addrs);
900 #endif
901         SAFE_FREE(addr);
902         addr = NULL;
903         return ret;
904 }
905
906 #define MAX_NETBIOSNAME_LEN 16
907  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
908                                                    const char *netbios_name)
909 {
910         krb5_error_code ret = 0;
911         char buf[MAX_NETBIOSNAME_LEN];
912         int len;
913 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
914         krb5_address **addrs = NULL;
915 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
916         krb5_addresses *addrs = NULL;
917 #endif
918
919         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
920         if (*kerb_addr == NULL) {
921                 return ENOMEM;
922         }
923
924         /* temporarily duplicate put_name() code here to avoid dependency
925          * issues for a 5 lines function */
926         len = strlen(netbios_name);
927         memcpy(buf, netbios_name,
928                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
929         if (len < MAX_NETBIOSNAME_LEN - 1) {
930                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
931         }
932         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
933
934 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
935         {
936                 int num_addr = 2;
937
938                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
939                 if (addrs == NULL) {
940                         SAFE_FREE(*kerb_addr);
941                         return ENOMEM;
942                 }
943
944                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
945
946                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
947                 if (addrs[0] == NULL) {
948                         SAFE_FREE(addrs);
949                         SAFE_FREE(*kerb_addr);
950                         return ENOMEM;
951                 }
952
953                 addrs[0]->magic = KV5M_ADDRESS;
954                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
955                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
956                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
957                 if (addrs[0]->contents == NULL) {
958                         SAFE_FREE(addrs[0]);
959                         SAFE_FREE(addrs);
960                         SAFE_FREE(*kerb_addr);
961                         return ENOMEM;
962                 }
963
964                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
965
966                 addrs[1] = NULL;
967         }
968 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
969         {
970                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
971                 if (addrs == NULL) {
972                         SAFE_FREE(*kerb_addr);
973                         return ENOMEM;
974                 }
975
976                 memset(addrs, 0, sizeof(krb5_addresses));
977
978                 addrs->len = 1;
979                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
980                 if (addrs->val == NULL) {
981                         SAFE_FREE(addrs);
982                         SAFE_FREE(kerb_addr);
983                         return ENOMEM;
984                 }
985
986                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
987                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
988                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
989                 if (addrs->val[0].address.data == NULL) {
990                         SAFE_FREE(addrs->val);
991                         SAFE_FREE(addrs);
992                         SAFE_FREE(*kerb_addr);
993                         return ENOMEM;
994                 }
995
996                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
997         }
998 #else
999 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1000 #endif
1001         (*kerb_addr)->addrs = addrs;
1002
1003         return ret;
1004 }
1005
1006  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1007 {
1008 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1009         krb5_free_error_contents(context, krberror);
1010 #else /* MIT */
1011         krb5_free_error(context, krberror);
1012 #endif
1013 }
1014
1015  krb5_error_code handle_krberror_packet(krb5_context context,
1016                                         krb5_data *packet)
1017 {
1018         krb5_error_code ret;
1019         bool got_error_code = false;
1020
1021         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1022
1023 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1024         {
1025                 krb5_error krberror;
1026
1027                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1028                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1029                                 error_message(ret)));
1030                         return ret;
1031                 }
1032
1033                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1034                         ret = (krb5_error_code) krberror.error_code;
1035                         got_error_code = true;
1036                 }
1037
1038                 smb_krb5_free_error(context, &krberror);
1039         }
1040 #else /* MIT */
1041         {
1042                 krb5_error *krberror;
1043
1044                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1045                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1046                                 error_message(ret)));
1047                         return ret;
1048                 }
1049
1050                 if (krberror->e_data.data == NULL) {
1051 #if defined(ERROR_TABLE_BASE_krb5)
1052                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1053 #else
1054                         ret = (krb5_error_code)krberror->error;
1055 #endif
1056                         got_error_code = true;
1057                 }
1058                 smb_krb5_free_error(context, krberror);
1059         }
1060 #endif
1061         if (got_error_code) {
1062                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1063                         error_message(ret), ret));
1064         }
1065         return ret;
1066 }
1067
1068 krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1069                                             krb5_get_init_creds_opt **opt)
1070 {
1071         /* Heimdal or modern MIT version */
1072         return krb5_get_init_creds_opt_alloc(context, opt);
1073 }
1074
1075 void smb_krb5_get_init_creds_opt_free(krb5_context context,
1076                                 krb5_get_init_creds_opt *opt)
1077 {
1078         /* Modern MIT or Heimdal version */
1079         krb5_get_init_creds_opt_free(context, opt);
1080 }
1081
1082 krb5_enctype smb_get_enctype_from_kt_entry(krb5_keytab_entry *kt_entry)
1083 {
1084         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1085 }
1086
1087 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1088                                         krb5_keytab_entry *kt_entry)
1089 {
1090 /* Try krb5_free_keytab_entry_contents first, since
1091  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1092  * krb5_kt_free_entry but only has a prototype for the first, while the
1093  * second is considered private.
1094  */
1095 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1096         return krb5_free_keytab_entry_contents(context, kt_entry);
1097 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1098         return krb5_kt_free_entry(context, kt_entry);
1099 #else
1100 #error UNKNOWN_KT_FREE_FUNCTION
1101 #endif
1102 }
1103
1104
1105 /* caller needs to free etype_s */
1106 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1107                                            krb5_enctype enctype,
1108                                            char **etype_s)
1109 {
1110 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1111         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1112 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1113         char buf[256];
1114         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1115         if (ret) {
1116                 return ret;
1117         }
1118         *etype_s = SMB_STRDUP(buf);
1119         if (!*etype_s) {
1120                 return ENOMEM;
1121         }
1122         return ret;
1123 #else
1124 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1125 #endif
1126 }
1127
1128 /**********************************************************************
1129  * Open a krb5 keytab with flags, handles readonly or readwrite access and
1130  * allows to process non-default keytab names.
1131  * @param context krb5_context
1132  * @param keytab_name_req string
1133  * @param write_access bool if writable keytab is required
1134  * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
1135  * @return krb5_error_code
1136 **********************************************************************/
1137
1138 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1139 #ifndef MAX_KEYTAB_NAME_LEN
1140 #define MAX_KEYTAB_NAME_LEN 1100
1141 #endif
1142
1143 krb5_error_code smb_krb5_open_keytab(krb5_context context,
1144                                      const char *keytab_name_req,
1145                                      bool write_access,
1146                                      krb5_keytab *keytab)
1147 {
1148         krb5_error_code ret = 0;
1149         TALLOC_CTX *mem_ctx;
1150         char keytab_string[MAX_KEYTAB_NAME_LEN];
1151         char *kt_str = NULL;
1152         bool found_valid_name = false;
1153         const char *pragma = "FILE";
1154         const char *tmp = NULL;
1155
1156         if (!write_access && !keytab_name_req) {
1157                 /* caller just wants to read the default keytab readonly, so be it */
1158                 return krb5_kt_default(context, keytab);
1159         }
1160
1161         mem_ctx = talloc_init("smb_krb5_open_keytab");
1162         if (!mem_ctx) {
1163                 return ENOMEM;
1164         }
1165
1166 #ifdef HAVE_WRFILE_KEYTAB
1167         if (write_access) {
1168                 pragma = "WRFILE";
1169         }
1170 #endif
1171
1172         if (keytab_name_req) {
1173
1174                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1175                         ret = KRB5_CONFIG_NOTENUFSPACE;
1176                         goto out;
1177                 }
1178
1179                 if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) ||
1180                     (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
1181                         tmp = keytab_name_req;
1182                         goto resolve;
1183                 }
1184
1185                 if (keytab_name_req[0] != '/') {
1186                         ret = KRB5_KT_BADNAME;
1187                         goto out;
1188                 }
1189
1190                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1191                 if (!tmp) {
1192                         ret = ENOMEM;
1193                         goto out;
1194                 }
1195
1196                 goto resolve;
1197         }
1198
1199         /* we need to handle more complex keytab_strings, like:
1200          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1201
1202         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1203         if (ret) {
1204                 goto out;
1205         }
1206
1207         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1208
1209         tmp = talloc_strdup(mem_ctx, keytab_string);
1210         if (!tmp) {
1211                 ret = ENOMEM;
1212                 goto out;
1213         }
1214
1215         if (strncmp(tmp, "ANY:", 4) == 0) {
1216                 tmp += 4;
1217         }
1218
1219         memset(&keytab_string, '\0', sizeof(keytab_string));
1220
1221         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1222                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1223                         found_valid_name = true;
1224                         tmp = kt_str;
1225                         tmp += 7;
1226                 }
1227
1228                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1229                         found_valid_name = true;
1230                         tmp = kt_str;
1231                         tmp += 5;
1232                 }
1233
1234                 if (tmp[0] == '/') {
1235                         /* Treat as a FILE: keytab definition. */
1236                         found_valid_name = true;
1237                 }
1238
1239                 if (found_valid_name) {
1240                         if (tmp[0] != '/') {
1241                                 ret = KRB5_KT_BADNAME;
1242                                 goto out;
1243                         }
1244
1245                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1246                         if (!tmp) {
1247                                 ret = ENOMEM;
1248                                 goto out;
1249                         }
1250                         break;
1251                 }
1252         }
1253
1254         if (!found_valid_name) {
1255                 ret = KRB5_KT_UNKNOWN_TYPE;
1256                 goto out;
1257         }
1258
1259  resolve:
1260         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1261         ret = krb5_kt_resolve(context, tmp, keytab);
1262
1263  out:
1264         TALLOC_FREE(mem_ctx);
1265         return ret;
1266 }
1267
1268 krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
1269                                      krb5_context context,
1270                                      krb5_keytab keytab,
1271                                      const char **keytab_name)
1272 {
1273         char keytab_string[MAX_KEYTAB_NAME_LEN];
1274         krb5_error_code ret = 0;
1275
1276         ret = krb5_kt_get_name(context, keytab,
1277                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1278         if (ret) {
1279                 return ret;
1280         }
1281
1282         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1283         if (!*keytab_name) {
1284                 return ENOMEM;
1285         }
1286
1287         return ret;
1288 }
1289
1290 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1291     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1292     defined(HAVE_KRB5_GET_CREDS)
1293 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1294                                                              krb5_ccache ccache,
1295                                                              krb5_principal me,
1296                                                              krb5_principal server,
1297                                                              krb5_principal impersonate_princ,
1298                                                              krb5_creds **out_creds)
1299 {
1300         krb5_error_code ret;
1301         krb5_get_creds_opt opt;
1302
1303         ret = krb5_get_creds_opt_alloc(context, &opt);
1304         if (ret) {
1305                 goto done;
1306         }
1307         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1308
1309         if (impersonate_princ) {
1310                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1311                                                          impersonate_princ);
1312                 if (ret) {
1313                         goto done;
1314                 }
1315         }
1316
1317         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1318         if (ret) {
1319                 goto done;
1320         }
1321
1322  done:
1323         if (opt) {
1324                 krb5_get_creds_opt_free(context, opt);
1325         }
1326         return ret;
1327 }
1328 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1329
1330 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1331 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1332                                                          krb5_ccache ccache,
1333                                                          krb5_principal me,
1334                                                          krb5_principal server,
1335                                                          krb5_principal impersonate_princ,
1336                                                          krb5_creds **out_creds)
1337 {
1338         krb5_error_code ret;
1339         krb5_creds in_creds;
1340
1341 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1342 krb5_error_code KRB5_CALLCONV
1343 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1344                               krb5_ccache ccache, krb5_creds *in_creds,
1345                               krb5_data *subject_cert,
1346                               krb5_creds **out_creds);
1347 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1348
1349         ZERO_STRUCT(in_creds);
1350
1351         if (impersonate_princ) {
1352
1353                 in_creds.server = me;
1354                 in_creds.client = impersonate_princ;
1355
1356                 ret = krb5_get_credentials_for_user(context,
1357                                                     0, /* krb5_flags options */
1358                                                     ccache,
1359                                                     &in_creds,
1360                                                     NULL, /* krb5_data *subject_cert */
1361                                                     out_creds);
1362         } else {
1363                 in_creds.client = me;
1364                 in_creds.server = server;
1365
1366                 ret = krb5_get_credentials(context, 0, ccache,
1367                                            &in_creds, out_creds);
1368         }
1369
1370         return ret;
1371 }
1372 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1373
1374 /*
1375  * smb_krb5_get_credentials
1376  *
1377  * @brief Get krb5 credentials for a server
1378  *
1379  * @param[in] context           An initialized krb5_context
1380  * @param[in] ccache            An initialized krb5_ccache
1381  * @param[in] me                The krb5_principal of the caller
1382  * @param[in] server            The krb5_principal of the requested service
1383  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1384  * @param[out] out_creds        The returned krb5_creds structure
1385  * @return krb5_error_code
1386  *
1387  */
1388 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1389                                          krb5_ccache ccache,
1390                                          krb5_principal me,
1391                                          krb5_principal server,
1392                                          krb5_principal impersonate_princ,
1393                                          krb5_creds **out_creds)
1394 {
1395         krb5_error_code ret;
1396         krb5_creds *creds = NULL;
1397
1398         *out_creds = NULL;
1399
1400         if (impersonate_princ) {
1401 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1402                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1403 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1404                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1405 #else
1406                 ret = ENOTSUP;
1407 #endif
1408         } else {
1409                 krb5_creds in_creds;
1410
1411                 ZERO_STRUCT(in_creds);
1412
1413                 in_creds.client = me;
1414                 in_creds.server = server;
1415
1416                 ret = krb5_get_credentials(context, 0, ccache,
1417                                            &in_creds, &creds);
1418         }
1419         if (ret) {
1420                 goto done;
1421         }
1422
1423         if (out_creds) {
1424                 *out_creds = creds;
1425         }
1426
1427  done:
1428         if (creds && ret) {
1429                 krb5_free_creds(context, creds);
1430         }
1431
1432         return ret;
1433 }
1434
1435 /*
1436  * smb_krb5_get_creds
1437  *
1438  * @brief Get krb5 credentials for a server
1439  *
1440  * @param[in] server_s          The string name of the service
1441  * @param[in] time_offset       The offset to the KDCs time in seconds (optional)
1442  * @param[in] cc                The krb5 credential cache string name (optional)
1443  * @param[in] impersonate_princ_s The string principal name to impersonate (optional)
1444  * @param[out] creds_p          The returned krb5_creds structure
1445  * @return krb5_error_code
1446  *
1447  */
1448 krb5_error_code smb_krb5_get_creds(const char *server_s,
1449                                    time_t time_offset,
1450                                    const char *cc,
1451                                    const char *impersonate_princ_s,
1452                                    krb5_creds **creds_p)
1453 {
1454         krb5_error_code ret;
1455         krb5_context context = NULL;
1456         krb5_principal me = NULL;
1457         krb5_principal server = NULL;
1458         krb5_principal impersonate_princ = NULL;
1459         krb5_creds *creds = NULL;
1460         krb5_ccache ccache = NULL;
1461
1462         *creds_p = NULL;
1463
1464         initialize_krb5_error_table();
1465         ret = krb5_init_context(&context);
1466         if (ret) {
1467                 goto done;
1468         }
1469
1470         if (time_offset != 0) {
1471                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
1472         }
1473
1474         ret = krb5_cc_resolve(context, cc ? cc :
1475                 krb5_cc_default_name(context), &ccache);
1476         if (ret) {
1477                 goto done;
1478         }
1479
1480         ret = krb5_cc_get_principal(context, ccache, &me);
1481         if (ret) {
1482                 goto done;
1483         }
1484
1485         ret = smb_krb5_parse_name(context, server_s, &server);
1486         if (ret) {
1487                 goto done;
1488         }
1489
1490         if (impersonate_princ_s) {
1491                 ret = smb_krb5_parse_name(context, impersonate_princ_s,
1492                                           &impersonate_princ);
1493                 if (ret) {
1494                         goto done;
1495                 }
1496         }
1497
1498         ret = smb_krb5_get_credentials(context, ccache,
1499                                        me, server, impersonate_princ,
1500                                        &creds);
1501         if (ret) {
1502                 goto done;
1503         }
1504
1505         ret = krb5_cc_store_cred(context, ccache, creds);
1506         if (ret) {
1507                 goto done;
1508         }
1509
1510         if (creds_p) {
1511                 *creds_p = creds;
1512         }
1513
1514         DEBUG(1,("smb_krb5_get_creds: got ticket for %s\n",
1515                 server_s));
1516
1517         if (impersonate_princ_s) {
1518                 char *client = NULL;
1519
1520                 ret = smb_krb5_unparse_name(talloc_tos(), context, creds->client, &client);
1521                 if (ret) {
1522                         goto done;
1523                 }
1524                 DEBUGADD(1,("smb_krb5_get_creds: using S4U2SELF impersonation as %s\n",
1525                         client));
1526                 TALLOC_FREE(client);
1527         }
1528
1529  done:
1530         if (!context) {
1531                 return ret;
1532         }
1533
1534         if (creds && ret) {
1535                 krb5_free_creds(context, creds);
1536         }
1537         if (server) {
1538                 krb5_free_principal(context, server);
1539         }
1540         if (me) {
1541                 krb5_free_principal(context, me);
1542         }
1543         if (impersonate_princ) {
1544                 krb5_free_principal(context, impersonate_princ);
1545         }
1546         if (ccache) {
1547                 krb5_cc_close(context, ccache);
1548         }
1549         krb5_free_context(context);
1550
1551         return ret;
1552 }
1553
1554 /*
1555  * smb_krb5_principal_get_realm
1556  *
1557  * @brief Get realm of a principal
1558  *
1559  * @param[in] context           The krb5_context
1560  * @param[in] principal         The principal
1561  * @return pointer to the realm
1562  *
1563  */
1564
1565 char *smb_krb5_principal_get_realm(krb5_context context,
1566                                    krb5_principal principal)
1567 {
1568 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
1569         return discard_const_p(char, krb5_principal_get_realm(context, principal));
1570 #elif defined(krb5_princ_realm) /* MIT */
1571         krb5_data *realm;
1572         realm = krb5_princ_realm(context, principal);
1573         return discard_const_p(char, realm->data);
1574 #else
1575         return NULL;
1576 #endif
1577 }
1578
1579 /************************************************************************
1580  Routine to get the default realm from the kerberos credentials cache.
1581  Caller must free if the return value is not NULL.
1582 ************************************************************************/
1583
1584 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
1585 {
1586         char *realm = NULL;
1587         krb5_context ctx = NULL;
1588         krb5_ccache cc = NULL;
1589         krb5_principal princ = NULL;
1590
1591         initialize_krb5_error_table();
1592         if (krb5_init_context(&ctx)) {
1593                 return NULL;
1594         }
1595
1596         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
1597                 "Trying to read krb5 cache: %s\n",
1598                 krb5_cc_default_name(ctx)));
1599         if (krb5_cc_default(ctx, &cc)) {
1600                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
1601                         "failed to read default cache\n"));
1602                 goto out;
1603         }
1604         if (krb5_cc_get_principal(ctx, cc, &princ)) {
1605                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
1606                         "failed to get default principal\n"));
1607                 goto out;
1608         }
1609
1610 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
1611         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
1612 #elif defined(HAVE_KRB5_PRINC_REALM)
1613         {
1614                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
1615                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
1616         }
1617 #endif
1618
1619   out:
1620
1621         if (ctx) {
1622                 if (princ) {
1623                         krb5_free_principal(ctx, princ);
1624                 }
1625                 if (cc) {
1626                         krb5_cc_close(ctx, cc);
1627                 }
1628                 krb5_free_context(ctx);
1629         }
1630
1631         return realm;
1632 }
1633
1634 /************************************************************************
1635  Routine to get the realm from a given DNS name.
1636 ************************************************************************/
1637
1638 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
1639                                                 const char *hostname)
1640 {
1641 #if defined(HAVE_KRB5_REALM_TYPE)
1642         /* Heimdal. */
1643         krb5_realm *realm_list = NULL;
1644 #else
1645         /* MIT */
1646         char **realm_list = NULL;
1647 #endif
1648         char *realm = NULL;
1649         krb5_error_code kerr;
1650         krb5_context ctx = NULL;
1651
1652         initialize_krb5_error_table();
1653         if (krb5_init_context(&ctx)) {
1654                 return NULL;
1655         }
1656
1657         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
1658         if (kerr != 0) {
1659                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
1660                         "failed %s\n",
1661                         hostname ? hostname : "(NULL)",
1662                         error_message(kerr) ));
1663                 goto out;
1664         }
1665
1666         if (realm_list && realm_list[0]) {
1667                 realm = talloc_strdup(mem_ctx, realm_list[0]);
1668         }
1669
1670   out:
1671
1672         if (ctx) {
1673                 if (realm_list) {
1674                         krb5_free_host_realm(ctx, realm_list);
1675                         realm_list = NULL;
1676                 }
1677                 krb5_free_context(ctx);
1678                 ctx = NULL;
1679         }
1680         return realm;
1681 }
1682
1683 char *kerberos_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
1684                                                    const char *service,
1685                                                    const char *remote_name,
1686                                                    const char *default_realm)
1687 {
1688         char *realm = NULL;
1689         char *host = NULL;
1690         char *principal;
1691         host = strchr_m(remote_name, '.');
1692         if (host) {
1693                 /* DNS name. */
1694                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
1695                                                          remote_name);
1696         } else {
1697                 /* NetBIOS name - use our realm. */
1698                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
1699         }
1700
1701         if (realm == NULL || *realm == '\0') {
1702                 realm = talloc_strdup(talloc_tos(), default_realm);
1703                 if (!realm) {
1704                         return NULL;
1705                 }
1706                 DEBUG(3,("kerberos_get_principal_from_service_hostname: "
1707                          "cannot get realm from, "
1708                          "desthost %s or default ccache. Using default "
1709                          "smb.conf realm %s\n",
1710                          remote_name,
1711                          realm));
1712         }
1713
1714         principal = talloc_asprintf(mem_ctx,
1715                                     "%s/%s@%s",
1716                                     service, remote_name,
1717                                     realm);
1718         TALLOC_FREE(realm);
1719         return principal;
1720 }
1721
1722 char *smb_get_krb5_error_message(krb5_context context,
1723                                  krb5_error_code code,
1724                                  TALLOC_CTX *mem_ctx)
1725 {
1726         char *ret;
1727
1728 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
1729         const char *context_error = krb5_get_error_message(context, code);
1730         if (context_error) {
1731                 ret = talloc_asprintf(mem_ctx, "%s: %s",
1732                                         error_message(code), context_error);
1733                 krb5_free_error_message(context, context_error);
1734                 return ret;
1735         }
1736 #endif
1737         ret = talloc_strdup(mem_ctx, error_message(code));
1738         return ret;
1739 }
1740
1741 #else /* HAVE_KRB5 */
1742  /* this saves a few linking headaches */
1743  int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
1744                         const char *principal, time_t time_offset,
1745                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
1746                         uint32_t extra_ap_opts,
1747                         const char *ccname, time_t *tgs_expire,
1748                         const char *impersonate_princ_s)
1749 {
1750          DEBUG(0,("NO KERBEROS SUPPORT\n"));
1751          return 1;
1752 }
1753
1754 #endif /* HAVE_KRB5 */