WAF: Fix detection of IPv6
[Samba.git] / lib / krb5_wrap / krb5_samba.c
blob307be9352db9be5621f09087bc2c73a4fdf31be6
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
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.
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.
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/>.
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "krb5_samba.h"
27 #ifdef HAVE_COM_ERR_H
28 #include <com_err.h>
29 #endif /* HAVE_COM_ERR_H */
31 #ifndef KRB5_AUTHDATA_WIN2K_PAC
32 #define KRB5_AUTHDATA_WIN2K_PAC 128
33 #endif
35 #ifndef KRB5_AUTHDATA_IF_RELEVANT
36 #define KRB5_AUTHDATA_IF_RELEVANT 1
37 #endif
39 #ifdef HAVE_KRB5
41 #define GSSAPI_CHECKSUM 0x8003 /* Checksum type value for Kerberos */
42 #define GSSAPI_BNDLENGTH 16 /* Bind Length (rfc-1964 pg.3) */
43 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
44 bind field, flags field. */
45 #define GSS_C_DELEG_FLAG 1
47 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
48 but still has the symbol */
49 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
50 krb5_error_code krb5_auth_con_set_req_cksumtype(
51 krb5_context context,
52 krb5_auth_context auth_context,
53 krb5_cksumtype cksumtype);
54 #endif
56 #if !defined(SMB_MALLOC)
57 #undef malloc
58 #define SMB_MALLOC(s) malloc((s))
59 #endif
61 #ifndef SMB_STRDUP
62 #define SMB_STRDUP(s) strdup(s)
63 #endif
65 /**********************************************************
66 * MISSING FUNCTIONS
67 **********************************************************/
69 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
71 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
73 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
74 * to krb5_set_default_tgs_ktypes. See
75 * http://lists.samba.org/archive/samba-technical/2006-July/048271.html
77 * If the MIT libraries are not exporting internal symbols, we will end up in
78 * this branch, which is correct. Otherwise we will continue to use the
79 * internal symbol
81 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
83 return krb5_set_default_tgs_enctypes(ctx, enc);
86 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
88 /* Heimdal */
89 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
91 return krb5_set_default_in_tkt_etypes(ctx, enc);
94 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
96 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
99 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
100 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
101 krb5_auth_context auth_context,
102 krb5_keyblock *keyblock)
104 return krb5_auth_con_setkey(context, auth_context, keyblock);
106 #endif
108 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
109 void krb5_free_unparsed_name(krb5_context context, char *val)
111 SAFE_FREE(val);
113 #endif
115 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
116 const krb5_data *krb5_princ_component(krb5_context context,
117 krb5_principal principal, int i);
119 const krb5_data *krb5_princ_component(krb5_context context,
120 krb5_principal principal, int i)
122 static krb5_data kdata;
124 kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
125 kdata.length = strlen((const char *)kdata.data);
126 return &kdata;
128 #endif
131 /**********************************************************
132 * WRAPPING FUNCTIONS
133 **********************************************************/
135 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
136 /* HEIMDAL */
139 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
141 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
142 * address from.
144 * @param[out] pkaddr A Kerberos address to store tha address in.
146 * @return True on success, false if an error occured.
148 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
149 krb5_address *pkaddr)
151 memset(pkaddr, '\0', sizeof(krb5_address));
152 #if defined(HAVE_IPV6) && defined(KRB5_ADDRESS_INET6)
153 if (paddr->ss_family == AF_INET6) {
154 pkaddr->addr_type = KRB5_ADDRESS_INET6;
155 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
156 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
157 return true;
159 #endif
160 if (paddr->ss_family == AF_INET) {
161 pkaddr->addr_type = KRB5_ADDRESS_INET;
162 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
163 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
164 return true;
166 return false;
168 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
169 /* MIT */
172 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
174 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
175 * address from.
177 * @param[in] pkaddr A Kerberos address to store tha address in.
179 * @return True on success, false if an error occured.
181 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
182 krb5_address *pkaddr)
184 memset(pkaddr, '\0', sizeof(krb5_address));
185 #if defined(HAVE_IPV6) && defined(ADDRTYPE_INET6)
186 if (paddr->ss_family == AF_INET6) {
187 pkaddr->addrtype = ADDRTYPE_INET6;
188 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
189 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
190 return true;
192 #endif
193 if (paddr->ss_family == AF_INET) {
194 pkaddr->addrtype = ADDRTYPE_INET;
195 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
196 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
197 return true;
199 return false;
201 #else
202 #error UNKNOWN_ADDRTYPE
203 #endif
205 krb5_error_code smb_krb5_mk_error(krb5_context context,
206 krb5_error_code error_code,
207 const char *e_text,
208 krb5_data *e_data,
209 const krb5_principal client,
210 const krb5_principal server,
211 krb5_data *enc_err)
213 krb5_error_code code = EINVAL;
214 #ifdef SAMBA4_USES_HEIMDAL
215 code = krb5_mk_error(context,
216 error_code,
217 e_text,
218 e_data,
219 client,
220 server,
221 NULL, /* client_time */
222 NULL, /* client_usec */
223 enc_err);
224 #else
225 krb5_principal unspec_server = NULL;
226 krb5_error errpkt;
228 errpkt.ctime = 0;
229 errpkt.cusec = 0;
231 code = krb5_us_timeofday(context,
232 &errpkt.stime,
233 &errpkt.susec);
234 if (code != 0) {
235 return code;
238 errpkt.error = error_code;
240 errpkt.text.length = 0;
241 if (e_text != NULL) {
242 errpkt.text.length = strlen(e_text);
243 errpkt.text.data = discard_const_p(char, e_text);
246 errpkt.e_data.magic = KV5M_DATA;
247 errpkt.e_data.length = 0;
248 errpkt.e_data.data = NULL;
249 if (e_data != NULL) {
250 errpkt.e_data = *e_data;
253 errpkt.client = client;
255 if (server != NULL) {
256 errpkt.server = server;
257 } else {
258 code = smb_krb5_make_principal(context,
259 &unspec_server,
260 "<unspecified realm>",
261 NULL);
262 if (code != 0) {
263 return code;
265 errpkt.server = unspec_server;
268 code = krb5_mk_error(context,
269 &errpkt,
270 enc_err);
271 krb5_free_principal(context, unspec_server);
272 #endif
273 return code;
277 * @brief Create a keyblock based on input parameters
279 * @param context The krb5_context
280 * @param host_princ The krb5_principal to use
281 * @param salt The optional salt, if omitted, salt is calculated with
282 * the provided principal.
283 * @param password The krb5_data containing the password
284 * @param enctype The krb5_enctype to use for the keyblock generation
285 * @param key The returned krb5_keyblock, caller needs to free with
286 * krb5_free_keyblock().
288 * @return krb5_error_code
290 int smb_krb5_create_key_from_string(krb5_context context,
291 krb5_const_principal host_princ,
292 krb5_data *salt,
293 krb5_data *password,
294 krb5_enctype enctype,
295 krb5_keyblock *key)
297 int ret = 0;
299 if (host_princ == NULL && salt == NULL) {
300 return -1;
303 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
304 {/* MIT */
305 krb5_data _salt;
307 if (salt == NULL) {
308 ret = krb5_principal2salt(context, host_princ, &_salt);
309 if (ret) {
310 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
311 return ret;
313 } else {
314 _salt = *salt;
316 ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
317 if (salt == NULL) {
318 SAFE_FREE(_salt.data);
321 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
322 {/* Heimdal */
323 krb5_salt _salt;
325 if (salt == NULL) {
326 ret = krb5_get_pw_salt(context, host_princ, &_salt);
327 if (ret) {
328 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
329 return ret;
331 } else {
332 _salt.saltvalue = *salt;
333 _salt.salttype = KRB5_PW_SALT;
336 ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
337 if (salt == NULL) {
338 krb5_free_salt(context, _salt);
341 #else
342 #error UNKNOWN_CREATE_KEY_FUNCTIONS
343 #endif
344 return ret;
348 * @brief Create a salt for a given principal
350 * @param context The initialized krb5_context
351 * @param host_princ The krb5_principal to create the salt for
352 * @param psalt A pointer to a krb5_data struct
354 * caller has to free the contents of psalt with smb_krb5_free_data_contents
355 * when function has succeeded
357 * @return krb5_error_code, returns 0 on success, error code otherwise
360 int smb_krb5_get_pw_salt(krb5_context context,
361 krb5_const_principal host_princ,
362 krb5_data *psalt)
363 #if defined(HAVE_KRB5_GET_PW_SALT)
364 /* Heimdal */
366 int ret;
367 krb5_salt salt;
369 ret = krb5_get_pw_salt(context, host_princ, &salt);
370 if (ret) {
371 return ret;
374 psalt->data = salt.saltvalue.data;
375 psalt->length = salt.saltvalue.length;
377 return ret;
379 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
380 /* MIT */
382 return krb5_principal2salt(context, host_princ, psalt);
384 #else
385 #error UNKNOWN_SALT_FUNCTIONS
386 #endif
388 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
390 * @brief Get a list of encryption types allowed for session keys
392 * @param[in] context The library context
394 * @param[in] enctypes An allocated, zero-terminated list of encryption types
396 * This function returns an allocated list of encryption types allowed for
397 * session keys.
399 * Use free() to free the enctypes when it is no longer needed.
401 * @retval 0 Success; otherwise - Kerberos error codes
403 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
404 krb5_enctype **enctypes)
406 return krb5_get_permitted_enctypes(context, enctypes);
408 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
409 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
410 krb5_enctype **enctypes)
412 #ifdef HAVE_KRB5_PDU_NONE_DECL
413 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
414 #else
415 return krb5_get_default_in_tkt_etypes(context, enctypes);
416 #endif
418 #else
419 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
420 #endif
424 * @brief Convert a string principal name to a Kerberos principal.
426 * @param[in] context The library context
428 * @param[in] name The principal as a unix charset string.
430 * @param[out] principal The newly allocated principal.
432 * Use krb5_free_principal() to free a principal when it is no longer needed.
434 * @return 0 on success, a Kerberos error code otherwise.
436 krb5_error_code smb_krb5_parse_name(krb5_context context,
437 const char *name,
438 krb5_principal *principal)
440 krb5_error_code ret;
441 char *utf8_name;
442 size_t converted_size;
443 TALLOC_CTX *frame = talloc_stackframe();
445 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
446 talloc_free(frame);
447 return ENOMEM;
450 ret = krb5_parse_name(context, utf8_name, principal);
451 TALLOC_FREE(frame);
452 return ret;
456 * @brief Convert a Kerberos principal structure to a string representation.
458 * The resulting string representation will be a unix charset name and is
459 * talloc'ed.
461 * @param[in] mem_ctx The talloc context to allocate memory on.
463 * @param[in] context The library context.
465 * @param[in] principal The principal.
467 * @param[out] unix_name A string representation of the princpial name as with
468 * unix charset.
470 * Use talloc_free() to free the string representation if it is no longer
471 * needed.
473 * @return 0 on success, a Kerberos error code otherwise.
475 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
476 krb5_context context,
477 krb5_const_principal principal,
478 char **unix_name)
480 krb5_error_code ret;
481 char *utf8_name;
482 size_t converted_size;
484 *unix_name = NULL;
485 ret = krb5_unparse_name(context, principal, &utf8_name);
486 if (ret) {
487 return ret;
490 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
491 krb5_free_unparsed_name(context, utf8_name);
492 return ENOMEM;
494 krb5_free_unparsed_name(context, utf8_name);
495 return 0;
499 * @brief Free the contents of a krb5_data structure and zero the data field.
501 * @param[in] context The krb5 context
503 * @param[in] pdata The data structure to free contents of
505 * This function frees the contents, not the structure itself.
507 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
509 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
510 if (pdata->data) {
511 krb5_free_data_contents(context, pdata);
513 #elif defined(HAVE_KRB5_DATA_FREE)
514 krb5_data_free(context, pdata);
515 #else
516 SAFE_FREE(pdata->data);
517 #endif
521 * @brief copy a buffer into a krb5_data struct
523 * @param[in] p The krb5_data
524 * @param[in] data The data to copy
525 * @param[in] length The length of the data to copy
526 * @return krb5_error_code
528 * Caller has to free krb5_data with smb_krb5_free_data_contents().
530 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
531 const void *data,
532 size_t len)
534 #if defined(HAVE_KRB5_DATA_COPY)
535 return krb5_data_copy(p, data, len);
536 #else
537 if (len) {
538 p->data = malloc(len);
539 if (p->data == NULL) {
540 return ENOMEM;
542 memmove(p->data, data, len);
543 } else {
544 p->data = NULL;
546 p->length = len;
547 p->magic = KV5M_DATA;
548 return 0;
549 #endif
552 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
553 krb5_context context,
554 krb5_auth_context auth_context,
555 DATA_BLOB *session_key,
556 bool remote)
558 krb5_keyblock *skey = NULL;
559 krb5_error_code err = 0;
560 bool ret = false;
562 if (remote) {
563 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
564 err = krb5_auth_con_getrecvsubkey(context,
565 auth_context,
566 &skey);
567 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
568 err = krb5_auth_con_getremotesubkey(context,
569 auth_context, &skey);
570 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
571 } else {
572 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
573 err = krb5_auth_con_getsendsubkey(context,
574 auth_context,
575 &skey);
576 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
577 err = krb5_auth_con_getlocalsubkey(context,
578 auth_context, &skey);
579 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
582 if (err || skey == NULL) {
583 DEBUG(10, ("KRB5 error getting session key %d\n", err));
584 goto done;
587 DEBUG(10, ("Got KRB5 session key of length %d\n",
588 (int)KRB5_KEY_LENGTH(skey)));
590 *session_key = data_blob_talloc(mem_ctx,
591 KRB5_KEY_DATA(skey),
592 KRB5_KEY_LENGTH(skey));
593 dump_data_pw("KRB5 Session Key:\n",
594 session_key->data,
595 session_key->length);
597 ret = true;
599 done:
600 if (skey) {
601 krb5_free_keyblock(context, skey);
604 return ret;
609 * @brief Get talloced string component of a principal
611 * @param[in] mem_ctx The TALLOC_CTX
612 * @param[in] context The krb5_context
613 * @param[in] principal The principal
614 * @param[in] component The component
615 * @return string component
617 * Caller must talloc_free if the return value is not NULL.
620 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
621 krb5_context context,
622 krb5_const_principal principal,
623 unsigned int component)
625 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
626 return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
627 #else
628 krb5_data *data;
630 if (component >= krb5_princ_size(context, principal)) {
631 return NULL;
634 data = krb5_princ_component(context, principal, component);
635 if (data == NULL) {
636 return NULL;
639 return talloc_strndup(mem_ctx, data->data, data->length);
640 #endif
644 * @brief
646 * @param[in] ccache_string A string pointing to the cache to renew the ticket
647 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
648 * ccache has not been specified, the default ccache
649 * will be used.
651 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
652 * or NULL. If the principal string has not been
653 * specified, the principal from the ccache will be
654 * retrieved.
656 * @param[in] service_string The service ticket string
657 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
658 * the sevice ticket is specified, it is parsed (
659 * with the realm part ignored) and used as the
660 * server principal of the credential. Otherwise
661 * the ticket-granting service is used.
663 * @param[in] expire_time A pointer to store the credentials end time or
664 * NULL.
666 * @return 0 on Succes, a Kerberos error code otherwise.
668 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
669 const char *client_string,
670 const char *service_string,
671 time_t *expire_time)
673 krb5_error_code ret;
674 krb5_context context = NULL;
675 krb5_ccache ccache = NULL;
676 krb5_principal client = NULL;
677 krb5_creds creds, creds_in;
679 ZERO_STRUCT(creds);
680 ZERO_STRUCT(creds_in);
682 initialize_krb5_error_table();
683 ret = krb5_init_context(&context);
684 if (ret) {
685 goto done;
688 if (!ccache_string) {
689 ccache_string = krb5_cc_default_name(context);
692 if (!ccache_string) {
693 ret = EINVAL;
694 goto done;
697 DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
699 /* FIXME: we should not fall back to defaults */
700 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
701 if (ret) {
702 goto done;
705 if (client_string) {
706 ret = smb_krb5_parse_name(context, client_string, &client);
707 if (ret) {
708 goto done;
710 } else {
711 ret = krb5_cc_get_principal(context, ccache, &client);
712 if (ret) {
713 goto done;
717 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
718 if (ret) {
719 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
720 goto done;
723 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
724 ret = krb5_cc_initialize(context, ccache, client);
725 if (ret) {
726 goto done;
729 ret = krb5_cc_store_cred(context, ccache, &creds);
731 if (expire_time) {
732 *expire_time = (time_t) creds.times.endtime;
735 done:
736 krb5_free_cred_contents(context, &creds_in);
737 krb5_free_cred_contents(context, &creds);
739 if (client) {
740 krb5_free_principal(context, client);
742 if (ccache) {
743 krb5_cc_close(context, ccache);
745 if (context) {
746 krb5_free_context(context);
749 return ret;
753 * @brief Free the data stored in an smb_krb5_addresses structure.
755 * @param[in] context The library context
757 * @param[in] addr The address structure to free.
759 * @return 0 on success, a Kerberos error code otherwise.
761 krb5_error_code smb_krb5_free_addresses(krb5_context context,
762 smb_krb5_addresses *addr)
764 krb5_error_code ret = 0;
765 if (addr == NULL) {
766 return ret;
768 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
769 krb5_free_addresses(context, addr->addrs);
770 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
771 ret = krb5_free_addresses(context, addr->addrs);
772 SAFE_FREE(addr->addrs);
773 #endif
774 SAFE_FREE(addr);
775 addr = NULL;
776 return ret;
779 #define MAX_NETBIOSNAME_LEN 16
782 * @brief Add a netbios name to the array of addresses
784 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
785 * netbios name to.
787 * @param[in] netbios_name The netbios name to add.
789 * @return 0 on success, a Kerberos error code otherwise.
791 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
792 const char *netbios_name)
794 krb5_error_code ret = 0;
795 char buf[MAX_NETBIOSNAME_LEN];
796 int len;
797 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
798 krb5_address **addrs = NULL;
799 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
800 krb5_addresses *addrs = NULL;
801 #endif
803 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
804 if (*kerb_addr == NULL) {
805 return ENOMEM;
808 /* temporarily duplicate put_name() code here to avoid dependency
809 * issues for a 5 lines function */
810 len = strlen(netbios_name);
811 memcpy(buf, netbios_name,
812 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
813 if (len < MAX_NETBIOSNAME_LEN - 1) {
814 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
816 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
818 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
820 int num_addr = 2;
822 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
823 if (addrs == NULL) {
824 SAFE_FREE(*kerb_addr);
825 return ENOMEM;
828 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
830 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
831 if (addrs[0] == NULL) {
832 SAFE_FREE(addrs);
833 SAFE_FREE(*kerb_addr);
834 return ENOMEM;
837 addrs[0]->magic = KV5M_ADDRESS;
838 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
839 addrs[0]->length = MAX_NETBIOSNAME_LEN;
840 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
841 if (addrs[0]->contents == NULL) {
842 SAFE_FREE(addrs[0]);
843 SAFE_FREE(addrs);
844 SAFE_FREE(*kerb_addr);
845 return ENOMEM;
848 memcpy(addrs[0]->contents, buf, addrs[0]->length);
850 addrs[1] = NULL;
852 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
854 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
855 if (addrs == NULL) {
856 SAFE_FREE(*kerb_addr);
857 return ENOMEM;
860 memset(addrs, 0, sizeof(krb5_addresses));
862 addrs->len = 1;
863 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
864 if (addrs->val == NULL) {
865 SAFE_FREE(addrs);
866 SAFE_FREE(kerb_addr);
867 return ENOMEM;
870 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
871 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
872 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
873 if (addrs->val[0].address.data == NULL) {
874 SAFE_FREE(addrs->val);
875 SAFE_FREE(addrs);
876 SAFE_FREE(*kerb_addr);
877 return ENOMEM;
880 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
882 #else
883 #error UNKNOWN_KRB5_ADDRESS_FORMAT
884 #endif
885 (*kerb_addr)->addrs = addrs;
887 return ret;
891 * @brief Get the enctype from a key table entry
893 * @param[in] kt_entry Key table entry to get the enctype from.
895 * @return The enctype from the entry.
897 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
899 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
903 * @brief Free the contents of a key table entry.
905 * @param[in] context The library context.
907 * @param[in] kt_entry The key table entry to free the contents of.
909 * @return 0 on success, a Kerberos error code otherwise.
911 * The pointer itself is not freed.
913 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
914 krb5_keytab_entry *kt_entry)
916 /* Try krb5_free_keytab_entry_contents first, since
917 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
918 * krb5_kt_free_entry but only has a prototype for the first, while the
919 * second is considered private.
921 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
922 return krb5_free_keytab_entry_contents(context, kt_entry);
923 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
924 return krb5_kt_free_entry(context, kt_entry);
925 #else
926 #error UNKNOWN_KT_FREE_FUNCTION
927 #endif
932 * @brief Convert an encryption type to a string.
934 * @param[in] context The library context.
936 * @param[in] enctype The encryption type.
938 * @param[in] etype_s A pointer to store the allocated encryption type as a
939 * string.
941 * @return 0 on success, a Kerberos error code otherwise.
943 * The caller needs to free the allocated string etype_s.
945 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
946 krb5_enctype enctype,
947 char **etype_s)
949 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
950 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
951 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
952 char buf[256];
953 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
954 if (ret) {
955 return ret;
957 *etype_s = SMB_STRDUP(buf);
958 if (!*etype_s) {
959 return ENOMEM;
961 return ret;
962 #else
963 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
964 #endif
967 /* This MAX_NAME_LEN is a constant defined in krb5.h */
968 #ifndef MAX_KEYTAB_NAME_LEN
969 #define MAX_KEYTAB_NAME_LEN 1100
970 #endif
973 * @brief Open a key table readonly or with readwrite access.
975 * Allows to use a different keytab than the default one using a relative
976 * path to the keytab.
978 * @param[in] context The library context
980 * @param[in] keytab_name_req The path to the key table.
982 * @param[in] write_access Open with readwrite access.
984 * @param[in] keytab A pointer o the opended key table.
986 * The keytab pointer should be freed using krb5_kt_close().
988 * @return 0 on success, a Kerberos error code otherwise.
990 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
991 const char *keytab_name_req,
992 bool write_access,
993 krb5_keytab *keytab)
995 krb5_error_code ret = 0;
996 TALLOC_CTX *mem_ctx;
997 char keytab_string[MAX_KEYTAB_NAME_LEN];
998 char *kt_str = NULL;
999 bool found_valid_name = false;
1000 const char *pragma = "FILE";
1001 const char *tmp = NULL;
1003 if (!write_access && !keytab_name_req) {
1004 /* caller just wants to read the default keytab readonly, so be it */
1005 return krb5_kt_default(context, keytab);
1008 mem_ctx = talloc_init("smb_krb5_open_keytab");
1009 if (!mem_ctx) {
1010 return ENOMEM;
1013 #ifdef HAVE_WRFILE_KEYTAB
1014 if (write_access) {
1015 pragma = "WRFILE";
1017 #endif
1019 if (keytab_name_req) {
1021 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1022 ret = KRB5_CONFIG_NOTENUFSPACE;
1023 goto out;
1026 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1027 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1028 tmp = keytab_name_req;
1029 goto resolve;
1032 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1033 if (!tmp) {
1034 ret = ENOMEM;
1035 goto out;
1038 goto resolve;
1041 /* we need to handle more complex keytab_strings, like:
1042 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1044 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1045 if (ret) {
1046 goto out;
1049 DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1051 tmp = talloc_strdup(mem_ctx, keytab_string);
1052 if (!tmp) {
1053 ret = ENOMEM;
1054 goto out;
1057 if (strncmp(tmp, "ANY:", 4) == 0) {
1058 tmp += 4;
1061 memset(&keytab_string, '\0', sizeof(keytab_string));
1063 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1064 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1065 found_valid_name = true;
1066 tmp = kt_str;
1067 tmp += 7;
1070 if (strncmp(kt_str, "FILE:", 5) == 0) {
1071 found_valid_name = true;
1072 tmp = kt_str;
1073 tmp += 5;
1076 if (tmp[0] == '/') {
1077 /* Treat as a FILE: keytab definition. */
1078 found_valid_name = true;
1081 if (found_valid_name) {
1082 if (tmp[0] != '/') {
1083 ret = KRB5_KT_BADNAME;
1084 goto out;
1087 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1088 if (!tmp) {
1089 ret = ENOMEM;
1090 goto out;
1092 break;
1096 if (!found_valid_name) {
1097 ret = KRB5_KT_UNKNOWN_TYPE;
1098 goto out;
1101 resolve:
1102 DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1103 ret = krb5_kt_resolve(context, tmp, keytab);
1105 out:
1106 TALLOC_FREE(mem_ctx);
1107 return ret;
1111 * @brief Open a key table readonly or with readwrite access.
1113 * Allows to use a different keytab than the default one. The path needs to be
1114 * an absolute path or an error will be returned.
1116 * @param[in] context The library context
1118 * @param[in] keytab_name_req The path to the key table.
1120 * @param[in] write_access Open with readwrite access.
1122 * @param[in] keytab A pointer o the opended key table.
1124 * The keytab pointer should be freed using krb5_kt_close().
1126 * @return 0 on success, a Kerberos error code otherwise.
1128 krb5_error_code smb_krb5_kt_open(krb5_context context,
1129 const char *keytab_name_req,
1130 bool write_access,
1131 krb5_keytab *keytab)
1133 int cmp;
1135 if (keytab_name_req == NULL) {
1136 return KRB5_KT_BADNAME;
1139 if (keytab_name_req[0] == '/') {
1140 goto open_keytab;
1143 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1144 if (cmp == 0) {
1145 goto open_keytab;
1148 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1149 if (cmp == 0) {
1150 goto open_keytab;
1153 return KRB5_KT_BADNAME;
1155 open_keytab:
1156 return smb_krb5_kt_open_relative(context,
1157 keytab_name_req,
1158 write_access,
1159 keytab);
1163 * @brief Get a key table name.
1165 * @param[in] mem_ctx The talloc context to use for allocation.
1167 * @param[in] context The library context.
1169 * @param[in] keytab The key table to get the name from.
1171 * @param[in] keytab_name A talloc'ed string of the key table name.
1173 * The talloc'ed name string needs to be freed with talloc_free().
1175 * @return 0 on success, a Kerberos error code otherwise.
1177 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1178 krb5_context context,
1179 krb5_keytab keytab,
1180 const char **keytab_name)
1182 char keytab_string[MAX_KEYTAB_NAME_LEN];
1183 krb5_error_code ret = 0;
1185 ret = krb5_kt_get_name(context, keytab,
1186 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1187 if (ret) {
1188 return ret;
1191 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1192 if (!*keytab_name) {
1193 return ENOMEM;
1196 return ret;
1200 * @brief Seek and delete old entries in a keytab based on the passed
1201 * principal.
1203 * @param[in] context The KRB5 context to use.
1205 * @param[in] keytab The keytab to operate on.
1207 * @param[in] kvno The kvnco to use.
1209 * @param[in] princ_s The principal as a string to search for.
1211 * @param[in] princ The principal as a krb5_principal to search for.
1213 * @param[in] flush Weather to flush the complete keytab.
1215 * @param[in] keep_old_entries Keep the entry with the previous kvno.
1217 * @retval 0 on Sucess
1219 * @return An appropriate KRB5 error code.
1221 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1222 krb5_keytab keytab,
1223 krb5_kvno kvno,
1224 krb5_enctype enctype,
1225 const char *princ_s,
1226 krb5_principal princ,
1227 bool flush,
1228 bool keep_old_entries)
1230 krb5_error_code ret;
1231 krb5_kt_cursor cursor;
1232 krb5_kt_cursor zero_csr;
1233 krb5_keytab_entry kt_entry;
1234 krb5_keytab_entry zero_kt_entry;
1235 char *ktprinc = NULL;
1236 krb5_kvno old_kvno = kvno - 1;
1237 TALLOC_CTX *tmp_ctx;
1239 ZERO_STRUCT(cursor);
1240 ZERO_STRUCT(zero_csr);
1241 ZERO_STRUCT(kt_entry);
1242 ZERO_STRUCT(zero_kt_entry);
1244 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1245 if (ret == KRB5_KT_END || ret == ENOENT ) {
1246 /* no entries */
1247 return 0;
1250 tmp_ctx = talloc_new(NULL);
1251 if (tmp_ctx == NULL) {
1252 return ENOMEM;
1255 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1256 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1257 bool name_ok = false;
1258 krb5_enctype kt_entry_enctype =
1259 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1261 if (!flush && (princ_s != NULL)) {
1262 ret = smb_krb5_unparse_name(tmp_ctx, context,
1263 kt_entry.principal,
1264 &ktprinc);
1265 if (ret) {
1266 DEBUG(1, (__location__
1267 ": smb_krb5_unparse_name failed "
1268 "(%s)\n", error_message(ret)));
1269 goto out;
1272 #ifdef HAVE_KRB5_KT_COMPARE
1273 name_ok = krb5_kt_compare(context, &kt_entry,
1274 princ, 0, 0);
1275 #else
1276 name_ok = (strcmp(ktprinc, princ_s) == 0);
1277 #endif
1279 if (!name_ok) {
1280 DEBUG(10, (__location__ ": ignoring keytab "
1281 "entry principal %s, kvno = %d\n",
1282 ktprinc, kt_entry.vno));
1284 /* Not a match,
1285 * just free this entry and continue. */
1286 ret = smb_krb5_kt_free_entry(context,
1287 &kt_entry);
1288 ZERO_STRUCT(kt_entry);
1289 if (ret) {
1290 DEBUG(1, (__location__
1291 ": smb_krb5_kt_free_entry "
1292 "failed (%s)\n",
1293 error_message(ret)));
1294 goto out;
1297 TALLOC_FREE(ktprinc);
1298 continue;
1301 TALLOC_FREE(ktprinc);
1304 /*------------------------------------------------------------
1305 * Save the entries with kvno - 1. This is what microsoft does
1306 * to allow people with existing sessions that have kvno - 1
1307 * to still work. Otherwise, when the password for the machine
1308 * changes, all kerberizied sessions will 'break' until either
1309 * the client reboots or the client's session key expires and
1310 * they get a new session ticket with the new kvno.
1311 * Some keytab files only store the kvno in 8bits, limit
1312 * the compare accordingly.
1315 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1316 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1317 "entry for principal: %s.\n",
1318 old_kvno, princ_s));
1319 continue;
1322 if (keep_old_entries) {
1323 DEBUG(5, (__location__ ": Saving old (kvno %d) "
1324 "entry for principal: %s.\n",
1325 kvno, princ_s));
1326 continue;
1329 if (!flush &&
1330 (kt_entry.vno == kvno) &&
1331 (kt_entry_enctype != enctype))
1333 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1334 "enctype [%d] for principal: %s.\n",
1335 kvno, kt_entry_enctype, princ_s));
1336 continue;
1339 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1340 "(kvno %d) - trying to remove it.\n",
1341 princ_s, kt_entry.vno));
1343 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1344 ZERO_STRUCT(cursor);
1345 if (ret) {
1346 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1347 "failed (%s)\n", error_message(ret)));
1348 goto out;
1350 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1351 if (ret) {
1352 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1353 "failed (%s)\n", error_message(ret)));
1354 goto out;
1357 DEBUG(5, (__location__ ": removed old entry for principal: "
1358 "%s (kvno %d).\n", princ_s, kt_entry.vno));
1360 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1361 if (ret) {
1362 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1363 "(%s)\n", error_message(ret)));
1364 goto out;
1366 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1367 ZERO_STRUCT(kt_entry);
1368 if (ret) {
1369 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1370 "failed (%s)\n", error_message(ret)));
1371 goto out;
1375 out:
1376 talloc_free(tmp_ctx);
1377 if (memcmp(&zero_kt_entry, &kt_entry, sizeof(krb5_keytab_entry))) {
1378 smb_krb5_kt_free_entry(context, &kt_entry);
1380 if (memcmp(&cursor, &zero_csr, sizeof(krb5_kt_cursor)) != 0) {
1381 krb5_kt_end_seq_get(context, keytab, &cursor);
1383 return ret;
1387 * @brief Add a keytab entry for the given principal
1389 * @param[in] context The krb5 context to use.
1391 * @param[in] keytab The keytab to add the entry to.
1393 * @param[in] kvno The kvno to use.
1395 * @param[in] princ_s The principal as a string.
1397 * @param[in] salt_principal The salt principal to salt the password with.
1398 * Only needed for keys which support salting.
1399 * If no salt is used set no_salt to false and
1400 * pass NULL here.
1402 * @param[in] enctype The encryption type of the keytab entry.
1404 * @param[in] password The password of the keytab entry.
1406 * @param[in] no_salt If the password should not be salted. Normally
1407 * this is only set to false for encryption types
1408 * which do not support salting like RC4.
1410 * @param[in] keep_old_entries Wether to keep or delte old keytab entries.
1412 * @retval 0 on Success
1414 * @return A corresponding KRB5 error code.
1416 * @see smb_krb5_kt_open()
1418 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1419 krb5_keytab keytab,
1420 krb5_kvno kvno,
1421 const char *princ_s,
1422 const char *salt_principal,
1423 krb5_enctype enctype,
1424 krb5_data *password,
1425 bool no_salt,
1426 bool keep_old_entries)
1428 krb5_error_code ret;
1429 krb5_keytab_entry kt_entry;
1430 krb5_principal princ = NULL;
1431 krb5_keyblock *keyp;
1433 ZERO_STRUCT(kt_entry);
1435 ret = smb_krb5_parse_name(context, princ_s, &princ);
1436 if (ret) {
1437 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1438 "failed (%s)\n", princ_s, error_message(ret)));
1439 goto out;
1442 /* Seek and delete old keytab entries */
1443 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1444 keytab,
1445 kvno,
1446 enctype,
1447 princ_s,
1448 princ,
1449 false,
1450 keep_old_entries);
1451 if (ret) {
1452 goto out;
1455 /* If we get here, we have deleted all the old entries with kvno's
1456 * not equal to the current kvno-1. */
1458 keyp = KRB5_KT_KEY(&kt_entry);
1460 if (no_salt) {
1461 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1462 if (KRB5_KEY_DATA(keyp) == NULL) {
1463 ret = ENOMEM;
1464 goto out;
1466 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1467 KRB5_KEY_LENGTH(keyp) = password->length;
1468 KRB5_KEY_TYPE(keyp) = enctype;
1469 } else {
1470 krb5_principal salt_princ = NULL;
1472 /* Now add keytab entries for all encryption types */
1473 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1474 if (ret) {
1475 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1476 salt_principal, error_message(ret));
1477 goto out;
1480 ret = smb_krb5_create_key_from_string(context,
1481 salt_princ,
1482 NULL,
1483 password,
1484 enctype,
1485 keyp);
1486 krb5_free_principal(context, salt_princ);
1487 if (ret != 0) {
1488 goto out;
1492 kt_entry.principal = princ;
1493 kt_entry.vno = kvno;
1495 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1496 "encryption type (%d) and version (%d)\n",
1497 princ_s, enctype, kt_entry.vno));
1498 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1499 krb5_free_keyblock_contents(context, keyp);
1500 ZERO_STRUCT(kt_entry);
1501 if (ret) {
1502 DEBUG(1, (__location__ ": adding entry to keytab "
1503 "failed (%s)\n", error_message(ret)));
1504 goto out;
1507 out:
1508 if (princ) {
1509 krb5_free_principal(context, princ);
1512 return ret;
1515 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1516 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1517 defined(HAVE_KRB5_GET_CREDS)
1518 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1519 krb5_ccache ccache,
1520 krb5_principal me,
1521 krb5_principal server,
1522 krb5_principal impersonate_princ,
1523 krb5_creds **out_creds)
1525 krb5_error_code ret;
1526 krb5_get_creds_opt opt;
1528 ret = krb5_get_creds_opt_alloc(context, &opt);
1529 if (ret) {
1530 goto done;
1532 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1534 if (impersonate_princ) {
1535 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1536 impersonate_princ);
1537 if (ret) {
1538 goto done;
1542 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1543 if (ret) {
1544 goto done;
1547 done:
1548 if (opt) {
1549 krb5_get_creds_opt_free(context, opt);
1551 return ret;
1553 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1555 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1557 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1558 krb5_error_code KRB5_CALLCONV
1559 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1560 krb5_ccache ccache, krb5_creds *in_creds,
1561 krb5_data *subject_cert,
1562 krb5_creds **out_creds);
1563 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1565 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1566 krb5_ccache ccache,
1567 krb5_principal me,
1568 krb5_principal server,
1569 krb5_principal impersonate_princ,
1570 krb5_creds **out_creds)
1572 krb5_error_code ret;
1573 krb5_creds in_creds;
1575 ZERO_STRUCT(in_creds);
1577 if (impersonate_princ) {
1579 in_creds.server = me;
1580 in_creds.client = impersonate_princ;
1582 ret = krb5_get_credentials_for_user(context,
1583 0, /* krb5_flags options */
1584 ccache,
1585 &in_creds,
1586 NULL, /* krb5_data *subject_cert */
1587 out_creds);
1588 } else {
1589 in_creds.client = me;
1590 in_creds.server = server;
1592 ret = krb5_get_credentials(context, 0, ccache,
1593 &in_creds, out_creds);
1596 return ret;
1598 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1601 * smb_krb5_get_credentials
1603 * @brief Get krb5 credentials for a server
1605 * @param[in] context An initialized krb5_context
1606 * @param[in] ccache An initialized krb5_ccache
1607 * @param[in] me The krb5_principal of the caller
1608 * @param[in] server The krb5_principal of the requested service
1609 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1610 * @param[out] out_creds The returned krb5_creds structure
1611 * @return krb5_error_code
1614 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1615 krb5_ccache ccache,
1616 krb5_principal me,
1617 krb5_principal server,
1618 krb5_principal impersonate_princ,
1619 krb5_creds **out_creds)
1621 krb5_error_code ret;
1622 krb5_creds *creds = NULL;
1624 if (out_creds != NULL) {
1625 *out_creds = NULL;
1628 if (impersonate_princ) {
1629 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1630 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1631 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1632 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1633 #else
1634 ret = ENOTSUP;
1635 #endif
1636 } else {
1637 krb5_creds in_creds;
1639 ZERO_STRUCT(in_creds);
1641 in_creds.client = me;
1642 in_creds.server = server;
1644 ret = krb5_get_credentials(context, 0, ccache,
1645 &in_creds, &creds);
1647 if (ret) {
1648 goto done;
1651 if (out_creds) {
1652 *out_creds = creds;
1655 done:
1656 if (creds && ret) {
1657 krb5_free_creds(context, creds);
1660 return ret;
1664 * @brief Initialize a krb5_keyblock with the given data.
1666 * Initialized a new keyblock, allocates the contents fo the key and
1667 * copies the data into the keyblock.
1669 * @param[in] context The library context
1671 * @param[in] enctype The encryption type.
1673 * @param[in] data The date to initialize the keyblock with.
1675 * @param[in] length The length of the keyblock.
1677 * @param[in] key Newly allocated keyblock structure.
1679 * The key date must be freed using krb5_free_keyblock_contents() when it is
1680 * no longer needed.
1682 * @return 0 on success, a Kerberos error code otherwise.
1684 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1685 krb5_enctype enctype,
1686 const void *data,
1687 size_t length,
1688 krb5_keyblock *key)
1690 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1691 return krb5_keyblock_init(context, enctype, data, length, key);
1692 #else
1693 memset(key, 0, sizeof(krb5_keyblock));
1694 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1695 if (NULL == KRB5_KEY_DATA(key)) {
1696 return ENOMEM;
1698 memcpy(KRB5_KEY_DATA(key), data, length);
1699 KRB5_KEY_LENGTH(key) = length;
1700 KRB5_KEY_TYPE(key) = enctype;
1701 return 0;
1702 #endif
1706 * @brief Simulate a kinit by putting the tgt in the given credential cache.
1708 * This function uses a keyblock rather than needingthe original password.
1710 * @param[in] ctx The library context
1712 * @param[in] cc The credential cache to put the tgt in.
1714 * @param[in] principal The client princial
1716 * @param[in] keyblock The keyblock to use.
1718 * @param[in] target_service The service name of the initial credentials (or NULL).
1720 * @param[in] krb_options Initial credential options.
1722 * @param[in] expire_time A pointer to store the experation time of the
1723 * credentials (or NULL).
1725 * @param[in] kdc_time A pointer to store the time when the ticket becomes
1726 * valid (or NULL).
1728 * @return 0 on success, a Kerberos error code otherwise.
1730 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
1731 krb5_ccache cc,
1732 krb5_principal principal,
1733 krb5_keyblock *keyblock,
1734 const char *target_service,
1735 krb5_get_init_creds_opt *krb_options,
1736 time_t *expire_time,
1737 time_t *kdc_time)
1739 krb5_error_code code = 0;
1740 krb5_creds my_creds;
1742 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1743 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1744 keyblock, 0, target_service,
1745 krb_options);
1746 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1748 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
1749 char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
1750 krb5_keytab_entry entry;
1751 krb5_keytab keytab;
1752 mode_t mask;
1754 memset(&entry, 0, sizeof(entry));
1755 entry.principal = principal;
1756 *(KRB5_KT_KEY(&entry)) = *keyblock;
1758 memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
1759 mask = umask(S_IRWXO | S_IRWXG);
1760 mktemp(tmp_name);
1761 umask(mask);
1762 if (tmp_name[0] == 0) {
1763 return KRB5_KT_BADNAME;
1765 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
1766 if (code) {
1767 return code;
1770 code = krb5_kt_add_entry(ctx, keytab, &entry);
1771 if (code) {
1772 (void)krb5_kt_close(ctx, keytab);
1773 goto done;
1776 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
1777 keytab, 0, target_service,
1778 krb_options);
1779 (void)krb5_kt_close(ctx, keytab);
1781 #else
1782 #error krb5_get_init_creds_keyblock not available!
1783 #endif
1784 if (code) {
1785 return code;
1788 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
1790 * We need to store the principal as returned from the KDC to the
1791 * credentials cache. If we don't do that the KRB5 library is not
1792 * able to find the tickets it is looking for
1794 principal = my_creds.client;
1795 #endif
1796 code = krb5_cc_initialize(ctx, cc, principal);
1797 if (code) {
1798 goto done;
1801 code = krb5_cc_store_cred(ctx, cc, &my_creds);
1802 if (code) {
1803 goto done;
1806 if (expire_time) {
1807 *expire_time = (time_t) my_creds.times.endtime;
1810 if (kdc_time) {
1811 *kdc_time = (time_t) my_creds.times.starttime;
1814 code = 0;
1815 done:
1816 krb5_free_cred_contents(ctx, &my_creds);
1817 return code;
1821 * @brief Simulate a kinit by putting the tgt in the given credential cache.
1823 * @param[in] ctx The library context
1825 * @param[in] cc The credential cache to put the tgt in.
1827 * @param[in] principal The client princial
1829 * @param[in] password The password (or NULL).
1831 * @param[in] target_service The service name of the initial credentials (or NULL).
1833 * @param[in] krb_options Initial credential options.
1835 * @param[in] expire_time A pointer to store the experation time of the
1836 * credentials (or NULL).
1838 * @param[in] kdc_time A pointer to store the time when the ticket becomes
1839 * valid (or NULL).
1841 * @return 0 on success, a Kerberos error code otherwise.
1843 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
1844 krb5_ccache cc,
1845 krb5_principal principal,
1846 const char *password,
1847 const char *target_service,
1848 krb5_get_init_creds_opt *krb_options,
1849 time_t *expire_time,
1850 time_t *kdc_time)
1852 krb5_error_code code = 0;
1853 krb5_creds my_creds;
1855 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
1856 password, NULL, NULL, 0,
1857 target_service, krb_options);
1858 if (code) {
1859 return code;
1862 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
1864 * We need to store the principal as returned from the KDC to the
1865 * credentials cache. If we don't do that the KRB5 library is not
1866 * able to find the tickets it is looking for
1868 principal = my_creds.client;
1869 #endif
1870 code = krb5_cc_initialize(ctx, cc, principal);
1871 if (code) {
1872 goto done;
1875 code = krb5_cc_store_cred(ctx, cc, &my_creds);
1876 if (code) {
1877 goto done;
1880 if (expire_time) {
1881 *expire_time = (time_t) my_creds.times.endtime;
1884 if (kdc_time) {
1885 *kdc_time = (time_t) my_creds.times.starttime;
1888 code = 0;
1889 done:
1890 krb5_free_cred_contents(ctx, &my_creds);
1891 return code;
1894 #ifdef SAMBA4_USES_HEIMDAL
1896 * @brief Simulate a kinit by putting the tgt in the given credential cache.
1898 * @param[in] ctx The library context
1900 * @param[in] cc The credential cache to store the tgt in.
1902 * @param[in] principal The initial client princial.
1904 * @param[in] password The password (or NULL).
1906 * @param[in] impersonate_principal The impersonatiion principal (or NULL).
1908 * @param[in] self_service The local service for S4U2Self if
1909 * impersonate_principal is specified).
1911 * @param[in] target_service The service name of the initial credentials
1912 * (kpasswd/REALM or a remote service). It defaults
1913 * to the krbtgt if NULL.
1915 * @param[in] krb_options Initial credential options.
1917 * @param[in] expire_time A pointer to store the experation time of the
1918 * credentials (or NULL).
1920 * @param[in] kdc_time A pointer to store the time when the ticket becomes
1921 * valid (or NULL).
1923 * @return 0 on success, a Kerberos error code otherwise.
1925 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
1926 krb5_ccache store_cc,
1927 krb5_principal init_principal,
1928 const char *init_password,
1929 krb5_principal impersonate_principal,
1930 const char *self_service,
1931 const char *target_service,
1932 krb5_get_init_creds_opt *krb_options,
1933 time_t *expire_time,
1934 time_t *kdc_time)
1936 krb5_error_code code = 0;
1937 krb5_get_creds_opt options;
1938 krb5_principal store_principal;
1939 krb5_creds store_creds;
1940 krb5_creds *s4u2self_creds;
1941 Ticket s4u2self_ticket;
1942 size_t s4u2self_ticketlen;
1943 krb5_creds *s4u2proxy_creds;
1944 krb5_principal self_princ;
1945 bool s4u2proxy;
1946 krb5_principal target_princ;
1947 krb5_ccache tmp_cc;
1948 const char *self_realm;
1949 krb5_principal blacklist_principal = NULL;
1950 krb5_principal whitelist_principal = NULL;
1952 code = krb5_get_init_creds_password(ctx, &store_creds,
1953 init_principal,
1954 init_password,
1955 NULL, NULL,
1957 NULL,
1958 krb_options);
1959 if (code != 0) {
1960 return code;
1963 store_principal = init_principal;
1966 * We are trying S4U2Self now:
1968 * As we do not want to expose our TGT in the
1969 * krb5_ccache, which is also holds the impersonated creds.
1971 * Some low level krb5/gssapi function might use the TGT
1972 * identity and let the client act as our machine account.
1974 * We need to avoid that and use a temporary krb5_ccache
1975 * in order to pass our TGT to the krb5_get_creds() function.
1977 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
1978 if (code != 0) {
1979 krb5_free_cred_contents(ctx, &store_creds);
1980 return code;
1983 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
1984 if (code != 0) {
1985 krb5_cc_destroy(ctx, tmp_cc);
1986 krb5_free_cred_contents(ctx, &store_creds);
1987 return code;
1990 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
1991 if (code != 0) {
1992 krb5_free_cred_contents(ctx, &store_creds);
1993 krb5_cc_destroy(ctx, tmp_cc);
1994 return code;
1998 * we need to remember the client principal of our
1999 * TGT and make sure the KDC does not return this
2000 * in the impersonated tickets. This can happen
2001 * if the KDC does not support S4U2Self and S4U2Proxy.
2003 blacklist_principal = store_creds.client;
2004 store_creds.client = NULL;
2005 krb5_free_cred_contents(ctx, &store_creds);
2008 * Check if we also need S4U2Proxy or if S4U2Self is
2009 * enough in order to get a ticket for the target.
2011 if (target_service == NULL) {
2012 s4u2proxy = false;
2013 } else if (strcmp(target_service, self_service) == 0) {
2014 s4u2proxy = false;
2015 } else {
2016 s4u2proxy = true;
2020 * For S4U2Self we need our own service principal,
2021 * which belongs to our own realm (available on
2022 * our client principal).
2024 self_realm = krb5_principal_get_realm(ctx, init_principal);
2026 code = krb5_parse_name(ctx, self_service, &self_princ);
2027 if (code != 0) {
2028 krb5_free_principal(ctx, blacklist_principal);
2029 krb5_cc_destroy(ctx, tmp_cc);
2030 return code;
2033 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2034 if (code != 0) {
2035 krb5_free_principal(ctx, blacklist_principal);
2036 krb5_free_principal(ctx, self_princ);
2037 krb5_cc_destroy(ctx, tmp_cc);
2038 return code;
2041 code = krb5_get_creds_opt_alloc(ctx, &options);
2042 if (code != 0) {
2043 krb5_free_principal(ctx, blacklist_principal);
2044 krb5_free_principal(ctx, self_princ);
2045 krb5_cc_destroy(ctx, tmp_cc);
2046 return code;
2049 if (s4u2proxy) {
2051 * If we want S4U2Proxy, we need the forwardable flag
2052 * on the S4U2Self ticket.
2054 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2057 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2058 impersonate_principal);
2059 if (code != 0) {
2060 krb5_get_creds_opt_free(ctx, options);
2061 krb5_free_principal(ctx, blacklist_principal);
2062 krb5_free_principal(ctx, self_princ);
2063 krb5_cc_destroy(ctx, tmp_cc);
2064 return code;
2067 code = krb5_get_creds(ctx, options, tmp_cc,
2068 self_princ, &s4u2self_creds);
2069 krb5_get_creds_opt_free(ctx, options);
2070 krb5_free_principal(ctx, self_princ);
2071 if (code != 0) {
2072 krb5_free_principal(ctx, blacklist_principal);
2073 krb5_cc_destroy(ctx, tmp_cc);
2074 return code;
2077 if (!s4u2proxy) {
2078 krb5_cc_destroy(ctx, tmp_cc);
2081 * Now make sure we store the impersonated principal
2082 * and creds instead of the TGT related stuff
2083 * in the krb5_ccache of the caller.
2085 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2086 &store_creds);
2087 krb5_free_creds(ctx, s4u2self_creds);
2088 if (code != 0) {
2089 return code;
2093 * It's important to store the principal the KDC
2094 * returned, as otherwise the caller would not find
2095 * the S4U2Self ticket in the krb5_ccache lookup.
2097 store_principal = store_creds.client;
2098 goto store;
2102 * We are trying S4U2Proxy:
2104 * We need the ticket from the S4U2Self step
2105 * and our TGT in order to get the delegated ticket.
2107 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2108 s4u2self_creds->ticket.length,
2109 &s4u2self_ticket,
2110 &s4u2self_ticketlen);
2111 if (code != 0) {
2112 krb5_free_creds(ctx, s4u2self_creds);
2113 krb5_free_principal(ctx, blacklist_principal);
2114 krb5_cc_destroy(ctx, tmp_cc);
2115 return code;
2119 * we need to remember the client principal of the
2120 * S4U2Self stage and as it needs to match the one we
2121 * will get for the S4U2Proxy stage. We need this
2122 * in order to detect KDCs which does not support S4U2Proxy.
2124 whitelist_principal = s4u2self_creds->client;
2125 s4u2self_creds->client = NULL;
2126 krb5_free_creds(ctx, s4u2self_creds);
2129 * For S4U2Proxy we also got a target service principal,
2130 * which also belongs to our own realm (available on
2131 * our client principal).
2133 code = krb5_parse_name(ctx, target_service, &target_princ);
2134 if (code != 0) {
2135 free_Ticket(&s4u2self_ticket);
2136 krb5_free_principal(ctx, whitelist_principal);
2137 krb5_free_principal(ctx, blacklist_principal);
2138 krb5_cc_destroy(ctx, tmp_cc);
2139 return code;
2142 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2143 if (code != 0) {
2144 free_Ticket(&s4u2self_ticket);
2145 krb5_free_principal(ctx, target_princ);
2146 krb5_free_principal(ctx, whitelist_principal);
2147 krb5_free_principal(ctx, blacklist_principal);
2148 krb5_cc_destroy(ctx, tmp_cc);
2149 return code;
2152 code = krb5_get_creds_opt_alloc(ctx, &options);
2153 if (code != 0) {
2154 free_Ticket(&s4u2self_ticket);
2155 krb5_free_principal(ctx, target_princ);
2156 krb5_free_principal(ctx, whitelist_principal);
2157 krb5_free_principal(ctx, blacklist_principal);
2158 krb5_cc_destroy(ctx, tmp_cc);
2159 return code;
2162 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2163 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2165 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2166 free_Ticket(&s4u2self_ticket);
2167 if (code != 0) {
2168 krb5_get_creds_opt_free(ctx, options);
2169 krb5_free_principal(ctx, target_princ);
2170 krb5_free_principal(ctx, whitelist_principal);
2171 krb5_free_principal(ctx, blacklist_principal);
2172 krb5_cc_destroy(ctx, tmp_cc);
2173 return code;
2176 code = krb5_get_creds(ctx, options, tmp_cc,
2177 target_princ, &s4u2proxy_creds);
2178 krb5_get_creds_opt_free(ctx, options);
2179 krb5_free_principal(ctx, target_princ);
2180 krb5_cc_destroy(ctx, tmp_cc);
2181 if (code != 0) {
2182 krb5_free_principal(ctx, whitelist_principal);
2183 krb5_free_principal(ctx, blacklist_principal);
2184 return code;
2188 * Now make sure we store the impersonated principal
2189 * and creds instead of the TGT related stuff
2190 * in the krb5_ccache of the caller.
2192 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2193 &store_creds);
2194 krb5_free_creds(ctx, s4u2proxy_creds);
2195 if (code != 0) {
2196 krb5_free_principal(ctx, whitelist_principal);
2197 krb5_free_principal(ctx, blacklist_principal);
2198 return code;
2202 * It's important to store the principal the KDC
2203 * returned, as otherwise the caller would not find
2204 * the S4U2Self ticket in the krb5_ccache lookup.
2206 store_principal = store_creds.client;
2208 store:
2209 if (blacklist_principal &&
2210 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2211 char *sp = NULL;
2212 char *ip = NULL;
2214 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2215 if (code != 0) {
2216 sp = NULL;
2218 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2219 if (code != 0) {
2220 ip = NULL;
2222 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2223 "KDC returned self principal[%s] while impersonating [%s]\n",
2224 sp?sp:"<no memory>",
2225 ip?ip:"<no memory>"));
2227 SAFE_FREE(sp);
2228 SAFE_FREE(ip);
2230 krb5_free_principal(ctx, whitelist_principal);
2231 krb5_free_principal(ctx, blacklist_principal);
2232 krb5_free_cred_contents(ctx, &store_creds);
2233 return KRB5_FWD_BAD_PRINCIPAL;
2235 if (blacklist_principal) {
2236 krb5_free_principal(ctx, blacklist_principal);
2239 if (whitelist_principal &&
2240 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2241 char *sp = NULL;
2242 char *ep = NULL;
2244 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2245 if (code != 0) {
2246 sp = NULL;
2248 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2249 if (code != 0) {
2250 ep = NULL;
2252 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2253 "KDC returned wrong principal[%s] we expected [%s]\n",
2254 sp?sp:"<no memory>",
2255 ep?ep:"<no memory>"));
2257 SAFE_FREE(sp);
2258 SAFE_FREE(ep);
2260 krb5_free_principal(ctx, whitelist_principal);
2261 krb5_free_cred_contents(ctx, &store_creds);
2262 return KRB5_FWD_BAD_PRINCIPAL;
2264 if (whitelist_principal) {
2265 krb5_free_principal(ctx, whitelist_principal);
2268 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2269 if (code != 0) {
2270 krb5_free_cred_contents(ctx, &store_creds);
2271 return code;
2274 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2275 if (code != 0) {
2276 krb5_free_cred_contents(ctx, &store_creds);
2277 return code;
2280 if (expire_time) {
2281 *expire_time = (time_t) store_creds.times.endtime;
2284 if (kdc_time) {
2285 *kdc_time = (time_t) store_creds.times.starttime;
2288 krb5_free_cred_contents(ctx, &store_creds);
2290 return 0;
2292 #endif
2294 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2296 * @brief Create a principal name using a variable argument list.
2298 * @param[in] context The library context.
2300 * @param[inout] principal A pointer to the principal structure.
2302 * @param[in] _realm The realm to use. If NULL then the function will
2303 * get the default realm name.
2305 * @param[in] ... A list of 'char *' components, ending with NULL.
2307 * Use krb5_free_principal() to free the principal when it is no longer needed.
2309 * @return 0 on success, a Kerberos error code otherwise.
2311 krb5_error_code smb_krb5_make_principal(krb5_context context,
2312 krb5_principal *principal,
2313 const char *_realm, ...)
2315 krb5_error_code code;
2316 bool free_realm;
2317 char *realm;
2318 va_list ap;
2320 if (_realm) {
2321 realm = discard_const_p(char, _realm);
2322 free_realm = false;
2323 } else {
2324 code = krb5_get_default_realm(context, &realm);
2325 if (code) {
2326 return code;
2328 free_realm = true;
2331 va_start(ap, _realm);
2332 code = krb5_build_principal_alloc_va(context, principal,
2333 strlen(realm), realm,
2334 ap);
2335 va_end(ap);
2337 if (free_realm) {
2338 krb5_free_default_realm(context, realm);
2341 return code;
2343 #endif
2345 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2347 * @brief Get the lifetime of the initial ticket in the cache.
2349 * @param[in] context The kerberos context.
2351 * @param[in] id The credential cache to get the ticket lifetime.
2353 * @param[out] t A pointer to a time value to store the lifetime.
2355 * @return 0 on success, a krb5_error_code on error.
2357 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2358 krb5_ccache id,
2359 time_t *t)
2361 krb5_cc_cursor cursor;
2362 krb5_error_code kerr;
2363 krb5_creds cred;
2364 krb5_timestamp now;
2366 *t = 0;
2368 kerr = krb5_timeofday(context, &now);
2369 if (kerr) {
2370 return kerr;
2373 kerr = krb5_cc_start_seq_get(context, id, &cursor);
2374 if (kerr) {
2375 return kerr;
2378 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2379 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2380 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2381 #else
2382 if (cred.flags.b.initial) {
2383 #endif
2384 if (now < cred.times.endtime) {
2385 *t = (time_t) (cred.times.endtime - now);
2387 krb5_free_cred_contents(context, &cred);
2388 break;
2390 krb5_free_cred_contents(context, &cred);
2393 krb5_cc_end_seq_get(context, id, &cursor);
2395 return kerr;
2397 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2399 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2400 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2402 free_Checksum(cksum);
2404 #endif
2407 * @brief Compute a checksum operating on a keyblock.
2409 * This function computes a checksum over a PAC using the keyblock for a keyed
2410 * checksum.
2412 * @param[in] mem_ctx A talloc context to alocate the signature on.
2414 * @param[in] pac_data The PAC as input.
2416 * @param[in] context The library context.
2418 * @param[in] keyblock Encryption key for a keyed checksum.
2420 * @param[out] sig_type The checksum type
2422 * @param[out] sig_blob The talloc'ed checksum
2424 * The caller must free the sig_blob with talloc_free() when it is not needed
2425 * anymore.
2427 * @return 0 on success, a Kerberos error code otherwise.
2429 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2430 DATA_BLOB *pac_data,
2431 krb5_context context,
2432 const krb5_keyblock *keyblock,
2433 uint32_t *sig_type,
2434 DATA_BLOB *sig_blob)
2436 krb5_error_code ret;
2437 krb5_checksum cksum;
2438 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2439 krb5_crypto crypto;
2442 ret = krb5_crypto_init(context,
2443 keyblock,
2445 &crypto);
2446 if (ret) {
2447 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2448 smb_get_krb5_error_message(context, ret, mem_ctx)));
2449 return ret;
2451 ret = krb5_create_checksum(context,
2452 crypto,
2453 KRB5_KU_OTHER_CKSUM,
2455 pac_data->data,
2456 pac_data->length,
2457 &cksum);
2458 if (ret) {
2459 DEBUG(2, ("PAC Verification failed: %s\n",
2460 smb_get_krb5_error_message(context, ret, mem_ctx)));
2463 krb5_crypto_destroy(context, crypto);
2465 if (ret) {
2466 return ret;
2469 *sig_type = cksum.cksumtype;
2470 *sig_blob = data_blob_talloc(mem_ctx,
2471 cksum.checksum.data,
2472 cksum.checksum.length);
2473 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2474 krb5_data input;
2476 input.data = (char *)pac_data->data;
2477 input.length = pac_data->length;
2479 ret = krb5_c_make_checksum(context,
2481 keyblock,
2482 KRB5_KEYUSAGE_APP_DATA_CKSUM,
2483 &input,
2484 &cksum);
2485 if (ret) {
2486 DEBUG(2, ("PAC Verification failed: %s\n",
2487 smb_get_krb5_error_message(context, ret, mem_ctx)));
2488 return ret;
2491 *sig_type = cksum.checksum_type;
2492 *sig_blob = data_blob_talloc(mem_ctx,
2493 cksum.contents,
2494 cksum.length);
2496 #else
2497 #error krb5_create_checksum or krb5_c_make_checksum not available
2498 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2499 smb_krb5_free_checksum_contents(context, &cksum);
2501 return 0;
2506 * @brief Get realm of a principal
2508 * @param[in] context The library context
2510 * @param[in] principal The principal to get the realm from.
2512 * @return An allocated string with the realm or NULL if an error occured.
2514 * The caller must free the realm string with free() if not needed anymore.
2516 char *smb_krb5_principal_get_realm(krb5_context context,
2517 krb5_const_principal principal)
2519 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2520 return strdup(discard_const_p(char, krb5_principal_get_realm(context, principal)));
2521 #elif defined(krb5_princ_realm) /* MIT */
2522 krb5_data *realm;
2523 realm = discard_const_p(krb5_data,
2524 krb5_princ_realm(context, principal));
2525 return strndup(realm->data, realm->length);
2526 #else
2527 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2528 #endif
2532 * @brief Get realm of a principal
2534 * @param[in] context The library context
2536 * @param[in] principal The principal to set the realm
2538 * @param[in] realm The realm as a string to set.
2540 * @retur 0 on success, a Kerberos error code otherwise.
2542 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2543 krb5_principal principal,
2544 const char *realm)
2546 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2547 return krb5_principal_set_realm(context, principal, realm);
2548 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2549 krb5_error_code ret;
2550 krb5_data data;
2551 krb5_data *old_data;
2553 old_data = krb5_princ_realm(context, principal);
2555 ret = smb_krb5_copy_data_contents(&data,
2556 realm,
2557 strlen(realm));
2558 if (ret) {
2559 return ret;
2562 /* free realm before setting */
2563 free(old_data->data);
2565 krb5_princ_set_realm(context, principal, &data);
2567 return ret;
2568 #else
2569 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2570 #endif
2574 /************************************************************************
2575 Routine to get the default realm from the kerberos credentials cache.
2576 Caller must free if the return value is not NULL.
2577 ************************************************************************/
2579 static char *smb_krb5_get_default_realm_from_ccache(TALLOC_CTX *mem_ctx)
2581 char *realm = NULL;
2582 krb5_context ctx = NULL;
2583 krb5_ccache cc = NULL;
2584 krb5_principal princ = NULL;
2586 initialize_krb5_error_table();
2587 if (krb5_init_context(&ctx)) {
2588 return NULL;
2591 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2592 "Trying to read krb5 cache: %s\n",
2593 krb5_cc_default_name(ctx)));
2594 if (krb5_cc_default(ctx, &cc)) {
2595 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2596 "failed to read default cache\n"));
2597 goto out;
2599 if (krb5_cc_get_principal(ctx, cc, &princ)) {
2600 DEBUG(5,("kerberos_get_default_realm_from_ccache: "
2601 "failed to get default principal\n"));
2602 goto out;
2605 #if defined(HAVE_KRB5_PRINCIPAL_GET_REALM)
2606 realm = talloc_strdup(mem_ctx, krb5_principal_get_realm(ctx, princ));
2607 #elif defined(HAVE_KRB5_PRINC_REALM)
2609 krb5_data *realm_data = krb5_princ_realm(ctx, princ);
2610 realm = talloc_strndup(mem_ctx, realm_data->data, realm_data->length);
2612 #endif
2614 out:
2616 if (ctx) {
2617 if (princ) {
2618 krb5_free_principal(ctx, princ);
2620 if (cc) {
2621 krb5_cc_close(ctx, cc);
2623 krb5_free_context(ctx);
2626 return realm;
2629 /************************************************************************
2630 Routine to get the realm from a given DNS name.
2631 ************************************************************************/
2633 static char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2634 const char *hostname)
2636 #if defined(HAVE_KRB5_REALM_TYPE)
2637 /* Heimdal. */
2638 krb5_realm *realm_list = NULL;
2639 #else
2640 /* MIT */
2641 char **realm_list = NULL;
2642 #endif
2643 char *realm = NULL;
2644 krb5_error_code kerr;
2645 krb5_context ctx = NULL;
2647 initialize_krb5_error_table();
2648 if (krb5_init_context(&ctx)) {
2649 return NULL;
2652 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2653 if (kerr != 0) {
2654 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2655 "failed %s\n",
2656 hostname ? hostname : "(NULL)",
2657 error_message(kerr) ));
2658 goto out;
2661 if (realm_list && realm_list[0]) {
2662 realm = talloc_strdup(mem_ctx, realm_list[0]);
2665 out:
2667 if (ctx) {
2668 if (realm_list) {
2669 krb5_free_host_realm(ctx, realm_list);
2670 realm_list = NULL;
2672 krb5_free_context(ctx);
2673 ctx = NULL;
2675 return realm;
2679 * @brief Get the principal as a string from the service hostname.
2681 * @param[in] mem_ctx The talloc context
2683 * @param[in] service The service name
2685 * @param[in] remote_name The remote name
2687 * @param[in] default_realm The default_realm if we cannot get it from the
2688 * hostname or netbios name.
2690 * @return A talloc'ed principal string or NULL if an error occured.
2692 * The caller needs to free the principal with talloc_free() if it isn't needed
2693 * anymore.
2695 char *smb_krb5_get_principal_from_service_hostname(TALLOC_CTX *mem_ctx,
2696 const char *service,
2697 const char *remote_name,
2698 const char *default_realm)
2700 char *realm = NULL;
2701 char *host = NULL;
2702 char *principal;
2703 host = strchr_m(remote_name, '.');
2704 if (host) {
2705 /* DNS name. */
2706 realm = smb_krb5_get_realm_from_hostname(talloc_tos(),
2707 remote_name);
2708 } else {
2709 /* NetBIOS name - use our realm. */
2710 realm = smb_krb5_get_default_realm_from_ccache(talloc_tos());
2713 if (realm == NULL || *realm == '\0') {
2714 realm = talloc_strdup(talloc_tos(), default_realm);
2715 if (!realm) {
2716 return NULL;
2718 DEBUG(3,("Cannot get realm from, "
2719 "desthost %s or default ccache. Using default "
2720 "smb.conf realm %s\n",
2721 remote_name,
2722 realm));
2725 principal = talloc_asprintf(mem_ctx,
2726 "%s/%s@%s",
2727 service, remote_name,
2728 realm);
2729 TALLOC_FREE(realm);
2730 return principal;
2734 * @brief Get an error string from a Kerberos error code.
2736 * @param[in] context The library context.
2738 * @param[in] code The Kerberos error code.
2740 * @param[in] mem_ctx The talloc context to allocate the error string on.
2742 * @return A talloc'ed error string or NULL if an error occured.
2744 * The caller must free the returned error string with talloc_free() if not
2745 * needed anymore
2747 char *smb_get_krb5_error_message(krb5_context context,
2748 krb5_error_code code,
2749 TALLOC_CTX *mem_ctx)
2751 char *ret;
2753 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2754 const char *context_error = krb5_get_error_message(context, code);
2755 if (context_error) {
2756 ret = talloc_asprintf(mem_ctx, "%s: %s",
2757 error_message(code), context_error);
2758 krb5_free_error_message(context, context_error);
2759 return ret;
2761 #endif
2762 ret = talloc_strdup(mem_ctx, error_message(code));
2763 return ret;
2768 * @brief Return the kerberos library setting for: libdefaults:allow_weak_crypto
2770 * @param[in] context The library context
2772 * @return True if weak crypto is allowed, false if not.
2774 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2775 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2777 return krb5_config_get_bool_default(context,
2778 NULL,
2779 FALSE,
2780 "libdefaults",
2781 "allow_weak_crypto",
2782 NULL);
2784 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2786 #include <profile.h>
2787 krb5_error_code ret;
2788 krb5_boolean ret_default = false;
2789 profile_t profile;
2790 int ret_profile;
2792 ret = krb5_get_profile(context,
2793 &profile);
2794 if (ret) {
2795 return ret_default;
2798 ret = profile_get_boolean(profile,
2799 "libdefaults",
2800 "allow_weak_crypto",
2801 NULL, /* subsubname */
2802 ret_default, /* def_val */
2803 &ret_profile /* *ret_default */);
2804 if (ret) {
2805 return ret_default;
2808 profile_release(profile);
2810 return ret_profile;
2812 #else
2813 #error UNKNOWN_KRB5_CONFIG_ROUTINES
2814 #endif
2817 * @brief Return the type of a krb5_principal
2819 * @param[in] context The library context.
2821 * @param[in] principal The principal to get the type from.
2823 * @return The integer type of the principal.
2825 int smb_krb5_principal_get_type(krb5_context context,
2826 krb5_const_principal principal)
2828 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
2829 return krb5_principal_get_type(context, principal);
2830 #elif defined(krb5_princ_type) /* MIT */
2831 return krb5_princ_type(context, principal);
2832 #else
2833 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
2834 #endif
2838 * @brief Set the type of a principal
2840 * @param[in] context The library context
2842 * @param[inout] principal The principal to set the type for.
2844 * @param[in] type The principal type to set.
2846 void smb_krb5_principal_set_type(krb5_context context,
2847 krb5_principal principal,
2848 int type)
2850 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
2851 krb5_principal_set_type(context, principal, type);
2852 #elif defined(krb5_princ_type) /* MIT */
2853 krb5_princ_type(context, principal) = type;
2854 #else
2855 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
2856 #endif
2859 #if !defined(HAVE_KRB5_WARNX)
2861 * @brief Log a Kerberos message
2863 * It sends the message to com_err.
2865 * @param[in] context The library context
2867 * @param[in] fmt The message format
2869 * @param[in] ... The message arguments
2871 * @return 0 on success.
2873 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
2875 va_list args;
2877 va_start(args, fmt);
2878 com_err_va("samba-kdc", errno, fmt, args);
2879 va_end(args);
2881 return 0;
2883 #endif
2886 * @brief Copy a credential cache.
2888 * @param[in] context The library context.
2890 * @param[in] incc Credential cache to be copied.
2892 * @param[inout] outcc Copy of credential cache to be filled in.
2894 * @return 0 on success, a Kerberos error code otherwise.
2896 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
2897 krb5_ccache incc, krb5_ccache outcc)
2899 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
2900 return krb5_cc_copy_cache(context, incc, outcc);
2901 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
2902 krb5_error_code ret;
2903 krb5_principal princ = NULL;
2905 ret = krb5_cc_get_principal(context, incc, &princ);
2906 if (ret != 0) {
2907 return ret;
2909 ret = krb5_cc_initialize(context, outcc, princ);
2910 krb5_free_principal(context, princ);
2911 if (ret != 0) {
2912 return ret;
2914 return krb5_cc_copy_creds(context, incc, outcc);
2915 #else
2916 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
2917 #endif
2920 /**********************************************************
2921 * ADS KRB5 CALLS
2922 **********************************************************/
2924 static bool ads_cleanup_expired_creds(krb5_context context,
2925 krb5_ccache ccache,
2926 krb5_creds *credsp)
2928 krb5_error_code retval;
2929 const char *cc_type = krb5_cc_get_type(context, ccache);
2931 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
2932 cc_type, krb5_cc_get_name(context, ccache),
2933 http_timestring(talloc_tos(), credsp->times.endtime)));
2935 /* we will probably need new tickets if the current ones
2936 will expire within 10 seconds.
2938 if (credsp->times.endtime >= (time(NULL) + 10))
2939 return false;
2941 /* heimdal won't remove creds from a file ccache, and
2942 perhaps we shouldn't anyway, since internally we
2943 use memory ccaches, and a FILE one probably means that
2944 we're using creds obtained outside of our exectuable
2946 if (strequal(cc_type, "FILE")) {
2947 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
2948 return false;
2951 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
2952 if (retval) {
2953 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
2954 error_message(retval)));
2955 /* If we have an error in this, we want to display it,
2956 but continue as though we deleted it */
2958 return true;
2961 /* Allocate and setup the auth context into the state we need. */
2963 static krb5_error_code ads_setup_auth_context(krb5_context context,
2964 krb5_auth_context *auth_context)
2966 krb5_error_code retval;
2968 retval = krb5_auth_con_init(context, auth_context );
2969 if (retval) {
2970 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
2971 error_message(retval)));
2972 return retval;
2975 /* Ensure this is an addressless ticket. */
2976 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
2977 if (retval) {
2978 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
2979 error_message(retval)));
2982 return retval;
2985 #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)
2986 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
2987 uint32_t gss_flags)
2989 unsigned int orig_length = in_data->length;
2990 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
2991 char *gss_cksum = NULL;
2993 if (orig_length) {
2994 /* Extra length field for delgated ticket. */
2995 base_cksum_size += 4;
2998 if ((unsigned int)base_cksum_size + orig_length <
2999 (unsigned int)base_cksum_size) {
3000 return EINVAL;
3003 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3004 if (gss_cksum == NULL) {
3005 return ENOMEM;
3008 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3009 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3012 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3013 * This matches the behavior of heimdal and mit.
3015 * And it is needed to work against some closed source
3016 * SMB servers.
3018 * See bug #7883
3020 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3022 SIVAL(gss_cksum, 20, gss_flags);
3024 if (orig_length) {
3025 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3026 SSVAL(gss_cksum, 26, orig_length);
3027 /* Copy the kerberos KRB_CRED data */
3028 memcpy(gss_cksum + 28, in_data->data, orig_length);
3029 free(in_data->data);
3030 in_data->data = NULL;
3031 in_data->length = 0;
3033 in_data->data = gss_cksum;
3034 in_data->length = base_cksum_size + orig_length;
3035 return 0;
3037 #endif
3040 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3041 * format.
3043 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3044 krb5_auth_context *auth_context,
3045 const krb5_flags ap_req_options,
3046 const char *principal,
3047 krb5_ccache ccache,
3048 krb5_data *outbuf,
3049 time_t *expire_time,
3050 const char *impersonate_princ_s)
3052 krb5_error_code retval;
3053 krb5_principal server;
3054 krb5_principal impersonate_princ = NULL;
3055 krb5_creds *credsp;
3056 krb5_creds creds;
3057 krb5_data in_data;
3058 bool creds_ready = false;
3059 int i = 0, maxtries = 3;
3060 bool ok;
3062 ZERO_STRUCT(in_data);
3064 retval = smb_krb5_parse_name(context, principal, &server);
3065 if (retval != 0) {
3066 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3067 return retval;
3070 if (impersonate_princ_s) {
3071 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3072 &impersonate_princ);
3073 if (retval) {
3074 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3075 goto cleanup_princ;
3079 /* obtain ticket & session key */
3080 ZERO_STRUCT(creds);
3081 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3082 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3083 error_message(retval)));
3084 goto cleanup_princ;
3087 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3088 if (retval != 0) {
3089 /* This can commonly fail on smbd startup with no ticket in the cache.
3090 * Report at higher level than 1. */
3091 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3092 error_message(retval)));
3093 goto cleanup_creds;
3096 while (!creds_ready && (i < maxtries)) {
3098 retval = smb_krb5_get_credentials(context,
3099 ccache,
3100 creds.client,
3101 creds.server,
3102 impersonate_princ,
3103 &credsp);
3104 if (retval != 0) {
3105 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3106 "(%s)\n",
3107 principal,
3108 error_message(retval));
3109 goto cleanup_creds;
3112 /* cope with ticket being in the future due to clock skew */
3113 if ((unsigned)credsp->times.starttime > time(NULL)) {
3114 time_t t = time(NULL);
3115 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3116 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3117 krb5_set_real_time(context, t + time_offset + 1, 0);
3120 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3121 if (!ok) {
3122 creds_ready = true;
3125 i++;
3128 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3129 principal,
3130 krb5_cc_get_type(context, ccache),
3131 krb5_cc_get_name(context, ccache),
3132 http_timestring(talloc_tos(),
3133 (unsigned)credsp->times.endtime),
3134 (unsigned)credsp->times.endtime);
3136 if (expire_time) {
3137 *expire_time = (time_t)credsp->times.endtime;
3140 /* Allocate the auth_context. */
3141 retval = ads_setup_auth_context(context, auth_context);
3142 if (retval != 0) {
3143 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3144 error_message(retval));
3145 goto cleanup_creds;
3148 #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)
3150 uint32_t gss_flags = 0;
3152 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3154 * Fetch a forwarded TGT from the KDC so that we can
3155 * hand off a 2nd ticket as part of the kerberos
3156 * exchange.
3159 DBG_INFO("Server marked as OK to delegate to, building "
3160 "forwardable TGT\n");
3162 retval = krb5_auth_con_setuseruserkey(context,
3163 *auth_context,
3164 &credsp->keyblock );
3165 if (retval != 0) {
3166 DBG_WARNING("krb5_auth_con_setuseruserkey "
3167 "failed (%s)\n",
3168 error_message(retval));
3169 goto cleanup_creds;
3172 /* Must use a subkey for forwarded tickets. */
3173 retval = krb5_auth_con_setflags(context,
3174 *auth_context,
3175 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3176 if (retval != 0) {
3177 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3178 error_message(retval));
3179 goto cleanup_creds;
3182 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3183 *auth_context, /* Authentication context [in] */
3184 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3185 credsp->client, /* Client principal for the tgt [in] */
3186 credsp->server, /* Server principal for the tgt [in] */
3187 ccache, /* Credential cache to use for storage [in] */
3188 1, /* Turn on for "Forwardable ticket" [in] */
3189 &in_data ); /* Resulting response [out] */
3191 if (retval) {
3192 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3193 error_message(retval));
3196 * This is not fatal. Delete the *auth_context and continue
3197 * with krb5_mk_req_extended to get a non-forwardable ticket.
3200 if (in_data.data) {
3201 free( in_data.data );
3202 in_data.data = NULL;
3203 in_data.length = 0;
3205 krb5_auth_con_free(context, *auth_context);
3206 *auth_context = NULL;
3207 retval = ads_setup_auth_context(context, auth_context);
3208 if (retval != 0) {
3209 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3210 error_message(retval));
3211 goto cleanup_creds;
3213 } else {
3214 /* We got a delegated ticket. */
3215 gss_flags |= GSS_C_DELEG_FLAG;
3219 /* Frees and reallocates in_data into a GSS checksum blob. */
3220 retval = ads_create_gss_checksum(&in_data, gss_flags);
3221 if (retval != 0) {
3222 goto cleanup_data;
3225 /* We always want GSS-checksum types. */
3226 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3227 if (retval != 0) {
3228 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3229 error_message(retval)));
3230 goto cleanup_data;
3233 #endif
3235 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3236 &in_data, credsp, outbuf);
3237 if (retval != 0) {
3238 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3239 error_message(retval));
3242 #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)
3243 cleanup_data:
3244 #endif
3246 if (in_data.data) {
3247 free( in_data.data );
3248 in_data.length = 0;
3251 krb5_free_creds(context, credsp);
3253 cleanup_creds:
3254 krb5_free_cred_contents(context, &creds);
3256 cleanup_princ:
3257 krb5_free_principal(context, server);
3258 if (impersonate_princ) {
3259 krb5_free_principal(context, impersonate_princ);
3262 return retval;
3266 get a kerberos5 ticket for the given service
3268 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3269 const char *principal,
3270 time_t time_offset,
3271 DATA_BLOB *ticket,
3272 DATA_BLOB *session_key_krb5,
3273 uint32_t extra_ap_opts, const char *ccname,
3274 time_t *tgs_expire,
3275 const char *impersonate_princ_s)
3277 krb5_error_code retval;
3278 krb5_data packet;
3279 krb5_context context = NULL;
3280 krb5_ccache ccdef = NULL;
3281 krb5_auth_context auth_context = NULL;
3282 krb5_enctype enc_types[] = {
3283 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3284 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3285 #endif
3286 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3287 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3288 #endif
3289 ENCTYPE_ARCFOUR_HMAC,
3290 ENCTYPE_DES_CBC_MD5,
3291 ENCTYPE_DES_CBC_CRC,
3292 ENCTYPE_NULL};
3293 bool ok;
3295 initialize_krb5_error_table();
3296 retval = krb5_init_context(&context);
3297 if (retval != 0) {
3298 DBG_WARNING("krb5_init_context failed (%s)\n",
3299 error_message(retval));
3300 goto failed;
3303 if (time_offset != 0) {
3304 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3307 retval = krb5_cc_resolve(context,
3308 ccname ? ccname : krb5_cc_default_name(context),
3309 &ccdef);
3310 if (retval != 0) {
3311 DBG_WARNING("krb5_cc_default failed (%s)\n",
3312 error_message(retval));
3313 goto failed;
3316 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3317 if (retval != 0) {
3318 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3319 error_message(retval));
3320 goto failed;
3323 retval = ads_krb5_mk_req(context,
3324 &auth_context,
3325 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3326 principal,
3327 ccdef,
3328 &packet,
3329 tgs_expire,
3330 impersonate_princ_s);
3331 if (retval != 0) {
3332 goto failed;
3335 ok = smb_krb5_get_smb_session_key(mem_ctx,
3336 context,
3337 auth_context,
3338 session_key_krb5,
3339 false);
3340 if (!ok) {
3341 retval = ENOMEM;
3342 goto failed;
3345 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3347 smb_krb5_free_data_contents(context, &packet);
3349 failed:
3351 if (context) {
3352 if (ccdef) {
3353 krb5_cc_close(context, ccdef);
3355 if (auth_context) {
3356 krb5_auth_con_free(context, auth_context);
3358 krb5_free_context(context);
3361 return retval;
3364 #else /* HAVE_KRB5 */
3365 /* This saves a few linking headaches */
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)
3375 DEBUG(0,("NO KERBEROS SUPPORT\n"));
3376 return 1;
3379 #endif /* HAVE_KRB5 */