krb5_wrap: Do not use deprecated KRB5 functions
[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 "system/filesys.h"
25 #include "krb5_samba.h"
26 #include "lib/util/asn1.h"
27
28 #ifdef HAVE_COM_ERR_H
29 #include <com_err.h>
30 #endif /* HAVE_COM_ERR_H */
31
32 #ifndef KRB5_AUTHDATA_WIN2K_PAC
33 #define KRB5_AUTHDATA_WIN2K_PAC 128
34 #endif
35
36 #ifndef KRB5_AUTHDATA_IF_RELEVANT
37 #define KRB5_AUTHDATA_IF_RELEVANT 1
38 #endif
39
40 #ifdef HAVE_KRB5
41
42 #define GSSAPI_CHECKSUM      0x8003             /* Checksum type value for Kerberos */
43 #define GSSAPI_BNDLENGTH     16                 /* Bind Length (rfc-1964 pg.3) */
44 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
45                                                         bind field, flags field. */
46 #define GSS_C_DELEG_FLAG 1
47
48 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
49    but still has the symbol */
50 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
51 krb5_error_code krb5_auth_con_set_req_cksumtype(
52         krb5_context     context,
53         krb5_auth_context      auth_context,
54         krb5_cksumtype     cksumtype);
55 #endif
56
57 #if !defined(SMB_MALLOC)
58 #undef malloc
59 #define SMB_MALLOC(s) malloc((s))
60 #endif
61
62 #ifndef SMB_STRDUP
63 #define SMB_STRDUP(s) strdup(s)
64 #endif
65
66 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
67
68 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
69
70 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
71  * to krb5_set_default_tgs_ktypes. See
72  *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
73  *
74  * If the MIT libraries are not exporting internal symbols, we will end up in
75  * this branch, which is correct. Otherwise we will continue to use the
76  * internal symbol
77  */
78  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
79 {
80     return krb5_set_default_tgs_enctypes(ctx, enc);
81 }
82
83 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
84
85 /* Heimdal */
86  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
87 {
88         return krb5_set_default_in_tkt_etypes(ctx, enc);
89 }
90
91 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
92
93 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
94
95 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
96 /* HEIMDAL */
97  bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
98 {
99         memset(pkaddr, '\0', sizeof(krb5_address));
100 #if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
101         if (paddr->ss_family == AF_INET6) {
102                 pkaddr->addr_type = KRB5_ADDRESS_INET6;
103                 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
104                 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
105                 return true;
106         }
107 #endif
108         if (paddr->ss_family == AF_INET) {
109                 pkaddr->addr_type = KRB5_ADDRESS_INET;
110                 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
111                 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
112                 return true;
113         }
114         return false;
115 }
116 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
117 /* MIT */
118 bool setup_kaddr( krb5_address *pkaddr, struct sockaddr_storage *paddr)
119 {
120         memset(pkaddr, '\0', sizeof(krb5_address));
121 #if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
122         if (paddr->ss_family == AF_INET6) {
123                 pkaddr->addrtype = ADDRTYPE_INET6;
124                 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
125                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
126                 return true;
127         }
128 #endif
129         if (paddr->ss_family == AF_INET) {
130                 pkaddr->addrtype = ADDRTYPE_INET;
131                 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
132                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
133                 return true;
134         }
135         return false;
136 }
137 #else
138 #error UNKNOWN_ADDRTYPE
139 #endif
140
141 /**
142 * @brief Create a keyblock based on input parameters
143 *
144 * @param context        The krb5_context
145 * @param host_princ     The krb5_principal to use
146 * @param salt           The optional salt, if omitted, salt is calculated with
147 *                       the provided principal.
148 * @param password       The krb5_data containing the password
149 * @param enctype        The krb5_enctype to use for the keyblock generation
150 * @param key            The returned krb5_keyblock, caller needs to free with
151 *                       krb5_free_keyblock().
152 *
153 * @return krb5_error_code
154 */
155 int smb_krb5_create_key_from_string(krb5_context context,
156                                     krb5_const_principal host_princ,
157                                     krb5_data *salt,
158                                     krb5_data *password,
159                                     krb5_enctype enctype,
160                                     krb5_keyblock *key)
161 {
162         int ret = 0;
163
164         if (host_princ == NULL && salt == NULL) {
165                 return -1;
166         }
167
168 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
169 {/* MIT */
170         krb5_data _salt;
171
172         if (salt == NULL) {
173                 ret = krb5_principal2salt(context, host_princ, &_salt);
174                 if (ret) {
175                         DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
176                         return ret;
177                 }
178         } else {
179                 _salt = *salt;
180         }
181         ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
182         if (salt == NULL) {
183                 SAFE_FREE(_salt.data);
184         }
185 }
186 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
187 {/* Heimdal */
188         krb5_salt _salt;
189
190         if (salt == NULL) {
191                 ret = krb5_get_pw_salt(context, host_princ, &_salt);
192                 if (ret) {
193                         DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
194                         return ret;
195                 }
196         } else {
197                 _salt.saltvalue = *salt;
198                 _salt.salttype = KRB5_PW_SALT;
199         }
200
201         ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
202         if (salt == NULL) {
203                 krb5_free_salt(context, _salt);
204         }
205 }
206 #else
207 #error UNKNOWN_CREATE_KEY_FUNCTIONS
208 #endif
209         return ret;
210 }
211
212 /**
213 * @brief Create a salt for a given principal
214 *
215 * @param context        The initialized krb5_context
216 * @param host_princ     The krb5_principal to create the salt for
217 * @param psalt          A pointer to a krb5_data struct
218 *
219 * caller has to free the contents of psalt with kerberos_free_data_contents
220 * when function has succeeded
221 *
222 * @return krb5_error_code, returns 0 on success, error code otherwise
223 */
224
225 int smb_krb5_get_pw_salt(krb5_context context,
226                          krb5_const_principal host_princ,
227                          krb5_data *psalt)
228 #if defined(HAVE_KRB5_GET_PW_SALT)
229 /* Heimdal */
230 {
231         int ret;
232         krb5_salt salt;
233
234         ret = krb5_get_pw_salt(context, host_princ, &salt);
235         if (ret) {
236                 return ret;
237         }
238
239         psalt->data = salt.saltvalue.data;
240         psalt->length = salt.saltvalue.length;
241
242         return ret;
243 }
244 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
245 /* MIT */
246 {
247         return krb5_principal2salt(context, host_princ, psalt);
248 }
249 #else
250 #error UNKNOWN_SALT_FUNCTIONS
251 #endif
252
253 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
254  krb5_error_code get_kerberos_allowed_etypes(krb5_context context,
255                                             krb5_enctype **enctypes)
256 {
257         return krb5_get_permitted_enctypes(context, enctypes);
258 }
259 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
260  krb5_error_code get_kerberos_allowed_etypes(krb5_context context,
261                                             krb5_enctype **enctypes)
262 {
263 #ifdef HAVE_KRB5_PDU_NONE_DECL
264         return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
265 #else
266         return krb5_get_default_in_tkt_etypes(context, enctypes);
267 #endif
268 }
269 #else
270 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
271 #endif
272
273 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
274  krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
275                                         krb5_auth_context auth_context,
276                                         krb5_keyblock *keyblock)
277 {
278         return krb5_auth_con_setkey(context, auth_context, keyblock);
279 }
280 #endif
281
282 bool unwrap_edata_ntstatus(TALLOC_CTX *mem_ctx,
283                            DATA_BLOB *edata,
284                            DATA_BLOB *edata_out)
285 {
286         DATA_BLOB edata_contents;
287         ASN1_DATA *data;
288         int edata_type;
289
290         if (!edata->length) {
291                 return false;
292         }
293
294         data = asn1_init(mem_ctx);
295         if (data == NULL) {
296                 return false;
297         }
298
299         if (!asn1_load(data, *edata)) goto err;
300         if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto err;
301         if (!asn1_start_tag(data, ASN1_CONTEXT(1))) goto err;
302         if (!asn1_read_Integer(data, &edata_type)) goto err;
303
304         if (edata_type != KRB5_PADATA_PW_SALT) {
305                 DEBUG(0,("edata is not of required type %d but of type %d\n",
306                         KRB5_PADATA_PW_SALT, edata_type));
307                 goto err;
308         }
309
310         if (!asn1_start_tag(data, ASN1_CONTEXT(2))) goto err;
311         if (!asn1_read_OctetString(data, talloc_tos(), &edata_contents)) goto err;
312         if (!asn1_end_tag(data)) goto err;
313         if (!asn1_end_tag(data)) goto err;
314         if (!asn1_end_tag(data)) goto err;
315         asn1_free(data);
316
317         *edata_out = data_blob_talloc(mem_ctx, edata_contents.data, edata_contents.length);
318
319         data_blob_free(&edata_contents);
320
321         return true;
322
323   err:
324
325         asn1_free(data);
326         return false;
327 }
328
329
330 static bool ads_cleanup_expired_creds(krb5_context context,
331                                       krb5_ccache  ccache,
332                                       krb5_creds  *credsp)
333 {
334         krb5_error_code retval;
335         const char *cc_type = krb5_cc_get_type(context, ccache);
336
337         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
338                   cc_type, krb5_cc_get_name(context, ccache),
339                   http_timestring(talloc_tos(), credsp->times.endtime)));
340
341         /* we will probably need new tickets if the current ones
342            will expire within 10 seconds.
343         */
344         if (credsp->times.endtime >= (time(NULL) + 10))
345                 return false;
346
347         /* heimdal won't remove creds from a file ccache, and
348            perhaps we shouldn't anyway, since internally we
349            use memory ccaches, and a FILE one probably means that
350            we're using creds obtained outside of our exectuable
351         */
352         if (strequal(cc_type, "FILE")) {
353                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
354                 return false;
355         }
356
357         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
358         if (retval) {
359                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
360                           error_message(retval)));
361                 /* If we have an error in this, we want to display it,
362                    but continue as though we deleted it */
363         }
364         return true;
365 }
366
367 /* Allocate and setup the auth context into the state we need. */
368
369 static krb5_error_code setup_auth_context(krb5_context context,
370                         krb5_auth_context *auth_context)
371 {
372         krb5_error_code retval;
373
374         retval = krb5_auth_con_init(context, auth_context );
375         if (retval) {
376                 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
377                         error_message(retval)));
378                 return retval;
379         }
380
381         /* Ensure this is an addressless ticket. */
382         retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
383         if (retval) {
384                 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
385                         error_message(retval)));
386         }
387
388         return retval;
389 }
390
391 #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)
392 static krb5_error_code create_gss_checksum(krb5_data *in_data, /* [inout] */
393                                                 uint32_t gss_flags)
394 {
395         unsigned int orig_length = in_data->length;
396         unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
397         char *gss_cksum = NULL;
398
399         if (orig_length) {
400                 /* Extra length field for delgated ticket. */
401                 base_cksum_size += 4;
402         }
403
404         if ((unsigned int)base_cksum_size + orig_length <
405                         (unsigned int)base_cksum_size) {
406                 return EINVAL;
407         }
408
409         gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
410         if (gss_cksum == NULL) {
411                 return ENOMEM;
412         }
413
414         memset(gss_cksum, '\0', base_cksum_size + orig_length);
415         SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
416
417         /*
418          * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
419          * This matches the behavior of heimdal and mit.
420          *
421          * And it is needed to work against some closed source
422          * SMB servers.
423          *
424          * See bug #7883
425          */
426         memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
427
428         SIVAL(gss_cksum, 20, gss_flags);
429
430         if (orig_length) {
431                 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
432                 SSVAL(gss_cksum, 26, orig_length);
433                 /* Copy the kerberos KRB_CRED data */
434                 memcpy(gss_cksum + 28, in_data->data, orig_length);
435                 free(in_data->data);
436                 in_data->data = NULL;
437                 in_data->length = 0;
438         }
439         in_data->data = gss_cksum;
440         in_data->length = base_cksum_size + orig_length;
441         return 0;
442 }
443 #endif
444
445 /**************************************************************
446  krb5_parse_name that takes a UNIX charset.
447 **************************************************************/
448
449 krb5_error_code smb_krb5_parse_name(krb5_context context,
450                                 const char *name, /* in unix charset */
451                                 krb5_principal *principal)
452 {
453         krb5_error_code ret;
454         char *utf8_name;
455         size_t converted_size;
456         TALLOC_CTX *frame = talloc_stackframe();
457
458         if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
459                 talloc_free(frame);
460                 return ENOMEM;
461         }
462
463         ret = krb5_parse_name(context, utf8_name, principal);
464         TALLOC_FREE(frame);
465         return ret;
466 }
467
468 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
469 void krb5_free_unparsed_name(krb5_context context, char *val)
470 {
471         SAFE_FREE(val);
472 }
473 #endif
474
475 /**************************************************************
476  krb5_parse_name that returns a UNIX charset name. Must
477  be freed with talloc_free() call.
478 **************************************************************/
479
480 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
481                                       krb5_context context,
482                                       krb5_const_principal principal,
483                                       char **unix_name)
484 {
485         krb5_error_code ret;
486         char *utf8_name;
487         size_t converted_size;
488
489         *unix_name = NULL;
490         ret = krb5_unparse_name(context, principal, &utf8_name);
491         if (ret) {
492                 return ret;
493         }
494
495         if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
496                 krb5_free_unparsed_name(context, utf8_name);
497                 return ENOMEM;
498         }
499         krb5_free_unparsed_name(context, utf8_name);
500         return 0;
501 }
502
503 krb5_error_code smb_krb5_parse_name_norealm(krb5_context context, 
504                                             const char *name, 
505                                             krb5_principal *principal)
506 {
507         /* we are cheating here because parse_name will in fact set the realm.
508          * We don't care as the only caller of smb_krb5_parse_name_norealm
509          * ignores the realm anyway when calling
510          * smb_krb5_principal_compare_any_realm later - Guenther */
511
512         return smb_krb5_parse_name(context, name, principal);
513 }
514
515 bool smb_krb5_principal_compare_any_realm(krb5_context context, 
516                                           krb5_const_principal princ1, 
517                                           krb5_const_principal princ2)
518 {
519         return krb5_principal_compare_any_realm(context, princ1, princ2);
520 }
521
522 /*
523   we can't use krb5_mk_req because w2k wants the service to be in a particular format
524 */
525 static krb5_error_code ads_krb5_mk_req(krb5_context context,
526                                        krb5_auth_context *auth_context,
527                                        const krb5_flags ap_req_options,
528                                        const char *principal,
529                                        krb5_ccache ccache,
530                                        krb5_data *outbuf,
531                                        time_t *expire_time,
532                                        const char *impersonate_princ_s)
533 {
534         krb5_error_code           retval;
535         krb5_principal    server;
536         krb5_principal impersonate_princ = NULL;
537         krb5_creds              * credsp;
538         krb5_creds                creds;
539         krb5_data in_data;
540         bool creds_ready = false;
541         int i = 0, maxtries = 3;
542
543         ZERO_STRUCT(in_data);
544
545         retval = smb_krb5_parse_name(context, principal, &server);
546         if (retval) {
547                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
548                 return retval;
549         }
550
551         if (impersonate_princ_s) {
552                 retval = smb_krb5_parse_name(context, impersonate_princ_s,
553                                              &impersonate_princ);
554                 if (retval) {
555                         DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
556                         goto cleanup_princ;
557                 }
558         }
559
560         /* obtain ticket & session key */
561         ZERO_STRUCT(creds);
562         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
563                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
564                          error_message(retval)));
565                 goto cleanup_princ;
566         }
567
568         if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
569                 /* This can commonly fail on smbd startup with no ticket in the cache.
570                  * Report at higher level than 1. */
571                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
572                          error_message(retval)));
573                 goto cleanup_creds;
574         }
575
576         while (!creds_ready && (i < maxtries)) {
577
578                 if ((retval = smb_krb5_get_credentials(context, ccache,
579                                                        creds.client,
580                                                        creds.server,
581                                                        impersonate_princ,
582                                                        &credsp))) {
583                         DEBUG(1,("ads_krb5_mk_req: smb_krb5_get_credentials failed for %s (%s)\n",
584                                 principal, error_message(retval)));
585                         goto cleanup_creds;
586                 }
587
588                 /* cope with ticket being in the future due to clock skew */
589                 if ((unsigned)credsp->times.starttime > time(NULL)) {
590                         time_t t = time(NULL);
591                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
592                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
593                         krb5_set_real_time(context, t + time_offset + 1, 0);
594                 }
595
596                 if (!ads_cleanup_expired_creds(context, ccache, credsp)) {
597                         creds_ready = true;
598                 }
599
600                 i++;
601         }
602
603         DEBUG(10,("ads_krb5_mk_req: Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
604                   principal, krb5_cc_get_type(context, ccache), krb5_cc_get_name(context, ccache),
605                   http_timestring(talloc_tos(), (unsigned)credsp->times.endtime), 
606                   (unsigned)credsp->times.endtime));
607
608         if (expire_time) {
609                 *expire_time = (time_t)credsp->times.endtime;
610         }
611
612         /* Allocate the auth_context. */
613         retval = setup_auth_context(context, auth_context);
614         if (retval) {
615                 DEBUG(1,("setup_auth_context failed (%s)\n",
616                         error_message(retval)));
617                 goto cleanup_creds;
618         }
619
620 #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)
621         {
622                 uint32_t gss_flags = 0;
623
624                 if( credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE ) {
625                         /* Fetch a forwarded TGT from the KDC so that we can hand off a 2nd ticket
626                          as part of the kerberos exchange. */
627
628                         DEBUG( 3, ("ads_krb5_mk_req: server marked as OK to delegate to, building forwardable TGT\n")  );
629
630                         retval = krb5_auth_con_setuseruserkey(context,
631                                         *auth_context,
632                                         &credsp->keyblock );
633                         if (retval) {
634                                 DEBUG(1,("krb5_auth_con_setuseruserkey failed (%s)\n",
635                                         error_message(retval)));
636                                 goto cleanup_creds;
637                         }
638
639                         /* Must use a subkey for forwarded tickets. */
640                         retval = krb5_auth_con_setflags(context,
641                                 *auth_context,
642                                 KRB5_AUTH_CONTEXT_USE_SUBKEY);
643                         if (retval) {
644                                 DEBUG(1,("krb5_auth_con_setflags failed (%s)\n",
645                                         error_message(retval)));
646                                 goto cleanup_creds;
647                         }
648
649                         retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
650                                 *auth_context,  /* Authentication context [in] */
651                                 discard_const_p(char, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
652                                 credsp->client, /* Client principal for the tgt [in] */
653                                 credsp->server, /* Server principal for the tgt [in] */
654                                 ccache,         /* Credential cache to use for storage [in] */
655                                 1,              /* Turn on for "Forwardable ticket" [in] */
656                                 &in_data );     /* Resulting response [out] */
657
658                         if (retval) {
659                                 DEBUG( 3, ("krb5_fwd_tgt_creds failed (%s)\n",
660                                            error_message( retval ) ) );
661
662                                 /*
663                                  * This is not fatal. Delete the *auth_context and continue
664                                  * with krb5_mk_req_extended to get a non-forwardable ticket.
665                                  */
666
667                                 if (in_data.data) {
668                                         free( in_data.data );
669                                         in_data.data = NULL;
670                                         in_data.length = 0;
671                                 }
672                                 krb5_auth_con_free(context, *auth_context);
673                                 *auth_context = NULL;
674                                 retval = setup_auth_context(context, auth_context);
675                                 if (retval) {
676                                         DEBUG(1,("setup_auth_context failed (%s)\n",
677                                                 error_message(retval)));
678                                         goto cleanup_creds;
679                                 }
680                         } else {
681                                 /* We got a delegated ticket. */
682                                 gss_flags |= GSS_C_DELEG_FLAG;
683                         }
684                 }
685
686                 /* Frees and reallocates in_data into a GSS checksum blob. */
687                 retval = create_gss_checksum(&in_data, gss_flags);
688                 if (retval) {
689                         goto cleanup_data;
690                 }
691
692                 /* We always want GSS-checksum types. */
693                 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
694                 if (retval) {
695                         DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
696                                 error_message(retval)));
697                         goto cleanup_data;
698                 }
699         }
700 #endif
701
702         retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
703                                       &in_data, credsp, outbuf);
704         if (retval) {
705                 DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
706                          error_message(retval)));
707         }
708
709 #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)
710 cleanup_data:
711 #endif
712
713         if (in_data.data) {
714                 free( in_data.data );
715                 in_data.length = 0;
716         }
717
718         krb5_free_creds(context, credsp);
719
720 cleanup_creds:
721         krb5_free_cred_contents(context, &creds);
722
723 cleanup_princ:
724         krb5_free_principal(context, server);
725         if (impersonate_princ) {
726                 krb5_free_principal(context, impersonate_princ);
727         }
728
729         return retval;
730 }
731
732 void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
733 {
734 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
735         if (pdata->data) {
736                 krb5_free_data_contents(context, pdata);
737         }
738 #elif defined(HAVE_KRB5_DATA_FREE)
739         krb5_data_free(context, pdata);
740 #else
741         SAFE_FREE(pdata->data);
742 #endif
743 }
744
745 /*
746  * @brief copy a buffer into a krb5_data struct
747  *
748  * @param[in] p                 The krb5_data
749  * @param[in] data              The data to copy
750  * @param[in] length            The length of the data to copy
751  * @return krb5_error_code
752  *
753  * Caller has to free krb5_data with kerberos_free_data_contents().
754  */
755
756 krb5_error_code krb5_copy_data_contents(krb5_data *p,
757                                         const void *data,
758                                         size_t len)
759 {
760 #if defined(HAVE_KRB5_DATA_COPY)
761         return krb5_data_copy(p, data, len);
762 #else
763         if (len) {
764                 p->data = malloc(len);
765                 if (p->data == NULL) {
766                         return ENOMEM;
767                 }
768                 memmove(p->data, data, len);
769         } else {
770                 p->data = NULL;
771         }
772         p->length = len;
773         p->magic = KV5M_DATA;
774         return 0;
775 #endif
776 }
777
778 /*
779   get a kerberos5 ticket for the given service
780 */
781 int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
782                         const char *principal, time_t time_offset,
783                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
784                         uint32_t extra_ap_opts, const char *ccname,
785                         time_t *tgs_expire,
786                         const char *impersonate_princ_s)
787
788 {
789         krb5_error_code retval;
790         krb5_data packet;
791         krb5_context context = NULL;
792         krb5_ccache ccdef = NULL;
793         krb5_auth_context auth_context = NULL;
794         krb5_enctype enc_types[] = {
795 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
796                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
797 #endif
798 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
799                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
800 #endif
801                 ENCTYPE_ARCFOUR_HMAC,
802                 ENCTYPE_DES_CBC_MD5,
803                 ENCTYPE_DES_CBC_CRC,
804                 ENCTYPE_NULL};
805
806         initialize_krb5_error_table();
807         retval = krb5_init_context(&context);
808         if (retval) {
809                 DEBUG(1, ("krb5_init_context failed (%s)\n",
810                          error_message(retval)));
811                 goto failed;
812         }
813
814         if (time_offset != 0) {
815                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
816         }
817
818         if ((retval = krb5_cc_resolve(context, ccname ?
819                         ccname : krb5_cc_default_name(context), &ccdef))) {
820                 DEBUG(1, ("krb5_cc_default failed (%s)\n",
821                          error_message(retval)));
822                 goto failed;
823         }
824
825         if ((retval = krb5_set_default_tgs_ktypes(context, enc_types))) {
826                 DEBUG(1, ("krb5_set_default_tgs_ktypes failed (%s)\n",
827                          error_message(retval)));
828                 goto failed;
829         }
830
831         retval = ads_krb5_mk_req(context, &auth_context,
832                                 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
833                                 principal, ccdef, &packet,
834                                 tgs_expire, impersonate_princ_s);
835         if (retval) {
836                 goto failed;
837         }
838
839         get_krb5_smb_session_key(mem_ctx, context, auth_context,
840                                  session_key_krb5, false);
841
842         *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
843
844         kerberos_free_data_contents(context, &packet);
845
846 failed:
847
848         if (context) {
849                 if (ccdef)
850                         krb5_cc_close(context, ccdef);
851                 if (auth_context)
852                         krb5_auth_con_free(context, auth_context);
853                 krb5_free_context(context);
854         }
855
856         return retval;
857 }
858
859 bool get_krb5_smb_session_key(TALLOC_CTX *mem_ctx,
860                               krb5_context context,
861                               krb5_auth_context auth_context,
862                               DATA_BLOB *session_key, bool remote)
863 {
864         krb5_keyblock *skey = NULL;
865         krb5_error_code err = 0;
866         bool ret = false;
867
868         if (remote) {
869 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
870                 err = krb5_auth_con_getrecvsubkey(context,
871                                                   auth_context,
872                                                   &skey);
873 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
874                 err = krb5_auth_con_getremotesubkey(context,
875                                                     auth_context, &skey);
876 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
877         } else {
878 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
879                 err = krb5_auth_con_getsendsubkey(context,
880                                                   auth_context,
881                                                   &skey);
882 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
883                 err = krb5_auth_con_getlocalsubkey(context,
884                                                    auth_context, &skey);
885 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
886         }
887
888         if (err || skey == NULL) {
889                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
890                 goto done;
891         }
892
893         DEBUG(10, ("Got KRB5 session key of length %d\n",
894                    (int)KRB5_KEY_LENGTH(skey)));
895
896         *session_key = data_blob_talloc(mem_ctx,
897                                          KRB5_KEY_DATA(skey),
898                                          KRB5_KEY_LENGTH(skey));
899         dump_data_pw("KRB5 Session Key:\n",
900                      session_key->data,
901                      session_key->length);
902
903         ret = true;
904
905 done:
906         if (skey) {
907                 krb5_free_keyblock(context, skey);
908         }
909
910         return ret;
911 }
912
913
914 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
915  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i );
916
917  const krb5_data *krb5_princ_component(krb5_context context, krb5_principal principal, int i )
918 {
919         static krb5_data kdata;
920
921         kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
922         kdata.length = strlen((const char *)kdata.data);
923         return &kdata;
924 }
925 #endif
926
927 /*
928  * @brief Get talloced string component of a principal
929  *
930  * @param[in] mem_ctx           The TALLOC_CTX
931  * @param[in] context           The krb5_context
932  * @param[in] principal         The principal
933  * @param[in] component         The component
934  * @return string component
935  *
936  * Caller must talloc_free if the return value is not NULL.
937  *
938  */
939
940 /* caller has to free returned string with talloc_free() */
941 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
942                                          krb5_context context,
943                                          krb5_const_principal principal,
944                                          unsigned int component)
945 {
946 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
947         return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
948 #else
949         krb5_data *data;
950
951         if (component >= krb5_princ_size(context, principal)) {
952                 return NULL;
953         }
954
955         data = krb5_princ_component(context, principal, component);
956         if (data == NULL) {
957                 return NULL;
958         }
959
960         return talloc_strndup(mem_ctx, data->data, data->length);
961 #endif
962 }
963
964 /* Prototypes */
965
966  krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,       /* FILE:/tmp/krb5cc_0 */
967                                        const char *client_string,       /* gd@BER.SUSE.DE */
968                                        const char *service_string,      /* krbtgt/BER.SUSE.DE@BER.SUSE.DE */
969                                        time_t *expire_time)
970 {
971         krb5_error_code ret;
972         krb5_context context = NULL;
973         krb5_ccache ccache = NULL;
974         krb5_principal client = NULL;
975         krb5_creds creds, creds_in;
976
977         ZERO_STRUCT(creds);
978         ZERO_STRUCT(creds_in);
979
980         initialize_krb5_error_table();
981         ret = krb5_init_context(&context);
982         if (ret) {
983                 goto done;
984         }
985
986         if (!ccache_string) {
987                 ccache_string = krb5_cc_default_name(context);
988         }
989
990         if (!ccache_string) {
991                 ret = EINVAL;
992                 goto done;
993         }
994
995         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
996
997         /* FIXME: we should not fall back to defaults */
998         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
999         if (ret) {
1000                 goto done;
1001         }
1002
1003         if (client_string) {
1004                 ret = smb_krb5_parse_name(context, client_string, &client);
1005                 if (ret) {
1006                         goto done;
1007                 }
1008         } else {
1009                 ret = krb5_cc_get_principal(context, ccache, &client);
1010                 if (ret) {
1011                         goto done;
1012                 }
1013         }
1014
1015         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
1016         if (ret) {
1017                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
1018                 goto done;
1019         }
1020
1021         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
1022         ret = krb5_cc_initialize(context, ccache, client);
1023         if (ret) {
1024                 goto done;
1025         }
1026
1027         ret = krb5_cc_store_cred(context, ccache, &creds);
1028
1029         if (expire_time) {
1030                 *expire_time = (time_t) creds.times.endtime;
1031         }
1032
1033 done:
1034         krb5_free_cred_contents(context, &creds_in);
1035         krb5_free_cred_contents(context, &creds);
1036
1037         if (client) {
1038                 krb5_free_principal(context, client);
1039         }
1040         if (ccache) {
1041                 krb5_cc_close(context, ccache);
1042         }
1043         if (context) {
1044                 krb5_free_context(context);
1045         }
1046
1047         return ret;
1048 }
1049
1050  krb5_error_code smb_krb5_free_addresses(krb5_context context, smb_krb5_addresses *addr)
1051 {
1052         krb5_error_code ret = 0;
1053         if (addr == NULL) {
1054                 return ret;
1055         }
1056 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1057         krb5_free_addresses(context, addr->addrs);
1058 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1059         ret = krb5_free_addresses(context, addr->addrs);
1060         SAFE_FREE(addr->addrs);
1061 #endif
1062         SAFE_FREE(addr);
1063         addr = NULL;
1064         return ret;
1065 }
1066
1067 #define MAX_NETBIOSNAME_LEN 16
1068  krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1069                                                    const char *netbios_name)
1070 {
1071         krb5_error_code ret = 0;
1072         char buf[MAX_NETBIOSNAME_LEN];
1073         int len;
1074 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1075         krb5_address **addrs = NULL;
1076 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1077         krb5_addresses *addrs = NULL;
1078 #endif
1079
1080         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1081         if (*kerb_addr == NULL) {
1082                 return ENOMEM;
1083         }
1084
1085         /* temporarily duplicate put_name() code here to avoid dependency
1086          * issues for a 5 lines function */
1087         len = strlen(netbios_name);
1088         memcpy(buf, netbios_name,
1089                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1090         if (len < MAX_NETBIOSNAME_LEN - 1) {
1091                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1092         }
1093         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1094
1095 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1096         {
1097                 int num_addr = 2;
1098
1099                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1100                 if (addrs == NULL) {
1101                         SAFE_FREE(*kerb_addr);
1102                         return ENOMEM;
1103                 }
1104
1105                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1106
1107                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1108                 if (addrs[0] == NULL) {
1109                         SAFE_FREE(addrs);
1110                         SAFE_FREE(*kerb_addr);
1111                         return ENOMEM;
1112                 }
1113
1114                 addrs[0]->magic = KV5M_ADDRESS;
1115                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1116                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1117                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1118                 if (addrs[0]->contents == NULL) {
1119                         SAFE_FREE(addrs[0]);
1120                         SAFE_FREE(addrs);
1121                         SAFE_FREE(*kerb_addr);
1122                         return ENOMEM;
1123                 }
1124
1125                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1126
1127                 addrs[1] = NULL;
1128         }
1129 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1130         {
1131                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1132                 if (addrs == NULL) {
1133                         SAFE_FREE(*kerb_addr);
1134                         return ENOMEM;
1135                 }
1136
1137                 memset(addrs, 0, sizeof(krb5_addresses));
1138
1139                 addrs->len = 1;
1140                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1141                 if (addrs->val == NULL) {
1142                         SAFE_FREE(addrs);
1143                         SAFE_FREE(kerb_addr);
1144                         return ENOMEM;
1145                 }
1146
1147                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1148                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1149                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1150                 if (addrs->val[0].address.data == NULL) {
1151                         SAFE_FREE(addrs->val);
1152                         SAFE_FREE(addrs);
1153                         SAFE_FREE(*kerb_addr);
1154                         return ENOMEM;
1155                 }
1156
1157                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1158         }
1159 #else
1160 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1161 #endif
1162         (*kerb_addr)->addrs = addrs;
1163
1164         return ret;
1165 }
1166
1167  void smb_krb5_free_error(krb5_context context, krb5_error *krberror)
1168 {
1169 #ifdef HAVE_KRB5_FREE_ERROR_CONTENTS /* Heimdal */
1170         krb5_free_error_contents(context, krberror);
1171 #else /* MIT */
1172         krb5_free_error(context, krberror);
1173 #endif
1174 }
1175
1176  krb5_error_code handle_krberror_packet(krb5_context context,
1177                                         krb5_data *packet)
1178 {
1179         krb5_error_code ret;
1180         bool got_error_code = false;
1181
1182         DEBUG(10,("handle_krberror_packet: got error packet\n"));
1183
1184 #ifdef HAVE_E_DATA_POINTER_IN_KRB5_ERROR /* Heimdal */
1185         {
1186                 krb5_error krberror;
1187
1188                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1189                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1190                                 error_message(ret)));
1191                         return ret;
1192                 }
1193
1194                 if (krberror.e_data == NULL || krberror.e_data->data == NULL) {
1195                         ret = (krb5_error_code) krberror.error_code;
1196                         got_error_code = true;
1197                 }
1198
1199                 smb_krb5_free_error(context, &krberror);
1200         }
1201 #else /* MIT */
1202         {
1203                 krb5_error *krberror;
1204
1205                 if ((ret = krb5_rd_error(context, packet, &krberror))) {
1206                         DEBUG(10,("handle_krberror_packet: krb5_rd_error failed with: %s\n", 
1207                                 error_message(ret)));
1208                         return ret;
1209                 }
1210
1211                 if (krberror->e_data.data == NULL) {
1212 #if defined(ERROR_TABLE_BASE_krb5)
1213                         ret = ERROR_TABLE_BASE_krb5 + (krb5_error_code) krberror->error;
1214 #else
1215                         ret = (krb5_error_code)krberror->error;
1216 #endif
1217                         got_error_code = true;
1218                 }
1219                 smb_krb5_free_error(context, krberror);
1220         }
1221 #endif
1222         if (got_error_code) {
1223                 DEBUG(5,("handle_krberror_packet: got KERBERR from kpasswd: %s (%d)\n", 
1224                         error_message(ret), ret));
1225         }
1226         return ret;
1227 }
1228
1229 krb5_error_code smb_krb5_get_init_creds_opt_alloc(krb5_context context,
1230                                             krb5_get_init_creds_opt **opt)
1231 {
1232         /* Heimdal or modern MIT version */
1233         return krb5_get_init_creds_opt_alloc(context, opt);
1234 }
1235
1236 void smb_krb5_get_init_creds_opt_free(krb5_context context,
1237                                 krb5_get_init_creds_opt *opt)
1238 {
1239         /* Modern MIT or Heimdal version */
1240         krb5_get_init_creds_opt_free(context, opt);
1241 }
1242
1243 krb5_enctype smb_get_enctype_from_kt_entry(krb5_keytab_entry *kt_entry)
1244 {
1245         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1246 }
1247
1248 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1249                                         krb5_keytab_entry *kt_entry)
1250 {
1251 /* Try krb5_free_keytab_entry_contents first, since
1252  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1253  * krb5_kt_free_entry but only has a prototype for the first, while the
1254  * second is considered private.
1255  */
1256 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1257         return krb5_free_keytab_entry_contents(context, kt_entry);
1258 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1259         return krb5_kt_free_entry(context, kt_entry);
1260 #else
1261 #error UNKNOWN_KT_FREE_FUNCTION
1262 #endif
1263 }
1264
1265
1266 /* caller needs to free etype_s */
1267 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1268                                            krb5_enctype enctype,
1269                                            char **etype_s)
1270 {
1271 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1272         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1273 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1274         char buf[256];
1275         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1276         if (ret) {
1277                 return ret;
1278         }
1279         *etype_s = SMB_STRDUP(buf);
1280         if (!*etype_s) {
1281                 return ENOMEM;
1282         }
1283         return ret;
1284 #else
1285 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1286 #endif
1287 }
1288
1289 /**********************************************************************
1290  * Open a krb5 keytab with flags, handles readonly or readwrite access and
1291  * allows one to process non-default keytab names.
1292  * @param context krb5_context
1293  * @param keytab_name_req string
1294  * @param write_access bool if writable keytab is required
1295  * @param krb5_keytab pointer to krb5_keytab (close with krb5_kt_close())
1296  * @return krb5_error_code
1297 **********************************************************************/
1298
1299 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1300 #ifndef MAX_KEYTAB_NAME_LEN
1301 #define MAX_KEYTAB_NAME_LEN 1100
1302 #endif
1303
1304 krb5_error_code smb_krb5_open_keytab(krb5_context context,
1305                                      const char *keytab_name_req,
1306                                      bool write_access,
1307                                      krb5_keytab *keytab)
1308 {
1309         krb5_error_code ret = 0;
1310         TALLOC_CTX *mem_ctx;
1311         char keytab_string[MAX_KEYTAB_NAME_LEN];
1312         char *kt_str = NULL;
1313         bool found_valid_name = false;
1314         const char *pragma = "FILE";
1315         const char *tmp = NULL;
1316
1317         if (!write_access && !keytab_name_req) {
1318                 /* caller just wants to read the default keytab readonly, so be it */
1319                 return krb5_kt_default(context, keytab);
1320         }
1321
1322         mem_ctx = talloc_init("smb_krb5_open_keytab");
1323         if (!mem_ctx) {
1324                 return ENOMEM;
1325         }
1326
1327 #ifdef HAVE_WRFILE_KEYTAB
1328         if (write_access) {
1329                 pragma = "WRFILE";
1330         }
1331 #endif
1332
1333         if (keytab_name_req) {
1334
1335                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1336                         ret = KRB5_CONFIG_NOTENUFSPACE;
1337                         goto out;
1338                 }
1339
1340                 if ((strncmp(keytab_name_req, "WRFILE:/", 8) == 0) ||
1341                     (strncmp(keytab_name_req, "FILE:/", 6) == 0)) {
1342                         tmp = keytab_name_req;
1343                         goto resolve;
1344                 }
1345
1346                 if (keytab_name_req[0] != '/') {
1347                         ret = KRB5_KT_BADNAME;
1348                         goto out;
1349                 }
1350
1351                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1352                 if (!tmp) {
1353                         ret = ENOMEM;
1354                         goto out;
1355                 }
1356
1357                 goto resolve;
1358         }
1359
1360         /* we need to handle more complex keytab_strings, like:
1361          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1362
1363         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1364         if (ret) {
1365                 goto out;
1366         }
1367
1368         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1369
1370         tmp = talloc_strdup(mem_ctx, keytab_string);
1371         if (!tmp) {
1372                 ret = ENOMEM;
1373                 goto out;
1374         }
1375
1376         if (strncmp(tmp, "ANY:", 4) == 0) {
1377                 tmp += 4;
1378         }
1379
1380         memset(&keytab_string, '\0', sizeof(keytab_string));
1381
1382         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1383                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1384                         found_valid_name = true;
1385                         tmp = kt_str;
1386                         tmp += 7;
1387                 }
1388
1389                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1390                         found_valid_name = true;
1391                         tmp = kt_str;
1392                         tmp += 5;
1393                 }
1394
1395                 if (tmp[0] == '/') {
1396                         /* Treat as a FILE: keytab definition. */
1397                         found_valid_name = true;
1398                 }
1399
1400                 if (found_valid_name) {
1401                         if (tmp[0] != '/') {
1402                                 ret = KRB5_KT_BADNAME;
1403                                 goto out;
1404                         }
1405
1406                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1407                         if (!tmp) {
1408                                 ret = ENOMEM;
1409                                 goto out;
1410                         }
1411                         break;
1412                 }
1413         }
1414
1415         if (!found_valid_name) {
1416                 ret = KRB5_KT_UNKNOWN_TYPE;
1417                 goto out;
1418         }
1419
1420  resolve:
1421         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1422         ret = krb5_kt_resolve(context, tmp, keytab);
1423
1424  out:
1425         TALLOC_FREE(mem_ctx);
1426         return ret;
1427 }
1428
1429 krb5_error_code smb_krb5_keytab_name(TALLOC_CTX *mem_ctx,
1430                                      krb5_context context,
1431                                      krb5_keytab keytab,
1432                                      const char **keytab_name)
1433 {
1434         char keytab_string[MAX_KEYTAB_NAME_LEN];
1435         krb5_error_code ret = 0;
1436
1437         ret = krb5_kt_get_name(context, keytab,
1438                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1439         if (ret) {
1440                 return ret;
1441         }
1442
1443         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1444         if (!*keytab_name) {
1445                 return ENOMEM;
1446         }
1447
1448         return ret;
1449 }
1450
1451 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1452     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1453     defined(HAVE_KRB5_GET_CREDS)
1454 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1455                                                              krb5_ccache ccache,
1456                                                              krb5_principal me,
1457                                                              krb5_principal server,
1458                                                              krb5_principal impersonate_princ,
1459                                                              krb5_creds **out_creds)
1460 {
1461         krb5_error_code ret;
1462         krb5_get_creds_opt opt;
1463
1464         ret = krb5_get_creds_opt_alloc(context, &opt);
1465         if (ret) {
1466                 goto done;
1467         }
1468         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1469
1470         if (impersonate_princ) {
1471                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1472                                                          impersonate_princ);
1473                 if (ret) {
1474                         goto done;
1475                 }
1476         }
1477
1478         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1479         if (ret) {
1480                 goto done;
1481         }
1482
1483  done:
1484         if (opt) {
1485                 krb5_get_creds_opt_free(context, opt);
1486         }
1487         return ret;
1488 }
1489 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1490
1491 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1492
1493 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1494 krb5_error_code KRB5_CALLCONV
1495 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1496                               krb5_ccache ccache, krb5_creds *in_creds,
1497                               krb5_data *subject_cert,
1498                               krb5_creds **out_creds);
1499 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1500
1501 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1502                                                          krb5_ccache ccache,
1503                                                          krb5_principal me,
1504                                                          krb5_principal server,
1505                                                          krb5_principal impersonate_princ,
1506                                                          krb5_creds **out_creds)
1507 {
1508         krb5_error_code ret;
1509         krb5_creds in_creds;
1510
1511         ZERO_STRUCT(in_creds);
1512
1513         if (impersonate_princ) {
1514
1515                 in_creds.server = me;
1516                 in_creds.client = impersonate_princ;
1517
1518                 ret = krb5_get_credentials_for_user(context,
1519                                                     0, /* krb5_flags options */
1520                                                     ccache,
1521                                                     &in_creds,
1522                                                     NULL, /* krb5_data *subject_cert */
1523                                                     out_creds);
1524         } else {
1525                 in_creds.client = me;
1526                 in_creds.server = server;
1527
1528                 ret = krb5_get_credentials(context, 0, ccache,
1529                                            &in_creds, out_creds);
1530         }
1531
1532         return ret;
1533 }
1534 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1535
1536 /*
1537  * smb_krb5_get_credentials
1538  *
1539  * @brief Get krb5 credentials for a server
1540  *
1541  * @param[in] context           An initialized krb5_context
1542  * @param[in] ccache            An initialized krb5_ccache
1543  * @param[in] me                The krb5_principal of the caller
1544  * @param[in] server            The krb5_principal of the requested service
1545  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1546  * @param[out] out_creds        The returned krb5_creds structure
1547  * @return krb5_error_code
1548  *
1549  */
1550 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1551                                          krb5_ccache ccache,
1552                                          krb5_principal me,
1553                                          krb5_principal server,
1554                                          krb5_principal impersonate_princ,
1555                                          krb5_creds **out_creds)
1556 {
1557         krb5_error_code ret;
1558         krb5_creds *creds = NULL;
1559
1560         if (out_creds != NULL) {
1561                 *out_creds = NULL;
1562         }
1563
1564         if (impersonate_princ) {
1565 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1566                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1567 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1568                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1569 #else
1570                 ret = ENOTSUP;
1571 #endif
1572         } else {
1573                 krb5_creds in_creds;
1574
1575                 ZERO_STRUCT(in_creds);
1576
1577                 in_creds.client = me;
1578                 in_creds.server = server;
1579
1580                 ret = krb5_get_credentials(context, 0, ccache,
1581                                            &in_creds, &creds);
1582         }
1583         if (ret) {
1584                 goto done;
1585         }
1586
1587         if (out_creds) {
1588                 *out_creds = creds;
1589         }
1590
1591  done:
1592         if (creds && ret) {
1593                 krb5_free_creds(context, creds);
1594         }
1595
1596         return ret;
1597 }
1598
1599 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1600                                                 krb5_enctype enctype,
1601                                                 const void *data,
1602                                                 size_t length,
1603                                                 krb5_keyblock *key)
1604 {
1605 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1606         return krb5_keyblock_init(context, enctype, data, length, key);
1607 #else
1608         memset(key, 0, sizeof(krb5_keyblock));
1609         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1610         if (NULL == KRB5_KEY_DATA(key)) {
1611                 return ENOMEM;
1612         }
1613         memcpy(KRB5_KEY_DATA(key), data, length);
1614         KRB5_KEY_LENGTH(key) = length;
1615         KRB5_KEY_TYPE(key) = enctype;
1616         return 0;
1617 #endif
1618 }
1619
1620 /*
1621   simulate a kinit, putting the tgt in the given credentials cache.
1622   Orignally by remus@snapserver.com
1623
1624   This version is built to use a keyblock, rather than needing the
1625   original password.
1626
1627   The impersonate_principal is the principal if NULL, or the principal
1628   to impersonate
1629
1630   The target_service defaults to the krbtgt if NULL, but could be
1631    kpasswd/realm or the local service (if we are doing s4u2self)
1632 */
1633 krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc,
1634                                            krb5_principal principal,
1635                                            krb5_keyblock *keyblock,
1636                                            const char *target_service,
1637                                            krb5_get_init_creds_opt *krb_options,
1638                                            time_t *expire_time,
1639                                            time_t *kdc_time)
1640 {
1641         krb5_error_code code = 0;
1642         krb5_creds my_creds;
1643
1644 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1645         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1646                                             keyblock, 0, target_service,
1647                                             krb_options);
1648 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1649 {
1650 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1651         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1652         krb5_keytab_entry entry;
1653         krb5_keytab keytab;
1654         mode_t mask;
1655
1656         memset(&entry, 0, sizeof(entry));
1657         entry.principal = principal;
1658         *(KRB5_KT_KEY(&entry)) = *keyblock;
1659
1660         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1661         mask = umask(S_IRWXO | S_IRWXG);
1662         mktemp(tmp_name);
1663         umask(mask);
1664         if (tmp_name[0] == 0) {
1665                 return KRB5_KT_BADNAME;
1666         }
1667         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1668         if (code) {
1669                 return code;
1670         }
1671
1672         code = krb5_kt_add_entry(ctx, keytab, &entry);
1673         if (code) {
1674                 (void)krb5_kt_close(ctx, keytab);
1675                 goto done;
1676         }
1677
1678         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
1679                                           keytab, 0, target_service,
1680                                           krb_options);
1681         (void)krb5_kt_close(ctx, keytab);
1682 }
1683 #else
1684 #error krb5_get_init_creds_keyblock not available!
1685 #endif
1686         if (code) {
1687                 return code;
1688         }
1689
1690         code = krb5_cc_initialize(ctx, cc, principal);
1691         if (code) {
1692                 goto done;
1693         }
1694
1695         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1696         if (code) {
1697                 goto done;
1698         }
1699
1700         if (expire_time) {
1701                 *expire_time = (time_t) my_creds.times.endtime;
1702         }
1703
1704         if (kdc_time) {
1705                 *kdc_time = (time_t) my_creds.times.starttime;
1706         }
1707
1708         code = 0;
1709 done:
1710         krb5_free_cred_contents(ctx, &my_creds);
1711         return code;
1712 }
1713
1714 krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc,
1715                                            krb5_principal principal,
1716                                            const char *password,
1717                                            const char *target_service,
1718                                            krb5_get_init_creds_opt *krb_options,
1719                                            time_t *expire_time,
1720                                            time_t *kdc_time)
1721 {
1722         krb5_error_code code = 0;
1723         krb5_creds my_creds;
1724
1725         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
1726                                             password, NULL, NULL, 0,
1727                                             target_service, krb_options);
1728         if (code) {
1729                 return code;
1730         }
1731
1732 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
1733         /*
1734          * We need to store the principal as returned from the KDC to the
1735          * credentials cache. If we don't do that the KRB5 library is not
1736          * able to find the tickets it is looking for
1737          */
1738         principal = my_creds.client;
1739 #endif
1740         code = krb5_cc_initialize(ctx, cc, principal);
1741         if (code) {
1742                 goto done;
1743         }
1744
1745         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1746         if (code) {
1747                 goto done;
1748         }
1749
1750         if (expire_time) {
1751                 *expire_time = (time_t) my_creds.times.endtime;
1752         }
1753
1754         if (kdc_time) {
1755                 *kdc_time = (time_t) my_creds.times.starttime;
1756         }
1757
1758         code = 0;
1759 done:
1760         krb5_free_cred_contents(ctx, &my_creds);
1761         return code;
1762 }
1763
1764 #ifdef SAMBA4_USES_HEIMDAL
1765 /*
1766   simulate a kinit, putting the tgt in the given credentials cache.
1767   Orignally by remus@snapserver.com
1768
1769   The impersonate_principal is the principal
1770
1771   The self_service, should be the local service (for S4U2Self if
1772   impersonate_principal is given).
1773
1774   The target_service defaults to the krbtgt if NULL, but could be
1775   kpasswd/realm or a remote service (for S4U2Proxy)
1776
1777 */
1778 krb5_error_code kerberos_kinit_s4u2_cc(krb5_context ctx,
1779                                         krb5_ccache store_cc,
1780                                         krb5_principal init_principal,
1781                                         const char *init_password,
1782                                         krb5_principal impersonate_principal,
1783                                         const char *self_service,
1784                                         const char *target_service,
1785                                         krb5_get_init_creds_opt *krb_options,
1786                                         time_t *expire_time,
1787                                         time_t *kdc_time)
1788 {
1789         krb5_error_code code = 0;
1790         krb5_get_creds_opt options;
1791         krb5_principal store_principal;
1792         krb5_creds store_creds;
1793         krb5_creds *s4u2self_creds;
1794         Ticket s4u2self_ticket;
1795         size_t s4u2self_ticketlen;
1796         krb5_creds *s4u2proxy_creds;
1797         krb5_principal self_princ;
1798         bool s4u2proxy;
1799         krb5_principal target_princ;
1800         krb5_ccache tmp_cc;
1801         const char *self_realm;
1802         krb5_principal blacklist_principal = NULL;
1803         krb5_principal whitelist_principal = NULL;
1804
1805         code = krb5_get_init_creds_password(ctx, &store_creds,
1806                                             init_principal,
1807                                             init_password,
1808                                             NULL, NULL,
1809                                             0,
1810                                             NULL,
1811                                             krb_options);
1812         if (code != 0) {
1813                 return code;
1814         }
1815
1816         store_principal = init_principal;
1817
1818         /*
1819          * We are trying S4U2Self now:
1820          *
1821          * As we do not want to expose our TGT in the
1822          * krb5_ccache, which is also holds the impersonated creds.
1823          *
1824          * Some low level krb5/gssapi function might use the TGT
1825          * identity and let the client act as our machine account.
1826          *
1827          * We need to avoid that and use a temporary krb5_ccache
1828          * in order to pass our TGT to the krb5_get_creds() function.
1829          */
1830         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
1831         if (code != 0) {
1832                 krb5_free_cred_contents(ctx, &store_creds);
1833                 return code;
1834         }
1835
1836         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
1837         if (code != 0) {
1838                 krb5_cc_destroy(ctx, tmp_cc);
1839                 krb5_free_cred_contents(ctx, &store_creds);
1840                 return code;
1841         }
1842
1843         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
1844         if (code != 0) {
1845                 krb5_free_cred_contents(ctx, &store_creds);
1846                 krb5_cc_destroy(ctx, tmp_cc);
1847                 return code;
1848         }
1849
1850         /*
1851          * we need to remember the client principal of our
1852          * TGT and make sure the KDC does not return this
1853          * in the impersonated tickets. This can happen
1854          * if the KDC does not support S4U2Self and S4U2Proxy.
1855          */
1856         blacklist_principal = store_creds.client;
1857         store_creds.client = NULL;
1858         krb5_free_cred_contents(ctx, &store_creds);
1859
1860         /*
1861          * Check if we also need S4U2Proxy or if S4U2Self is
1862          * enough in order to get a ticket for the target.
1863          */
1864         if (target_service == NULL) {
1865                 s4u2proxy = false;
1866         } else if (strcmp(target_service, self_service) == 0) {
1867                 s4u2proxy = false;
1868         } else {
1869                 s4u2proxy = true;
1870         }
1871
1872         /*
1873          * For S4U2Self we need our own service principal,
1874          * which belongs to our own realm (available on
1875          * our client principal).
1876          */
1877         self_realm = krb5_principal_get_realm(ctx, init_principal);
1878
1879         code = krb5_parse_name(ctx, self_service, &self_princ);
1880         if (code != 0) {
1881                 krb5_free_principal(ctx, blacklist_principal);
1882                 krb5_cc_destroy(ctx, tmp_cc);
1883                 return code;
1884         }
1885
1886         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
1887         if (code != 0) {
1888                 krb5_free_principal(ctx, blacklist_principal);
1889                 krb5_free_principal(ctx, self_princ);
1890                 krb5_cc_destroy(ctx, tmp_cc);
1891                 return code;
1892         }
1893
1894         code = krb5_get_creds_opt_alloc(ctx, &options);
1895         if (code != 0) {
1896                 krb5_free_principal(ctx, blacklist_principal);
1897                 krb5_free_principal(ctx, self_princ);
1898                 krb5_cc_destroy(ctx, tmp_cc);
1899                 return code;
1900         }
1901
1902         if (s4u2proxy) {
1903                 /*
1904                  * If we want S4U2Proxy, we need the forwardable flag
1905                  * on the S4U2Self ticket.
1906                  */
1907                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
1908         }
1909
1910         code = krb5_get_creds_opt_set_impersonate(ctx, options,
1911                                                   impersonate_principal);
1912         if (code != 0) {
1913                 krb5_get_creds_opt_free(ctx, options);
1914                 krb5_free_principal(ctx, blacklist_principal);
1915                 krb5_free_principal(ctx, self_princ);
1916                 krb5_cc_destroy(ctx, tmp_cc);
1917                 return code;
1918         }
1919
1920         code = krb5_get_creds(ctx, options, tmp_cc,
1921                               self_princ, &s4u2self_creds);
1922         krb5_get_creds_opt_free(ctx, options);
1923         krb5_free_principal(ctx, self_princ);
1924         if (code != 0) {
1925                 krb5_free_principal(ctx, blacklist_principal);
1926                 krb5_cc_destroy(ctx, tmp_cc);
1927                 return code;
1928         }
1929
1930         if (!s4u2proxy) {
1931                 krb5_cc_destroy(ctx, tmp_cc);
1932
1933                 /*
1934                  * Now make sure we store the impersonated principal
1935                  * and creds instead of the TGT related stuff
1936                  * in the krb5_ccache of the caller.
1937                  */
1938                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
1939                                                 &store_creds);
1940                 krb5_free_creds(ctx, s4u2self_creds);
1941                 if (code != 0) {
1942                         return code;
1943                 }
1944
1945                 /*
1946                  * It's important to store the principal the KDC
1947                  * returned, as otherwise the caller would not find
1948                  * the S4U2Self ticket in the krb5_ccache lookup.
1949                  */
1950                 store_principal = store_creds.client;
1951                 goto store;
1952         }
1953
1954         /*
1955          * We are trying S4U2Proxy:
1956          *
1957          * We need the ticket from the S4U2Self step
1958          * and our TGT in order to get the delegated ticket.
1959          */
1960         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
1961                              s4u2self_creds->ticket.length,
1962                              &s4u2self_ticket,
1963                              &s4u2self_ticketlen);
1964         if (code != 0) {
1965                 krb5_free_creds(ctx, s4u2self_creds);
1966                 krb5_free_principal(ctx, blacklist_principal);
1967                 krb5_cc_destroy(ctx, tmp_cc);
1968                 return code;
1969         }
1970
1971         /*
1972          * we need to remember the client principal of the
1973          * S4U2Self stage and as it needs to match the one we
1974          * will get for the S4U2Proxy stage. We need this
1975          * in order to detect KDCs which does not support S4U2Proxy.
1976          */
1977         whitelist_principal = s4u2self_creds->client;
1978         s4u2self_creds->client = NULL;
1979         krb5_free_creds(ctx, s4u2self_creds);
1980
1981         /*
1982          * For S4U2Proxy we also got a target service principal,
1983          * which also belongs to our own realm (available on
1984          * our client principal).
1985          */
1986         code = krb5_parse_name(ctx, target_service, &target_princ);
1987         if (code != 0) {
1988                 free_Ticket(&s4u2self_ticket);
1989                 krb5_free_principal(ctx, whitelist_principal);
1990                 krb5_free_principal(ctx, blacklist_principal);
1991                 krb5_cc_destroy(ctx, tmp_cc);
1992                 return code;
1993         }
1994
1995         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
1996         if (code != 0) {
1997                 free_Ticket(&s4u2self_ticket);
1998                 krb5_free_principal(ctx, target_princ);
1999                 krb5_free_principal(ctx, whitelist_principal);
2000                 krb5_free_principal(ctx, blacklist_principal);
2001                 krb5_cc_destroy(ctx, tmp_cc);
2002                 return code;
2003         }
2004
2005         code = krb5_get_creds_opt_alloc(ctx, &options);
2006         if (code != 0) {
2007                 free_Ticket(&s4u2self_ticket);
2008                 krb5_free_principal(ctx, target_princ);
2009                 krb5_free_principal(ctx, whitelist_principal);
2010                 krb5_free_principal(ctx, blacklist_principal);
2011                 krb5_cc_destroy(ctx, tmp_cc);
2012                 return code;
2013         }
2014
2015         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2016         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2017
2018         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2019         free_Ticket(&s4u2self_ticket);
2020         if (code != 0) {
2021                 krb5_get_creds_opt_free(ctx, options);
2022                 krb5_free_principal(ctx, target_princ);
2023                 krb5_free_principal(ctx, whitelist_principal);
2024                 krb5_free_principal(ctx, blacklist_principal);
2025                 krb5_cc_destroy(ctx, tmp_cc);
2026                 return code;
2027         }
2028
2029         code = krb5_get_creds(ctx, options, tmp_cc,
2030                               target_princ, &s4u2proxy_creds);
2031         krb5_get_creds_opt_free(ctx, options);
2032         krb5_free_principal(ctx, target_princ);
2033         krb5_cc_destroy(ctx, tmp_cc);
2034         if (code != 0) {
2035                 krb5_free_principal(ctx, whitelist_principal);
2036                 krb5_free_principal(ctx, blacklist_principal);
2037                 return code;
2038         }
2039
2040         /*
2041          * Now make sure we store the impersonated principal
2042          * and creds instead of the TGT related stuff
2043          * in the krb5_ccache of the caller.
2044          */
2045         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2046                                         &store_creds);
2047         krb5_free_creds(ctx, s4u2proxy_creds);
2048         if (code != 0) {
2049                 krb5_free_principal(ctx, whitelist_principal);
2050                 krb5_free_principal(ctx, blacklist_principal);
2051                 return code;
2052         }
2053
2054         /*
2055          * It's important to store the principal the KDC
2056          * returned, as otherwise the caller would not find
2057          * the S4U2Self ticket in the krb5_ccache lookup.
2058          */
2059         store_principal = store_creds.client;
2060
2061  store:
2062         if (blacklist_principal &&
2063             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2064                 char *sp = NULL;
2065                 char *ip = NULL;
2066
2067                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2068                 if (code != 0) {
2069                         sp = NULL;
2070                 }
2071                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2072                 if (code != 0) {
2073                         ip = NULL;
2074                 }
2075                 DEBUG(1, ("kerberos_kinit_password_cc: "
2076                           "KDC returned self principal[%s] while impersonating [%s]\n",
2077                           sp?sp:"<no memory>",
2078                           ip?ip:"<no memory>"));
2079
2080                 SAFE_FREE(sp);
2081                 SAFE_FREE(ip);
2082
2083                 krb5_free_principal(ctx, whitelist_principal);
2084                 krb5_free_principal(ctx, blacklist_principal);
2085                 krb5_free_cred_contents(ctx, &store_creds);
2086                 return KRB5_FWD_BAD_PRINCIPAL;
2087         }
2088         if (blacklist_principal) {
2089                 krb5_free_principal(ctx, blacklist_principal);
2090         }
2091
2092         if (whitelist_principal &&
2093             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2094                 char *sp = NULL;
2095                 char *ep = NULL;
2096
2097                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2098                 if (code != 0) {
2099                         sp = NULL;
2100                 }
2101                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2102                 if (code != 0) {
2103                         ep = NULL;
2104                 }
2105                 DEBUG(1, ("kerberos_kinit_password_cc: "
2106                           "KDC returned wrong principal[%s] we expected [%s]\n",
2107                           sp?sp:"<no memory>",
2108                           ep?ep:"<no memory>"));
2109
2110                 SAFE_FREE(sp);
2111                 SAFE_FREE(ep);
2112
2113                 krb5_free_principal(ctx, whitelist_principal);
2114                 krb5_free_cred_contents(ctx, &store_creds);
2115                 return KRB5_FWD_BAD_PRINCIPAL;
2116         }
2117         if (whitelist_principal) {
2118                 krb5_free_principal(ctx, whitelist_principal);
2119         }
2120
2121         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2122         if (code != 0) {
2123                 krb5_free_cred_contents(ctx, &store_creds);
2124                 return code;
2125         }
2126
2127         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2128         if (code != 0) {
2129                 krb5_free_cred_contents(ctx, &store_creds);
2130                 return code;
2131         }
2132
2133         if (expire_time) {
2134                 *expire_time = (time_t) store_creds.times.endtime;
2135         }
2136
2137         if (kdc_time) {
2138                 *kdc_time = (time_t) store_creds.times.starttime;
2139         }
2140
2141         krb5_free_cred_contents(ctx, &store_creds);
2142
2143         return 0;
2144 }
2145 #endif
2146
2147 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2148 krb5_error_code smb_krb5_make_principal(krb5_context context,
2149                                         krb5_principal *principal,
2150                                         const char *_realm, ...)
2151 {
2152         krb5_error_code code;
2153         bool free_realm;
2154         char *realm;
2155         va_list ap;
2156
2157         if (_realm) {
2158                 realm = discard_const_p(char, _realm);
2159                 free_realm = false;
2160         } else {
2161                 code = krb5_get_default_realm(context, &realm);
2162                 if (code) {
2163                         return code;
2164                 }
2165                 free_realm = true;
2166         }
2167
2168         va_start(ap, _realm);
2169         code = krb5_build_principal_alloc_va(context, principal,
2170                                              strlen(realm), realm,
2171                                              ap);
2172         va_end(ap);
2173
2174         if (free_realm) {
2175                 krb5_free_default_realm(context, realm);
2176         }
2177
2178         return code;
2179 }
2180 #endif
2181
2182 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2183 /**
2184  * @brief Get the lifetime of the initial ticket in the cache.
2185  *
2186  * @param[in]  context  The kerberos context.
2187  *
2188  * @param[in]  id       The credential cache to get the ticket lifetime.
2189  *
2190  * @param[out] t        A pointer to a time value to store the lifetime.
2191  *
2192  * @return              0 on success, a krb5_error_code on error.
2193  */
2194 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2195                                          krb5_ccache id,
2196                                          time_t *t)
2197 {
2198         krb5_cc_cursor cursor;
2199         krb5_error_code kerr;
2200         krb5_creds cred;
2201         krb5_timestamp now;
2202
2203         *t = 0;
2204
2205         kerr = krb5_timeofday(context, &now);
2206         if (kerr) {
2207                 return kerr;
2208         }
2209
2210         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2211         if (kerr) {
2212                 return kerr;
2213         }
2214
2215         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2216 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2217                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2218 #else
2219                 if (cred.flags.b.initial) {
2220 #endif
2221                         if (now < cred.times.endtime) {
2222                                 *t = (time_t) (cred.times.endtime - now);
2223                         }
2224                         krb5_free_cred_contents(context, &cred);
2225                         break;
2226                 }
2227                 krb5_free_cred_contents(context, &cred);
2228         }
2229
2230         krb5_cc_end_seq_get(context, id, &cursor);
2231
2232         return kerr;
2233 }
2234 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2235
2236 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2237 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2238 {
2239         free_Checksum(cksum);
2240 }
2241 #endif
2242
2243 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2244                                            DATA_BLOB *pac_data,
2245                                            krb5_context context,
2246                                            const krb5_keyblock *keyblock,
2247                                            uint32_t *sig_type,
2248                                            DATA_BLOB *sig_blob)
2249 {
2250         krb5_error_code ret;
2251         krb5_checksum cksum;
2252 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2253         krb5_crypto crypto;
2254
2255
2256         ret = krb5_crypto_init(context,
2257                                keyblock,
2258                                0,
2259                                &crypto);
2260         if (ret) {
2261                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2262                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2263                 return ret;
2264         }
2265         ret = krb5_create_checksum(context,
2266                                    crypto,
2267                                    KRB5_KU_OTHER_CKSUM,
2268                                    0,
2269                                    pac_data->data,
2270                                    pac_data->length,
2271                                    &cksum);
2272         if (ret) {
2273                 DEBUG(2, ("PAC Verification failed: %s\n",
2274                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2275         }
2276
2277         krb5_crypto_destroy(context, crypto);
2278
2279         if (ret) {
2280                 return ret;
2281         }
2282
2283         *sig_type = cksum.cksumtype;
2284         *sig_blob = data_blob_talloc(mem_ctx,
2285                                         cksum.checksum.data,
2286                                         cksum.checksum.length);
2287 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2288         krb5_data input;
2289
2290         input.data = (char *)pac_data->data;
2291         input.length = pac_data->length;
2292
2293         ret = krb5_c_make_checksum(context,
2294                                    0,
2295                                    keyblock,
2296                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2297                                    &input,
2298                                    &cksum);
2299         if (ret) {
2300                 DEBUG(2, ("PAC Verification failed: %s\n",
2301                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2302                 return ret;
2303         }
2304
2305         *sig_type = cksum.checksum_type;
2306         *sig_blob = data_blob_talloc(mem_ctx,
2307                                         cksum.contents,
2308                                         cksum.length);
2309
2310 #else
2311 #error krb5_create_checksum or krb5_c_make_checksum not available
2312 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2313         smb_krb5_free_checksum_contents(context, &cksum);
2314
2315         return 0;
2316 }
2317
2318
2319 /*
2320  * smb_krb5_principal_get_realm
2321  *
2322  * @brief Get realm of a principal
2323  *
2324  * @param[in] context           The krb5_context
2325  * @param[in] principal         The principal
2326  * @return pointer to the realm
2327  *
2328  * Caller must free if the return value is not NULL.
2329  *
2330  */
2331
2332 char *smb_krb5_principal_get_realm(krb5_context context,
2333                                    krb5_const_principal principal)
2334 {
2335 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2336         return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2337 #elif defined(krb5_princ_realm) /* MIT */
2338         krb5_data *realm;
2339         realm = discard_const_p(krb5_data,
2340                                 krb5_princ_realm(context, principal));
2341         return strndup(realm->data, realm->length);
2342 #else
2343 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2344 #endif
2345 }
2346
2347 /*
2348  * smb_krb5_principal_set_realm
2349  *
2350  * @brief Get realm of a principal
2351  *
2352  * @param[in] context           The krb5_context
2353  * @param[in] principal         The principal
2354  * @param[in] realm             The realm
2355  * @return                      0 on success, a krb5_error_code on error.
2356  *
2357  */
2358
2359 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2360                                              krb5_principal principal,
2361                                              const char *realm)
2362 {
2363 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2364         return krb5_principal_set_realm(context, principal, realm);
2365 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2366         krb5_error_code ret;
2367         krb5_data data;
2368         krb5_data *old_data;
2369
2370         old_data = krb5_princ_realm(context, principal);
2371
2372         ret = krb5_copy_data_contents(&data,
2373                                       realm,
2374                                       strlen(realm));
2375         if (ret) {
2376                 return ret;
2377         }
2378
2379         /* free realm before setting */
2380         free(old_data->data);
2381
2382         krb5_princ_set_realm(context, principal, &data);
2383
2384         return ret;
2385 #else
2386 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2387 #endif
2388 }
2389
2390
2391 /************************************************************************
2392  Routine to get the default realm from the kerberos credentials cache.
2393  Caller must free if the return value is not NULL.
2394 ************************************************************************/
2395
2396 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2397 {
2398         char *realm = NULL;
2399         krb5_context ctx = NULL;
2400         krb5_ccache cc = NULL;
2401         krb5_principal princ = NULL;
2402
2403         initialize_krb5_error_table();
2404         if (krb5_init_context(&ctx)) {
2405                 return NULL;
2406         }
2407
2408         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2409                 "Trying to read krb5 cache: %s\n",
2410                 krb5_cc_default_name(ctx)));
2411         if (krb5_cc_default(ctx, &cc)) {
2412                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2413                         "failed to read default cache\n"));
2414                 goto out;
2415         }
2416         if (krb5_cc_get_principal(ctx, cc, &princ)) {
2417                 DEBUG(0,("kerberos_get_default_realm_from_ccache: "
2418                         "failed to get default principal\n"));
2419                 goto out;
2420         }
2421
2422 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2423         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2424 #elif defined(HAVE_KRB5_PRINC_REALM)
2425         {
2426                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2427                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2428         }
2429 #endif
2430
2431   out:
2432
2433         if (ctx) {
2434                 if (princ) {
2435                         krb5_free_principal(ctx, princ);
2436                 }
2437                 if (cc) {
2438                         krb5_cc_close(ctx, cc);
2439                 }
2440                 krb5_free_context(ctx);
2441         }
2442
2443         return realm;
2444 }
2445
2446 /************************************************************************
2447  Routine to get the realm from a given DNS name.
2448 ************************************************************************/
2449
2450 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2451                                                 const char *hostname)
2452 {
2453 #if defined(HAVE_KRB5_REALM_TYPE)
2454         /* Heimdal. */
2455         krb5_realm *realm_list = NULL;
2456 #else
2457         /* MIT */
2458         char **realm_list = NULL;
2459 #endif
2460         char *realm = NULL;
2461         krb5_error_code kerr;
2462         krb5_context ctx = NULL;
2463
2464         initialize_krb5_error_table();
2465         if (krb5_init_context(&ctx)) {
2466                 return NULL;
2467         }
2468
2469         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2470         if (kerr != 0) {
2471                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2472                         "failed %s\n",
2473                         hostname ? hostname : "(NULL)",
2474                         error_message(kerr) ));
2475                 goto out;
2476         }
2477
2478         if (realm_list && realm_list[0]) {
2479                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2480         }
2481
2482   out:
2483
2484         if (ctx) {
2485                 if (realm_list) {
2486                         krb5_free_host_realm(ctx, realm_list);
2487                         realm_list = NULL;
2488                 }
2489                 krb5_free_context(ctx);
2490                 ctx = NULL;
2491         }
2492         return realm;
2493 }
2494
2495 char *kerberos_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2496                                                    const char *service,
2497                                                    const char *remote_name,
2498                                                    const char *default_realm)
2499 {
2500         char *realm = NULL;
2501         char *host = NULL;
2502         char *principal;
2503         host = strchr_m(remote_name, '.');
2504         if (host) {
2505                 /* DNS name. */
2506                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2507                                                          remote_name);
2508         } else {
2509                 /* NetBIOS name - use our realm. */
2510                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2511         }
2512
2513         if (realm == NULL || *realm == '\0') {
2514                 realm = talloc_strdup(talloc_tos(), default_realm);
2515                 if (!realm) {
2516                         return NULL;
2517                 }
2518                 DEBUG(3,("kerberos_get_principal_from_service_hostname: "
2519                          "cannot get realm from, "
2520                          "desthost %s or default ccache. Using default "
2521                          "smb.conf realm %s\n",
2522                          remote_name,
2523                          realm));
2524         }
2525
2526         principal = talloc_asprintf(mem_ctx,
2527                                     "%s/%s@%s",
2528                                     service, remote_name,
2529                                     realm);
2530         TALLOC_FREE(realm);
2531         return principal;
2532 }
2533
2534 char *smb_get_krb5_error_message(krb5_context context,
2535                                  krb5_error_code code,
2536                                  TALLOC_CTX *mem_ctx)
2537 {
2538         char *ret;
2539
2540 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2541         const char *context_error = krb5_get_error_message(context, code);
2542         if (context_error) {
2543                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2544                                         error_message(code), context_error);
2545                 krb5_free_error_message(context, context_error);
2546                 return ret;
2547         }
2548 #endif
2549         ret = talloc_strdup(mem_ctx, error_message(code));
2550         return ret;
2551 }
2552
2553
2554 /**
2555 * @brief Return the kerberos library setting for "libdefaults:allow_weak_crypto"
2556 *
2557 * @param context        The krb5_context
2558 *
2559 * @return krb5_boolean
2560 *
2561 * Function returns true if weak crypto is allowd, false if not
2562 */
2563
2564 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2565 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2566 {
2567         return krb5_config_get_bool_default(context,
2568                                             NULL,
2569                                             FALSE,
2570                                             "libdefaults",
2571                                             "allow_weak_crypto",
2572                                             NULL);
2573 }
2574 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2575 {
2576 #include <profile.h>
2577         krb5_error_code ret;
2578         krb5_boolean ret_default = false;
2579         profile_t profile;
2580         int ret_profile;
2581
2582         ret = krb5_get_profile(context,
2583                                &profile);
2584         if (ret) {
2585                 return ret_default;
2586         }
2587
2588         ret = profile_get_boolean(profile,
2589                                   "libdefaults",
2590                                   "allow_weak_crypto",
2591                                   NULL, /* subsubname */
2592                                   ret_default, /* def_val */
2593                                   &ret_profile /* *ret_default */);
2594         if (ret) {
2595                 return ret_default;
2596         }
2597
2598         profile_release(profile);
2599
2600         return ret_profile;
2601 }
2602 #else
2603 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2604 #endif
2605
2606 /**
2607 * @brief Return the type of a krb5_principal
2608 *
2609 * @param context        The krb5_context
2610 * @param principal      The const krb5_principal
2611 *
2612 * @return integer type of the principal
2613 */
2614 int smb_krb5_principal_get_type(krb5_context context,
2615                                 krb5_const_principal principal)
2616 {
2617 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
2618         return krb5_principal_get_type(context, principal);
2619 #elif defined(krb5_princ_type) /* MIT */
2620         return krb5_princ_type(context, principal);
2621 #else
2622 #error  UNKNOWN_PRINC_GET_TYPE_FUNCTION
2623 #endif
2624 }
2625
2626 /**
2627 * @brief Set the type of a krb5_principal
2628 *
2629 * @param context        The krb5_context
2630 * @param principal      The const krb5_principal
2631 * @param type           The principal type
2632 *
2633 */
2634 void smb_krb5_principal_set_type(krb5_context context,
2635                                  krb5_principal principal,
2636                                  int type)
2637 {
2638 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
2639         krb5_principal_set_type(context, principal, type);
2640 #elif defined(krb5_princ_type) /* MIT */
2641         krb5_princ_type(context, principal) = type;
2642 #else
2643 #error  UNKNOWN_PRINC_SET_TYPE_FUNCTION
2644 #endif
2645 }
2646
2647 /**
2648 * @brief Generate a krb5 warning, forwarding to com_err
2649 *
2650 * @param context        The krb5_context
2651 * @param fmt            The message format
2652 * @param ...            The message arguments
2653 *
2654 * @return
2655 */
2656 #if !defined(HAVE_KRB5_WARNX)
2657 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
2658 {
2659         va_list args;
2660
2661         va_start(args, fmt);
2662         com_err_va("kdb_samba", errno, fmt, args);
2663         va_end(args);
2664
2665         return 0;
2666 }
2667 #endif
2668
2669 #else /* HAVE_KRB5 */
2670  /* this saves a few linking headaches */
2671  int cli_krb5_get_ticket(TALLOC_CTX *mem_ctx,
2672                         const char *principal, time_t time_offset,
2673                         DATA_BLOB *ticket, DATA_BLOB *session_key_krb5,
2674                         uint32_t extra_ap_opts,
2675                         const char *ccname, time_t *tgs_expire,
2676                         const char *impersonate_princ_s)
2677 {
2678          DEBUG(0,("NO KERBEROS SUPPORT\n"));
2679          return 1;
2680 }
2681
2682 #endif /* HAVE_KRB5 */