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