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