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