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