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