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/>.
24 #include "system/filesys.h"
25 #include "krb5_samba.h"
26 #include "lib/crypto/crypto.h"
27 #include "../libds/common/flags.h"
31 #endif /* HAVE_COM_ERR_H */
33 #ifndef KRB5_AUTHDATA_WIN2K_PAC
34 #define KRB5_AUTHDATA_WIN2K_PAC 128
37 #ifndef KRB5_AUTHDATA_IF_RELEVANT
38 #define KRB5_AUTHDATA_IF_RELEVANT 1
43 #define GSSAPI_CHECKSUM 0x8003 /* Checksum type value for Kerberos */
44 #define GSSAPI_BNDLENGTH 16 /* Bind Length (rfc-1964 pg.3) */
45 #define GSSAPI_CHECKSUM_SIZE (4+GSSAPI_BNDLENGTH+4) /* Length of bind length,
46 bind field, flags field. */
47 #define GSS_C_DELEG_FLAG 1
49 /* MIT krb5 1.7beta3 (in Ubuntu Karmic) is missing the prototype,
50 but still has the symbol */
51 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
52 krb5_error_code krb5_auth_con_set_req_cksumtype(
54 krb5_auth_context auth_context,
55 krb5_cksumtype cksumtype);
58 #if !defined(SMB_MALLOC)
60 #define SMB_MALLOC(s) malloc((s))
64 #define SMB_STRDUP(s) strdup(s)
67 /**********************************************************
69 **********************************************************/
71 #if !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
73 #if defined(HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES)
75 /* With MIT kerberos, we should use krb5_set_default_tgs_enctypes in preference
76 * to krb5_set_default_tgs_ktypes. See
77 * http://lists.samba.org/archive/samba-technical/2006-July/048271.html
79 * If the MIT libraries are not exporting internal symbols, we will end up in
80 * this branch, which is correct. Otherwise we will continue to use the
83 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
85 return krb5_set_default_tgs_enctypes(ctx, enc);
88 #elif defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES)
91 krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
93 return krb5_set_default_in_tkt_etypes(ctx, enc);
96 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_ENCTYPES */
98 #endif /* HAVE_KRB5_SET_DEFAULT_TGS_KTYPES */
101 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
102 krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
103 krb5_auth_context auth_context,
104 krb5_keyblock *keyblock)
106 return krb5_auth_con_setkey(context, auth_context, keyblock);
110 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
111 void krb5_free_unparsed_name(krb5_context context, char *val)
117 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING) && !defined(HAVE_KRB5_PRINC_COMPONENT)
118 const krb5_data *krb5_princ_component(krb5_context context,
119 krb5_principal principal, int i);
121 const krb5_data *krb5_princ_component(krb5_context context,
122 krb5_principal principal, int i)
124 static krb5_data kdata;
126 kdata.data = discard_const_p(char, krb5_principal_get_comp_string(context, principal, i));
127 kdata.length = strlen((const char *)kdata.data);
133 /**********************************************************
135 **********************************************************/
137 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
141 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
143 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
146 * @param[out] pkaddr A Kerberos address to store tha address in.
148 * @return True on success, false if an error occurred.
150 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
151 krb5_address *pkaddr)
153 memset(pkaddr, '\0', sizeof(krb5_address));
155 if (paddr->ss_family == AF_INET6) {
156 pkaddr->addr_type = KRB5_ADDRESS_INET6;
157 pkaddr->address.length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
158 pkaddr->address.data = (char *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
162 if (paddr->ss_family == AF_INET) {
163 pkaddr->addr_type = KRB5_ADDRESS_INET;
164 pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
165 pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
170 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
174 * @brief Stores the address of a 'struct sockaddr_storage' a krb5_address
176 * @param[in] paddr A pointer to a 'struct sockaddr_storage to extract the
179 * @param[in] pkaddr A Kerberos address to store tha address in.
181 * @return True on success, false if an error occurred.
183 bool smb_krb5_sockaddr_to_kaddr(struct sockaddr_storage *paddr,
184 krb5_address *pkaddr)
186 memset(pkaddr, '\0', sizeof(krb5_address));
188 if (paddr->ss_family == AF_INET6) {
189 pkaddr->addrtype = ADDRTYPE_INET6;
190 pkaddr->length = sizeof(((struct sockaddr_in6 *)paddr)->sin6_addr);
191 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in6 *)paddr)->sin6_addr);
195 if (paddr->ss_family == AF_INET) {
196 pkaddr->addrtype = ADDRTYPE_INET;
197 pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
198 pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
204 #error UNKNOWN_ADDRTYPE
207 krb5_error_code smb_krb5_mk_error(krb5_context context,
208 krb5_error_code error_code,
211 const krb5_principal client,
212 const krb5_principal server,
215 krb5_error_code code = EINVAL;
216 #ifdef SAMBA4_USES_HEIMDAL
217 code = krb5_mk_error(context,
223 NULL, /* client_time */
224 NULL, /* client_usec */
227 krb5_principal unspec_server = NULL;
233 code = krb5_us_timeofday(context,
240 errpkt.error = error_code;
242 errpkt.text.length = 0;
243 if (e_text != NULL) {
244 errpkt.text.length = strlen(e_text);
245 errpkt.text.data = discard_const_p(char, e_text);
248 errpkt.e_data.magic = KV5M_DATA;
249 errpkt.e_data.length = 0;
250 errpkt.e_data.data = NULL;
251 if (e_data != NULL) {
252 errpkt.e_data = *e_data;
255 errpkt.client = client;
257 if (server != NULL) {
258 errpkt.server = server;
260 code = smb_krb5_make_principal(context,
262 "<unspecified realm>",
267 errpkt.server = unspec_server;
270 code = krb5_mk_error(context,
273 krb5_free_principal(context, unspec_server);
279 * @brief Create a keyblock based on input parameters
281 * @param context The krb5_context
282 * @param host_princ The krb5_principal to use
283 * @param salt The optional salt, if omitted, salt is calculated with
284 * the provided principal.
285 * @param password The krb5_data containing the password
286 * @param enctype The krb5_enctype to use for the keyblock generation
287 * @param key The returned krb5_keyblock, caller needs to free with
288 * krb5_free_keyblock().
290 * @return krb5_error_code
292 int smb_krb5_create_key_from_string(krb5_context context,
293 krb5_const_principal host_princ,
296 krb5_enctype enctype,
301 if (host_princ == NULL && salt == NULL) {
305 if ((int)enctype == (int)ENCTYPE_ARCFOUR_HMAC) {
306 TALLOC_CTX *frame = talloc_stackframe();
307 uint8_t *utf16 = NULL;
308 size_t utf16_size = 0;
312 ok = convert_string_talloc(frame, CH_UNIX, CH_UTF16LE,
313 password->data, password->length,
314 (void **)&utf16, &utf16_size);
324 mdfour(nt_hash, utf16, utf16_size);
325 memset(utf16, 0, utf16_size);
326 ret = smb_krb5_keyblock_init_contents(context,
327 ENCTYPE_ARCFOUR_HMAC,
331 ZERO_STRUCT(nt_hash);
341 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_C_STRING_TO_KEY)
346 ret = krb5_principal2salt(context, host_princ, &_salt);
348 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
354 ret = krb5_c_string_to_key(context, enctype, password, &_salt, key);
356 SAFE_FREE(_salt.data);
359 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
364 ret = krb5_get_pw_salt(context, host_princ, &_salt);
366 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
370 _salt.saltvalue = *salt;
371 _salt.salttype = KRB5_PW_SALT;
374 ret = krb5_string_to_key_salt(context, enctype, (const char *)password->data, _salt, key);
376 krb5_free_salt(context, _salt);
380 #error UNKNOWN_CREATE_KEY_FUNCTIONS
386 * @brief Create a salt for a given principal
388 * @param context The initialized krb5_context
389 * @param host_princ The krb5_principal to create the salt for
390 * @param psalt A pointer to a krb5_data struct
392 * caller has to free the contents of psalt with smb_krb5_free_data_contents
393 * when function has succeeded
395 * @return krb5_error_code, returns 0 on success, error code otherwise
398 int smb_krb5_get_pw_salt(krb5_context context,
399 krb5_const_principal host_princ,
401 #if defined(HAVE_KRB5_GET_PW_SALT)
407 ret = krb5_get_pw_salt(context, host_princ, &salt);
412 psalt->data = salt.saltvalue.data;
413 psalt->length = salt.saltvalue.length;
417 #elif defined(HAVE_KRB5_PRINCIPAL2SALT)
420 return krb5_principal2salt(context, host_princ, psalt);
423 #error UNKNOWN_SALT_FUNCTIONS
427 * @brief This constructs the salt principal used by active directory
429 * Most Kerberos encryption types require a salt in order to
430 * calculate the long term private key for user/computer object
431 * based on a password.
433 * The returned _salt_principal is a string in forms like this:
434 * - host/somehost.example.com@EXAMPLE.COM
435 * - SomeAccount@EXAMPLE.COM
436 * - SomePrincipal@EXAMPLE.COM
438 * This is not the form that's used as salt, it's just
439 * the human readable form. It needs to be converted by
440 * smb_krb5_salt_principal2data().
442 * @param[in] realm The realm the user/computer is added too.
444 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
446 * @param[in] userPrincipalName The userPrincipalName attribute of the object
447 * or NULL is not available.
449 * @param[in] uac_flags UF_ACCOUNT_TYPE_MASKed userAccountControl field
451 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
453 * @param[out] _salt_principal The resulting principal as string.
455 * @retval 0 Success; otherwise - Kerberos error codes
457 * @see smb_krb5_salt_principal2data
459 int smb_krb5_salt_principal(const char *realm,
460 const char *sAMAccountName,
461 const char *userPrincipalName,
464 char **_salt_principal)
466 TALLOC_CTX *frame = talloc_stackframe();
467 char *upper_realm = NULL;
468 const char *principal = NULL;
469 int principal_len = 0;
471 *_salt_principal = NULL;
473 if (sAMAccountName == NULL) {
483 if (uac_flags & ~UF_ACCOUNT_TYPE_MASK) {
485 * catch callers which still
491 if (uac_flags == 0) {
493 * catch callers which still
500 upper_realm = strupper_talloc(frame, realm);
501 if (upper_realm == NULL) {
506 /* Many, many thanks to lukeh@padl.com for this
507 * algorithm, described in his Nov 10 2004 mail to
508 * samba-technical@lists.samba.org */
511 * Determine a salting principal
513 if (uac_flags & UF_TRUST_ACCOUNT_MASK) {
514 int computer_len = 0;
517 computer_len = strlen(sAMAccountName);
518 if (sAMAccountName[computer_len-1] == '$') {
522 if (uac_flags & UF_INTERDOMAIN_TRUST_ACCOUNT) {
523 principal = talloc_asprintf(frame, "krbtgt/%*.*s",
524 computer_len, computer_len,
526 if (principal == NULL) {
532 tmp = talloc_asprintf(frame, "host/%*.*s.%s",
533 computer_len, computer_len,
534 sAMAccountName, realm);
540 principal = strlower_talloc(frame, tmp);
542 if (principal == NULL) {
548 principal_len = strlen(principal);
550 } else if (userPrincipalName != NULL) {
553 principal = userPrincipalName;
554 p = strchr(principal, '@');
556 principal_len = PTR_DIFF(p, principal);
558 principal_len = strlen(principal);
561 principal = sAMAccountName;
562 principal_len = strlen(principal);
565 *_salt_principal = talloc_asprintf(mem_ctx, "%*.*s@%s",
566 principal_len, principal_len,
567 principal, upper_realm);
568 if (*_salt_principal == NULL) {
578 * @brief Converts the salt principal string into the salt data blob
580 * This function takes a salt_principal as string in forms like this:
581 * - host/somehost.example.com@EXAMPLE.COM
582 * - SomeAccount@EXAMPLE.COM
583 * - SomePrincipal@EXAMPLE.COM
585 * It generates values like:
586 * - EXAMPLE.COMhost/somehost.example.com
587 * - EXAMPLE.COMSomeAccount
588 * - EXAMPLE.COMSomePrincipal
590 * @param[in] realm The realm the user/computer is added too.
592 * @param[in] sAMAccountName The sAMAccountName attribute of the object.
594 * @param[in] userPrincipalName The userPrincipalName attribute of the object
595 * or NULL is not available.
597 * @param[in] is_computer The indication of the object includes
598 * objectClass=computer.
600 * @param[in] mem_ctx The TALLOC_CTX to allocate _salt_principal.
602 * @param[out] _salt_principal The resulting principal as string.
604 * @retval 0 Success; otherwise - Kerberos error codes
606 * @see smb_krb5_salt_principal
608 int smb_krb5_salt_principal2data(krb5_context context,
609 const char *salt_principal,
614 krb5_principal salt_princ = NULL;
619 ret = krb5_parse_name(context, salt_principal, &salt_princ);
624 ret = smb_krb5_get_pw_salt(context, salt_princ, &salt);
625 krb5_free_principal(context, salt_princ);
630 *_salt_data = talloc_strndup(mem_ctx,
633 smb_krb5_free_data_contents(context, &salt);
634 if (*_salt_data == NULL) {
641 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
643 * @brief Get a list of encryption types allowed for session keys
645 * @param[in] context The library context
647 * @param[in] enctypes An allocated, zero-terminated list of encryption types
649 * This function returns an allocated list of encryption types allowed for
652 * Use free() to free the enctypes when it is no longer needed.
654 * @retval 0 Success; otherwise - Kerberos error codes
656 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
657 krb5_enctype **enctypes)
659 return krb5_get_permitted_enctypes(context, enctypes);
661 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
662 krb5_error_code smb_krb5_get_allowed_etypes(krb5_context context,
663 krb5_enctype **enctypes)
665 #ifdef HAVE_KRB5_PDU_NONE_DECL
666 return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, enctypes);
668 return krb5_get_default_in_tkt_etypes(context, enctypes);
672 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
677 * @brief Convert a string principal name to a Kerberos principal.
679 * @param[in] context The library context
681 * @param[in] name The principal as a unix charset string.
683 * @param[out] principal The newly allocated principal.
685 * Use krb5_free_principal() to free a principal when it is no longer needed.
687 * @return 0 on success, a Kerberos error code otherwise.
689 krb5_error_code smb_krb5_parse_name(krb5_context context,
691 krb5_principal *principal)
695 size_t converted_size;
696 TALLOC_CTX *frame = talloc_stackframe();
698 if (!push_utf8_talloc(frame, &utf8_name, name, &converted_size)) {
703 ret = krb5_parse_name(context, utf8_name, principal);
709 * @brief Convert a Kerberos principal structure to a string representation.
711 * The resulting string representation will be a unix charset name and is
714 * @param[in] mem_ctx The talloc context to allocate memory on.
716 * @param[in] context The library context.
718 * @param[in] principal The principal.
720 * @param[out] unix_name A string representation of the princpial name as with
723 * Use talloc_free() to free the string representation if it is no longer
726 * @return 0 on success, a Kerberos error code otherwise.
728 krb5_error_code smb_krb5_unparse_name(TALLOC_CTX *mem_ctx,
729 krb5_context context,
730 krb5_const_principal principal,
735 size_t converted_size;
738 ret = krb5_unparse_name(context, principal, &utf8_name);
743 if (!pull_utf8_talloc(mem_ctx, unix_name, utf8_name, &converted_size)) {
744 krb5_free_unparsed_name(context, utf8_name);
747 krb5_free_unparsed_name(context, utf8_name);
752 * @brief Free the contents of a krb5_data structure and zero the data field.
754 * @param[in] context The krb5 context
756 * @param[in] pdata The data structure to free contents of
758 * This function frees the contents, not the structure itself.
760 void smb_krb5_free_data_contents(krb5_context context, krb5_data *pdata)
762 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
764 krb5_free_data_contents(context, pdata);
766 #elif defined(HAVE_KRB5_DATA_FREE)
767 krb5_data_free(context, pdata);
769 SAFE_FREE(pdata->data);
774 * @brief copy a buffer into a krb5_data struct
776 * @param[in] p The krb5_data
777 * @param[in] data The data to copy
778 * @param[in] length The length of the data to copy
779 * @return krb5_error_code
781 * Caller has to free krb5_data with smb_krb5_free_data_contents().
783 krb5_error_code smb_krb5_copy_data_contents(krb5_data *p,
787 #if defined(HAVE_KRB5_DATA_COPY)
788 return krb5_data_copy(p, data, len);
791 p->data = malloc(len);
792 if (p->data == NULL) {
795 memmove(p->data, data, len);
800 p->magic = KV5M_DATA;
805 bool smb_krb5_get_smb_session_key(TALLOC_CTX *mem_ctx,
806 krb5_context context,
807 krb5_auth_context auth_context,
808 DATA_BLOB *session_key,
811 krb5_keyblock *skey = NULL;
812 krb5_error_code err = 0;
816 #ifdef HAVE_KRB5_AUTH_CON_GETRECVSUBKEY
817 err = krb5_auth_con_getrecvsubkey(context,
820 #else /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
821 err = krb5_auth_con_getremotesubkey(context,
822 auth_context, &skey);
823 #endif /* HAVE_KRB5_AUTH_CON_GETRECVSUBKEY */
825 #ifdef HAVE_KRB5_AUTH_CON_GETSENDSUBKEY
826 err = krb5_auth_con_getsendsubkey(context,
829 #else /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
830 err = krb5_auth_con_getlocalsubkey(context,
831 auth_context, &skey);
832 #endif /* HAVE_KRB5_AUTH_CON_GETSENDSUBKEY */
835 if (err || skey == NULL) {
836 DEBUG(10, ("KRB5 error getting session key %d\n", err));
840 DEBUG(10, ("Got KRB5 session key of length %d\n",
841 (int)KRB5_KEY_LENGTH(skey)));
843 *session_key = data_blob_talloc(mem_ctx,
845 KRB5_KEY_LENGTH(skey));
846 dump_data_pw("KRB5 Session Key:\n",
848 session_key->length);
854 krb5_free_keyblock(context, skey);
862 * @brief Get talloced string component of a principal
864 * @param[in] mem_ctx The TALLOC_CTX
865 * @param[in] context The krb5_context
866 * @param[in] principal The principal
867 * @param[in] component The component
868 * @return string component
870 * Caller must talloc_free if the return value is not NULL.
873 char *smb_krb5_principal_get_comp_string(TALLOC_CTX *mem_ctx,
874 krb5_context context,
875 krb5_const_principal principal,
876 unsigned int component)
878 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
879 return talloc_strdup(mem_ctx, krb5_principal_get_comp_string(context, principal, component));
883 if (component >= krb5_princ_size(context, principal)) {
887 data = krb5_princ_component(context, principal, component);
892 return talloc_strndup(mem_ctx, data->data, data->length);
899 * @param[in] ccache_string A string pointing to the cache to renew the ticket
900 * (e.g. FILE:/tmp/krb5cc_0) or NULL. If the principal
901 * ccache has not been specified, the default ccache
904 * @param[in] client_string The client principal string (e.g. user@SAMBA.SITE)
905 * or NULL. If the principal string has not been
906 * specified, the principal from the ccache will be
909 * @param[in] service_string The service ticket string
910 * (e.g. krbtgt/SAMBA.SITE@SAMBA.SITE) or NULL. If
911 * the sevice ticket is specified, it is parsed (
912 * with the realm part ignored) and used as the
913 * server principal of the credential. Otherwise
914 * the ticket-granting service is used.
916 * @param[in] expire_time A pointer to store the credentials end time or
919 * @return 0 on Succes, a Kerberos error code otherwise.
921 krb5_error_code smb_krb5_renew_ticket(const char *ccache_string,
922 const char *client_string,
923 const char *service_string,
927 krb5_context context = NULL;
928 krb5_ccache ccache = NULL;
929 krb5_principal client = NULL;
930 krb5_creds creds, creds_in;
933 ZERO_STRUCT(creds_in);
935 initialize_krb5_error_table();
936 ret = krb5_init_context(&context);
941 if (!ccache_string) {
942 ccache_string = krb5_cc_default_name(context);
945 if (!ccache_string) {
950 DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
952 /* FIXME: we should not fall back to defaults */
953 ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
959 ret = smb_krb5_parse_name(context, client_string, &client);
964 ret = krb5_cc_get_principal(context, ccache, &client);
970 ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
972 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
976 /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
977 ret = krb5_cc_initialize(context, ccache, client);
982 ret = krb5_cc_store_cred(context, ccache, &creds);
985 *expire_time = (time_t) creds.times.endtime;
989 krb5_free_cred_contents(context, &creds_in);
990 krb5_free_cred_contents(context, &creds);
993 krb5_free_principal(context, client);
996 krb5_cc_close(context, ccache);
999 krb5_free_context(context);
1006 * @brief Free the data stored in an smb_krb5_addresses structure.
1008 * @param[in] context The library context
1010 * @param[in] addr The address structure to free.
1012 * @return 0 on success, a Kerberos error code otherwise.
1014 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1015 smb_krb5_addresses *addr)
1017 krb5_error_code ret = 0;
1021 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1022 krb5_free_addresses(context, addr->addrs);
1023 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1024 ret = krb5_free_addresses(context, addr->addrs);
1025 SAFE_FREE(addr->addrs);
1032 #define MAX_NETBIOSNAME_LEN 16
1035 * @brief Add a netbios name to the array of addresses
1037 * @param[in] kerb_addr A pointer to the smb_krb5_addresses to add the
1040 * @param[in] netbios_name The netbios name to add.
1042 * @return 0 on success, a Kerberos error code otherwise.
1044 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1045 const char *netbios_name)
1047 krb5_error_code ret = 0;
1048 char buf[MAX_NETBIOSNAME_LEN];
1050 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1051 krb5_address **addrs = NULL;
1052 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1053 krb5_addresses *addrs = NULL;
1056 *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1057 if (*kerb_addr == NULL) {
1061 /* temporarily duplicate put_name() code here to avoid dependency
1062 * issues for a 5 lines function */
1063 len = strlen(netbios_name);
1064 memcpy(buf, netbios_name,
1065 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1066 if (len < MAX_NETBIOSNAME_LEN - 1) {
1067 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1069 buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1071 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1075 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1076 if (addrs == NULL) {
1077 SAFE_FREE(*kerb_addr);
1081 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1083 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1084 if (addrs[0] == NULL) {
1086 SAFE_FREE(*kerb_addr);
1090 addrs[0]->magic = KV5M_ADDRESS;
1091 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1092 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1093 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1094 if (addrs[0]->contents == NULL) {
1095 SAFE_FREE(addrs[0]);
1097 SAFE_FREE(*kerb_addr);
1101 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1105 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1107 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1108 if (addrs == NULL) {
1109 SAFE_FREE(*kerb_addr);
1113 memset(addrs, 0, sizeof(krb5_addresses));
1116 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1117 if (addrs->val == NULL) {
1119 SAFE_FREE(*kerb_addr);
1123 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1124 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1125 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1126 if (addrs->val[0].address.data == NULL) {
1127 SAFE_FREE(addrs->val);
1129 SAFE_FREE(*kerb_addr);
1133 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1136 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1138 (*kerb_addr)->addrs = addrs;
1144 * @brief Get the enctype from a key table entry
1146 * @param[in] kt_entry Key table entry to get the enctype from.
1148 * @return The enctype from the entry.
1150 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1152 return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1156 * @brief Free the contents of a key table entry.
1158 * @param[in] context The library context.
1160 * @param[in] kt_entry The key table entry to free the contents of.
1162 * @return 0 on success, a Kerberos error code otherwise.
1164 * The pointer itself is not freed.
1166 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1167 krb5_keytab_entry *kt_entry)
1169 /* Try krb5_free_keytab_entry_contents first, since
1170 * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1171 * krb5_kt_free_entry but only has a prototype for the first, while the
1172 * second is considered private.
1174 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1175 return krb5_free_keytab_entry_contents(context, kt_entry);
1176 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1177 return krb5_kt_free_entry(context, kt_entry);
1179 #error UNKNOWN_KT_FREE_FUNCTION
1185 * @brief Convert an encryption type to a string.
1187 * @param[in] context The library context.
1189 * @param[in] enctype The encryption type.
1191 * @param[in] etype_s A pointer to store the allocated encryption type as a
1194 * @return 0 on success, a Kerberos error code otherwise.
1196 * The caller needs to free the allocated string etype_s.
1198 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1199 krb5_enctype enctype,
1202 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1203 return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1204 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1206 krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1210 *etype_s = SMB_STRDUP(buf);
1216 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1220 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1221 #ifndef MAX_KEYTAB_NAME_LEN
1222 #define MAX_KEYTAB_NAME_LEN 1100
1226 * @brief Open a key table readonly or with readwrite access.
1228 * Allows one to use a different keytab than the default one using a relative
1229 * path to the keytab.
1231 * @param[in] context The library context
1233 * @param[in] keytab_name_req The path to the key table.
1235 * @param[in] write_access Open with readwrite access.
1237 * @param[in] keytab A pointer o the opended key table.
1239 * The keytab pointer should be freed using krb5_kt_close().
1241 * @return 0 on success, a Kerberos error code otherwise.
1243 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1244 const char *keytab_name_req,
1246 krb5_keytab *keytab)
1248 krb5_error_code ret = 0;
1249 TALLOC_CTX *mem_ctx;
1250 char keytab_string[MAX_KEYTAB_NAME_LEN];
1251 char *kt_str = NULL;
1252 bool found_valid_name = false;
1253 const char *pragma = "FILE";
1254 const char *tmp = NULL;
1256 if (!write_access && !keytab_name_req) {
1257 /* caller just wants to read the default keytab readonly, so be it */
1258 return krb5_kt_default(context, keytab);
1261 mem_ctx = talloc_init("smb_krb5_open_keytab");
1266 #ifdef HAVE_WRFILE_KEYTAB
1272 if (keytab_name_req) {
1274 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1275 ret = KRB5_CONFIG_NOTENUFSPACE;
1279 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1280 (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1281 tmp = keytab_name_req;
1285 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1294 /* we need to handle more complex keytab_strings, like:
1295 * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1297 ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1302 DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1304 tmp = talloc_strdup(mem_ctx, keytab_string);
1310 if (strncmp(tmp, "ANY:", 4) == 0) {
1314 memset(&keytab_string, '\0', sizeof(keytab_string));
1316 while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1317 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1318 found_valid_name = true;
1323 if (strncmp(kt_str, "FILE:", 5) == 0) {
1324 found_valid_name = true;
1329 if (tmp[0] == '/') {
1330 /* Treat as a FILE: keytab definition. */
1331 found_valid_name = true;
1334 if (found_valid_name) {
1335 if (tmp[0] != '/') {
1336 ret = KRB5_KT_BADNAME;
1340 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1349 if (!found_valid_name) {
1350 ret = KRB5_KT_UNKNOWN_TYPE;
1355 DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1356 ret = krb5_kt_resolve(context, tmp, keytab);
1359 TALLOC_FREE(mem_ctx);
1364 * @brief Open a key table readonly or with readwrite access.
1366 * Allows one to use a different keytab than the default one. The path needs to be
1367 * an absolute path or an error will be returned.
1369 * @param[in] context The library context
1371 * @param[in] keytab_name_req The path to the key table.
1373 * @param[in] write_access Open with readwrite access.
1375 * @param[in] keytab A pointer o the opended key table.
1377 * The keytab pointer should be freed using krb5_kt_close().
1379 * @return 0 on success, a Kerberos error code otherwise.
1381 krb5_error_code smb_krb5_kt_open(krb5_context context,
1382 const char *keytab_name_req,
1384 krb5_keytab *keytab)
1388 if (keytab_name_req == NULL) {
1389 return KRB5_KT_BADNAME;
1392 if (keytab_name_req[0] == '/') {
1396 cmp = strncmp(keytab_name_req, "FILE:/", 6);
1401 cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1406 DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1408 return KRB5_KT_BADNAME;
1411 return smb_krb5_kt_open_relative(context,
1418 * @brief Get a key table name.
1420 * @param[in] mem_ctx The talloc context to use for allocation.
1422 * @param[in] context The library context.
1424 * @param[in] keytab The key table to get the name from.
1426 * @param[in] keytab_name A talloc'ed string of the key table name.
1428 * The talloc'ed name string needs to be freed with talloc_free().
1430 * @return 0 on success, a Kerberos error code otherwise.
1432 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1433 krb5_context context,
1435 const char **keytab_name)
1437 char keytab_string[MAX_KEYTAB_NAME_LEN];
1438 krb5_error_code ret = 0;
1440 ret = krb5_kt_get_name(context, keytab,
1441 keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1446 *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1447 if (!*keytab_name) {
1455 * @brief Seek and delete old entries in a keytab based on the passed
1458 * @param[in] context The KRB5 context to use.
1460 * @param[in] keytab The keytab to operate on.
1462 * @param[in] kvno The kvnco to use.
1464 * @param[in] princ_s The principal as a string to search for.
1466 * @param[in] princ The principal as a krb5_principal to search for.
1468 * @param[in] flush Weather to flush the complete keytab.
1470 * @param[in] keep_old_entries Keep the entry with the previous kvno.
1472 * @retval 0 on Sucess
1474 * @return An appropriate KRB5 error code.
1476 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1479 krb5_enctype enctype,
1480 const char *princ_s,
1481 krb5_principal princ,
1483 bool keep_old_entries)
1485 krb5_error_code ret;
1486 krb5_kt_cursor cursor;
1487 krb5_keytab_entry kt_entry;
1488 char *ktprinc = NULL;
1489 krb5_kvno old_kvno = kvno - 1;
1490 TALLOC_CTX *tmp_ctx;
1492 ZERO_STRUCT(cursor);
1493 ZERO_STRUCT(kt_entry);
1495 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1496 if (ret == KRB5_KT_END || ret == ENOENT ) {
1501 tmp_ctx = talloc_new(NULL);
1502 if (tmp_ctx == NULL) {
1506 DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1507 while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1508 bool name_ok = false;
1509 krb5_enctype kt_entry_enctype =
1510 smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1512 if (!flush && (princ_s != NULL)) {
1513 ret = smb_krb5_unparse_name(tmp_ctx, context,
1517 DEBUG(1, (__location__
1518 ": smb_krb5_unparse_name failed "
1519 "(%s)\n", error_message(ret)));
1523 #ifdef HAVE_KRB5_KT_COMPARE
1524 name_ok = krb5_kt_compare(context, &kt_entry,
1527 name_ok = (strcmp(ktprinc, princ_s) == 0);
1531 DEBUG(10, (__location__ ": ignoring keytab "
1532 "entry principal %s, kvno = %d\n",
1533 ktprinc, kt_entry.vno));
1536 * just free this entry and continue. */
1537 ret = smb_krb5_kt_free_entry(context,
1539 ZERO_STRUCT(kt_entry);
1541 DEBUG(1, (__location__
1542 ": smb_krb5_kt_free_entry "
1544 error_message(ret)));
1548 TALLOC_FREE(ktprinc);
1552 TALLOC_FREE(ktprinc);
1555 /*------------------------------------------------------------
1556 * Save the entries with kvno - 1. This is what microsoft does
1557 * to allow people with existing sessions that have kvno - 1
1558 * to still work. Otherwise, when the password for the machine
1559 * changes, all kerberizied sessions will 'break' until either
1560 * the client reboots or the client's session key expires and
1561 * they get a new session ticket with the new kvno.
1562 * Some keytab files only store the kvno in 8bits, limit
1563 * the compare accordingly.
1566 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1567 DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1568 "entry for principal: %s.\n",
1569 old_kvno, princ_s));
1573 if (keep_old_entries) {
1574 DEBUG(5, (__location__ ": Saving old (kvno %d) "
1575 "entry for principal: %s.\n",
1581 ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1582 (kt_entry_enctype != enctype))
1584 DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1585 "enctype [%d] for principal: %s.\n",
1586 kvno, kt_entry_enctype, princ_s));
1590 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1591 "(kvno %d) - trying to remove it.\n",
1592 princ_s, kt_entry.vno));
1594 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1595 ZERO_STRUCT(cursor);
1597 DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1598 "failed (%s)\n", error_message(ret)));
1601 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1603 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1604 "failed (%s)\n", error_message(ret)));
1608 DEBUG(5, (__location__ ": removed old entry for principal: "
1609 "%s (kvno %d).\n", princ_s, kt_entry.vno));
1611 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1613 DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1614 "(%s)\n", error_message(ret)));
1617 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1618 ZERO_STRUCT(kt_entry);
1620 DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1621 "failed (%s)\n", error_message(ret)));
1627 talloc_free(tmp_ctx);
1628 if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1629 smb_krb5_kt_free_entry(context, &kt_entry);
1631 if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1632 krb5_kt_end_seq_get(context, keytab, &cursor);
1638 * @brief Add a keytab entry for the given principal
1640 * @param[in] context The krb5 context to use.
1642 * @param[in] keytab The keytab to add the entry to.
1644 * @param[in] kvno The kvno to use.
1646 * @param[in] princ_s The principal as a string.
1648 * @param[in] salt_principal The salt principal to salt the password with.
1649 * Only needed for keys which support salting.
1650 * If no salt is used set no_salt to false and
1653 * @param[in] enctype The encryption type of the keytab entry.
1655 * @param[in] password The password of the keytab entry.
1657 * @param[in] no_salt If the password should not be salted. Normally
1658 * this is only set to false for encryption types
1659 * which do not support salting like RC4.
1661 * @param[in] keep_old_entries Wether to keep or delte old keytab entries.
1663 * @retval 0 on Success
1665 * @return A corresponding KRB5 error code.
1667 * @see smb_krb5_kt_open()
1669 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1672 const char *princ_s,
1673 const char *salt_principal,
1674 krb5_enctype enctype,
1675 krb5_data *password,
1677 bool keep_old_entries)
1679 krb5_error_code ret;
1680 krb5_keytab_entry kt_entry;
1681 krb5_principal princ = NULL;
1682 krb5_keyblock *keyp;
1684 ZERO_STRUCT(kt_entry);
1686 ret = smb_krb5_parse_name(context, princ_s, &princ);
1688 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1689 "failed (%s)\n", princ_s, error_message(ret)));
1693 /* Seek and delete old keytab entries */
1694 ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1706 /* If we get here, we have deleted all the old entries with kvno's
1707 * not equal to the current kvno-1. */
1709 keyp = KRB5_KT_KEY(&kt_entry);
1712 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1713 if (KRB5_KEY_DATA(keyp) == NULL) {
1717 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1718 KRB5_KEY_LENGTH(keyp) = password->length;
1719 KRB5_KEY_TYPE(keyp) = enctype;
1721 krb5_principal salt_princ = NULL;
1723 /* Now add keytab entries for all encryption types */
1724 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1726 DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1727 salt_principal, error_message(ret));
1731 ret = smb_krb5_create_key_from_string(context,
1737 krb5_free_principal(context, salt_princ);
1743 kt_entry.principal = princ;
1744 kt_entry.vno = kvno;
1746 DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1747 "encryption type (%d) and version (%d)\n",
1748 princ_s, enctype, kt_entry.vno));
1749 ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1750 krb5_free_keyblock_contents(context, keyp);
1751 ZERO_STRUCT(kt_entry);
1753 DEBUG(1, (__location__ ": adding entry to keytab "
1754 "failed (%s)\n", error_message(ret)));
1760 krb5_free_principal(context, princ);
1766 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1767 defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1768 defined(HAVE_KRB5_GET_CREDS)
1769 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1772 krb5_principal server,
1773 krb5_principal impersonate_princ,
1774 krb5_creds **out_creds)
1776 krb5_error_code ret;
1777 krb5_get_creds_opt opt;
1779 ret = krb5_get_creds_opt_alloc(context, &opt);
1783 krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1785 if (impersonate_princ) {
1786 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1793 ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1800 krb5_get_creds_opt_free(context, opt);
1804 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1806 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1808 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1809 krb5_error_code KRB5_CALLCONV
1810 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1811 krb5_ccache ccache, krb5_creds *in_creds,
1812 krb5_data *subject_cert,
1813 krb5_creds **out_creds);
1814 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1816 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1819 krb5_principal server,
1820 krb5_principal impersonate_princ,
1821 krb5_creds **out_creds)
1823 krb5_error_code ret;
1824 krb5_creds in_creds;
1826 ZERO_STRUCT(in_creds);
1828 if (impersonate_princ) {
1830 in_creds.server = me;
1831 in_creds.client = impersonate_princ;
1833 ret = krb5_get_credentials_for_user(context,
1834 0, /* krb5_flags options */
1837 NULL, /* krb5_data *subject_cert */
1840 in_creds.client = me;
1841 in_creds.server = server;
1843 ret = krb5_get_credentials(context, 0, ccache,
1844 &in_creds, out_creds);
1849 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1852 * smb_krb5_get_credentials
1854 * @brief Get krb5 credentials for a server
1856 * @param[in] context An initialized krb5_context
1857 * @param[in] ccache An initialized krb5_ccache
1858 * @param[in] me The krb5_principal of the caller
1859 * @param[in] server The krb5_principal of the requested service
1860 * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1861 * @param[out] out_creds The returned krb5_creds structure
1862 * @return krb5_error_code
1865 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1868 krb5_principal server,
1869 krb5_principal impersonate_princ,
1870 krb5_creds **out_creds)
1872 krb5_error_code ret;
1873 krb5_creds *creds = NULL;
1875 if (out_creds != NULL) {
1879 if (impersonate_princ) {
1880 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1881 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1882 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1883 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1888 krb5_creds in_creds;
1890 ZERO_STRUCT(in_creds);
1892 in_creds.client = me;
1893 in_creds.server = server;
1895 ret = krb5_get_credentials(context, 0, ccache,
1908 krb5_free_creds(context, creds);
1915 * @brief Initialize a krb5_keyblock with the given data.
1917 * Initialized a new keyblock, allocates the contents fo the key and
1918 * copies the data into the keyblock.
1920 * @param[in] context The library context
1922 * @param[in] enctype The encryption type.
1924 * @param[in] data The date to initialize the keyblock with.
1926 * @param[in] length The length of the keyblock.
1928 * @param[in] key Newly allocated keyblock structure.
1930 * The key date must be freed using krb5_free_keyblock_contents() when it is
1933 * @return 0 on success, a Kerberos error code otherwise.
1935 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1936 krb5_enctype enctype,
1941 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1942 return krb5_keyblock_init(context, enctype, data, length, key);
1944 memset(key, 0, sizeof(krb5_keyblock));
1945 KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1946 if (NULL == KRB5_KEY_DATA(key)) {
1949 memcpy(KRB5_KEY_DATA(key), data, length);
1950 KRB5_KEY_LENGTH(key) = length;
1951 KRB5_KEY_TYPE(key) = enctype;
1957 * @brief Simulate a kinit by putting the tgt in the given credential cache.
1959 * This function uses a keyblock rather than needing the original password.
1961 * @param[in] ctx The library context
1963 * @param[in] cc The credential cache to put the tgt in.
1965 * @param[in] principal The client princial
1967 * @param[in] keyblock The keyblock to use.
1969 * @param[in] target_service The service name of the initial credentials (or NULL).
1971 * @param[in] krb_options Initial credential options.
1973 * @param[in] expire_time A pointer to store the experation time of the
1974 * credentials (or NULL).
1976 * @param[in] kdc_time A pointer to store the time when the ticket becomes
1979 * @return 0 on success, a Kerberos error code otherwise.
1981 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
1983 krb5_principal principal,
1984 krb5_keyblock *keyblock,
1985 const char *target_service,
1986 krb5_get_init_creds_opt *krb_options,
1987 time_t *expire_time,
1990 krb5_error_code code = 0;
1991 krb5_creds my_creds;
1993 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1994 code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1995 keyblock, 0, target_service,
1997 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1999 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
2000 char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
2001 krb5_keytab_entry entry;
2005 memset(&entry, 0, sizeof(entry));
2006 entry.principal = principal;
2007 *(KRB5_KT_KEY(&entry)) = *keyblock;
2009 memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
2010 mask = umask(S_IRWXO | S_IRWXG);
2013 if (tmp_name[0] == 0) {
2014 return KRB5_KT_BADNAME;
2016 code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2021 code = krb5_kt_add_entry(ctx, keytab, &entry);
2023 (void)krb5_kt_close(ctx, keytab);
2027 code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2028 keytab, 0, target_service,
2030 (void)krb5_kt_close(ctx, keytab);
2033 #error krb5_get_init_creds_keyblock not available!
2039 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2041 * We need to store the principal as returned from the KDC to the
2042 * credentials cache. If we don't do that the KRB5 library is not
2043 * able to find the tickets it is looking for
2045 principal = my_creds.client;
2047 code = krb5_cc_initialize(ctx, cc, principal);
2052 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2058 *expire_time = (time_t) my_creds.times.endtime;
2062 *kdc_time = (time_t) my_creds.times.starttime;
2067 krb5_free_cred_contents(ctx, &my_creds);
2072 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2074 * @param[in] ctx The library context
2076 * @param[in] cc The credential cache to put the tgt in.
2078 * @param[in] principal The client princial
2080 * @param[in] password The password (or NULL).
2082 * @param[in] target_service The service name of the initial credentials (or NULL).
2084 * @param[in] krb_options Initial credential options.
2086 * @param[in] expire_time A pointer to store the experation time of the
2087 * credentials (or NULL).
2089 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2092 * @return 0 on success, a Kerberos error code otherwise.
2094 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2096 krb5_principal principal,
2097 const char *password,
2098 const char *target_service,
2099 krb5_get_init_creds_opt *krb_options,
2100 time_t *expire_time,
2103 krb5_error_code code = 0;
2104 krb5_creds my_creds;
2106 code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2107 password, NULL, NULL, 0,
2108 target_service, krb_options);
2113 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2115 * We need to store the principal as returned from the KDC to the
2116 * credentials cache. If we don't do that the KRB5 library is not
2117 * able to find the tickets it is looking for
2119 principal = my_creds.client;
2121 code = krb5_cc_initialize(ctx, cc, principal);
2126 code = krb5_cc_store_cred(ctx, cc, &my_creds);
2132 *expire_time = (time_t) my_creds.times.endtime;
2136 *kdc_time = (time_t) my_creds.times.starttime;
2141 krb5_free_cred_contents(ctx, &my_creds);
2145 #ifdef SAMBA4_USES_HEIMDAL
2147 * @brief Simulate a kinit by putting the tgt in the given credential cache.
2149 * @param[in] ctx The library context
2151 * @param[in] cc The credential cache to store the tgt in.
2153 * @param[in] principal The initial client princial.
2155 * @param[in] password The password (or NULL).
2157 * @param[in] impersonate_principal The impersonatiion principal (or NULL).
2159 * @param[in] self_service The local service for S4U2Self if
2160 * impersonate_principal is specified).
2162 * @param[in] target_service The service name of the initial credentials
2163 * (kpasswd/REALM or a remote service). It defaults
2164 * to the krbtgt if NULL.
2166 * @param[in] krb_options Initial credential options.
2168 * @param[in] expire_time A pointer to store the experation time of the
2169 * credentials (or NULL).
2171 * @param[in] kdc_time A pointer to store the time when the ticket becomes
2174 * @return 0 on success, a Kerberos error code otherwise.
2176 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2177 krb5_ccache store_cc,
2178 krb5_principal init_principal,
2179 const char *init_password,
2180 krb5_principal impersonate_principal,
2181 const char *self_service,
2182 const char *target_service,
2183 krb5_get_init_creds_opt *krb_options,
2184 time_t *expire_time,
2187 krb5_error_code code = 0;
2188 krb5_get_creds_opt options;
2189 krb5_principal store_principal;
2190 krb5_creds store_creds;
2191 krb5_creds *s4u2self_creds;
2192 Ticket s4u2self_ticket;
2193 size_t s4u2self_ticketlen;
2194 krb5_creds *s4u2proxy_creds;
2195 krb5_principal self_princ;
2197 krb5_principal target_princ;
2199 const char *self_realm;
2200 const char *client_realm = NULL;
2201 krb5_principal blacklist_principal = NULL;
2202 krb5_principal whitelist_principal = NULL;
2204 code = krb5_get_init_creds_password(ctx, &store_creds,
2215 store_principal = init_principal;
2218 * We are trying S4U2Self now:
2220 * As we do not want to expose our TGT in the
2221 * krb5_ccache, which is also holds the impersonated creds.
2223 * Some low level krb5/gssapi function might use the TGT
2224 * identity and let the client act as our machine account.
2226 * We need to avoid that and use a temporary krb5_ccache
2227 * in order to pass our TGT to the krb5_get_creds() function.
2229 code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2231 krb5_free_cred_contents(ctx, &store_creds);
2235 code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2237 krb5_cc_destroy(ctx, tmp_cc);
2238 krb5_free_cred_contents(ctx, &store_creds);
2242 code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2244 krb5_free_cred_contents(ctx, &store_creds);
2245 krb5_cc_destroy(ctx, tmp_cc);
2250 * we need to remember the client principal of our
2251 * TGT and make sure the KDC does not return this
2252 * in the impersonated tickets. This can happen
2253 * if the KDC does not support S4U2Self and S4U2Proxy.
2255 blacklist_principal = store_creds.client;
2256 store_creds.client = NULL;
2257 krb5_free_cred_contents(ctx, &store_creds);
2260 * Check if we also need S4U2Proxy or if S4U2Self is
2261 * enough in order to get a ticket for the target.
2263 if (target_service == NULL) {
2265 } else if (strcmp(target_service, self_service) == 0) {
2272 * For S4U2Self we need our own service principal,
2273 * which belongs to our own realm (available on
2274 * our client principal).
2276 self_realm = krb5_principal_get_realm(ctx, init_principal);
2278 code = krb5_parse_name(ctx, self_service, &self_princ);
2280 krb5_free_principal(ctx, blacklist_principal);
2281 krb5_cc_destroy(ctx, tmp_cc);
2285 code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2287 krb5_free_principal(ctx, blacklist_principal);
2288 krb5_free_principal(ctx, self_princ);
2289 krb5_cc_destroy(ctx, tmp_cc);
2293 code = krb5_get_creds_opt_alloc(ctx, &options);
2295 krb5_free_principal(ctx, blacklist_principal);
2296 krb5_free_principal(ctx, self_princ);
2297 krb5_cc_destroy(ctx, tmp_cc);
2303 * If we want S4U2Proxy, we need the forwardable flag
2304 * on the S4U2Self ticket.
2306 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2309 code = krb5_get_creds_opt_set_impersonate(ctx, options,
2310 impersonate_principal);
2312 krb5_get_creds_opt_free(ctx, options);
2313 krb5_free_principal(ctx, blacklist_principal);
2314 krb5_free_principal(ctx, self_princ);
2315 krb5_cc_destroy(ctx, tmp_cc);
2319 code = krb5_get_creds(ctx, options, tmp_cc,
2320 self_princ, &s4u2self_creds);
2321 krb5_get_creds_opt_free(ctx, options);
2322 krb5_free_principal(ctx, self_princ);
2324 krb5_free_principal(ctx, blacklist_principal);
2325 krb5_cc_destroy(ctx, tmp_cc);
2330 krb5_cc_destroy(ctx, tmp_cc);
2333 * Now make sure we store the impersonated principal
2334 * and creds instead of the TGT related stuff
2335 * in the krb5_ccache of the caller.
2337 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2339 krb5_free_creds(ctx, s4u2self_creds);
2345 * It's important to store the principal the KDC
2346 * returned, as otherwise the caller would not find
2347 * the S4U2Self ticket in the krb5_ccache lookup.
2349 store_principal = store_creds.client;
2354 * We are trying S4U2Proxy:
2356 * We need the ticket from the S4U2Self step
2357 * and our TGT in order to get the delegated ticket.
2359 code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2360 s4u2self_creds->ticket.length,
2362 &s4u2self_ticketlen);
2364 krb5_free_creds(ctx, s4u2self_creds);
2365 krb5_free_principal(ctx, blacklist_principal);
2366 krb5_cc_destroy(ctx, tmp_cc);
2371 * we need to remember the client principal of the
2372 * S4U2Self stage and as it needs to match the one we
2373 * will get for the S4U2Proxy stage. We need this
2374 * in order to detect KDCs which does not support S4U2Proxy.
2376 whitelist_principal = s4u2self_creds->client;
2377 s4u2self_creds->client = NULL;
2378 krb5_free_creds(ctx, s4u2self_creds);
2381 * For S4U2Proxy we also got a target service principal,
2382 * which also belongs to our own realm (available on
2383 * our client principal).
2385 code = krb5_parse_name(ctx, target_service, &target_princ);
2387 free_Ticket(&s4u2self_ticket);
2388 krb5_free_principal(ctx, whitelist_principal);
2389 krb5_free_principal(ctx, blacklist_principal);
2390 krb5_cc_destroy(ctx, tmp_cc);
2394 code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2396 free_Ticket(&s4u2self_ticket);
2397 krb5_free_principal(ctx, target_princ);
2398 krb5_free_principal(ctx, whitelist_principal);
2399 krb5_free_principal(ctx, blacklist_principal);
2400 krb5_cc_destroy(ctx, tmp_cc);
2404 code = krb5_get_creds_opt_alloc(ctx, &options);
2406 free_Ticket(&s4u2self_ticket);
2407 krb5_free_principal(ctx, target_princ);
2408 krb5_free_principal(ctx, whitelist_principal);
2409 krb5_free_principal(ctx, blacklist_principal);
2410 krb5_cc_destroy(ctx, tmp_cc);
2414 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2415 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2417 code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2418 free_Ticket(&s4u2self_ticket);
2420 krb5_get_creds_opt_free(ctx, options);
2421 krb5_free_principal(ctx, target_princ);
2422 krb5_free_principal(ctx, whitelist_principal);
2423 krb5_free_principal(ctx, blacklist_principal);
2424 krb5_cc_destroy(ctx, tmp_cc);
2428 code = krb5_get_creds(ctx, options, tmp_cc,
2429 target_princ, &s4u2proxy_creds);
2430 krb5_get_creds_opt_free(ctx, options);
2431 krb5_free_principal(ctx, target_princ);
2432 krb5_cc_destroy(ctx, tmp_cc);
2434 krb5_free_principal(ctx, whitelist_principal);
2435 krb5_free_principal(ctx, blacklist_principal);
2440 * Now make sure we store the impersonated principal
2441 * and creds instead of the TGT related stuff
2442 * in the krb5_ccache of the caller.
2444 code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2446 krb5_free_creds(ctx, s4u2proxy_creds);
2448 krb5_free_principal(ctx, whitelist_principal);
2449 krb5_free_principal(ctx, blacklist_principal);
2454 * It's important to store the principal the KDC
2455 * returned, as otherwise the caller would not find
2456 * the S4U2Self ticket in the krb5_ccache lookup.
2458 store_principal = store_creds.client;
2461 if (blacklist_principal &&
2462 krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2466 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2470 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2474 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2475 "KDC returned self principal[%s] while impersonating [%s]\n",
2476 sp?sp:"<no memory>",
2477 ip?ip:"<no memory>"));
2482 krb5_free_principal(ctx, whitelist_principal);
2483 krb5_free_principal(ctx, blacklist_principal);
2484 krb5_free_cred_contents(ctx, &store_creds);
2485 return KRB5_FWD_BAD_PRINCIPAL;
2487 if (blacklist_principal) {
2488 krb5_free_principal(ctx, blacklist_principal);
2491 if (whitelist_principal &&
2492 !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2496 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2500 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2504 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2505 "KDC returned wrong principal[%s] we expected [%s]\n",
2506 sp?sp:"<no memory>",
2507 ep?ep:"<no memory>"));
2512 krb5_free_principal(ctx, whitelist_principal);
2513 krb5_free_cred_contents(ctx, &store_creds);
2514 return KRB5_FWD_BAD_PRINCIPAL;
2516 if (whitelist_principal) {
2517 krb5_free_principal(ctx, whitelist_principal);
2520 code = krb5_cc_initialize(ctx, store_cc, store_principal);
2522 krb5_free_cred_contents(ctx, &store_creds);
2526 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2528 krb5_free_cred_contents(ctx, &store_creds);
2532 client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2533 if (client_realm != NULL) {
2535 * Because the CANON flag doesn't have any impact
2536 * on the impersonate_principal => store_creds.client
2537 * realm mapping. We need to store the credentials twice,
2538 * once with the returned realm and once with the
2539 * realm of impersonate_principal.
2541 code = krb5_principal_set_realm(ctx, store_creds.server,
2544 krb5_free_cred_contents(ctx, &store_creds);
2548 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2550 krb5_free_cred_contents(ctx, &store_creds);
2556 *expire_time = (time_t) store_creds.times.endtime;
2560 *kdc_time = (time_t) store_creds.times.starttime;
2563 krb5_free_cred_contents(ctx, &store_creds);
2569 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2571 * @brief Create a principal name using a variable argument list.
2573 * @param[in] context The library context.
2575 * @param[inout] principal A pointer to the principal structure.
2577 * @param[in] _realm The realm to use. If NULL then the function will
2578 * get the default realm name.
2580 * @param[in] ... A list of 'char *' components, ending with NULL.
2582 * Use krb5_free_principal() to free the principal when it is no longer needed.
2584 * @return 0 on success, a Kerberos error code otherwise.
2586 krb5_error_code smb_krb5_make_principal(krb5_context context,
2587 krb5_principal *principal,
2588 const char *_realm, ...)
2590 krb5_error_code code;
2596 realm = discard_const_p(char, _realm);
2599 code = krb5_get_default_realm(context, &realm);
2606 va_start(ap, _realm);
2607 code = krb5_build_principal_alloc_va(context, principal,
2608 strlen(realm), realm,
2613 krb5_free_default_realm(context, realm);
2620 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2622 * @brief Get the lifetime of the initial ticket in the cache.
2624 * @param[in] context The kerberos context.
2626 * @param[in] id The credential cache to get the ticket lifetime.
2628 * @param[out] t A pointer to a time value to store the lifetime.
2630 * @return 0 on success, a krb5_error_code on error.
2632 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2636 krb5_cc_cursor cursor;
2637 krb5_error_code kerr;
2643 kerr = krb5_timeofday(context, &now);
2648 kerr = krb5_cc_start_seq_get(context, id, &cursor);
2653 while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2654 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2655 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2657 if (cred.flags.b.initial) {
2659 if (now < cred.times.endtime) {
2660 *t = (time_t) (cred.times.endtime - now);
2662 krb5_free_cred_contents(context, &cred);
2665 krb5_free_cred_contents(context, &cred);
2668 krb5_cc_end_seq_get(context, id, &cursor);
2672 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2674 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2675 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2677 free_Checksum(cksum);
2682 * @brief Compute a checksum operating on a keyblock.
2684 * This function computes a checksum over a PAC using the keyblock for a keyed
2687 * @param[in] mem_ctx A talloc context to alocate the signature on.
2689 * @param[in] pac_data The PAC as input.
2691 * @param[in] context The library context.
2693 * @param[in] keyblock Encryption key for a keyed checksum.
2695 * @param[out] sig_type The checksum type
2697 * @param[out] sig_blob The talloc'ed checksum
2699 * The caller must free the sig_blob with talloc_free() when it is not needed
2702 * @return 0 on success, a Kerberos error code otherwise.
2704 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2705 DATA_BLOB *pac_data,
2706 krb5_context context,
2707 const krb5_keyblock *keyblock,
2709 DATA_BLOB *sig_blob)
2711 krb5_error_code ret;
2712 krb5_checksum cksum;
2713 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2717 ret = krb5_crypto_init(context,
2722 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2723 smb_get_krb5_error_message(context, ret, mem_ctx)));
2726 ret = krb5_create_checksum(context,
2728 KRB5_KU_OTHER_CKSUM,
2734 DEBUG(2, ("PAC Verification failed: %s\n",
2735 smb_get_krb5_error_message(context, ret, mem_ctx)));
2738 krb5_crypto_destroy(context, crypto);
2744 *sig_type = cksum.cksumtype;
2745 *sig_blob = data_blob_talloc(mem_ctx,
2746 cksum.checksum.data,
2747 cksum.checksum.length);
2748 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2751 input.data = (char *)pac_data->data;
2752 input.length = pac_data->length;
2754 ret = krb5_c_make_checksum(context,
2757 KRB5_KEYUSAGE_APP_DATA_CKSUM,
2761 DEBUG(2, ("PAC Verification failed: %s\n",
2762 smb_get_krb5_error_message(context, ret, mem_ctx)));
2766 *sig_type = cksum.checksum_type;
2767 *sig_blob = data_blob_talloc(mem_ctx,
2772 #error krb5_create_checksum or krb5_c_make_checksum not available
2773 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2774 smb_krb5_free_checksum_contents(context, &cksum);
2781 * @brief Get realm of a principal
2783 * @param[in] mem_ctx The talloc ctx to put the result on
2785 * @param[in] context The library context
2787 * @param[in] principal The principal to get the realm from.
2789 * @return A talloced string with the realm or NULL if an error occurred.
2791 char *smb_krb5_principal_get_realm(TALLOC_CTX *mem_ctx,
2792 krb5_context context,
2793 krb5_const_principal principal)
2795 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2796 return talloc_strdup(mem_ctx,
2797 krb5_principal_get_realm(context, principal));
2798 #elif defined(krb5_princ_realm) /* MIT */
2799 const krb5_data *realm;
2800 realm = krb5_princ_realm(context, principal);
2801 return talloc_strndup(mem_ctx, realm->data, realm->length);
2803 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2808 * @brief Get realm of a principal
2810 * @param[in] context The library context
2812 * @param[in] principal The principal to set the realm
2814 * @param[in] realm The realm as a string to set.
2816 * @retur 0 on success, a Kerberos error code otherwise.
2818 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2819 krb5_principal principal,
2822 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2823 return krb5_principal_set_realm(context, principal, realm);
2824 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2825 krb5_error_code ret;
2827 krb5_data *old_data;
2829 old_data = krb5_princ_realm(context, principal);
2831 ret = smb_krb5_copy_data_contents(&data,
2838 /* free realm before setting */
2839 free(old_data->data);
2841 krb5_princ_set_realm(context, principal, &data);
2845 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2851 * @brief Get the realm from the service hostname.
2853 * This function will look for a domain realm mapping in the [domain_realm]
2854 * section of the krb5.conf first and fallback to extract the realm from
2855 * the provided service hostname. As a last resort it will return the
2856 * provided client_realm.
2858 * @param[in] mem_ctx The talloc context
2860 * @param[in] hostname The service hostname
2862 * @param[in] client_realm If we can not find a mapping, fall back to
2865 * @return The realm to use for the service hostname, NULL if a fatal error
2868 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2869 const char *hostname,
2870 const char *client_realm)
2872 #if defined(HAVE_KRB5_REALM_TYPE)
2874 krb5_realm *realm_list = NULL;
2877 char **realm_list = NULL;
2880 krb5_error_code kerr;
2881 krb5_context ctx = NULL;
2883 initialize_krb5_error_table();
2884 if (krb5_init_context(&ctx)) {
2888 kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2889 if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
2894 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2896 hostname ? hostname : "(NULL)",
2897 error_message(kerr) ));
2901 if (realm_list != NULL &&
2902 realm_list[0] != NULL &&
2903 realm_list[0][0] != '\0') {
2904 realm = talloc_strdup(mem_ctx, realm_list[0]);
2905 if (realm == NULL) {
2909 const char *p = NULL;
2912 * "dc6.samba2003.example.com"
2913 * returns a realm of "SAMBA2003.EXAMPLE.COM"
2915 * "dc6." returns realm as NULL
2917 p = strchr_m(hostname, '.');
2918 if (p != NULL && p[1] != '\0') {
2919 realm = talloc_strdup_upper(mem_ctx, p + 1);
2920 if (realm == NULL) {
2926 if (realm == NULL) {
2927 realm = talloc_strdup(mem_ctx, client_realm);
2934 krb5_free_host_realm(ctx, realm_list);
2937 krb5_free_context(ctx);
2944 * @brief Get an error string from a Kerberos error code.
2946 * @param[in] context The library context.
2948 * @param[in] code The Kerberos error code.
2950 * @param[in] mem_ctx The talloc context to allocate the error string on.
2952 * @return A talloc'ed error string or NULL if an error occurred.
2954 * The caller must free the returned error string with talloc_free() if not
2957 char *smb_get_krb5_error_message(krb5_context context,
2958 krb5_error_code code,
2959 TALLOC_CTX *mem_ctx)
2963 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2964 const char *context_error = krb5_get_error_message(context, code);
2965 if (context_error) {
2966 ret = talloc_asprintf(mem_ctx, "%s: %s",
2967 error_message(code), context_error);
2968 krb5_free_error_message(context, context_error);
2972 ret = talloc_strdup(mem_ctx, error_message(code));
2978 * @brief Return the kerberos library setting for: libdefaults:allow_weak_crypto
2980 * @param[in] context The library context
2982 * @return True if weak crypto is allowed, false if not.
2984 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2985 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2987 return krb5_config_get_bool_default(context,
2991 "allow_weak_crypto",
2994 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2996 #include <profile.h>
2997 krb5_error_code ret;
2998 krb5_boolean ret_default = false;
3002 ret = krb5_get_profile(context,
3008 ret = profile_get_boolean(profile,
3010 "allow_weak_crypto",
3011 NULL, /* subsubname */
3012 ret_default, /* def_val */
3013 &ret_profile /* *ret_default */);
3018 profile_release(profile);
3023 #error UNKNOWN_KRB5_CONFIG_ROUTINES
3027 * @brief Return the type of a krb5_principal
3029 * @param[in] context The library context.
3031 * @param[in] principal The principal to get the type from.
3033 * @return The integer type of the principal.
3035 int smb_krb5_principal_get_type(krb5_context context,
3036 krb5_const_principal principal)
3038 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3039 return krb5_principal_get_type(context, principal);
3040 #elif defined(krb5_princ_type) /* MIT */
3041 return krb5_princ_type(context, principal);
3043 #error UNKNOWN_PRINC_GET_TYPE_FUNCTION
3048 * @brief Set the type of a principal
3050 * @param[in] context The library context
3052 * @param[inout] principal The principal to set the type for.
3054 * @param[in] type The principal type to set.
3056 void smb_krb5_principal_set_type(krb5_context context,
3057 krb5_principal principal,
3060 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3061 krb5_principal_set_type(context, principal, type);
3062 #elif defined(krb5_princ_type) /* MIT */
3063 krb5_princ_type(context, principal) = type;
3065 #error UNKNOWN_PRINC_SET_TYPE_FUNCTION
3069 #if !defined(HAVE_KRB5_WARNX)
3071 * @brief Log a Kerberos message
3073 * It sends the message to com_err.
3075 * @param[in] context The library context
3077 * @param[in] fmt The message format
3079 * @param[in] ... The message arguments
3081 * @return 0 on success.
3083 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3087 va_start(args, fmt);
3088 com_err_va("samba-kdc", errno, fmt, args);
3096 * @brief Copy a credential cache.
3098 * @param[in] context The library context.
3100 * @param[in] incc Credential cache to be copied.
3102 * @param[inout] outcc Copy of credential cache to be filled in.
3104 * @return 0 on success, a Kerberos error code otherwise.
3106 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3107 krb5_ccache incc, krb5_ccache outcc)
3109 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3110 return krb5_cc_copy_cache(context, incc, outcc);
3111 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3112 krb5_error_code ret;
3113 krb5_principal princ = NULL;
3115 ret = krb5_cc_get_principal(context, incc, &princ);
3119 ret = krb5_cc_initialize(context, outcc, princ);
3120 krb5_free_principal(context, princ);
3124 return krb5_cc_copy_creds(context, incc, outcc);
3126 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3130 /**********************************************************
3132 **********************************************************/
3134 static bool ads_cleanup_expired_creds(krb5_context context,
3138 krb5_error_code retval;
3139 const char *cc_type = krb5_cc_get_type(context, ccache);
3141 DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3142 cc_type, krb5_cc_get_name(context, ccache),
3143 http_timestring(talloc_tos(), credsp->times.endtime)));
3145 /* we will probably need new tickets if the current ones
3146 will expire within 10 seconds.
3148 if (credsp->times.endtime >= (time(NULL) + 10))
3151 /* heimdal won't remove creds from a file ccache, and
3152 perhaps we shouldn't anyway, since internally we
3153 use memory ccaches, and a FILE one probably means that
3154 we're using creds obtained outside of our exectuable
3156 if (strequal(cc_type, "FILE")) {
3157 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3161 retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3163 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3164 error_message(retval)));
3165 /* If we have an error in this, we want to display it,
3166 but continue as though we deleted it */
3171 /* Allocate and setup the auth context into the state we need. */
3173 static krb5_error_code ads_setup_auth_context(krb5_context context,
3174 krb5_auth_context *auth_context)
3176 krb5_error_code retval;
3178 retval = krb5_auth_con_init(context, auth_context );
3180 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3181 error_message(retval)));
3185 /* Ensure this is an addressless ticket. */
3186 retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3188 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3189 error_message(retval)));
3195 #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)
3196 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3199 unsigned int orig_length = in_data->length;
3200 unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3201 char *gss_cksum = NULL;
3204 /* Extra length field for delgated ticket. */
3205 base_cksum_size += 4;
3208 if ((unsigned int)base_cksum_size + orig_length <
3209 (unsigned int)base_cksum_size) {
3213 gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3214 if (gss_cksum == NULL) {
3218 memset(gss_cksum, '\0', base_cksum_size + orig_length);
3219 SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3222 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3223 * This matches the behavior of heimdal and mit.
3225 * And it is needed to work against some closed source
3230 memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3232 SIVAL(gss_cksum, 20, gss_flags);
3235 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3236 SSVAL(gss_cksum, 26, orig_length);
3237 /* Copy the kerberos KRB_CRED data */
3238 memcpy(gss_cksum + 28, in_data->data, orig_length);
3239 free(in_data->data);
3240 in_data->data = NULL;
3241 in_data->length = 0;
3243 in_data->data = gss_cksum;
3244 in_data->length = base_cksum_size + orig_length;
3250 * We can't use krb5_mk_req because w2k wants the service to be in a particular
3253 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3254 krb5_auth_context *auth_context,
3255 const krb5_flags ap_req_options,
3256 const char *principal,
3259 time_t *expire_time,
3260 const char *impersonate_princ_s)
3262 krb5_error_code retval;
3263 krb5_principal server;
3264 krb5_principal impersonate_princ = NULL;
3268 bool creds_ready = false;
3269 int i = 0, maxtries = 3;
3272 ZERO_STRUCT(in_data);
3274 retval = smb_krb5_parse_name(context, principal, &server);
3276 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3280 if (impersonate_princ_s) {
3281 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3282 &impersonate_princ);
3284 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3289 /* obtain ticket & session key */
3291 if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3292 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3293 error_message(retval)));
3297 retval = krb5_cc_get_principal(context, ccache, &creds.client);
3299 /* This can commonly fail on smbd startup with no ticket in the cache.
3300 * Report at higher level than 1. */
3301 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3302 error_message(retval)));
3306 while (!creds_ready && (i < maxtries)) {
3308 retval = smb_krb5_get_credentials(context,
3315 DBG_WARNING("smb_krb5_get_credentials failed for %s "
3318 error_message(retval));
3322 /* cope with ticket being in the future due to clock skew */
3323 if ((unsigned)credsp->times.starttime > time(NULL)) {
3324 time_t t = time(NULL);
3325 int time_offset =(int)((unsigned)credsp->times.starttime-t);
3326 DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3327 krb5_set_real_time(context, t + time_offset + 1, 0);
3330 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3338 DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3340 krb5_cc_get_type(context, ccache),
3341 krb5_cc_get_name(context, ccache),
3342 http_timestring(talloc_tos(),
3343 (unsigned)credsp->times.endtime),
3344 (unsigned)credsp->times.endtime);
3347 *expire_time = (time_t)credsp->times.endtime;
3350 /* Allocate the auth_context. */
3351 retval = ads_setup_auth_context(context, auth_context);
3353 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3354 error_message(retval));
3358 #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)
3360 uint32_t gss_flags = 0;
3362 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3364 * Fetch a forwarded TGT from the KDC so that we can
3365 * hand off a 2nd ticket as part of the kerberos
3369 DBG_INFO("Server marked as OK to delegate to, building "
3370 "forwardable TGT\n");
3372 retval = krb5_auth_con_setuseruserkey(context,
3374 &credsp->keyblock );
3376 DBG_WARNING("krb5_auth_con_setuseruserkey "
3378 error_message(retval));
3382 /* Must use a subkey for forwarded tickets. */
3383 retval = krb5_auth_con_setflags(context,
3385 KRB5_AUTH_CONTEXT_USE_SUBKEY);
3387 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3388 error_message(retval));
3392 retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3393 *auth_context, /* Authentication context [in] */
3394 discard_const_p(char, KRB5_TGS_NAME), /* Ticket service name ("krbtgt") [in] */
3395 credsp->client, /* Client principal for the tgt [in] */
3396 credsp->server, /* Server principal for the tgt [in] */
3397 ccache, /* Credential cache to use for storage [in] */
3398 1, /* Turn on for "Forwardable ticket" [in] */
3399 &in_data ); /* Resulting response [out] */
3402 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3403 error_message(retval));
3406 * This is not fatal. Delete the *auth_context and continue
3407 * with krb5_mk_req_extended to get a non-forwardable ticket.
3411 free( in_data.data );
3412 in_data.data = NULL;
3415 krb5_auth_con_free(context, *auth_context);
3416 *auth_context = NULL;
3417 retval = ads_setup_auth_context(context, auth_context);
3419 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3420 error_message(retval));
3424 /* We got a delegated ticket. */
3425 gss_flags |= GSS_C_DELEG_FLAG;
3429 /* Frees and reallocates in_data into a GSS checksum blob. */
3430 retval = ads_create_gss_checksum(&in_data, gss_flags);
3435 /* We always want GSS-checksum types. */
3436 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3438 DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3439 error_message(retval)));
3445 retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3446 &in_data, credsp, outbuf);
3448 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3449 error_message(retval));
3452 #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)
3457 free( in_data.data );
3461 krb5_free_creds(context, credsp);
3464 krb5_free_cred_contents(context, &creds);
3467 krb5_free_principal(context, server);
3468 if (impersonate_princ) {
3469 krb5_free_principal(context, impersonate_princ);
3476 get a kerberos5 ticket for the given service
3478 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3479 const char *principal,
3482 DATA_BLOB *session_key_krb5,
3483 uint32_t extra_ap_opts, const char *ccname,
3485 const char *impersonate_princ_s)
3487 krb5_error_code retval;
3489 krb5_context context = NULL;
3490 krb5_ccache ccdef = NULL;
3491 krb5_auth_context auth_context = NULL;
3492 krb5_enctype enc_types[] = {
3493 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3494 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3496 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3497 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3499 ENCTYPE_ARCFOUR_HMAC,
3500 ENCTYPE_DES_CBC_MD5,
3501 ENCTYPE_DES_CBC_CRC,
3505 initialize_krb5_error_table();
3506 retval = krb5_init_context(&context);
3508 DBG_WARNING("krb5_init_context failed (%s)\n",
3509 error_message(retval));
3513 if (time_offset != 0) {
3514 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3517 retval = krb5_cc_resolve(context,
3518 ccname ? ccname : krb5_cc_default_name(context),
3521 DBG_WARNING("krb5_cc_default failed (%s)\n",
3522 error_message(retval));
3526 retval = krb5_set_default_tgs_ktypes(context, enc_types);
3528 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3529 error_message(retval));
3533 retval = ads_krb5_mk_req(context,
3535 AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3540 impersonate_princ_s);
3545 ok = smb_krb5_get_smb_session_key(mem_ctx,
3555 *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3557 smb_krb5_free_data_contents(context, &packet);
3563 krb5_cc_close(context, ccdef);
3566 krb5_auth_con_free(context, auth_context);
3568 krb5_free_context(context);
3574 #ifndef SAMBA4_USES_HEIMDAL /* MITKRB5 tracing callback */
3575 static void smb_krb5_trace_cb(krb5_context ctx,
3576 const krb5_trace_info *info,
3580 DBGC_DEBUG(DBGC_KERBEROS, "%s", info->message);
3585 krb5_error_code smb_krb5_init_context_common(krb5_context *_krb5_context)
3587 krb5_error_code ret;
3588 krb5_context krb5_ctx;
3590 initialize_krb5_error_table();
3592 ret = krb5_init_context(&krb5_ctx);
3594 DBG_ERR("Krb5 context initialization failed (%s)\n",
3595 error_message(ret));
3599 /* The MIT Kerberos build relies on using the system krb5.conf file.
3600 * If you really want to use another file please set KRB5_CONFIG
3602 #ifndef SAMBA4_USES_HEIMDAL
3603 ret = krb5_set_trace_callback(krb5_ctx, smb_krb5_trace_cb, NULL);
3605 DBG_ERR("Failed to set MIT kerberos trace callback! (%s)\n",
3606 error_message(ret));
3609 *_krb5_context = krb5_ctx;
3613 #else /* HAVE_KRB5 */
3614 /* This saves a few linking headaches */
3615 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3616 const char *principal,
3619 DATA_BLOB *session_key_krb5,
3620 uint32_t extra_ap_opts, const char *ccname,
3622 const char *impersonate_princ_s)
3624 DEBUG(0,("NO KERBEROS SUPPORT\n"));
3628 #endif /* HAVE_KRB5 */