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