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