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