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