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