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