krb5_wrap: let smb_krb5_kinit_s4u2_ccache() work if store_creds.client and server...
[vlendec/samba-autobuild/.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
27 #ifdef HAVE_COM_ERR_H
28 #include <com_err.h>
29 #endif /* HAVE_COM_ERR_H */
30
31 #ifndef KRB5_AUTHDATA_WIN2K_PAC
32 #define KRB5_AUTHDATA_WIN2K_PAC 128
33 #endif
34
35 #ifndef KRB5_AUTHDATA_IF_RELEVANT
36 #define KRB5_AUTHDATA_IF_RELEVANT 1
37 #endif
38
39 #ifdef HAVE_KRB5
40
41 #define GSSAPI_CHECKSUM      0x8003             /* Checksum type value for Kerberos */
42 #define GSSAPI_BNDLENGTH     16                 /* Bind Length (rfc-1964 pg.3) */
43 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
44                                                         bind field, flags field. */
45 #define GSS_C_DELEG_FLAG 1
46
47 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
48    but still has the symbol */
49 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
50 krb5_error_code krb5_auth_con_set_req_cksumtype(
51         krb5_context     context,
52         krb5_auth_context      auth_context,
53         krb5_cksumtype     cksumtype);
54 #endif
55
56 #if !defined(SMB_MALLOC)
57 #undef malloc
58 #define SMB_MALLOC(s) malloc((s))
59 #endif
60
61 #ifndef SMB_STRDUP
62 #define SMB_STRDUP(s) strdup(s)
63 #endif
64
65 /**********************************************************
66  * MISSING FUNCTIONS
67  **********************************************************/
68
69 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
70
71 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
72
73 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
74  * to krb5_set_default_tgs_ktypes. See
75  *         http://lists.samba.org/archive/samba-technical/2006-July/048271.html
76  *
77  * If the MIT libraries are not exporting internal symbols, we will end up in
78  * this branch, which is correct. Otherwise we will continue to use the
79  * internal symbol
80  */
81  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
82 {
83     return krb5_set_default_tgs_enctypes(ctx, enc);
84 }
85
86 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
87
88 /* Heimdal */
89  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
90 {
91         return krb5_set_default_in_tkt_etypes(ctx, enc);
92 }
93
94 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
95
96 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
97
98
99 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
100 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
101                                              krb5_auth_context auth_context,
102                                              krb5_keyblock *keyblock)
103 {
104         return krb5_auth_con_setkey(context, auth_context, keyblock);
105 }
106 #endif
107
108 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
109 void krb5_free_unparsed_name(krb5_context context, char *val)
110 {
111         SAFE_FREE(val);
112 }
113 #endif
114
115 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
116 const krb5_data *krb5_princ_component(krb5_context context,
117                                       krb5_principal principal, int i);
118
119 const krb5_data *krb5_princ_component(krb5_context context,
120                                       krb5_principal principal, int i)
121 {
122         static krb5_data kdata;
123
124         kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
125         kdata.length = strlen((const char *)kdata.data);
126         return &kdata;
127 }
128 #endif
129
130
131 /**********************************************************
132  * WRAPPING FUNCTIONS
133  **********************************************************/
134
135 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
136 /* HEIMDAL */
137
138 /**
139  * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
140  *
141  * @param[in]  paddr    A pointer to a 'struct sockaddr_storage to extract the
142  *                      address from.
143  *
144  * @param[out] pkaddr   A Kerberos address to store tha address in.
145  *
146  * @return True on success, false if an error occured.
147  */
148 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
149                                 krb5_address *pkaddr)
150 {
151         memset(pkaddr, '\0', sizeof(krb5_address));
152 #if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
153         if (paddr->ss_family == AF_INET6) {
154                 pkaddr->addr_type = KRB5_ADDRESS_INET6;
155                 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
156                 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
157                 return true;
158         }
159 #endif
160         if (paddr->ss_family == AF_INET) {
161                 pkaddr->addr_type = KRB5_ADDRESS_INET;
162                 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
163                 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
164                 return true;
165         }
166         return false;
167 }
168 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
169 /* MIT */
170
171 /**
172  * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
173  *
174  * @param[in]  paddr    A pointer to a 'struct sockaddr_storage to extract the
175  *                      address from.
176  *
177  * @param[in]  pkaddr A Kerberos address to store tha address in.
178  *
179  * @return True on success, false if an error occured.
180  */
181 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
182                                 krb5_address *pkaddr)
183 {
184         memset(pkaddr, '\0', sizeof(krb5_address));
185 #if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
186         if (paddr->ss_family == AF_INET6) {
187                 pkaddr->addrtype = ADDRTYPE_INET6;
188                 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
189                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
190                 return true;
191         }
192 #endif
193         if (paddr->ss_family == AF_INET) {
194                 pkaddr->addrtype = ADDRTYPE_INET;
195                 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
196                 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
197                 return true;
198         }
199         return false;
200 }
201 #else
202 #error UNKNOWN_ADDRTYPE
203 #endif
204
205 krb5_error_code smb_krb5_mk_error(krb5_context context,
206                                   krb5_error_code error_code,
207                                   const char *e_text,
208                                   krb5_data *e_data,
209                                   const krb5_principal client,
210                                   const krb5_principal server,
211                                   krb5_data *enc_err)
212 {
213         krb5_error_code code = EINVAL;
214 #ifdef SAMBA4_USES_HEIMDAL
215         code = krb5_mk_error(context,
216                              error_code,
217                              e_text,
218                              e_data,
219                              client,
220                              server,
221                              NULL, /* client_time */
222                              NULL, /* client_usec */
223                              enc_err);
224 #else
225         krb5_principal unspec_server = NULL;
226         krb5_error errpkt;
227
228         errpkt.ctime = 0;
229         errpkt.cusec = 0;
230
231         code = krb5_us_timeofday(context,
232                                  &errpkt.stime,
233                                  &errpkt.susec);
234         if (code != 0) {
235                 return code;
236         }
237
238         errpkt.error = error_code;
239
240         errpkt.text.length = 0;
241         if (e_text != NULL) {
242                 errpkt.text.length = strlen(e_text);
243                 errpkt.text.data = discard_const_p(char, e_text);
244         }
245
246         errpkt.e_data.magic = KV5M_DATA;
247         errpkt.e_data.length = 0;
248         errpkt.e_data.data = NULL;
249         if (e_data != NULL) {
250                 errpkt.e_data = *e_data;
251         }
252
253         errpkt.client = client;
254
255         if (server != NULL) {
256                 errpkt.server = server;
257         } else {
258                 code = smb_krb5_make_principal(context,
259                                                &unspec_server,
260                                                "<unspecified realm>",
261                                                NULL);
262                 if (code != 0) {
263                         return code;
264                 }
265                 errpkt.server = unspec_server;
266         }
267
268         code = krb5_mk_error(context,
269                              &errpkt,
270                              enc_err);
271         krb5_free_principal(context, unspec_server);
272 #endif
273         return code;
274 }
275
276 /**
277 * @brief Create a keyblock based on input parameters
278 *
279 * @param context        The krb5_context
280 * @param host_princ     The krb5_principal to use
281 * @param salt           The optional salt, if omitted, salt is calculated with
282 *                       the provided principal.
283 * @param password       The krb5_data containing the password
284 * @param enctype        The krb5_enctype to use for the keyblock generation
285 * @param key            The returned krb5_keyblock, caller needs to free with
286 *                       krb5_free_keyblock().
287 *
288 * @return krb5_error_code
289 */
290 int smb_krb5_create_key_from_string(krb5_context context,
291                                     krb5_const_principal host_princ,
292                                     krb5_data *salt,
293                                     krb5_data *password,
294                                     krb5_enctype enctype,
295                                     krb5_keyblock *key)
296 {
297         int ret = 0;
298
299         if (host_princ == NULL && salt == NULL) {
300                 return -1;
301         }
302
303 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
304 {/* MIT */
305         krb5_data _salt;
306
307         if (salt == NULL) {
308                 ret = krb5_principal2salt(context, host_princ, &_salt);
309                 if (ret) {
310                         DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
311                         return ret;
312                 }
313         } else {
314                 _salt = *salt;
315         }
316         ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
317         if (salt == NULL) {
318                 SAFE_FREE(_salt.data);
319         }
320 }
321 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
322 {/* Heimdal */
323         krb5_salt _salt;
324
325         if (salt == NULL) {
326                 ret = krb5_get_pw_salt(context, host_princ, &_salt);
327                 if (ret) {
328                         DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
329                         return ret;
330                 }
331         } else {
332                 _salt.saltvalue = *salt;
333                 _salt.salttype = KRB5_PW_SALT;
334         }
335
336         ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
337         if (salt == NULL) {
338                 krb5_free_salt(context, _salt);
339         }
340 }
341 #else
342 #error UNKNOWN_CREATE_KEY_FUNCTIONS
343 #endif
344         return ret;
345 }
346
347 /**
348 * @brief Create a salt for a given principal
349 *
350 * @param context        The initialized krb5_context
351 * @param host_princ     The krb5_principal to create the salt for
352 * @param psalt          A pointer to a krb5_data struct
353 *
354 * caller has to free the contents of psalt with smb_krb5_free_data_contents
355 * when function has succeeded
356 *
357 * @return krb5_error_code, returns 0 on success, error code otherwise
358 */
359
360 int smb_krb5_get_pw_salt(krb5_context context,
361                          krb5_const_principal host_princ,
362                          krb5_data *psalt)
363 #if defined(HAVE_KRB5_GET_PW_SALT)
364 /* Heimdal */
365 {
366         int ret;
367         krb5_salt salt;
368
369         ret = krb5_get_pw_salt(context, host_princ, &salt);
370         if (ret) {
371                 return ret;
372         }
373
374         psalt->data = salt.saltvalue.data;
375         psalt->length = salt.saltvalue.length;
376
377         return ret;
378 }
379 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
380 /* MIT */
381 {
382         return krb5_principal2salt(context, host_princ, psalt);
383 }
384 #else
385 #error UNKNOWN_SALT_FUNCTIONS
386 #endif
387
388 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
389 /**
390  * @brief Get a list of encryption types allowed for session keys
391  *
392  * @param[in]  context  The library context
393  *
394  * @param[in]  enctypes An allocated, zero-terminated list of encryption types
395  *
396  * This function returns an allocated list of encryption types allowed for
397  * session keys.
398  *
399  * Use free() to free the enctypes when it is no longer needed.
400  *
401  * @retval 0 Success; otherwise - Kerberos error codes
402  */
403 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
404                                             krb5_enctype **enctypes)
405 {
406         return krb5_get_permitted_enctypes(context, enctypes);
407 }
408 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
409 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
410                                             krb5_enctype **enctypes)
411 {
412 #ifdef HAVE_KRB5_PDU_NONE_DECL
413         return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
414 #else
415         return krb5_get_default_in_tkt_etypes(context, enctypes);
416 #endif
417 }
418 #else
419 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
420 #endif
421
422
423 /**
424  * @brief Convert a string principal name to a Kerberos principal.
425  *
426  * @param[in]  context  The library context
427  *
428  * @param[in]  name     The principal as a unix charset string.
429  *
430  * @param[out] principal The newly allocated principal.
431  *
432  * Use krb5_free_principal() to free a principal when it is no longer needed.
433  *
434  * @return 0 on success, a Kerberos error code otherwise.
435  */
436 krb5_error_code smb_krb5_parse_name(krb5_context context,
437                                     const char *name,
438                                     krb5_principal *principal)
439 {
440         krb5_error_code ret;
441         char *utf8_name;
442         size_t converted_size;
443         TALLOC_CTX *frame = talloc_stackframe();
444
445         if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
446                 talloc_free(frame);
447                 return ENOMEM;
448         }
449
450         ret = krb5_parse_name(context, utf8_name, principal);
451         TALLOC_FREE(frame);
452         return ret;
453 }
454
455 /**
456  * @brief Convert a Kerberos principal structure to a string representation.
457  *
458  * The resulting string representation will be a unix charset name and is
459  * talloc'ed.
460  *
461  * @param[in]  mem_ctx  The talloc context to allocate memory on.
462  *
463  * @param[in]  context  The library context.
464  *
465  * @param[in]  principal The principal.
466  *
467  * @param[out] unix_name A string representation of the princpial name as with
468  *                       unix charset.
469  *
470  * Use talloc_free() to free the string representation if it is no longer
471  * needed.
472  *
473  * @return 0 on success, a Kerberos error code otherwise.
474  */
475 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
476                                       krb5_context context,
477                                       krb5_const_principal principal,
478                                       char **unix_name)
479 {
480         krb5_error_code ret;
481         char *utf8_name;
482         size_t converted_size;
483
484         *unix_name = NULL;
485         ret = krb5_unparse_name(context, principal, &utf8_name);
486         if (ret) {
487                 return ret;
488         }
489
490         if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
491                 krb5_free_unparsed_name(context, utf8_name);
492                 return ENOMEM;
493         }
494         krb5_free_unparsed_name(context, utf8_name);
495         return 0;
496 }
497
498 /**
499  * @brief Free the contents of a krb5_data structure and zero the data field.
500  *
501  * @param[in]  context  The krb5 context
502  *
503  * @param[in]  pdata    The data structure to free contents of
504  *
505  * This function frees the contents, not the structure itself.
506  */
507 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
508 {
509 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
510         if (pdata->data) {
511                 krb5_free_data_contents(context, pdata);
512         }
513 #elif defined(HAVE_KRB5_DATA_FREE)
514         krb5_data_free(context, pdata);
515 #else
516         SAFE_FREE(pdata->data);
517 #endif
518 }
519
520 /*
521  * @brief copy a buffer into a krb5_data struct
522  *
523  * @param[in] p                 The krb5_data
524  * @param[in] data              The data to copy
525  * @param[in] length            The length of the data to copy
526  * @return krb5_error_code
527  *
528  * Caller has to free krb5_data with smb_krb5_free_data_contents().
529  */
530 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
531                                             const void *data,
532                                             size_t len)
533 {
534 #if defined(HAVE_KRB5_DATA_COPY)
535         return krb5_data_copy(p, data, len);
536 #else
537         if (len) {
538                 p->data = malloc(len);
539                 if (p->data == NULL) {
540                         return ENOMEM;
541                 }
542                 memmove(p->data, data, len);
543         } else {
544                 p->data = NULL;
545         }
546         p->length = len;
547         p->magic = KV5M_DATA;
548         return 0;
549 #endif
550 }
551
552 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
553                                   krb5_context context,
554                                   krb5_auth_context auth_context,
555                                   DATA_BLOB *session_key,
556                                   bool remote)
557 {
558         krb5_keyblock *skey = NULL;
559         krb5_error_code err = 0;
560         bool ret = false;
561
562         if (remote) {
563 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
564                 err = krb5_auth_con_getrecvsubkey(context,
565                                                   auth_context,
566                                                   &skey);
567 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
568                 err = krb5_auth_con_getremotesubkey(context,
569                                                     auth_context, &skey);
570 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
571         } else {
572 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
573                 err = krb5_auth_con_getsendsubkey(context,
574                                                   auth_context,
575                                                   &skey);
576 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
577                 err = krb5_auth_con_getlocalsubkey(context,
578                                                    auth_context, &skey);
579 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
580         }
581
582         if (err || skey == NULL) {
583                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
584                 goto done;
585         }
586
587         DEBUG(10, ("Got KRB5 session key of length %d\n",
588                    (int)KRB5_KEY_LENGTH(skey)));
589
590         *session_key = data_blob_talloc(mem_ctx,
591                                          KRB5_KEY_DATA(skey),
592                                          KRB5_KEY_LENGTH(skey));
593         dump_data_pw("KRB5 Session Key:\n",
594                      session_key->data,
595                      session_key->length);
596
597         ret = true;
598
599 done:
600         if (skey) {
601                 krb5_free_keyblock(context, skey);
602         }
603
604         return ret;
605 }
606
607
608 /**
609  * @brief Get talloced string component of a principal
610  *
611  * @param[in] mem_ctx           The TALLOC_CTX
612  * @param[in] context           The krb5_context
613  * @param[in] principal         The principal
614  * @param[in] component         The component
615  * @return string component
616  *
617  * Caller must talloc_free if the return value is not NULL.
618  *
619  */
620 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
621                                          krb5_context context,
622                                          krb5_const_principal principal,
623                                          unsigned int component)
624 {
625 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
626         return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
627 #else
628         krb5_data *data;
629
630         if (component >= krb5_princ_size(context, principal)) {
631                 return NULL;
632         }
633
634         data = krb5_princ_component(context, principal, component);
635         if (data == NULL) {
636                 return NULL;
637         }
638
639         return talloc_strndup(mem_ctx, data->data, data->length);
640 #endif
641 }
642
643 /**
644  * @brief
645  *
646  * @param[in]  ccache_string A string pointing to the cache to renew the ticket
647  *                           (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
648  *                           ccache has not been specified, the default ccache
649  *                           will be used.
650  *
651  * @param[in]  client_string The client principal string (e.g. user@SAMBA.SITE)
652  *                           or NULL. If the principal string has not been
653  *                           specified, the principal from the ccache will be
654  *                           retrieved.
655  *
656  * @param[in]  service_string The service ticket string
657  *                            (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
658  *                            the sevice ticket is specified, it is parsed (
659  *                            with the realm part ignored) and used as the
660  *                            server principal of the credential. Otherwise
661  *                            the ticket-granting service is used.
662  *
663  * @param[in]  expire_time    A pointer to store the credentials end time or
664  *                            NULL.
665  *
666  * @return 0 on Succes, a Kerberos error code otherwise.
667  */
668 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
669                                       const char *client_string,
670                                       const char *service_string,
671                                       time_t *expire_time)
672 {
673         krb5_error_code ret;
674         krb5_context context = NULL;
675         krb5_ccache ccache = NULL;
676         krb5_principal client = NULL;
677         krb5_creds creds, creds_in;
678
679         ZERO_STRUCT(creds);
680         ZERO_STRUCT(creds_in);
681
682         initialize_krb5_error_table();
683         ret = krb5_init_context(&context);
684         if (ret) {
685                 goto done;
686         }
687
688         if (!ccache_string) {
689                 ccache_string = krb5_cc_default_name(context);
690         }
691
692         if (!ccache_string) {
693                 ret = EINVAL;
694                 goto done;
695         }
696
697         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
698
699         /* FIXME: we should not fall back to defaults */
700         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
701         if (ret) {
702                 goto done;
703         }
704
705         if (client_string) {
706                 ret = smb_krb5_parse_name(context, client_string, &client);
707                 if (ret) {
708                         goto done;
709                 }
710         } else {
711                 ret = krb5_cc_get_principal(context, ccache, &client);
712                 if (ret) {
713                         goto done;
714                 }
715         }
716
717         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
718         if (ret) {
719                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
720                 goto done;
721         }
722
723         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
724         ret = krb5_cc_initialize(context, ccache, client);
725         if (ret) {
726                 goto done;
727         }
728
729         ret = krb5_cc_store_cred(context, ccache, &creds);
730
731         if (expire_time) {
732                 *expire_time = (time_t) creds.times.endtime;
733         }
734
735 done:
736         krb5_free_cred_contents(context, &creds_in);
737         krb5_free_cred_contents(context, &creds);
738
739         if (client) {
740                 krb5_free_principal(context, client);
741         }
742         if (ccache) {
743                 krb5_cc_close(context, ccache);
744         }
745         if (context) {
746                 krb5_free_context(context);
747         }
748
749         return ret;
750 }
751
752 /**
753  * @brief Free the data stored in an smb_krb5_addresses structure.
754  *
755  * @param[in]  context  The library context
756  *
757  * @param[in]  addr     The address structure to free.
758  *
759  * @return 0 on success, a Kerberos error code otherwise.
760  */
761 krb5_error_code smb_krb5_free_addresses(krb5_context context,
762                                         smb_krb5_addresses *addr)
763 {
764         krb5_error_code ret = 0;
765         if (addr == NULL) {
766                 return ret;
767         }
768 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
769         krb5_free_addresses(context, addr->addrs);
770 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
771         ret = krb5_free_addresses(context, addr->addrs);
772         SAFE_FREE(addr->addrs);
773 #endif
774         SAFE_FREE(addr);
775         addr = NULL;
776         return ret;
777 }
778
779 #define MAX_NETBIOSNAME_LEN 16
780
781 /**
782  * @brief Add a netbios name to the array of addresses
783  *
784  * @param[in]  kerb_addr A pointer to the smb_krb5_addresses to add the
785  *                       netbios name to.
786  *
787  * @param[in]  netbios_name The netbios name to add.
788  *
789  * @return 0 on success, a Kerberos error code otherwise.
790  */
791 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
792                                                    const char *netbios_name)
793 {
794         krb5_error_code ret = 0;
795         char buf[MAX_NETBIOSNAME_LEN];
796         int len;
797 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
798         krb5_address **addrs = NULL;
799 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
800         krb5_addresses *addrs = NULL;
801 #endif
802
803         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
804         if (*kerb_addr == NULL) {
805                 return ENOMEM;
806         }
807
808         /* temporarily duplicate put_name() code here to avoid dependency
809          * issues for a 5 lines function */
810         len = strlen(netbios_name);
811         memcpy(buf, netbios_name,
812                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
813         if (len < MAX_NETBIOSNAME_LEN - 1) {
814                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
815         }
816         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
817
818 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
819         {
820                 int num_addr = 2;
821
822                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
823                 if (addrs == NULL) {
824                         SAFE_FREE(*kerb_addr);
825                         return ENOMEM;
826                 }
827
828                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
829
830                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
831                 if (addrs[0] == NULL) {
832                         SAFE_FREE(addrs);
833                         SAFE_FREE(*kerb_addr);
834                         return ENOMEM;
835                 }
836
837                 addrs[0]->magic = KV5M_ADDRESS;
838                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
839                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
840                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
841                 if (addrs[0]->contents == NULL) {
842                         SAFE_FREE(addrs[0]);
843                         SAFE_FREE(addrs);
844                         SAFE_FREE(*kerb_addr);
845                         return ENOMEM;
846                 }
847
848                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
849
850                 addrs[1] = NULL;
851         }
852 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
853         {
854                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
855                 if (addrs == NULL) {
856                         SAFE_FREE(*kerb_addr);
857                         return ENOMEM;
858                 }
859
860                 memset(addrs, 0, sizeof(krb5_addresses));
861
862                 addrs->len = 1;
863                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
864                 if (addrs->val == NULL) {
865                         SAFE_FREE(addrs);
866                         SAFE_FREE(kerb_addr);
867                         return ENOMEM;
868                 }
869
870                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
871                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
872                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
873                 if (addrs->val[0].address.data == NULL) {
874                         SAFE_FREE(addrs->val);
875                         SAFE_FREE(addrs);
876                         SAFE_FREE(*kerb_addr);
877                         return ENOMEM;
878                 }
879
880                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
881         }
882 #else
883 #error UNKNOWN_KRB5_ADDRESS_FORMAT
884 #endif
885         (*kerb_addr)->addrs = addrs;
886
887         return ret;
888 }
889
890 /**
891  * @brief Get the enctype from a key table entry
892  *
893  * @param[in]  kt_entry Key table entry to get the enctype from.
894  *
895  * @return The enctype from the entry.
896  */
897 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
898 {
899         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
900 }
901
902 /**
903  * @brief Free the contents of a key table entry.
904  *
905  * @param[in]  context The library context.
906  *
907  * @param[in]  kt_entry The key table entry to free the contents of.
908  *
909  * @return 0 on success, a Kerberos error code otherwise.
910  *
911  * The pointer itself is not freed.
912  */
913 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
914                                         krb5_keytab_entry *kt_entry)
915 {
916 /* Try krb5_free_keytab_entry_contents first, since
917  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
918  * krb5_kt_free_entry but only has a prototype for the first, while the
919  * second is considered private.
920  */
921 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
922         return krb5_free_keytab_entry_contents(context, kt_entry);
923 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
924         return krb5_kt_free_entry(context, kt_entry);
925 #else
926 #error UNKNOWN_KT_FREE_FUNCTION
927 #endif
928 }
929
930
931 /**
932  * @brief Convert an encryption type to a string.
933  *
934  * @param[in]  context The library context.
935  *
936  * @param[in]  enctype The encryption type.
937  *
938  * @param[in]  etype_s A pointer to store the allocated encryption type as a
939  *                     string.
940  *
941  * @return 0 on success, a Kerberos error code otherwise.
942  *
943  * The caller needs to free the allocated string etype_s.
944  */
945 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
946                                            krb5_enctype enctype,
947                                            char **etype_s)
948 {
949 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
950         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
951 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
952         char buf[256];
953         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
954         if (ret) {
955                 return ret;
956         }
957         *etype_s = SMB_STRDUP(buf);
958         if (!*etype_s) {
959                 return ENOMEM;
960         }
961         return ret;
962 #else
963 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
964 #endif
965 }
966
967 /* This MAX_NAME_LEN is a constant defined in krb5.h */
968 #ifndef MAX_KEYTAB_NAME_LEN
969 #define MAX_KEYTAB_NAME_LEN 1100
970 #endif
971
972 /**
973  * @brief Open a key table readonly or with readwrite access.
974  *
975  * Allows to use a different keytab than the default one using a relative
976  * path to the keytab.
977  *
978  * @param[in]  context  The library context
979  *
980  * @param[in]  keytab_name_req The path to the key table.
981  *
982  * @param[in]  write_access Open with readwrite access.
983  *
984  * @param[in]  keytab A pointer o the opended key table.
985  *
986  * The keytab pointer should be freed using krb5_kt_close().
987  *
988  * @return 0 on success, a Kerberos error code otherwise.
989  */
990 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
991                                           const char *keytab_name_req,
992                                           bool write_access,
993                                           krb5_keytab *keytab)
994 {
995         krb5_error_code ret = 0;
996         TALLOC_CTX *mem_ctx;
997         char keytab_string[MAX_KEYTAB_NAME_LEN];
998         char *kt_str = NULL;
999         bool found_valid_name = false;
1000         const char *pragma = "FILE";
1001         const char *tmp = NULL;
1002
1003         if (!write_access && !keytab_name_req) {
1004                 /* caller just wants to read the default keytab readonly, so be it */
1005                 return krb5_kt_default(context, keytab);
1006         }
1007
1008         mem_ctx = talloc_init("smb_krb5_open_keytab");
1009         if (!mem_ctx) {
1010                 return ENOMEM;
1011         }
1012
1013 #ifdef HAVE_WRFILE_KEYTAB
1014         if (write_access) {
1015                 pragma = "WRFILE";
1016         }
1017 #endif
1018
1019         if (keytab_name_req) {
1020
1021                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1022                         ret = KRB5_CONFIG_NOTENUFSPACE;
1023                         goto out;
1024                 }
1025
1026                 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1027                     (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1028                         tmp = keytab_name_req;
1029                         goto resolve;
1030                 }
1031
1032                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1033                 if (!tmp) {
1034                         ret = ENOMEM;
1035                         goto out;
1036                 }
1037
1038                 goto resolve;
1039         }
1040
1041         /* we need to handle more complex keytab_strings, like:
1042          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1043
1044         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1045         if (ret) {
1046                 goto out;
1047         }
1048
1049         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1050
1051         tmp = talloc_strdup(mem_ctx, keytab_string);
1052         if (!tmp) {
1053                 ret = ENOMEM;
1054                 goto out;
1055         }
1056
1057         if (strncmp(tmp, "ANY:", 4) == 0) {
1058                 tmp += 4;
1059         }
1060
1061         memset(&keytab_string, '\0', sizeof(keytab_string));
1062
1063         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1064                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1065                         found_valid_name = true;
1066                         tmp = kt_str;
1067                         tmp += 7;
1068                 }
1069
1070                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1071                         found_valid_name = true;
1072                         tmp = kt_str;
1073                         tmp += 5;
1074                 }
1075
1076                 if (tmp[0] == '/') {
1077                         /* Treat as a FILE: keytab definition. */
1078                         found_valid_name = true;
1079                 }
1080
1081                 if (found_valid_name) {
1082                         if (tmp[0] != '/') {
1083                                 ret = KRB5_KT_BADNAME;
1084                                 goto out;
1085                         }
1086
1087                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1088                         if (!tmp) {
1089                                 ret = ENOMEM;
1090                                 goto out;
1091                         }
1092                         break;
1093                 }
1094         }
1095
1096         if (!found_valid_name) {
1097                 ret = KRB5_KT_UNKNOWN_TYPE;
1098                 goto out;
1099         }
1100
1101 resolve:
1102         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1103         ret = krb5_kt_resolve(context, tmp, keytab);
1104
1105 out:
1106         TALLOC_FREE(mem_ctx);
1107         return ret;
1108 }
1109
1110 /**
1111  * @brief Open a key table readonly or with readwrite access.
1112  *
1113  * Allows to use a different keytab than the default one. The path needs to be
1114  * an absolute path or an error will be returned.
1115  *
1116  * @param[in]  context  The library context
1117  *
1118  * @param[in]  keytab_name_req The path to the key table.
1119  *
1120  * @param[in]  write_access Open with readwrite access.
1121  *
1122  * @param[in]  keytab A pointer o the opended key table.
1123  *
1124  * The keytab pointer should be freed using krb5_kt_close().
1125  *
1126  * @return 0 on success, a Kerberos error code otherwise.
1127  */
1128 krb5_error_code smb_krb5_kt_open(krb5_context context,
1129                                  const char *keytab_name_req,
1130                                  bool write_access,
1131                                  krb5_keytab *keytab)
1132 {
1133         int cmp;
1134
1135         if (keytab_name_req == NULL) {
1136                 return KRB5_KT_BADNAME;
1137         }
1138
1139         if (keytab_name_req[0] == '/') {
1140                 goto open_keytab;
1141         }
1142
1143         cmp = strncmp(keytab_name_req, "FILE:/", 6);
1144         if (cmp == 0) {
1145                 goto open_keytab;
1146         }
1147
1148         cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1149         if (cmp == 0) {
1150                 goto open_keytab;
1151         }
1152
1153         return KRB5_KT_BADNAME;
1154
1155 open_keytab:
1156         return smb_krb5_kt_open_relative(context,
1157                                          keytab_name_req,
1158                                          write_access,
1159                                          keytab);
1160 }
1161
1162 /**
1163  * @brief Get a key table name.
1164  *
1165  * @param[in]  mem_ctx The talloc context to use for allocation.
1166  *
1167  * @param[in]  context The library context.
1168  *
1169  * @param[in]  keytab The key table to get the name from.
1170  *
1171  * @param[in]  keytab_name A talloc'ed string of the key table name.
1172  *
1173  * The talloc'ed name string needs to be freed with talloc_free().
1174  *
1175  * @return 0 on success, a Kerberos error code otherwise.
1176  */
1177 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1178                                      krb5_context context,
1179                                      krb5_keytab keytab,
1180                                      const char **keytab_name)
1181 {
1182         char keytab_string[MAX_KEYTAB_NAME_LEN];
1183         krb5_error_code ret = 0;
1184
1185         ret = krb5_kt_get_name(context, keytab,
1186                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1187         if (ret) {
1188                 return ret;
1189         }
1190
1191         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1192         if (!*keytab_name) {
1193                 return ENOMEM;
1194         }
1195
1196         return ret;
1197 }
1198
1199 /**
1200  * @brief Seek and delete old entries in a keytab based on the passed
1201  *        principal.
1202  *
1203  * @param[in]  context       The KRB5 context to use.
1204  *
1205  * @param[in]  keytab        The keytab to operate on.
1206  *
1207  * @param[in]  kvno          The kvnco to use.
1208  *
1209  * @param[in]  princ_s       The principal as a string to search for.
1210  *
1211  * @param[in]  princ         The principal as a krb5_principal to search for.
1212  *
1213  * @param[in]  flush         Weather to flush the complete keytab.
1214  *
1215  * @param[in]  keep_old_entries Keep the entry with the previous kvno.
1216  *
1217  * @retval 0 on Sucess
1218  *
1219  * @return An appropriate KRB5 error code.
1220  */
1221 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1222                                                         krb5_keytab keytab,
1223                                                         krb5_kvno kvno,
1224                                                         krb5_enctype enctype,
1225                                                         const char *princ_s,
1226                                                         krb5_principal princ,
1227                                                         bool flush,
1228                                                         bool keep_old_entries)
1229 {
1230         krb5_error_code ret;
1231         krb5_kt_cursor cursor;
1232         krb5_keytab_entry kt_entry;
1233         char *ktprinc = NULL;
1234         krb5_kvno old_kvno = kvno - 1;
1235         TALLOC_CTX *tmp_ctx;
1236
1237         ZERO_STRUCT(cursor);
1238         ZERO_STRUCT(kt_entry);
1239
1240         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1241         if (ret == KRB5_KT_END || ret == ENOENT ) {
1242                 /* no entries */
1243                 return 0;
1244         }
1245
1246         tmp_ctx = talloc_new(NULL);
1247         if (tmp_ctx == NULL) {
1248                 return ENOMEM;
1249         }
1250
1251         DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1252         while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1253                 bool name_ok = false;
1254                 krb5_enctype kt_entry_enctype =
1255                         smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1256
1257                 if (!flush && (princ_s != NULL)) {
1258                         ret = smb_krb5_unparse_name(tmp_ctx, context,
1259                                                     kt_entry.principal,
1260                                                     &ktprinc);
1261                         if (ret) {
1262                                 DEBUG(1, (__location__
1263                                           ": smb_krb5_unparse_name failed "
1264                                           "(%s)\n", error_message(ret)));
1265                                 goto out;
1266                         }
1267
1268 #ifdef HAVE_KRB5_KT_COMPARE
1269                         name_ok = krb5_kt_compare(context, &kt_entry,
1270                                                   princ, 0, 0);
1271 #else
1272                         name_ok = (strcmp(ktprinc, princ_s) == 0);
1273 #endif
1274
1275                         if (!name_ok) {
1276                                 DEBUG(10, (__location__ ": ignoring keytab "
1277                                            "entry principal %s, kvno = %d\n",
1278                                            ktprinc, kt_entry.vno));
1279
1280                                 /* Not a match,
1281                                  * just free this entry and continue. */
1282                                 ret = smb_krb5_kt_free_entry(context,
1283                                                              &kt_entry);
1284                                 ZERO_STRUCT(kt_entry);
1285                                 if (ret) {
1286                                         DEBUG(1, (__location__
1287                                                   ": smb_krb5_kt_free_entry "
1288                                                   "failed (%s)\n",
1289                                                   error_message(ret)));
1290                                         goto out;
1291                                 }
1292
1293                                 TALLOC_FREE(ktprinc);
1294                                 continue;
1295                         }
1296
1297                         TALLOC_FREE(ktprinc);
1298                 }
1299
1300                 /*------------------------------------------------------------
1301                  * Save the entries with kvno - 1. This is what microsoft does
1302                  * to allow people with existing sessions that have kvno - 1
1303                  * to still work. Otherwise, when the password for the machine
1304                  * changes, all kerberizied sessions will 'break' until either
1305                  * the client reboots or the client's session key expires and
1306                  * they get a new session ticket with the new kvno.
1307                  * Some keytab files only store the kvno in 8bits, limit
1308                  * the compare accordingly.
1309                  */
1310
1311                 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1312                         DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1313                                   "entry for principal: %s.\n",
1314                                   old_kvno, princ_s));
1315                         continue;
1316                 }
1317
1318                 if (keep_old_entries) {
1319                         DEBUG(5, (__location__ ": Saving old (kvno %d) "
1320                                   "entry for principal: %s.\n",
1321                                   kvno, princ_s));
1322                         continue;
1323                 }
1324
1325                 if (!flush &&
1326                     (kt_entry.vno == kvno) &&
1327                     (kt_entry_enctype != enctype))
1328                 {
1329                         DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1330                                   "enctype [%d] for principal: %s.\n",
1331                                   kvno, kt_entry_enctype, princ_s));
1332                         continue;
1333                 }
1334
1335                 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1336                           "(kvno %d) - trying to remove it.\n",
1337                           princ_s, kt_entry.vno));
1338
1339                 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1340                 ZERO_STRUCT(cursor);
1341                 if (ret) {
1342                         DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1343                                   "failed (%s)\n", error_message(ret)));
1344                         goto out;
1345                 }
1346                 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1347                 if (ret) {
1348                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1349                                   "failed (%s)\n", error_message(ret)));
1350                         goto out;
1351                 }
1352
1353                 DEBUG(5, (__location__ ": removed old entry for principal: "
1354                           "%s (kvno %d).\n", princ_s, kt_entry.vno));
1355
1356                 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1357                 if (ret) {
1358                         DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1359                                   "(%s)\n", error_message(ret)));
1360                         goto out;
1361                 }
1362                 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1363                 ZERO_STRUCT(kt_entry);
1364                 if (ret) {
1365                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1366                                   "failed (%s)\n", error_message(ret)));
1367                         goto out;
1368                 }
1369         }
1370
1371 out:
1372         talloc_free(tmp_ctx);
1373         if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1374                 smb_krb5_kt_free_entry(context, &kt_entry);
1375         }
1376         if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1377                 krb5_kt_end_seq_get(context, keytab, &cursor);
1378         }
1379         return ret;
1380 }
1381
1382 /**
1383  * @brief Add a keytab entry for the given principal
1384  *
1385  * @param[in]  context       The krb5 context to use.
1386  *
1387  * @param[in]  keytab        The keytab to add the entry to.
1388  *
1389  * @param[in]  kvno          The kvno to use.
1390  *
1391  * @param[in]  princ_s       The principal as a string.
1392  *
1393  * @param[in]  salt_principal The salt principal to salt the password with.
1394  *                            Only needed for keys which support salting.
1395  *                            If no salt is used set no_salt to false and
1396  *                            pass NULL here.
1397  *
1398  * @param[in]  enctype        The encryption type of the keytab entry.
1399  *
1400  * @param[in]  password       The password of the keytab entry.
1401  *
1402  * @param[in]  no_salt        If the password should not be salted. Normally
1403  *                            this is only set to false for encryption types
1404  *                            which do not support salting like RC4.
1405  *
1406  * @param[in]  keep_old_entries Wether to keep or delte old keytab entries.
1407  *
1408  * @retval 0 on Success
1409  *
1410  * @return A corresponding KRB5 error code.
1411  *
1412  * @see smb_krb5_kt_open()
1413  */
1414 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1415                                       krb5_keytab keytab,
1416                                       krb5_kvno kvno,
1417                                       const char *princ_s,
1418                                       const char *salt_principal,
1419                                       krb5_enctype enctype,
1420                                       krb5_data *password,
1421                                       bool no_salt,
1422                                       bool keep_old_entries)
1423 {
1424         krb5_error_code ret;
1425         krb5_keytab_entry kt_entry;
1426         krb5_principal princ = NULL;
1427         krb5_keyblock *keyp;
1428
1429         ZERO_STRUCT(kt_entry);
1430
1431         ret = smb_krb5_parse_name(context, princ_s, &princ);
1432         if (ret) {
1433                 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1434                           "failed (%s)\n", princ_s, error_message(ret)));
1435                 goto out;
1436         }
1437
1438         /* Seek and delete old keytab entries */
1439         ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1440                                                       keytab,
1441                                                       kvno,
1442                                                       enctype,
1443                                                       princ_s,
1444                                                       princ,
1445                                                       false,
1446                                                       keep_old_entries);
1447         if (ret) {
1448                 goto out;
1449         }
1450
1451         /* If we get here, we have deleted all the old entries with kvno's
1452          * not equal to the current kvno-1. */
1453
1454         keyp = KRB5_KT_KEY(&kt_entry);
1455
1456         if (no_salt) {
1457                 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1458                 if (KRB5_KEY_DATA(keyp) == NULL) {
1459                         ret = ENOMEM;
1460                         goto out;
1461                 }
1462                 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1463                 KRB5_KEY_LENGTH(keyp) = password->length;
1464                 KRB5_KEY_TYPE(keyp) = enctype;
1465         } else {
1466                 krb5_principal salt_princ = NULL;
1467
1468                 /* Now add keytab entries for all encryption types */
1469                 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1470                 if (ret) {
1471                         DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1472                                     salt_principal, error_message(ret));
1473                         goto out;
1474                 }
1475
1476                 ret = smb_krb5_create_key_from_string(context,
1477                                                       salt_princ,
1478                                                       NULL,
1479                                                       password,
1480                                                       enctype,
1481                                                       keyp);
1482                 krb5_free_principal(context, salt_princ);
1483                 if (ret != 0) {
1484                         goto out;
1485                 }
1486         }
1487
1488         kt_entry.principal = princ;
1489         kt_entry.vno       = kvno;
1490
1491         DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1492                   "encryption type (%d) and version (%d)\n",
1493                   princ_s, enctype, kt_entry.vno));
1494         ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1495         krb5_free_keyblock_contents(context, keyp);
1496         ZERO_STRUCT(kt_entry);
1497         if (ret) {
1498                 DEBUG(1, (__location__ ": adding entry to keytab "
1499                           "failed (%s)\n", error_message(ret)));
1500                 goto out;
1501         }
1502
1503 out:
1504         if (princ) {
1505                 krb5_free_principal(context, princ);
1506         }
1507
1508         return ret;
1509 }
1510
1511 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1512     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1513     defined(HAVE_KRB5_GET_CREDS)
1514 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1515                                                              krb5_ccache ccache,
1516                                                              krb5_principal me,
1517                                                              krb5_principal server,
1518                                                              krb5_principal impersonate_princ,
1519                                                              krb5_creds **out_creds)
1520 {
1521         krb5_error_code ret;
1522         krb5_get_creds_opt opt;
1523
1524         ret = krb5_get_creds_opt_alloc(context, &opt);
1525         if (ret) {
1526                 goto done;
1527         }
1528         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1529
1530         if (impersonate_princ) {
1531                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1532                                                          impersonate_princ);
1533                 if (ret) {
1534                         goto done;
1535                 }
1536         }
1537
1538         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1539         if (ret) {
1540                 goto done;
1541         }
1542
1543  done:
1544         if (opt) {
1545                 krb5_get_creds_opt_free(context, opt);
1546         }
1547         return ret;
1548 }
1549 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1550
1551 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1552
1553 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1554 krb5_error_code KRB5_CALLCONV
1555 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1556                               krb5_ccache ccache, krb5_creds *in_creds,
1557                               krb5_data *subject_cert,
1558                               krb5_creds **out_creds);
1559 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1560
1561 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1562                                                          krb5_ccache ccache,
1563                                                          krb5_principal me,
1564                                                          krb5_principal server,
1565                                                          krb5_principal impersonate_princ,
1566                                                          krb5_creds **out_creds)
1567 {
1568         krb5_error_code ret;
1569         krb5_creds in_creds;
1570
1571         ZERO_STRUCT(in_creds);
1572
1573         if (impersonate_princ) {
1574
1575                 in_creds.server = me;
1576                 in_creds.client = impersonate_princ;
1577
1578                 ret = krb5_get_credentials_for_user(context,
1579                                                     0, /* krb5_flags options */
1580                                                     ccache,
1581                                                     &in_creds,
1582                                                     NULL, /* krb5_data *subject_cert */
1583                                                     out_creds);
1584         } else {
1585                 in_creds.client = me;
1586                 in_creds.server = server;
1587
1588                 ret = krb5_get_credentials(context, 0, ccache,
1589                                            &in_creds, out_creds);
1590         }
1591
1592         return ret;
1593 }
1594 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1595
1596 /*
1597  * smb_krb5_get_credentials
1598  *
1599  * @brief Get krb5 credentials for a server
1600  *
1601  * @param[in] context           An initialized krb5_context
1602  * @param[in] ccache            An initialized krb5_ccache
1603  * @param[in] me                The krb5_principal of the caller
1604  * @param[in] server            The krb5_principal of the requested service
1605  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1606  * @param[out] out_creds        The returned krb5_creds structure
1607  * @return krb5_error_code
1608  *
1609  */
1610 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1611                                          krb5_ccache ccache,
1612                                          krb5_principal me,
1613                                          krb5_principal server,
1614                                          krb5_principal impersonate_princ,
1615                                          krb5_creds **out_creds)
1616 {
1617         krb5_error_code ret;
1618         krb5_creds *creds = NULL;
1619
1620         if (out_creds != NULL) {
1621                 *out_creds = NULL;
1622         }
1623
1624         if (impersonate_princ) {
1625 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1626                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1627 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1628                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1629 #else
1630                 ret = ENOTSUP;
1631 #endif
1632         } else {
1633                 krb5_creds in_creds;
1634
1635                 ZERO_STRUCT(in_creds);
1636
1637                 in_creds.client = me;
1638                 in_creds.server = server;
1639
1640                 ret = krb5_get_credentials(context, 0, ccache,
1641                                            &in_creds, &creds);
1642         }
1643         if (ret) {
1644                 goto done;
1645         }
1646
1647         if (out_creds) {
1648                 *out_creds = creds;
1649         }
1650
1651  done:
1652         if (creds && ret) {
1653                 krb5_free_creds(context, creds);
1654         }
1655
1656         return ret;
1657 }
1658
1659 /**
1660  * @brief Initialize a krb5_keyblock with the given data.
1661  *
1662  * Initialized a new keyblock, allocates the contents fo the key and
1663  * copies the data into the keyblock.
1664  *
1665  * @param[in]  context  The library context
1666  *
1667  * @param[in]  enctype  The encryption type.
1668  *
1669  * @param[in]  data     The date to initialize the keyblock with.
1670  *
1671  * @param[in]  length   The length of the keyblock.
1672  *
1673  * @param[in]  key      Newly allocated keyblock structure.
1674  *
1675  * The key date must be freed using krb5_free_keyblock_contents() when it is
1676  * no longer needed.
1677  *
1678  * @return 0 on success, a Kerberos error code otherwise.
1679  */
1680 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1681                                                 krb5_enctype enctype,
1682                                                 const void *data,
1683                                                 size_t length,
1684                                                 krb5_keyblock *key)
1685 {
1686 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1687         return krb5_keyblock_init(context, enctype, data, length, key);
1688 #else
1689         memset(key, 0, sizeof(krb5_keyblock));
1690         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1691         if (NULL == KRB5_KEY_DATA(key)) {
1692                 return ENOMEM;
1693         }
1694         memcpy(KRB5_KEY_DATA(key), data, length);
1695         KRB5_KEY_LENGTH(key) = length;
1696         KRB5_KEY_TYPE(key) = enctype;
1697         return 0;
1698 #endif
1699 }
1700
1701 /**
1702  * @brief Simulate a kinit by putting the tgt in the given credential cache.
1703  *
1704  * This function uses a keyblock rather than needingthe original password.
1705  *
1706  * @param[in]  ctx      The library context
1707  *
1708  * @param[in]  cc       The credential cache to put the tgt in.
1709  *
1710  * @param[in]  principal The client princial
1711  *
1712  * @param[in]  keyblock  The keyblock to use.
1713  *
1714  * @param[in]  target_service The service name of the initial credentials (or NULL).
1715  *
1716  * @param[in]  krb_options Initial credential options.
1717  *
1718  * @param[in]  expire_time    A pointer to store the experation time of the
1719  *                            credentials (or NULL).
1720  *
1721  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
1722  *                            valid (or NULL).
1723  *
1724  * @return 0 on success, a Kerberos error code otherwise.
1725  */
1726 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
1727                                                krb5_ccache cc,
1728                                                krb5_principal principal,
1729                                                krb5_keyblock *keyblock,
1730                                                const char *target_service,
1731                                                krb5_get_init_creds_opt *krb_options,
1732                                                time_t *expire_time,
1733                                                time_t *kdc_time)
1734 {
1735         krb5_error_code code = 0;
1736         krb5_creds my_creds;
1737
1738 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1739         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1740                                             keyblock, 0, target_service,
1741                                             krb_options);
1742 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1743 {
1744 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1745         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1746         krb5_keytab_entry entry;
1747         krb5_keytab keytab;
1748         mode_t mask;
1749
1750         memset(&entry, 0, sizeof(entry));
1751         entry.principal = principal;
1752         *(KRB5_KT_KEY(&entry)) = *keyblock;
1753
1754         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1755         mask = umask(S_IRWXO | S_IRWXG);
1756         mktemp(tmp_name);
1757         umask(mask);
1758         if (tmp_name[0] == 0) {
1759                 return KRB5_KT_BADNAME;
1760         }
1761         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1762         if (code) {
1763                 return code;
1764         }
1765
1766         code = krb5_kt_add_entry(ctx, keytab, &entry);
1767         if (code) {
1768                 (void)krb5_kt_close(ctx, keytab);
1769                 goto done;
1770         }
1771
1772         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
1773                                           keytab, 0, target_service,
1774                                           krb_options);
1775         (void)krb5_kt_close(ctx, keytab);
1776 }
1777 #else
1778 #error krb5_get_init_creds_keyblock not available!
1779 #endif
1780         if (code) {
1781                 return code;
1782         }
1783
1784 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
1785         /*
1786          * We need to store the principal as returned from the KDC to the
1787          * credentials cache. If we don't do that the KRB5 library is not
1788          * able to find the tickets it is looking for
1789          */
1790         principal = my_creds.client;
1791 #endif
1792         code = krb5_cc_initialize(ctx, cc, principal);
1793         if (code) {
1794                 goto done;
1795         }
1796
1797         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1798         if (code) {
1799                 goto done;
1800         }
1801
1802         if (expire_time) {
1803                 *expire_time = (time_t) my_creds.times.endtime;
1804         }
1805
1806         if (kdc_time) {
1807                 *kdc_time = (time_t) my_creds.times.starttime;
1808         }
1809
1810         code = 0;
1811 done:
1812         krb5_free_cred_contents(ctx, &my_creds);
1813         return code;
1814 }
1815
1816 /**
1817  * @brief Simulate a kinit by putting the tgt in the given credential cache.
1818  *
1819  * @param[in]  ctx      The library context
1820  *
1821  * @param[in]  cc       The credential cache to put the tgt in.
1822  *
1823  * @param[in]  principal The client princial
1824  *
1825  * @param[in]  password  The password (or NULL).
1826  *
1827  * @param[in]  target_service The service name of the initial credentials (or NULL).
1828  *
1829  * @param[in]  krb_options Initial credential options.
1830  *
1831  * @param[in]  expire_time    A pointer to store the experation time of the
1832  *                            credentials (or NULL).
1833  *
1834  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
1835  *                            valid (or NULL).
1836  *
1837  * @return 0 on success, a Kerberos error code otherwise.
1838  */
1839 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
1840                                                krb5_ccache cc,
1841                                                krb5_principal principal,
1842                                                const char *password,
1843                                                const char *target_service,
1844                                                krb5_get_init_creds_opt *krb_options,
1845                                                time_t *expire_time,
1846                                                time_t *kdc_time)
1847 {
1848         krb5_error_code code = 0;
1849         krb5_creds my_creds;
1850
1851         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
1852                                             password, NULL, NULL, 0,
1853                                             target_service, krb_options);
1854         if (code) {
1855                 return code;
1856         }
1857
1858 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
1859         /*
1860          * We need to store the principal as returned from the KDC to the
1861          * credentials cache. If we don't do that the KRB5 library is not
1862          * able to find the tickets it is looking for
1863          */
1864         principal = my_creds.client;
1865 #endif
1866         code = krb5_cc_initialize(ctx, cc, principal);
1867         if (code) {
1868                 goto done;
1869         }
1870
1871         code = krb5_cc_store_cred(ctx, cc, &my_creds);
1872         if (code) {
1873                 goto done;
1874         }
1875
1876         if (expire_time) {
1877                 *expire_time = (time_t) my_creds.times.endtime;
1878         }
1879
1880         if (kdc_time) {
1881                 *kdc_time = (time_t) my_creds.times.starttime;
1882         }
1883
1884         code = 0;
1885 done:
1886         krb5_free_cred_contents(ctx, &my_creds);
1887         return code;
1888 }
1889
1890 #ifdef SAMBA4_USES_HEIMDAL
1891 /**
1892  * @brief Simulate a kinit by putting the tgt in the given credential cache.
1893  *
1894  * @param[in]  ctx      The library context
1895  *
1896  * @param[in]  cc       The credential cache to store the tgt in.
1897  *
1898  * @param[in]  principal The initial client princial.
1899  *
1900  * @param[in]  password  The password (or NULL).
1901  *
1902  * @param[in]  impersonate_principal The impersonatiion principal (or NULL).
1903  *
1904  * @param[in]  self_service The local service for S4U2Self if
1905  *                          impersonate_principal is specified).
1906  *
1907  * @param[in]  target_service The service name of the initial credentials
1908  *                            (kpasswd/REALM or a remote service). It defaults
1909  *                            to the krbtgt if NULL.
1910  *
1911  * @param[in]  krb_options Initial credential options.
1912  *
1913  * @param[in]  expire_time    A pointer to store the experation time of the
1914  *                            credentials (or NULL).
1915  *
1916  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
1917  *                            valid (or NULL).
1918  *
1919  * @return 0 on success, a Kerberos error code otherwise.
1920  */
1921 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
1922                                            krb5_ccache store_cc,
1923                                            krb5_principal init_principal,
1924                                            const char *init_password,
1925                                            krb5_principal impersonate_principal,
1926                                            const char *self_service,
1927                                            const char *target_service,
1928                                            krb5_get_init_creds_opt *krb_options,
1929                                            time_t *expire_time,
1930                                            time_t *kdc_time)
1931 {
1932         krb5_error_code code = 0;
1933         krb5_get_creds_opt options;
1934         krb5_principal store_principal;
1935         krb5_creds store_creds;
1936         krb5_creds *s4u2self_creds;
1937         Ticket s4u2self_ticket;
1938         size_t s4u2self_ticketlen;
1939         krb5_creds *s4u2proxy_creds;
1940         krb5_principal self_princ;
1941         bool s4u2proxy;
1942         krb5_principal target_princ;
1943         krb5_ccache tmp_cc;
1944         const char *self_realm;
1945         const char *client_realm = NULL;
1946         krb5_principal blacklist_principal = NULL;
1947         krb5_principal whitelist_principal = NULL;
1948
1949         code = krb5_get_init_creds_password(ctx, &store_creds,
1950                                             init_principal,
1951                                             init_password,
1952                                             NULL, NULL,
1953                                             0,
1954                                             NULL,
1955                                             krb_options);
1956         if (code != 0) {
1957                 return code;
1958         }
1959
1960         store_principal = init_principal;
1961
1962         /*
1963          * We are trying S4U2Self now:
1964          *
1965          * As we do not want to expose our TGT in the
1966          * krb5_ccache, which is also holds the impersonated creds.
1967          *
1968          * Some low level krb5/gssapi function might use the TGT
1969          * identity and let the client act as our machine account.
1970          *
1971          * We need to avoid that and use a temporary krb5_ccache
1972          * in order to pass our TGT to the krb5_get_creds() function.
1973          */
1974         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
1975         if (code != 0) {
1976                 krb5_free_cred_contents(ctx, &store_creds);
1977                 return code;
1978         }
1979
1980         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
1981         if (code != 0) {
1982                 krb5_cc_destroy(ctx, tmp_cc);
1983                 krb5_free_cred_contents(ctx, &store_creds);
1984                 return code;
1985         }
1986
1987         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
1988         if (code != 0) {
1989                 krb5_free_cred_contents(ctx, &store_creds);
1990                 krb5_cc_destroy(ctx, tmp_cc);
1991                 return code;
1992         }
1993
1994         /*
1995          * we need to remember the client principal of our
1996          * TGT and make sure the KDC does not return this
1997          * in the impersonated tickets. This can happen
1998          * if the KDC does not support S4U2Self and S4U2Proxy.
1999          */
2000         blacklist_principal = store_creds.client;
2001         store_creds.client = NULL;
2002         krb5_free_cred_contents(ctx, &store_creds);
2003
2004         /*
2005          * Check if we also need S4U2Proxy or if S4U2Self is
2006          * enough in order to get a ticket for the target.
2007          */
2008         if (target_service == NULL) {
2009                 s4u2proxy = false;
2010         } else if (strcmp(target_service, self_service) == 0) {
2011                 s4u2proxy = false;
2012         } else {
2013                 s4u2proxy = true;
2014         }
2015
2016         /*
2017          * For S4U2Self we need our own service principal,
2018          * which belongs to our own realm (available on
2019          * our client principal).
2020          */
2021         self_realm = krb5_principal_get_realm(ctx, init_principal);
2022
2023         code = krb5_parse_name(ctx, self_service, &self_princ);
2024         if (code != 0) {
2025                 krb5_free_principal(ctx, blacklist_principal);
2026                 krb5_cc_destroy(ctx, tmp_cc);
2027                 return code;
2028         }
2029
2030         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2031         if (code != 0) {
2032                 krb5_free_principal(ctx, blacklist_principal);
2033                 krb5_free_principal(ctx, self_princ);
2034                 krb5_cc_destroy(ctx, tmp_cc);
2035                 return code;
2036         }
2037
2038         code = krb5_get_creds_opt_alloc(ctx, &options);
2039         if (code != 0) {
2040                 krb5_free_principal(ctx, blacklist_principal);
2041                 krb5_free_principal(ctx, self_princ);
2042                 krb5_cc_destroy(ctx, tmp_cc);
2043                 return code;
2044         }
2045
2046         if (s4u2proxy) {
2047                 /*
2048                  * If we want S4U2Proxy, we need the forwardable flag
2049                  * on the S4U2Self ticket.
2050                  */
2051                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2052         }
2053
2054         code = krb5_get_creds_opt_set_impersonate(ctx, options,
2055                                                   impersonate_principal);
2056         if (code != 0) {
2057                 krb5_get_creds_opt_free(ctx, options);
2058                 krb5_free_principal(ctx, blacklist_principal);
2059                 krb5_free_principal(ctx, self_princ);
2060                 krb5_cc_destroy(ctx, tmp_cc);
2061                 return code;
2062         }
2063
2064         code = krb5_get_creds(ctx, options, tmp_cc,
2065                               self_princ, &s4u2self_creds);
2066         krb5_get_creds_opt_free(ctx, options);
2067         krb5_free_principal(ctx, self_princ);
2068         if (code != 0) {
2069                 krb5_free_principal(ctx, blacklist_principal);
2070                 krb5_cc_destroy(ctx, tmp_cc);
2071                 return code;
2072         }
2073
2074         if (!s4u2proxy) {
2075                 krb5_cc_destroy(ctx, tmp_cc);
2076
2077                 /*
2078                  * Now make sure we store the impersonated principal
2079                  * and creds instead of the TGT related stuff
2080                  * in the krb5_ccache of the caller.
2081                  */
2082                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2083                                                 &store_creds);
2084                 krb5_free_creds(ctx, s4u2self_creds);
2085                 if (code != 0) {
2086                         return code;
2087                 }
2088
2089                 /*
2090                  * It's important to store the principal the KDC
2091                  * returned, as otherwise the caller would not find
2092                  * the S4U2Self ticket in the krb5_ccache lookup.
2093                  */
2094                 store_principal = store_creds.client;
2095                 goto store;
2096         }
2097
2098         /*
2099          * We are trying S4U2Proxy:
2100          *
2101          * We need the ticket from the S4U2Self step
2102          * and our TGT in order to get the delegated ticket.
2103          */
2104         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2105                              s4u2self_creds->ticket.length,
2106                              &s4u2self_ticket,
2107                              &s4u2self_ticketlen);
2108         if (code != 0) {
2109                 krb5_free_creds(ctx, s4u2self_creds);
2110                 krb5_free_principal(ctx, blacklist_principal);
2111                 krb5_cc_destroy(ctx, tmp_cc);
2112                 return code;
2113         }
2114
2115         /*
2116          * we need to remember the client principal of the
2117          * S4U2Self stage and as it needs to match the one we
2118          * will get for the S4U2Proxy stage. We need this
2119          * in order to detect KDCs which does not support S4U2Proxy.
2120          */
2121         whitelist_principal = s4u2self_creds->client;
2122         s4u2self_creds->client = NULL;
2123         krb5_free_creds(ctx, s4u2self_creds);
2124
2125         /*
2126          * For S4U2Proxy we also got a target service principal,
2127          * which also belongs to our own realm (available on
2128          * our client principal).
2129          */
2130         code = krb5_parse_name(ctx, target_service, &target_princ);
2131         if (code != 0) {
2132                 free_Ticket(&s4u2self_ticket);
2133                 krb5_free_principal(ctx, whitelist_principal);
2134                 krb5_free_principal(ctx, blacklist_principal);
2135                 krb5_cc_destroy(ctx, tmp_cc);
2136                 return code;
2137         }
2138
2139         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2140         if (code != 0) {
2141                 free_Ticket(&s4u2self_ticket);
2142                 krb5_free_principal(ctx, target_princ);
2143                 krb5_free_principal(ctx, whitelist_principal);
2144                 krb5_free_principal(ctx, blacklist_principal);
2145                 krb5_cc_destroy(ctx, tmp_cc);
2146                 return code;
2147         }
2148
2149         code = krb5_get_creds_opt_alloc(ctx, &options);
2150         if (code != 0) {
2151                 free_Ticket(&s4u2self_ticket);
2152                 krb5_free_principal(ctx, target_princ);
2153                 krb5_free_principal(ctx, whitelist_principal);
2154                 krb5_free_principal(ctx, blacklist_principal);
2155                 krb5_cc_destroy(ctx, tmp_cc);
2156                 return code;
2157         }
2158
2159         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2160         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2161
2162         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2163         free_Ticket(&s4u2self_ticket);
2164         if (code != 0) {
2165                 krb5_get_creds_opt_free(ctx, options);
2166                 krb5_free_principal(ctx, target_princ);
2167                 krb5_free_principal(ctx, whitelist_principal);
2168                 krb5_free_principal(ctx, blacklist_principal);
2169                 krb5_cc_destroy(ctx, tmp_cc);
2170                 return code;
2171         }
2172
2173         code = krb5_get_creds(ctx, options, tmp_cc,
2174                               target_princ, &s4u2proxy_creds);
2175         krb5_get_creds_opt_free(ctx, options);
2176         krb5_free_principal(ctx, target_princ);
2177         krb5_cc_destroy(ctx, tmp_cc);
2178         if (code != 0) {
2179                 krb5_free_principal(ctx, whitelist_principal);
2180                 krb5_free_principal(ctx, blacklist_principal);
2181                 return code;
2182         }
2183
2184         /*
2185          * Now make sure we store the impersonated principal
2186          * and creds instead of the TGT related stuff
2187          * in the krb5_ccache of the caller.
2188          */
2189         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2190                                         &store_creds);
2191         krb5_free_creds(ctx, s4u2proxy_creds);
2192         if (code != 0) {
2193                 krb5_free_principal(ctx, whitelist_principal);
2194                 krb5_free_principal(ctx, blacklist_principal);
2195                 return code;
2196         }
2197
2198         /*
2199          * It's important to store the principal the KDC
2200          * returned, as otherwise the caller would not find
2201          * the S4U2Self ticket in the krb5_ccache lookup.
2202          */
2203         store_principal = store_creds.client;
2204
2205  store:
2206         if (blacklist_principal &&
2207             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2208                 char *sp = NULL;
2209                 char *ip = NULL;
2210
2211                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2212                 if (code != 0) {
2213                         sp = NULL;
2214                 }
2215                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2216                 if (code != 0) {
2217                         ip = NULL;
2218                 }
2219                 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2220                           "KDC returned self principal[%s] while impersonating [%s]\n",
2221                           sp?sp:"<no memory>",
2222                           ip?ip:"<no memory>"));
2223
2224                 SAFE_FREE(sp);
2225                 SAFE_FREE(ip);
2226
2227                 krb5_free_principal(ctx, whitelist_principal);
2228                 krb5_free_principal(ctx, blacklist_principal);
2229                 krb5_free_cred_contents(ctx, &store_creds);
2230                 return KRB5_FWD_BAD_PRINCIPAL;
2231         }
2232         if (blacklist_principal) {
2233                 krb5_free_principal(ctx, blacklist_principal);
2234         }
2235
2236         if (whitelist_principal &&
2237             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2238                 char *sp = NULL;
2239                 char *ep = NULL;
2240
2241                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2242                 if (code != 0) {
2243                         sp = NULL;
2244                 }
2245                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2246                 if (code != 0) {
2247                         ep = NULL;
2248                 }
2249                 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2250                           "KDC returned wrong principal[%s] we expected [%s]\n",
2251                           sp?sp:"<no memory>",
2252                           ep?ep:"<no memory>"));
2253
2254                 SAFE_FREE(sp);
2255                 SAFE_FREE(ep);
2256
2257                 krb5_free_principal(ctx, whitelist_principal);
2258                 krb5_free_cred_contents(ctx, &store_creds);
2259                 return KRB5_FWD_BAD_PRINCIPAL;
2260         }
2261         if (whitelist_principal) {
2262                 krb5_free_principal(ctx, whitelist_principal);
2263         }
2264
2265         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2266         if (code != 0) {
2267                 krb5_free_cred_contents(ctx, &store_creds);
2268                 return code;
2269         }
2270
2271         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2272         if (code != 0) {
2273                 krb5_free_cred_contents(ctx, &store_creds);
2274                 return code;
2275         }
2276
2277         client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2278         if (client_realm != NULL) {
2279                 /*
2280                  * Because the CANON flag doesn't have any impact
2281                  * on the impersonate_principal => store_creds.client
2282                  * realm mapping. We need to store the credentials twice,
2283                  * once with the returned realm and once with the
2284                  * realm of impersonate_principal.
2285                  */
2286                 code = krb5_principal_set_realm(ctx, store_creds.server,
2287                                                 client_realm);
2288                 if (code != 0) {
2289                         krb5_free_cred_contents(ctx, &store_creds);
2290                         return code;
2291                 }
2292
2293                 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2294                 if (code != 0) {
2295                         krb5_free_cred_contents(ctx, &store_creds);
2296                         return code;
2297                 }
2298         }
2299
2300         if (expire_time) {
2301                 *expire_time = (time_t) store_creds.times.endtime;
2302         }
2303
2304         if (kdc_time) {
2305                 *kdc_time = (time_t) store_creds.times.starttime;
2306         }
2307
2308         krb5_free_cred_contents(ctx, &store_creds);
2309
2310         return 0;
2311 }
2312 #endif
2313
2314 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2315 /**
2316  * @brief Create a principal name using a variable argument list.
2317  *
2318  * @param[in]  context  The library context.
2319  *
2320  * @param[inout]  principal A pointer to the principal structure.
2321  *
2322  * @param[in]  _realm    The realm to use. If NULL then the function will
2323  *                       get the default realm name.
2324  *
2325  * @param[in]  ...       A list of 'char *' components, ending with NULL.
2326  *
2327  * Use krb5_free_principal() to free the principal when it is no longer needed.
2328  *
2329  * @return 0 on success, a Kerberos error code otherwise.
2330  */
2331 krb5_error_code smb_krb5_make_principal(krb5_context context,
2332                                         krb5_principal *principal,
2333                                         const char *_realm, ...)
2334 {
2335         krb5_error_code code;
2336         bool free_realm;
2337         char *realm;
2338         va_list ap;
2339
2340         if (_realm) {
2341                 realm = discard_const_p(char, _realm);
2342                 free_realm = false;
2343         } else {
2344                 code = krb5_get_default_realm(context, &realm);
2345                 if (code) {
2346                         return code;
2347                 }
2348                 free_realm = true;
2349         }
2350
2351         va_start(ap, _realm);
2352         code = krb5_build_principal_alloc_va(context, principal,
2353                                              strlen(realm), realm,
2354                                              ap);
2355         va_end(ap);
2356
2357         if (free_realm) {
2358                 krb5_free_default_realm(context, realm);
2359         }
2360
2361         return code;
2362 }
2363 #endif
2364
2365 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2366 /**
2367  * @brief Get the lifetime of the initial ticket in the cache.
2368  *
2369  * @param[in]  context  The kerberos context.
2370  *
2371  * @param[in]  id       The credential cache to get the ticket lifetime.
2372  *
2373  * @param[out] t        A pointer to a time value to store the lifetime.
2374  *
2375  * @return              0 on success, a krb5_error_code on error.
2376  */
2377 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2378                                          krb5_ccache id,
2379                                          time_t *t)
2380 {
2381         krb5_cc_cursor cursor;
2382         krb5_error_code kerr;
2383         krb5_creds cred;
2384         krb5_timestamp now;
2385
2386         *t = 0;
2387
2388         kerr = krb5_timeofday(context, &now);
2389         if (kerr) {
2390                 return kerr;
2391         }
2392
2393         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2394         if (kerr) {
2395                 return kerr;
2396         }
2397
2398         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2399 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2400                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2401 #else
2402                 if (cred.flags.b.initial) {
2403 #endif
2404                         if (now < cred.times.endtime) {
2405                                 *t = (time_t) (cred.times.endtime - now);
2406                         }
2407                         krb5_free_cred_contents(context, &cred);
2408                         break;
2409                 }
2410                 krb5_free_cred_contents(context, &cred);
2411         }
2412
2413         krb5_cc_end_seq_get(context, id, &cursor);
2414
2415         return kerr;
2416 }
2417 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2418
2419 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2420 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2421 {
2422         free_Checksum(cksum);
2423 }
2424 #endif
2425
2426 /**
2427  * @brief Compute a checksum operating on a keyblock.
2428  *
2429  * This function computes a checksum over a PAC using the keyblock for a keyed
2430  * checksum.
2431  *
2432  * @param[in]  mem_ctx A talloc context to alocate the signature on.
2433  *
2434  * @param[in]  pac_data The PAC as input.
2435  *
2436  * @param[in]  context  The library context.
2437  *
2438  * @param[in]  keyblock Encryption key for a keyed checksum.
2439  *
2440  * @param[out] sig_type The checksum type
2441  *
2442  * @param[out] sig_blob The talloc'ed checksum
2443  *
2444  * The caller must free the sig_blob with talloc_free() when it is not needed
2445  * anymore.
2446  *
2447  * @return 0 on success, a Kerberos error code otherwise.
2448  */
2449 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2450                                            DATA_BLOB *pac_data,
2451                                            krb5_context context,
2452                                            const krb5_keyblock *keyblock,
2453                                            uint32_t *sig_type,
2454                                            DATA_BLOB *sig_blob)
2455 {
2456         krb5_error_code ret;
2457         krb5_checksum cksum;
2458 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2459         krb5_crypto crypto;
2460
2461
2462         ret = krb5_crypto_init(context,
2463                                keyblock,
2464                                0,
2465                                &crypto);
2466         if (ret) {
2467                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2468                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2469                 return ret;
2470         }
2471         ret = krb5_create_checksum(context,
2472                                    crypto,
2473                                    KRB5_KU_OTHER_CKSUM,
2474                                    0,
2475                                    pac_data->data,
2476                                    pac_data->length,
2477                                    &cksum);
2478         if (ret) {
2479                 DEBUG(2, ("PAC Verification failed: %s\n",
2480                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2481         }
2482
2483         krb5_crypto_destroy(context, crypto);
2484
2485         if (ret) {
2486                 return ret;
2487         }
2488
2489         *sig_type = cksum.cksumtype;
2490         *sig_blob = data_blob_talloc(mem_ctx,
2491                                         cksum.checksum.data,
2492                                         cksum.checksum.length);
2493 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2494         krb5_data input;
2495
2496         input.data = (char *)pac_data->data;
2497         input.length = pac_data->length;
2498
2499         ret = krb5_c_make_checksum(context,
2500                                    0,
2501                                    keyblock,
2502                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2503                                    &input,
2504                                    &cksum);
2505         if (ret) {
2506                 DEBUG(2, ("PAC Verification failed: %s\n",
2507                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2508                 return ret;
2509         }
2510
2511         *sig_type = cksum.checksum_type;
2512         *sig_blob = data_blob_talloc(mem_ctx,
2513                                         cksum.contents,
2514                                         cksum.length);
2515
2516 #else
2517 #error krb5_create_checksum or krb5_c_make_checksum not available
2518 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2519         smb_krb5_free_checksum_contents(context, &cksum);
2520
2521         return 0;
2522 }
2523
2524
2525 /**
2526  * @brief Get realm of a principal
2527  *
2528  * @param[in] context   The library context
2529  *
2530  * @param[in] principal The principal to get the realm from.
2531  *
2532  * @return An allocated string with the realm or NULL if an error occured.
2533  *
2534  * The caller must free the realm string with free() if not needed anymore.
2535  */
2536 char *smb_krb5_principal_get_realm(krb5_context context,
2537                                    krb5_const_principal principal)
2538 {
2539 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2540         return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2541 #elif defined(krb5_princ_realm) /* MIT */
2542         krb5_data *realm;
2543         realm = discard_const_p(krb5_data,
2544                                 krb5_princ_realm(context, principal));
2545         return strndup(realm->data, realm->length);
2546 #else
2547 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2548 #endif
2549 }
2550
2551 /**
2552  * @brief Get realm of a principal
2553  *
2554  * @param[in] context   The library context
2555  *
2556  * @param[in] principal The principal to set the realm
2557  *
2558  * @param[in] realm     The realm as a string to set.
2559  *
2560  * @retur 0 on success, a Kerberos error code otherwise.
2561  */
2562 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2563                                              krb5_principal principal,
2564                                              const char *realm)
2565 {
2566 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2567         return krb5_principal_set_realm(context, principal, realm);
2568 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2569         krb5_error_code ret;
2570         krb5_data data;
2571         krb5_data *old_data;
2572
2573         old_data = krb5_princ_realm(context, principal);
2574
2575         ret = smb_krb5_copy_data_contents(&data,
2576                                           realm,
2577                                           strlen(realm));
2578         if (ret) {
2579                 return ret;
2580         }
2581
2582         /* free realm before setting */
2583         free(old_data->data);
2584
2585         krb5_princ_set_realm(context, principal, &data);
2586
2587         return ret;
2588 #else
2589 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2590 #endif
2591 }
2592
2593
2594 /************************************************************************
2595  Routine to get the default realm from the kerberos credentials cache.
2596  Caller must free if the return value is not NULL.
2597 ************************************************************************/
2598
2599 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2600 {
2601         char *realm = NULL;
2602         krb5_context ctx = NULL;
2603         krb5_ccache cc = NULL;
2604         krb5_principal princ = NULL;
2605
2606         initialize_krb5_error_table();
2607         if (krb5_init_context(&ctx)) {
2608                 return NULL;
2609         }
2610
2611         DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2612                 "Trying to read krb5 cache: %s\n",
2613                 krb5_cc_default_name(ctx)));
2614         if (krb5_cc_default(ctx, &cc)) {
2615                 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2616                         "failed to read default cache\n"));
2617                 goto out;
2618         }
2619         if (krb5_cc_get_principal(ctx, cc, &princ)) {
2620                 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2621                         "failed to get default principal\n"));
2622                 goto out;
2623         }
2624
2625 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2626         realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2627 #elif defined(HAVE_KRB5_PRINC_REALM)
2628         {
2629                 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2630                 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2631         }
2632 #endif
2633
2634   out:
2635
2636         if (ctx) {
2637                 if (princ) {
2638                         krb5_free_principal(ctx, princ);
2639                 }
2640                 if (cc) {
2641                         krb5_cc_close(ctx, cc);
2642                 }
2643                 krb5_free_context(ctx);
2644         }
2645
2646         return realm;
2647 }
2648
2649 /************************************************************************
2650  Routine to get the realm from a given DNS name.
2651 ************************************************************************/
2652
2653 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2654                                                 const char *hostname)
2655 {
2656 #if defined(HAVE_KRB5_REALM_TYPE)
2657         /* Heimdal. */
2658         krb5_realm *realm_list = NULL;
2659 #else
2660         /* MIT */
2661         char **realm_list = NULL;
2662 #endif
2663         char *realm = NULL;
2664         krb5_error_code kerr;
2665         krb5_context ctx = NULL;
2666
2667         initialize_krb5_error_table();
2668         if (krb5_init_context(&ctx)) {
2669                 return NULL;
2670         }
2671
2672         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2673         if (kerr != 0) {
2674                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2675                         "failed %s\n",
2676                         hostname ? hostname : "(NULL)",
2677                         error_message(kerr) ));
2678                 goto out;
2679         }
2680
2681         if (realm_list && realm_list[0]) {
2682                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2683         }
2684
2685   out:
2686
2687         if (ctx) {
2688                 if (realm_list) {
2689                         krb5_free_host_realm(ctx, realm_list);
2690                         realm_list = NULL;
2691                 }
2692                 krb5_free_context(ctx);
2693                 ctx = NULL;
2694         }
2695         return realm;
2696 }
2697
2698 /**
2699  * @brief Get the principal as a string from the service hostname.
2700  *
2701  * @param[in]  mem_ctx  The talloc context
2702  *
2703  * @param[in]  service  The service name
2704  *
2705  * @param[in]  remote_name The remote name
2706  *
2707  * @param[in]  default_realm The default_realm if we cannot get it from the
2708  *                           hostname or netbios name.
2709  *
2710  * @return A talloc'ed principal string or NULL if an error occured.
2711  *
2712  * The caller needs to free the principal with talloc_free() if it isn't needed
2713  * anymore.
2714  */
2715 char *smb_krb5_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2716                                                    const char *service,
2717                                                    const char *remote_name,
2718                                                    const char *default_realm)
2719 {
2720         char *realm = NULL;
2721         char *host = NULL;
2722         char *principal;
2723         host = strchr_m(remote_name, '.');
2724         if (host) {
2725                 /* DNS name. */
2726                 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2727                                                          remote_name);
2728         } else {
2729                 /* NetBIOS name - use our realm. */
2730                 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2731         }
2732
2733         if (realm == NULL || *realm == '\0') {
2734                 realm = talloc_strdup(talloc_tos(), default_realm);
2735                 if (!realm) {
2736                         return NULL;
2737                 }
2738                 DEBUG(3,("Cannot get realm from, "
2739                          "desthost %s or default ccache. Using default "
2740                          "smb.conf realm %s\n",
2741                          remote_name,
2742                          realm));
2743         }
2744
2745         principal = talloc_asprintf(mem_ctx,
2746                                     "%s/%s@%s",
2747                                     service, remote_name,
2748                                     realm);
2749         TALLOC_FREE(realm);
2750         return principal;
2751 }
2752
2753 /**
2754  * @brief Get an error string from a Kerberos error code.
2755  *
2756  * @param[in]  context  The library context.
2757  *
2758  * @param[in]  code     The Kerberos error code.
2759  *
2760  * @param[in]  mem_ctx  The talloc context to allocate the error string on.
2761  *
2762  * @return A talloc'ed error string or NULL if an error occured.
2763  *
2764  * The caller must free the returned error string with talloc_free() if not
2765  * needed anymore
2766  */
2767 char *smb_get_krb5_error_message(krb5_context context,
2768                                  krb5_error_code code,
2769                                  TALLOC_CTX *mem_ctx)
2770 {
2771         char *ret;
2772
2773 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2774         const char *context_error = krb5_get_error_message(context, code);
2775         if (context_error) {
2776                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2777                                         error_message(code), context_error);
2778                 krb5_free_error_message(context, context_error);
2779                 return ret;
2780         }
2781 #endif
2782         ret = talloc_strdup(mem_ctx, error_message(code));
2783         return ret;
2784 }
2785
2786
2787 /**
2788  * @brief Return the kerberos library setting for: libdefaults:allow_weak_crypto
2789  *
2790  * @param[in]  context  The library context
2791  *
2792  * @return True if weak crypto is allowed, false if not.
2793  */
2794 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2795 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2796 {
2797         return krb5_config_get_bool_default(context,
2798                                             NULL,
2799                                             FALSE,
2800                                             "libdefaults",
2801                                             "allow_weak_crypto",
2802                                             NULL);
2803 }
2804 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2805 {
2806 #include <profile.h>
2807         krb5_error_code ret;
2808         krb5_boolean ret_default = false;
2809         profile_t profile;
2810         int ret_profile;
2811
2812         ret = krb5_get_profile(context,
2813                                &profile);
2814         if (ret) {
2815                 return ret_default;
2816         }
2817
2818         ret = profile_get_boolean(profile,
2819                                   "libdefaults",
2820                                   "allow_weak_crypto",
2821                                   NULL, /* subsubname */
2822                                   ret_default, /* def_val */
2823                                   &ret_profile /* *ret_default */);
2824         if (ret) {
2825                 return ret_default;
2826         }
2827
2828         profile_release(profile);
2829
2830         return ret_profile;
2831 }
2832 #else
2833 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2834 #endif
2835
2836 /**
2837  * @brief Return the type of a krb5_principal
2838  *
2839  * @param[in]  context  The library context.
2840  *
2841  * @param[in]  principal The principal to get the type from.
2842  *
2843  * @return The integer type of the principal.
2844  */
2845 int smb_krb5_principal_get_type(krb5_context context,
2846                                 krb5_const_principal principal)
2847 {
2848 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
2849         return krb5_principal_get_type(context, principal);
2850 #elif defined(krb5_princ_type) /* MIT */
2851         return krb5_princ_type(context, principal);
2852 #else
2853 #error  UNKNOWN_PRINC_GET_TYPE_FUNCTION
2854 #endif
2855 }
2856
2857 /**
2858  * @brief Set the type of a principal
2859  *
2860  * @param[in]  context  The library context
2861  *
2862  * @param[inout] principal The principal to set the type for.
2863  *
2864  * @param[in]  type     The principal type to set.
2865  */
2866 void smb_krb5_principal_set_type(krb5_context context,
2867                                  krb5_principal principal,
2868                                  int type)
2869 {
2870 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
2871         krb5_principal_set_type(context, principal, type);
2872 #elif defined(krb5_princ_type) /* MIT */
2873         krb5_princ_type(context, principal) = type;
2874 #else
2875 #error  UNKNOWN_PRINC_SET_TYPE_FUNCTION
2876 #endif
2877 }
2878
2879 #if !defined(HAVE_KRB5_WARNX)
2880 /**
2881  * @brief Log a Kerberos message
2882  *
2883  * It sends the message to com_err.
2884  *
2885  * @param[in]  context  The library context
2886  *
2887  * @param[in]  fmt      The message format
2888  *
2889  * @param[in]  ...      The message arguments
2890  *
2891  * @return 0 on success.
2892  */
2893 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
2894 {
2895         va_list args;
2896
2897         va_start(args, fmt);
2898         com_err_va("samba-kdc", errno, fmt, args);
2899         va_end(args);
2900
2901         return 0;
2902 }
2903 #endif
2904
2905 /**
2906  * @brief Copy a credential cache.
2907  *
2908  * @param[in]  context  The library context.
2909  *
2910  * @param[in]  incc     Credential cache to be copied.
2911  *
2912  * @param[inout] outcc  Copy of credential cache to be filled in.
2913  *
2914  * @return 0 on success, a Kerberos error code otherwise.
2915  */
2916 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
2917                                        krb5_ccache incc, krb5_ccache outcc)
2918 {
2919 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
2920         return krb5_cc_copy_cache(context, incc, outcc);
2921 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
2922         krb5_error_code ret;
2923         krb5_principal princ = NULL;
2924
2925         ret = krb5_cc_get_principal(context, incc, &princ);
2926         if (ret != 0) {
2927                 return ret;
2928         }
2929         ret = krb5_cc_initialize(context, outcc, princ);
2930         krb5_free_principal(context, princ);
2931         if (ret != 0) {
2932                 return ret;
2933         }
2934         return krb5_cc_copy_creds(context, incc, outcc);
2935 #else
2936 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
2937 #endif
2938 }
2939
2940 /**********************************************************
2941  * ADS KRB5 CALLS
2942  **********************************************************/
2943
2944 static bool ads_cleanup_expired_creds(krb5_context context,
2945                                       krb5_ccache  ccache,
2946                                       krb5_creds  *credsp)
2947 {
2948         krb5_error_code retval;
2949         const char *cc_type = krb5_cc_get_type(context, ccache);
2950
2951         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
2952                   cc_type, krb5_cc_get_name(context, ccache),
2953                   http_timestring(talloc_tos(), credsp->times.endtime)));
2954
2955         /* we will probably need new tickets if the current ones
2956            will expire within 10 seconds.
2957         */
2958         if (credsp->times.endtime >= (time(NULL) + 10))
2959                 return false;
2960
2961         /* heimdal won't remove creds from a file ccache, and
2962            perhaps we shouldn't anyway, since internally we
2963            use memory ccaches, and a FILE one probably means that
2964            we're using creds obtained outside of our exectuable
2965         */
2966         if (strequal(cc_type, "FILE")) {
2967                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
2968                 return false;
2969         }
2970
2971         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
2972         if (retval) {
2973                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
2974                           error_message(retval)));
2975                 /* If we have an error in this, we want to display it,
2976                    but continue as though we deleted it */
2977         }
2978         return true;
2979 }
2980
2981 /* Allocate and setup the auth context into the state we need. */
2982
2983 static krb5_error_code ads_setup_auth_context(krb5_context context,
2984                                               krb5_auth_context *auth_context)
2985 {
2986         krb5_error_code retval;
2987
2988         retval = krb5_auth_con_init(context, auth_context );
2989         if (retval) {
2990                 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
2991                         error_message(retval)));
2992                 return retval;
2993         }
2994
2995         /* Ensure this is an addressless ticket. */
2996         retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
2997         if (retval) {
2998                 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
2999                         error_message(retval)));
3000         }
3001
3002         return retval;
3003 }
3004
3005 #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)
3006 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3007                                                uint32_t gss_flags)
3008 {
3009         unsigned int orig_length = in_data->length;
3010         unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3011         char *gss_cksum = NULL;
3012
3013         if (orig_length) {
3014                 /* Extra length field for delgated ticket. */
3015                 base_cksum_size += 4;
3016         }
3017
3018         if ((unsigned int)base_cksum_size + orig_length <
3019                         (unsigned int)base_cksum_size) {
3020                 return EINVAL;
3021         }
3022
3023         gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3024         if (gss_cksum == NULL) {
3025                 return ENOMEM;
3026         }
3027
3028         memset(gss_cksum, '\0', base_cksum_size + orig_length);
3029         SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3030
3031         /*
3032          * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3033          * This matches the behavior of heimdal and mit.
3034          *
3035          * And it is needed to work against some closed source
3036          * SMB servers.
3037          *
3038          * See bug #7883
3039          */
3040         memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3041
3042         SIVAL(gss_cksum, 20, gss_flags);
3043
3044         if (orig_length) {
3045                 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3046                 SSVAL(gss_cksum, 26, orig_length);
3047                 /* Copy the kerberos KRB_CRED data */
3048                 memcpy(gss_cksum + 28, in_data->data, orig_length);
3049                 free(in_data->data);
3050                 in_data->data = NULL;
3051                 in_data->length = 0;
3052         }
3053         in_data->data = gss_cksum;
3054         in_data->length = base_cksum_size + orig_length;
3055         return 0;
3056 }
3057 #endif
3058
3059 /*
3060  * We can't use krb5_mk_req because w2k wants the service to be in a particular
3061  * format.
3062  */
3063 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3064                                        krb5_auth_context *auth_context,
3065                                        const krb5_flags ap_req_options,
3066                                        const char *principal,
3067                                        krb5_ccache ccache,
3068                                        krb5_data *outbuf,
3069                                        time_t *expire_time,
3070                                        const char *impersonate_princ_s)
3071 {
3072         krb5_error_code retval;
3073         krb5_principal server;
3074         krb5_principal impersonate_princ = NULL;
3075         krb5_creds *credsp;
3076         krb5_creds creds;
3077         krb5_data in_data;
3078         bool creds_ready = false;
3079         int i = 0, maxtries = 3;
3080         bool ok;
3081
3082         ZERO_STRUCT(in_data);
3083
3084         retval = smb_krb5_parse_name(context, principal, &server);
3085         if (retval != 0) {
3086                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3087                 return retval;
3088         }
3089
3090         if (impersonate_princ_s) {
3091                 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3092                                              &impersonate_princ);
3093                 if (retval) {
3094                         DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3095                         goto cleanup_princ;
3096                 }
3097         }
3098
3099         /* obtain ticket & session key */
3100         ZERO_STRUCT(creds);
3101         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3102                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3103                          error_message(retval)));
3104                 goto cleanup_princ;
3105         }
3106
3107         retval = krb5_cc_get_principal(context, ccache, &creds.client);
3108         if (retval != 0) {
3109                 /* This can commonly fail on smbd startup with no ticket in the cache.
3110                  * Report at higher level than 1. */
3111                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3112                          error_message(retval)));
3113                 goto cleanup_creds;
3114         }
3115
3116         while (!creds_ready && (i < maxtries)) {
3117
3118                 retval = smb_krb5_get_credentials(context,
3119                                                   ccache,
3120                                                   creds.client,
3121                                                   creds.server,
3122                                                   impersonate_princ,
3123                                                   &credsp);
3124                 if (retval != 0) {
3125                         DBG_WARNING("smb_krb5_get_credentials failed for %s "
3126                                     "(%s)\n",
3127                                     principal,
3128                                     error_message(retval));
3129                         goto cleanup_creds;
3130                 }
3131
3132                 /* cope with ticket being in the future due to clock skew */
3133                 if ((unsigned)credsp->times.starttime > time(NULL)) {
3134                         time_t t = time(NULL);
3135                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
3136                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3137                         krb5_set_real_time(context, t + time_offset + 1, 0);
3138                 }
3139
3140                 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3141                 if (!ok) {
3142                         creds_ready = true;
3143                 }
3144
3145                 i++;
3146         }
3147
3148         DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3149                   principal,
3150                   krb5_cc_get_type(context, ccache),
3151                   krb5_cc_get_name(context, ccache),
3152                   http_timestring(talloc_tos(),
3153                                   (unsigned)credsp->times.endtime),
3154                   (unsigned)credsp->times.endtime);
3155
3156         if (expire_time) {
3157                 *expire_time = (time_t)credsp->times.endtime;
3158         }
3159
3160         /* Allocate the auth_context. */
3161         retval = ads_setup_auth_context(context, auth_context);
3162         if (retval != 0) {
3163                 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3164                             error_message(retval));
3165                 goto cleanup_creds;
3166         }
3167
3168 #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)
3169         {
3170                 uint32_t gss_flags = 0;
3171
3172                 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3173                         /*
3174                          * Fetch a forwarded TGT from the KDC so that we can
3175                          * hand off a 2nd ticket as part of the kerberos
3176                          * exchange.
3177                          */
3178
3179                         DBG_INFO("Server marked as OK to delegate to, building "
3180                                  "forwardable TGT\n");
3181
3182                         retval = krb5_auth_con_setuseruserkey(context,
3183                                         *auth_context,
3184                                         &credsp->keyblock );
3185                         if (retval != 0) {
3186                                 DBG_WARNING("krb5_auth_con_setuseruserkey "
3187                                             "failed (%s)\n",
3188                                             error_message(retval));
3189                                 goto cleanup_creds;
3190                         }
3191
3192                         /* Must use a subkey for forwarded tickets. */
3193                         retval = krb5_auth_con_setflags(context,
3194                                                         *auth_context,
3195                                                         KRB5_AUTH_CONTEXT_USE_SUBKEY);
3196                         if (retval != 0) {
3197                                 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3198                                             error_message(retval));
3199                                 goto cleanup_creds;
3200                         }
3201
3202                         retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3203                                 *auth_context,  /* Authentication context [in] */
3204                                 discard_const_p(char, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
3205                                 credsp->client, /* Client principal for the tgt [in] */
3206                                 credsp->server, /* Server principal for the tgt [in] */
3207                                 ccache,         /* Credential cache to use for storage [in] */
3208                                 1,              /* Turn on for "Forwardable ticket" [in] */
3209                                 &in_data );     /* Resulting response [out] */
3210
3211                         if (retval) {
3212                                 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3213                                          error_message(retval));
3214
3215                                 /*
3216                                  * This is not fatal. Delete the *auth_context and continue
3217                                  * with krb5_mk_req_extended to get a non-forwardable ticket.
3218                                  */
3219
3220                                 if (in_data.data) {
3221                                         free( in_data.data );
3222                                         in_data.data = NULL;
3223                                         in_data.length = 0;
3224                                 }
3225                                 krb5_auth_con_free(context, *auth_context);
3226                                 *auth_context = NULL;
3227                                 retval = ads_setup_auth_context(context, auth_context);
3228                                 if (retval != 0) {
3229                                         DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3230                                                     error_message(retval));
3231                                         goto cleanup_creds;
3232                                 }
3233                         } else {
3234                                 /* We got a delegated ticket. */
3235                                 gss_flags |= GSS_C_DELEG_FLAG;
3236                         }
3237                 }
3238
3239                 /* Frees and reallocates in_data into a GSS checksum blob. */
3240                 retval = ads_create_gss_checksum(&in_data, gss_flags);
3241                 if (retval != 0) {
3242                         goto cleanup_data;
3243                 }
3244
3245                 /* We always want GSS-checksum types. */
3246                 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3247                 if (retval != 0) {
3248                         DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3249                                 error_message(retval)));
3250                         goto cleanup_data;
3251                 }
3252         }
3253 #endif
3254
3255         retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3256                                       &in_data, credsp, outbuf);
3257         if (retval != 0) {
3258                 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3259                             error_message(retval));
3260         }
3261
3262 #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)
3263 cleanup_data:
3264 #endif
3265
3266         if (in_data.data) {
3267                 free( in_data.data );
3268                 in_data.length = 0;
3269         }
3270
3271         krb5_free_creds(context, credsp);
3272
3273 cleanup_creds:
3274         krb5_free_cred_contents(context, &creds);
3275
3276 cleanup_princ:
3277         krb5_free_principal(context, server);
3278         if (impersonate_princ) {
3279                 krb5_free_principal(context, impersonate_princ);
3280         }
3281
3282         return retval;
3283 }
3284
3285 /*
3286   get a kerberos5 ticket for the given service
3287 */
3288 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3289                             const char *principal,
3290                             time_t time_offset,
3291                             DATA_BLOB *ticket,
3292                             DATA_BLOB *session_key_krb5,
3293                             uint32_t extra_ap_opts, const char *ccname,
3294                             time_t *tgs_expire,
3295                             const char *impersonate_princ_s)
3296 {
3297         krb5_error_code retval;
3298         krb5_data packet;
3299         krb5_context context = NULL;
3300         krb5_ccache ccdef = NULL;
3301         krb5_auth_context auth_context = NULL;
3302         krb5_enctype enc_types[] = {
3303 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3304                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3305 #endif
3306 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3307                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3308 #endif
3309                 ENCTYPE_ARCFOUR_HMAC,
3310                 ENCTYPE_DES_CBC_MD5,
3311                 ENCTYPE_DES_CBC_CRC,
3312                 ENCTYPE_NULL};
3313         bool ok;
3314
3315         initialize_krb5_error_table();
3316         retval = krb5_init_context(&context);
3317         if (retval != 0) {
3318                 DBG_WARNING("krb5_init_context failed (%s)\n",
3319                             error_message(retval));
3320                 goto failed;
3321         }
3322
3323         if (time_offset != 0) {
3324                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3325         }
3326
3327         retval = krb5_cc_resolve(context,
3328                                  ccname ? ccname : krb5_cc_default_name(context),
3329                                  &ccdef);
3330         if (retval != 0) {
3331                 DBG_WARNING("krb5_cc_default failed (%s)\n",
3332                             error_message(retval));
3333                 goto failed;
3334         }
3335
3336         retval = krb5_set_default_tgs_ktypes(context, enc_types);
3337         if (retval != 0) {
3338                 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3339                             error_message(retval));
3340                 goto failed;
3341         }
3342
3343         retval = ads_krb5_mk_req(context,
3344                                  &auth_context,
3345                                  AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3346                                  principal,
3347                                  ccdef,
3348                                  &packet,
3349                                  tgs_expire,
3350                                  impersonate_princ_s);
3351         if (retval != 0) {
3352                 goto failed;
3353         }
3354
3355         ok = smb_krb5_get_smb_session_key(mem_ctx,
3356                                           context,
3357                                           auth_context,
3358                                           session_key_krb5,
3359                                           false);
3360         if (!ok) {
3361                 retval = ENOMEM;
3362                 goto failed;
3363         }
3364
3365         *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3366
3367         smb_krb5_free_data_contents(context, &packet);
3368
3369 failed:
3370
3371         if (context) {
3372                 if (ccdef) {
3373                         krb5_cc_close(context, ccdef);
3374                 }
3375                 if (auth_context) {
3376                         krb5_auth_con_free(context, auth_context);
3377                 }
3378                 krb5_free_context(context);
3379         }
3380
3381         return retval;
3382 }
3383
3384 #else /* HAVE_KRB5 */
3385 /* This saves a few linking headaches */
3386 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3387                             const char *principal,
3388                             time_t time_offset,
3389                             DATA_BLOB *ticket,
3390                             DATA_BLOB *session_key_krb5,
3391                             uint32_t extra_ap_opts, const char *ccname,
3392                             time_t *tgs_expire,
3393                             const char *impersonate_princ_s)
3394 {
3395          DEBUG(0,("NO KERBEROS SUPPORT\n"));
3396          return 1;
3397 }
3398
3399 #endif /* HAVE_KRB5 */