Add MIT kerberos tracing capability
[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         initialize_krb5_error_table();
936         ret = krb5_init_context(&context);
937         if (ret) {
938                 goto done;
939         }
940
941         if (!ccache_string) {
942                 ccache_string = krb5_cc_default_name(context);
943         }
944
945         if (!ccache_string) {
946                 ret = EINVAL;
947                 goto done;
948         }
949
950         DEBUG(10,("smb_krb5_renew_ticket: using %s as ccache\n", ccache_string));
951
952         /* FIXME: we should not fall back to defaults */
953         ret = krb5_cc_resolve(context, discard_const_p(char, ccache_string), &ccache);
954         if (ret) {
955                 goto done;
956         }
957
958         if (client_string) {
959                 ret = smb_krb5_parse_name(context, client_string, &client);
960                 if (ret) {
961                         goto done;
962                 }
963         } else {
964                 ret = krb5_cc_get_principal(context, ccache, &client);
965                 if (ret) {
966                         goto done;
967                 }
968         }
969
970         ret = krb5_get_renewed_creds(context, &creds, client, ccache, discard_const_p(char, service_string));
971         if (ret) {
972                 DEBUG(10,("smb_krb5_renew_ticket: krb5_get_kdc_cred failed: %s\n", error_message(ret)));
973                 goto done;
974         }
975
976         /* hm, doesn't that create a new one if the old one wasn't there? - Guenther */
977         ret = krb5_cc_initialize(context, ccache, client);
978         if (ret) {
979                 goto done;
980         }
981
982         ret = krb5_cc_store_cred(context, ccache, &creds);
983
984         if (expire_time) {
985                 *expire_time = (time_t) creds.times.endtime;
986         }
987
988 done:
989         krb5_free_cred_contents(context, &creds_in);
990         krb5_free_cred_contents(context, &creds);
991
992         if (client) {
993                 krb5_free_principal(context, client);
994         }
995         if (ccache) {
996                 krb5_cc_close(context, ccache);
997         }
998         if (context) {
999                 krb5_free_context(context);
1000         }
1001
1002         return ret;
1003 }
1004
1005 /**
1006  * @brief Free the data stored in an smb_krb5_addresses structure.
1007  *
1008  * @param[in]  context  The library context
1009  *
1010  * @param[in]  addr     The address structure to free.
1011  *
1012  * @return 0 on success, a Kerberos error code otherwise.
1013  */
1014 krb5_error_code smb_krb5_free_addresses(krb5_context context,
1015                                         smb_krb5_addresses *addr)
1016 {
1017         krb5_error_code ret = 0;
1018         if (addr == NULL) {
1019                 return ret;
1020         }
1021 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1022         krb5_free_addresses(context, addr->addrs);
1023 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1024         ret = krb5_free_addresses(context, addr->addrs);
1025         SAFE_FREE(addr->addrs);
1026 #endif
1027         SAFE_FREE(addr);
1028         addr = NULL;
1029         return ret;
1030 }
1031
1032 #define MAX_NETBIOSNAME_LEN 16
1033
1034 /**
1035  * @brief Add a netbios name to the array of addresses
1036  *
1037  * @param[in]  kerb_addr A pointer to the smb_krb5_addresses to add the
1038  *                       netbios name to.
1039  *
1040  * @param[in]  netbios_name The netbios name to add.
1041  *
1042  * @return 0 on success, a Kerberos error code otherwise.
1043  */
1044 krb5_error_code smb_krb5_gen_netbios_krb5_address(smb_krb5_addresses **kerb_addr,
1045                                                    const char *netbios_name)
1046 {
1047         krb5_error_code ret = 0;
1048         char buf[MAX_NETBIOSNAME_LEN];
1049         int len;
1050 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1051         krb5_address **addrs = NULL;
1052 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1053         krb5_addresses *addrs = NULL;
1054 #endif
1055
1056         *kerb_addr = (smb_krb5_addresses *)SMB_MALLOC(sizeof(smb_krb5_addresses));
1057         if (*kerb_addr == NULL) {
1058                 return ENOMEM;
1059         }
1060
1061         /* temporarily duplicate put_name() code here to avoid dependency
1062          * issues for a 5 lines function */
1063         len = strlen(netbios_name);
1064         memcpy(buf, netbios_name,
1065                 (len < MAX_NETBIOSNAME_LEN) ? len : MAX_NETBIOSNAME_LEN - 1);
1066         if (len < MAX_NETBIOSNAME_LEN - 1) {
1067                 memset(buf + len, ' ', MAX_NETBIOSNAME_LEN - 1 - len);
1068         }
1069         buf[MAX_NETBIOSNAME_LEN - 1] = 0x20;
1070
1071 #if defined(HAVE_MAGIC_IN_KRB5_ADDRESS) && defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS) /* MIT */
1072         {
1073                 int num_addr = 2;
1074
1075                 addrs = (krb5_address **)SMB_MALLOC(sizeof(krb5_address *) * num_addr);
1076                 if (addrs == NULL) {
1077                         SAFE_FREE(*kerb_addr);
1078                         return ENOMEM;
1079                 }
1080
1081                 memset(addrs, 0, sizeof(krb5_address *) * num_addr);
1082
1083                 addrs[0] = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1084                 if (addrs[0] == NULL) {
1085                         SAFE_FREE(addrs);
1086                         SAFE_FREE(*kerb_addr);
1087                         return ENOMEM;
1088                 }
1089
1090                 addrs[0]->magic = KV5M_ADDRESS;
1091                 addrs[0]->addrtype = KRB5_ADDR_NETBIOS;
1092                 addrs[0]->length = MAX_NETBIOSNAME_LEN;
1093                 addrs[0]->contents = (unsigned char *)SMB_MALLOC(addrs[0]->length);
1094                 if (addrs[0]->contents == NULL) {
1095                         SAFE_FREE(addrs[0]);
1096                         SAFE_FREE(addrs);
1097                         SAFE_FREE(*kerb_addr);
1098                         return ENOMEM;
1099                 }
1100
1101                 memcpy(addrs[0]->contents, buf, addrs[0]->length);
1102
1103                 addrs[1] = NULL;
1104         }
1105 #elif defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS) /* Heimdal */
1106         {
1107                 addrs = (krb5_addresses *)SMB_MALLOC(sizeof(krb5_addresses));
1108                 if (addrs == NULL) {
1109                         SAFE_FREE(*kerb_addr);
1110                         return ENOMEM;
1111                 }
1112
1113                 memset(addrs, 0, sizeof(krb5_addresses));
1114
1115                 addrs->len = 1;
1116                 addrs->val = (krb5_address *)SMB_MALLOC(sizeof(krb5_address));
1117                 if (addrs->val == NULL) {
1118                         SAFE_FREE(addrs);
1119                         SAFE_FREE(*kerb_addr);
1120                         return ENOMEM;
1121                 }
1122
1123                 addrs->val[0].addr_type = KRB5_ADDR_NETBIOS;
1124                 addrs->val[0].address.length = MAX_NETBIOSNAME_LEN;
1125                 addrs->val[0].address.data = (unsigned char *)SMB_MALLOC(addrs->val[0].address.length);
1126                 if (addrs->val[0].address.data == NULL) {
1127                         SAFE_FREE(addrs->val);
1128                         SAFE_FREE(addrs);
1129                         SAFE_FREE(*kerb_addr);
1130                         return ENOMEM;
1131                 }
1132
1133                 memcpy(addrs->val[0].address.data, buf, addrs->val[0].address.length);
1134         }
1135 #else
1136 #error UNKNOWN_KRB5_ADDRESS_FORMAT
1137 #endif
1138         (*kerb_addr)->addrs = addrs;
1139
1140         return ret;
1141 }
1142
1143 /**
1144  * @brief Get the enctype from a key table entry
1145  *
1146  * @param[in]  kt_entry Key table entry to get the enctype from.
1147  *
1148  * @return The enctype from the entry.
1149  */
1150 krb5_enctype smb_krb5_kt_get_enctype_from_entry(krb5_keytab_entry *kt_entry)
1151 {
1152         return KRB5_KEY_TYPE(KRB5_KT_KEY(kt_entry));
1153 }
1154
1155 /**
1156  * @brief Free the contents of a key table entry.
1157  *
1158  * @param[in]  context The library context.
1159  *
1160  * @param[in]  kt_entry The key table entry to free the contents of.
1161  *
1162  * @return 0 on success, a Kerberos error code otherwise.
1163  *
1164  * The pointer itself is not freed.
1165  */
1166 krb5_error_code smb_krb5_kt_free_entry(krb5_context context,
1167                                         krb5_keytab_entry *kt_entry)
1168 {
1169 /* Try krb5_free_keytab_entry_contents first, since
1170  * MIT Kerberos >= 1.7 has both krb5_free_keytab_entry_contents and
1171  * krb5_kt_free_entry but only has a prototype for the first, while the
1172  * second is considered private.
1173  */
1174 #if defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
1175         return krb5_free_keytab_entry_contents(context, kt_entry);
1176 #elif defined(HAVE_KRB5_KT_FREE_ENTRY)
1177         return krb5_kt_free_entry(context, kt_entry);
1178 #else
1179 #error UNKNOWN_KT_FREE_FUNCTION
1180 #endif
1181 }
1182
1183
1184 /**
1185  * @brief Convert an encryption type to a string.
1186  *
1187  * @param[in]  context The library context.
1188  *
1189  * @param[in]  enctype The encryption type.
1190  *
1191  * @param[in]  etype_s A pointer to store the allocated encryption type as a
1192  *                     string.
1193  *
1194  * @return 0 on success, a Kerberos error code otherwise.
1195  *
1196  * The caller needs to free the allocated string etype_s.
1197  */
1198 krb5_error_code smb_krb5_enctype_to_string(krb5_context context,
1199                                            krb5_enctype enctype,
1200                                            char **etype_s)
1201 {
1202 #ifdef HAVE_KRB5_ENCTYPE_TO_STRING_WITH_KRB5_CONTEXT_ARG
1203         return krb5_enctype_to_string(context, enctype, etype_s); /* Heimdal */
1204 #elif defined(HAVE_KRB5_ENCTYPE_TO_STRING_WITH_SIZE_T_ARG)
1205         char buf[256];
1206         krb5_error_code ret = krb5_enctype_to_string(enctype, buf, 256); /* MIT */
1207         if (ret) {
1208                 return ret;
1209         }
1210         *etype_s = SMB_STRDUP(buf);
1211         if (!*etype_s) {
1212                 return ENOMEM;
1213         }
1214         return ret;
1215 #else
1216 #error UNKNOWN_KRB5_ENCTYPE_TO_STRING_FUNCTION
1217 #endif
1218 }
1219
1220 /* This MAX_NAME_LEN is a constant defined in krb5.h */
1221 #ifndef MAX_KEYTAB_NAME_LEN
1222 #define MAX_KEYTAB_NAME_LEN 1100
1223 #endif
1224
1225 /**
1226  * @brief Open a key table readonly or with readwrite access.
1227  *
1228  * Allows one to use a different keytab than the default one using a relative
1229  * path to the keytab.
1230  *
1231  * @param[in]  context  The library context
1232  *
1233  * @param[in]  keytab_name_req The path to the key table.
1234  *
1235  * @param[in]  write_access Open with readwrite access.
1236  *
1237  * @param[in]  keytab A pointer o the opended key table.
1238  *
1239  * The keytab pointer should be freed using krb5_kt_close().
1240  *
1241  * @return 0 on success, a Kerberos error code otherwise.
1242  */
1243 krb5_error_code smb_krb5_kt_open_relative(krb5_context context,
1244                                           const char *keytab_name_req,
1245                                           bool write_access,
1246                                           krb5_keytab *keytab)
1247 {
1248         krb5_error_code ret = 0;
1249         TALLOC_CTX *mem_ctx;
1250         char keytab_string[MAX_KEYTAB_NAME_LEN];
1251         char *kt_str = NULL;
1252         bool found_valid_name = false;
1253         const char *pragma = "FILE";
1254         const char *tmp = NULL;
1255
1256         if (!write_access && !keytab_name_req) {
1257                 /* caller just wants to read the default keytab readonly, so be it */
1258                 return krb5_kt_default(context, keytab);
1259         }
1260
1261         mem_ctx = talloc_init("smb_krb5_open_keytab");
1262         if (!mem_ctx) {
1263                 return ENOMEM;
1264         }
1265
1266 #ifdef HAVE_WRFILE_KEYTAB
1267         if (write_access) {
1268                 pragma = "WRFILE";
1269         }
1270 #endif
1271
1272         if (keytab_name_req) {
1273
1274                 if (strlen(keytab_name_req) > MAX_KEYTAB_NAME_LEN) {
1275                         ret = KRB5_CONFIG_NOTENUFSPACE;
1276                         goto out;
1277                 }
1278
1279                 if ((strncmp(keytab_name_req, "WRFILE:", 7) == 0) ||
1280                     (strncmp(keytab_name_req, "FILE:", 5) == 0)) {
1281                         tmp = keytab_name_req;
1282                         goto resolve;
1283                 }
1284
1285                 tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, keytab_name_req);
1286                 if (!tmp) {
1287                         ret = ENOMEM;
1288                         goto out;
1289                 }
1290
1291                 goto resolve;
1292         }
1293
1294         /* we need to handle more complex keytab_strings, like:
1295          * "ANY:FILE:/etc/krb5.keytab,krb4:/etc/srvtab" */
1296
1297         ret = krb5_kt_default_name(context, &keytab_string[0], MAX_KEYTAB_NAME_LEN - 2);
1298         if (ret) {
1299                 goto out;
1300         }
1301
1302         DEBUG(10,("smb_krb5_open_keytab: krb5_kt_default_name returned %s\n", keytab_string));
1303
1304         tmp = talloc_strdup(mem_ctx, keytab_string);
1305         if (!tmp) {
1306                 ret = ENOMEM;
1307                 goto out;
1308         }
1309
1310         if (strncmp(tmp, "ANY:", 4) == 0) {
1311                 tmp += 4;
1312         }
1313
1314         memset(&keytab_string, '\0', sizeof(keytab_string));
1315
1316         while (next_token_talloc(mem_ctx, &tmp, &kt_str, ",")) {
1317                 if (strncmp(kt_str, "WRFILE:", 7) == 0) {
1318                         found_valid_name = true;
1319                         tmp = kt_str;
1320                         tmp += 7;
1321                 }
1322
1323                 if (strncmp(kt_str, "FILE:", 5) == 0) {
1324                         found_valid_name = true;
1325                         tmp = kt_str;
1326                         tmp += 5;
1327                 }
1328
1329                 if (tmp[0] == '/') {
1330                         /* Treat as a FILE: keytab definition. */
1331                         found_valid_name = true;
1332                 }
1333
1334                 if (found_valid_name) {
1335                         if (tmp[0] != '/') {
1336                                 ret = KRB5_KT_BADNAME;
1337                                 goto out;
1338                         }
1339
1340                         tmp = talloc_asprintf(mem_ctx, "%s:%s", pragma, tmp);
1341                         if (!tmp) {
1342                                 ret = ENOMEM;
1343                                 goto out;
1344                         }
1345                         break;
1346                 }
1347         }
1348
1349         if (!found_valid_name) {
1350                 ret = KRB5_KT_UNKNOWN_TYPE;
1351                 goto out;
1352         }
1353
1354 resolve:
1355         DEBUG(10,("smb_krb5_open_keytab: resolving: %s\n", tmp));
1356         ret = krb5_kt_resolve(context, tmp, keytab);
1357
1358 out:
1359         TALLOC_FREE(mem_ctx);
1360         return ret;
1361 }
1362
1363 /**
1364  * @brief Open a key table readonly or with readwrite access.
1365  *
1366  * Allows one to use a different keytab than the default one. The path needs to be
1367  * an absolute path or an error will be returned.
1368  *
1369  * @param[in]  context  The library context
1370  *
1371  * @param[in]  keytab_name_req The path to the key table.
1372  *
1373  * @param[in]  write_access Open with readwrite access.
1374  *
1375  * @param[in]  keytab A pointer o the opended key table.
1376  *
1377  * The keytab pointer should be freed using krb5_kt_close().
1378  *
1379  * @return 0 on success, a Kerberos error code otherwise.
1380  */
1381 krb5_error_code smb_krb5_kt_open(krb5_context context,
1382                                  const char *keytab_name_req,
1383                                  bool write_access,
1384                                  krb5_keytab *keytab)
1385 {
1386         int cmp;
1387
1388         if (keytab_name_req == NULL) {
1389                 return KRB5_KT_BADNAME;
1390         }
1391
1392         if (keytab_name_req[0] == '/') {
1393                 goto open_keytab;
1394         }
1395
1396         cmp = strncmp(keytab_name_req, "FILE:/", 6);
1397         if (cmp == 0) {
1398                 goto open_keytab;
1399         }
1400
1401         cmp = strncmp(keytab_name_req, "WRFILE:/", 8);
1402         if (cmp == 0) {
1403                 goto open_keytab;
1404         }
1405
1406         DBG_WARNING("ERROR: Invalid keytab name: %s\n", keytab_name_req);
1407
1408         return KRB5_KT_BADNAME;
1409
1410 open_keytab:
1411         return smb_krb5_kt_open_relative(context,
1412                                          keytab_name_req,
1413                                          write_access,
1414                                          keytab);
1415 }
1416
1417 /**
1418  * @brief Get a key table name.
1419  *
1420  * @param[in]  mem_ctx The talloc context to use for allocation.
1421  *
1422  * @param[in]  context The library context.
1423  *
1424  * @param[in]  keytab The key table to get the name from.
1425  *
1426  * @param[in]  keytab_name A talloc'ed string of the key table name.
1427  *
1428  * The talloc'ed name string needs to be freed with talloc_free().
1429  *
1430  * @return 0 on success, a Kerberos error code otherwise.
1431  */
1432 krb5_error_code smb_krb5_kt_get_name(TALLOC_CTX *mem_ctx,
1433                                      krb5_context context,
1434                                      krb5_keytab keytab,
1435                                      const char **keytab_name)
1436 {
1437         char keytab_string[MAX_KEYTAB_NAME_LEN];
1438         krb5_error_code ret = 0;
1439
1440         ret = krb5_kt_get_name(context, keytab,
1441                                keytab_string, MAX_KEYTAB_NAME_LEN - 2);
1442         if (ret) {
1443                 return ret;
1444         }
1445
1446         *keytab_name = talloc_strdup(mem_ctx, keytab_string);
1447         if (!*keytab_name) {
1448                 return ENOMEM;
1449         }
1450
1451         return ret;
1452 }
1453
1454 /**
1455  * @brief Seek and delete old entries in a keytab based on the passed
1456  *        principal.
1457  *
1458  * @param[in]  context       The KRB5 context to use.
1459  *
1460  * @param[in]  keytab        The keytab to operate on.
1461  *
1462  * @param[in]  kvno          The kvnco to use.
1463  *
1464  * @param[in]  princ_s       The principal as a string to search for.
1465  *
1466  * @param[in]  princ         The principal as a krb5_principal to search for.
1467  *
1468  * @param[in]  flush         Weather to flush the complete keytab.
1469  *
1470  * @param[in]  keep_old_entries Keep the entry with the previous kvno.
1471  *
1472  * @retval 0 on Sucess
1473  *
1474  * @return An appropriate KRB5 error code.
1475  */
1476 krb5_error_code smb_krb5_kt_seek_and_delete_old_entries(krb5_context context,
1477                                                         krb5_keytab keytab,
1478                                                         krb5_kvno kvno,
1479                                                         krb5_enctype enctype,
1480                                                         const char *princ_s,
1481                                                         krb5_principal princ,
1482                                                         bool flush,
1483                                                         bool keep_old_entries)
1484 {
1485         krb5_error_code ret;
1486         krb5_kt_cursor cursor;
1487         krb5_keytab_entry kt_entry;
1488         char *ktprinc = NULL;
1489         krb5_kvno old_kvno = kvno - 1;
1490         TALLOC_CTX *tmp_ctx;
1491
1492         ZERO_STRUCT(cursor);
1493         ZERO_STRUCT(kt_entry);
1494
1495         ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1496         if (ret == KRB5_KT_END || ret == ENOENT ) {
1497                 /* no entries */
1498                 return 0;
1499         }
1500
1501         tmp_ctx = talloc_new(NULL);
1502         if (tmp_ctx == NULL) {
1503                 return ENOMEM;
1504         }
1505
1506         DEBUG(3, (__location__ ": Will try to delete old keytab entries\n"));
1507         while (!krb5_kt_next_entry(context, keytab, &kt_entry, &cursor)) {
1508                 bool name_ok = false;
1509                 krb5_enctype kt_entry_enctype =
1510                         smb_krb5_kt_get_enctype_from_entry(&kt_entry);
1511
1512                 if (!flush && (princ_s != NULL)) {
1513                         ret = smb_krb5_unparse_name(tmp_ctx, context,
1514                                                     kt_entry.principal,
1515                                                     &ktprinc);
1516                         if (ret) {
1517                                 DEBUG(1, (__location__
1518                                           ": smb_krb5_unparse_name failed "
1519                                           "(%s)\n", error_message(ret)));
1520                                 goto out;
1521                         }
1522
1523 #ifdef HAVE_KRB5_KT_COMPARE
1524                         name_ok = krb5_kt_compare(context, &kt_entry,
1525                                                   princ, 0, 0);
1526 #else
1527                         name_ok = (strcmp(ktprinc, princ_s) == 0);
1528 #endif
1529
1530                         if (!name_ok) {
1531                                 DEBUG(10, (__location__ ": ignoring keytab "
1532                                            "entry principal %s, kvno = %d\n",
1533                                            ktprinc, kt_entry.vno));
1534
1535                                 /* Not a match,
1536                                  * just free this entry and continue. */
1537                                 ret = smb_krb5_kt_free_entry(context,
1538                                                              &kt_entry);
1539                                 ZERO_STRUCT(kt_entry);
1540                                 if (ret) {
1541                                         DEBUG(1, (__location__
1542                                                   ": smb_krb5_kt_free_entry "
1543                                                   "failed (%s)\n",
1544                                                   error_message(ret)));
1545                                         goto out;
1546                                 }
1547
1548                                 TALLOC_FREE(ktprinc);
1549                                 continue;
1550                         }
1551
1552                         TALLOC_FREE(ktprinc);
1553                 }
1554
1555                 /*------------------------------------------------------------
1556                  * Save the entries with kvno - 1. This is what microsoft does
1557                  * to allow people with existing sessions that have kvno - 1
1558                  * to still work. Otherwise, when the password for the machine
1559                  * changes, all kerberizied sessions will 'break' until either
1560                  * the client reboots or the client's session key expires and
1561                  * they get a new session ticket with the new kvno.
1562                  * Some keytab files only store the kvno in 8bits, limit
1563                  * the compare accordingly.
1564                  */
1565
1566                 if (!flush && ((kt_entry.vno & 0xff) == (old_kvno & 0xff))) {
1567                         DEBUG(5, (__location__ ": Saving previous (kvno %d) "
1568                                   "entry for principal: %s.\n",
1569                                   old_kvno, princ_s));
1570                         continue;
1571                 }
1572
1573                 if (keep_old_entries) {
1574                         DEBUG(5, (__location__ ": Saving old (kvno %d) "
1575                                   "entry for principal: %s.\n",
1576                                   kvno, princ_s));
1577                         continue;
1578                 }
1579
1580                 if (!flush &&
1581                     ((kt_entry.vno & 0xff) == (kvno & 0xff)) &&
1582                     (kt_entry_enctype != enctype))
1583                 {
1584                         DEBUG(5, (__location__ ": Saving entry with kvno [%d] "
1585                                   "enctype [%d] for principal: %s.\n",
1586                                   kvno, kt_entry_enctype, princ_s));
1587                         continue;
1588                 }
1589
1590                 DEBUG(5, (__location__ ": Found old entry for principal: %s "
1591                           "(kvno %d) - trying to remove it.\n",
1592                           princ_s, kt_entry.vno));
1593
1594                 ret = krb5_kt_end_seq_get(context, keytab, &cursor);
1595                 ZERO_STRUCT(cursor);
1596                 if (ret) {
1597                         DEBUG(1, (__location__ ": krb5_kt_end_seq_get() "
1598                                   "failed (%s)\n", error_message(ret)));
1599                         goto out;
1600                 }
1601                 ret = krb5_kt_remove_entry(context, keytab, &kt_entry);
1602                 if (ret) {
1603                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1604                                   "failed (%s)\n", error_message(ret)));
1605                         goto out;
1606                 }
1607
1608                 DEBUG(5, (__location__ ": removed old entry for principal: "
1609                           "%s (kvno %d).\n", princ_s, kt_entry.vno));
1610
1611                 ret = krb5_kt_start_seq_get(context, keytab, &cursor);
1612                 if (ret) {
1613                         DEBUG(1, (__location__ ": krb5_kt_start_seq() failed "
1614                                   "(%s)\n", error_message(ret)));
1615                         goto out;
1616                 }
1617                 ret = smb_krb5_kt_free_entry(context, &kt_entry);
1618                 ZERO_STRUCT(kt_entry);
1619                 if (ret) {
1620                         DEBUG(1, (__location__ ": krb5_kt_remove_entry() "
1621                                   "failed (%s)\n", error_message(ret)));
1622                         goto out;
1623                 }
1624         }
1625
1626 out:
1627         talloc_free(tmp_ctx);
1628         if (!all_zero((uint8_t *)&kt_entry, sizeof(kt_entry))) {
1629                 smb_krb5_kt_free_entry(context, &kt_entry);
1630         }
1631         if (!all_zero((uint8_t *)&cursor, sizeof(cursor))) {
1632                 krb5_kt_end_seq_get(context, keytab, &cursor);
1633         }
1634         return ret;
1635 }
1636
1637 /**
1638  * @brief Add a keytab entry for the given principal
1639  *
1640  * @param[in]  context       The krb5 context to use.
1641  *
1642  * @param[in]  keytab        The keytab to add the entry to.
1643  *
1644  * @param[in]  kvno          The kvno to use.
1645  *
1646  * @param[in]  princ_s       The principal as a string.
1647  *
1648  * @param[in]  salt_principal The salt principal to salt the password with.
1649  *                            Only needed for keys which support salting.
1650  *                            If no salt is used set no_salt to false and
1651  *                            pass NULL here.
1652  *
1653  * @param[in]  enctype        The encryption type of the keytab entry.
1654  *
1655  * @param[in]  password       The password of the keytab entry.
1656  *
1657  * @param[in]  no_salt        If the password should not be salted. Normally
1658  *                            this is only set to false for encryption types
1659  *                            which do not support salting like RC4.
1660  *
1661  * @param[in]  keep_old_entries Wether to keep or delte old keytab entries.
1662  *
1663  * @retval 0 on Success
1664  *
1665  * @return A corresponding KRB5 error code.
1666  *
1667  * @see smb_krb5_kt_open()
1668  */
1669 krb5_error_code smb_krb5_kt_add_entry(krb5_context context,
1670                                       krb5_keytab keytab,
1671                                       krb5_kvno kvno,
1672                                       const char *princ_s,
1673                                       const char *salt_principal,
1674                                       krb5_enctype enctype,
1675                                       krb5_data *password,
1676                                       bool no_salt,
1677                                       bool keep_old_entries)
1678 {
1679         krb5_error_code ret;
1680         krb5_keytab_entry kt_entry;
1681         krb5_principal princ = NULL;
1682         krb5_keyblock *keyp;
1683
1684         ZERO_STRUCT(kt_entry);
1685
1686         ret = smb_krb5_parse_name(context, princ_s, &princ);
1687         if (ret) {
1688                 DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
1689                           "failed (%s)\n", princ_s, error_message(ret)));
1690                 goto out;
1691         }
1692
1693         /* Seek and delete old keytab entries */
1694         ret = smb_krb5_kt_seek_and_delete_old_entries(context,
1695                                                       keytab,
1696                                                       kvno,
1697                                                       enctype,
1698                                                       princ_s,
1699                                                       princ,
1700                                                       false,
1701                                                       keep_old_entries);
1702         if (ret) {
1703                 goto out;
1704         }
1705
1706         /* If we get here, we have deleted all the old entries with kvno's
1707          * not equal to the current kvno-1. */
1708
1709         keyp = KRB5_KT_KEY(&kt_entry);
1710
1711         if (no_salt) {
1712                 KRB5_KEY_DATA(keyp) = (KRB5_KEY_DATA_CAST *)SMB_MALLOC(password->length);
1713                 if (KRB5_KEY_DATA(keyp) == NULL) {
1714                         ret = ENOMEM;
1715                         goto out;
1716                 }
1717                 memcpy(KRB5_KEY_DATA(keyp), password->data, password->length);
1718                 KRB5_KEY_LENGTH(keyp) = password->length;
1719                 KRB5_KEY_TYPE(keyp) = enctype;
1720         } else {
1721                 krb5_principal salt_princ = NULL;
1722
1723                 /* Now add keytab entries for all encryption types */
1724                 ret = smb_krb5_parse_name(context, salt_principal, &salt_princ);
1725                 if (ret) {
1726                         DBG_WARNING("krb5_parse_name(%s) failed (%s)\n",
1727                                     salt_principal, error_message(ret));
1728                         goto out;
1729                 }
1730
1731                 ret = smb_krb5_create_key_from_string(context,
1732                                                       salt_princ,
1733                                                       NULL,
1734                                                       password,
1735                                                       enctype,
1736                                                       keyp);
1737                 krb5_free_principal(context, salt_princ);
1738                 if (ret != 0) {
1739                         goto out;
1740                 }
1741         }
1742
1743         kt_entry.principal = princ;
1744         kt_entry.vno       = kvno;
1745
1746         DEBUG(3, (__location__ ": adding keytab entry for (%s) with "
1747                   "encryption type (%d) and version (%d)\n",
1748                   princ_s, enctype, kt_entry.vno));
1749         ret = krb5_kt_add_entry(context, keytab, &kt_entry);
1750         krb5_free_keyblock_contents(context, keyp);
1751         ZERO_STRUCT(kt_entry);
1752         if (ret) {
1753                 DEBUG(1, (__location__ ": adding entry to keytab "
1754                           "failed (%s)\n", error_message(ret)));
1755                 goto out;
1756         }
1757
1758 out:
1759         if (princ) {
1760                 krb5_free_principal(context, princ);
1761         }
1762
1763         return ret;
1764 }
1765
1766 #if defined(HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE) && \
1767     defined(HAVE_KRB5_GET_CREDS_OPT_ALLOC) && \
1768     defined(HAVE_KRB5_GET_CREDS)
1769 static krb5_error_code smb_krb5_get_credentials_for_user_opt(krb5_context context,
1770                                                              krb5_ccache ccache,
1771                                                              krb5_principal me,
1772                                                              krb5_principal server,
1773                                                              krb5_principal impersonate_princ,
1774                                                              krb5_creds **out_creds)
1775 {
1776         krb5_error_code ret;
1777         krb5_get_creds_opt opt;
1778
1779         ret = krb5_get_creds_opt_alloc(context, &opt);
1780         if (ret) {
1781                 goto done;
1782         }
1783         krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
1784
1785         if (impersonate_princ) {
1786                 ret = krb5_get_creds_opt_set_impersonate(context, opt,
1787                                                          impersonate_princ);
1788                 if (ret) {
1789                         goto done;
1790                 }
1791         }
1792
1793         ret = krb5_get_creds(context, opt, ccache, server, out_creds);
1794         if (ret) {
1795                 goto done;
1796         }
1797
1798  done:
1799         if (opt) {
1800                 krb5_get_creds_opt_free(context, opt);
1801         }
1802         return ret;
1803 }
1804 #endif /* HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE */
1805
1806 #ifdef HAVE_KRB5_GET_CREDENTIALS_FOR_USER
1807
1808 #if !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER
1809 krb5_error_code KRB5_CALLCONV
1810 krb5_get_credentials_for_user(krb5_context context, krb5_flags options,
1811                               krb5_ccache ccache, krb5_creds *in_creds,
1812                               krb5_data *subject_cert,
1813                               krb5_creds **out_creds);
1814 #endif /* !HAVE_DECL_KRB5_GET_CREDENTIALS_FOR_USER */
1815
1816 static krb5_error_code smb_krb5_get_credentials_for_user(krb5_context context,
1817                                                          krb5_ccache ccache,
1818                                                          krb5_principal me,
1819                                                          krb5_principal server,
1820                                                          krb5_principal impersonate_princ,
1821                                                          krb5_creds **out_creds)
1822 {
1823         krb5_error_code ret;
1824         krb5_creds in_creds;
1825
1826         ZERO_STRUCT(in_creds);
1827
1828         if (impersonate_princ) {
1829
1830                 in_creds.server = me;
1831                 in_creds.client = impersonate_princ;
1832
1833                 ret = krb5_get_credentials_for_user(context,
1834                                                     0, /* krb5_flags options */
1835                                                     ccache,
1836                                                     &in_creds,
1837                                                     NULL, /* krb5_data *subject_cert */
1838                                                     out_creds);
1839         } else {
1840                 in_creds.client = me;
1841                 in_creds.server = server;
1842
1843                 ret = krb5_get_credentials(context, 0, ccache,
1844                                            &in_creds, out_creds);
1845         }
1846
1847         return ret;
1848 }
1849 #endif /* HAVE_KRB5_GET_CREDENTIALS_FOR_USER */
1850
1851 /*
1852  * smb_krb5_get_credentials
1853  *
1854  * @brief Get krb5 credentials for a server
1855  *
1856  * @param[in] context           An initialized krb5_context
1857  * @param[in] ccache            An initialized krb5_ccache
1858  * @param[in] me                The krb5_principal of the caller
1859  * @param[in] server            The krb5_principal of the requested service
1860  * @param[in] impersonate_princ The krb5_principal of a user to impersonate as (optional)
1861  * @param[out] out_creds        The returned krb5_creds structure
1862  * @return krb5_error_code
1863  *
1864  */
1865 krb5_error_code smb_krb5_get_credentials(krb5_context context,
1866                                          krb5_ccache ccache,
1867                                          krb5_principal me,
1868                                          krb5_principal server,
1869                                          krb5_principal impersonate_princ,
1870                                          krb5_creds **out_creds)
1871 {
1872         krb5_error_code ret;
1873         krb5_creds *creds = NULL;
1874
1875         if (out_creds != NULL) {
1876                 *out_creds = NULL;
1877         }
1878
1879         if (impersonate_princ) {
1880 #ifdef HAVE_KRB5_GET_CREDS_OPT_SET_IMPERSONATE /* Heimdal */
1881                 ret = smb_krb5_get_credentials_for_user_opt(context, ccache, me, server, impersonate_princ, &creds);
1882 #elif defined(HAVE_KRB5_GET_CREDENTIALS_FOR_USER) /* MIT */
1883                 ret = smb_krb5_get_credentials_for_user(context, ccache, me, server, impersonate_princ, &creds);
1884 #else
1885                 ret = ENOTSUP;
1886 #endif
1887         } else {
1888                 krb5_creds in_creds;
1889
1890                 ZERO_STRUCT(in_creds);
1891
1892                 in_creds.client = me;
1893                 in_creds.server = server;
1894
1895                 ret = krb5_get_credentials(context, 0, ccache,
1896                                            &in_creds, &creds);
1897         }
1898         if (ret) {
1899                 goto done;
1900         }
1901
1902         if (out_creds) {
1903                 *out_creds = creds;
1904         }
1905
1906  done:
1907         if (creds && ret) {
1908                 krb5_free_creds(context, creds);
1909         }
1910
1911         return ret;
1912 }
1913
1914 /**
1915  * @brief Initialize a krb5_keyblock with the given data.
1916  *
1917  * Initialized a new keyblock, allocates the contents fo the key and
1918  * copies the data into the keyblock.
1919  *
1920  * @param[in]  context  The library context
1921  *
1922  * @param[in]  enctype  The encryption type.
1923  *
1924  * @param[in]  data     The date to initialize the keyblock with.
1925  *
1926  * @param[in]  length   The length of the keyblock.
1927  *
1928  * @param[in]  key      Newly allocated keyblock structure.
1929  *
1930  * The key date must be freed using krb5_free_keyblock_contents() when it is
1931  * no longer needed.
1932  *
1933  * @return 0 on success, a Kerberos error code otherwise.
1934  */
1935 krb5_error_code smb_krb5_keyblock_init_contents(krb5_context context,
1936                                                 krb5_enctype enctype,
1937                                                 const void *data,
1938                                                 size_t length,
1939                                                 krb5_keyblock *key)
1940 {
1941 #if defined(HAVE_KRB5_KEYBLOCK_INIT)
1942         return krb5_keyblock_init(context, enctype, data, length, key);
1943 #else
1944         memset(key, 0, sizeof(krb5_keyblock));
1945         KRB5_KEY_DATA(key) = SMB_MALLOC(length);
1946         if (NULL == KRB5_KEY_DATA(key)) {
1947                 return ENOMEM;
1948         }
1949         memcpy(KRB5_KEY_DATA(key), data, length);
1950         KRB5_KEY_LENGTH(key) = length;
1951         KRB5_KEY_TYPE(key) = enctype;
1952         return 0;
1953 #endif
1954 }
1955
1956 /**
1957  * @brief Simulate a kinit by putting the tgt in the given credential cache.
1958  *
1959  * This function uses a keyblock rather than needing the original password.
1960  *
1961  * @param[in]  ctx      The library context
1962  *
1963  * @param[in]  cc       The credential cache to put the tgt in.
1964  *
1965  * @param[in]  principal The client princial
1966  *
1967  * @param[in]  keyblock  The keyblock to use.
1968  *
1969  * @param[in]  target_service The service name of the initial credentials (or NULL).
1970  *
1971  * @param[in]  krb_options Initial credential options.
1972  *
1973  * @param[in]  expire_time    A pointer to store the experation time of the
1974  *                            credentials (or NULL).
1975  *
1976  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
1977  *                            valid (or NULL).
1978  *
1979  * @return 0 on success, a Kerberos error code otherwise.
1980  */
1981 krb5_error_code smb_krb5_kinit_keyblock_ccache(krb5_context ctx,
1982                                                krb5_ccache cc,
1983                                                krb5_principal principal,
1984                                                krb5_keyblock *keyblock,
1985                                                const char *target_service,
1986                                                krb5_get_init_creds_opt *krb_options,
1987                                                time_t *expire_time,
1988                                                time_t *kdc_time)
1989 {
1990         krb5_error_code code = 0;
1991         krb5_creds my_creds;
1992
1993 #if defined(HAVE_KRB5_GET_INIT_CREDS_KEYBLOCK)
1994         code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal,
1995                                             keyblock, 0, target_service,
1996                                             krb_options);
1997 #elif defined(HAVE_KRB5_GET_INIT_CREDS_KEYTAB)
1998 {
1999 #define SMB_CREDS_KEYTAB "MEMORY:tmp_smb_creds_XXXXXX"
2000         char tmp_name[sizeof(SMB_CREDS_KEYTAB)];
2001         krb5_keytab_entry entry;
2002         krb5_keytab keytab;
2003         mode_t mask;
2004
2005         memset(&entry, 0, sizeof(entry));
2006         entry.principal = principal;
2007         *(KRB5_KT_KEY(&entry)) = *keyblock;
2008
2009         memcpy(tmp_name, SMB_CREDS_KEYTAB, sizeof(SMB_CREDS_KEYTAB));
2010         mask = umask(S_IRWXO | S_IRWXG);
2011         mktemp(tmp_name);
2012         umask(mask);
2013         if (tmp_name[0] == 0) {
2014                 return KRB5_KT_BADNAME;
2015         }
2016         code = krb5_kt_resolve(ctx, tmp_name, &keytab);
2017         if (code) {
2018                 return code;
2019         }
2020
2021         code = krb5_kt_add_entry(ctx, keytab, &entry);
2022         if (code) {
2023                 (void)krb5_kt_close(ctx, keytab);
2024                 goto done;
2025         }
2026
2027         code = krb5_get_init_creds_keytab(ctx, &my_creds, principal,
2028                                           keytab, 0, target_service,
2029                                           krb_options);
2030         (void)krb5_kt_close(ctx, keytab);
2031 }
2032 #else
2033 #error krb5_get_init_creds_keyblock not available!
2034 #endif
2035         if (code) {
2036                 return code;
2037         }
2038
2039 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2040         /*
2041          * We need to store the principal as returned from the KDC to the
2042          * credentials cache. If we don't do that the KRB5 library is not
2043          * able to find the tickets it is looking for
2044          */
2045         principal = my_creds.client;
2046 #endif
2047         code = krb5_cc_initialize(ctx, cc, principal);
2048         if (code) {
2049                 goto done;
2050         }
2051
2052         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2053         if (code) {
2054                 goto done;
2055         }
2056
2057         if (expire_time) {
2058                 *expire_time = (time_t) my_creds.times.endtime;
2059         }
2060
2061         if (kdc_time) {
2062                 *kdc_time = (time_t) my_creds.times.starttime;
2063         }
2064
2065         code = 0;
2066 done:
2067         krb5_free_cred_contents(ctx, &my_creds);
2068         return code;
2069 }
2070
2071 /**
2072  * @brief Simulate a kinit by putting the tgt in the given credential cache.
2073  *
2074  * @param[in]  ctx      The library context
2075  *
2076  * @param[in]  cc       The credential cache to put the tgt in.
2077  *
2078  * @param[in]  principal The client princial
2079  *
2080  * @param[in]  password  The password (or NULL).
2081  *
2082  * @param[in]  target_service The service name of the initial credentials (or NULL).
2083  *
2084  * @param[in]  krb_options Initial credential options.
2085  *
2086  * @param[in]  expire_time    A pointer to store the experation time of the
2087  *                            credentials (or NULL).
2088  *
2089  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
2090  *                            valid (or NULL).
2091  *
2092  * @return 0 on success, a Kerberos error code otherwise.
2093  */
2094 krb5_error_code smb_krb5_kinit_password_ccache(krb5_context ctx,
2095                                                krb5_ccache cc,
2096                                                krb5_principal principal,
2097                                                const char *password,
2098                                                const char *target_service,
2099                                                krb5_get_init_creds_opt *krb_options,
2100                                                time_t *expire_time,
2101                                                time_t *kdc_time)
2102 {
2103         krb5_error_code code = 0;
2104         krb5_creds my_creds;
2105
2106         code = krb5_get_init_creds_password(ctx, &my_creds, principal,
2107                                             password, NULL, NULL, 0,
2108                                             target_service, krb_options);
2109         if (code) {
2110                 return code;
2111         }
2112
2113 #ifndef SAMBA4_USES_HEIMDAL /* MIT */
2114         /*
2115          * We need to store the principal as returned from the KDC to the
2116          * credentials cache. If we don't do that the KRB5 library is not
2117          * able to find the tickets it is looking for
2118          */
2119         principal = my_creds.client;
2120 #endif
2121         code = krb5_cc_initialize(ctx, cc, principal);
2122         if (code) {
2123                 goto done;
2124         }
2125
2126         code = krb5_cc_store_cred(ctx, cc, &my_creds);
2127         if (code) {
2128                 goto done;
2129         }
2130
2131         if (expire_time) {
2132                 *expire_time = (time_t) my_creds.times.endtime;
2133         }
2134
2135         if (kdc_time) {
2136                 *kdc_time = (time_t) my_creds.times.starttime;
2137         }
2138
2139         code = 0;
2140 done:
2141         krb5_free_cred_contents(ctx, &my_creds);
2142         return code;
2143 }
2144
2145 #ifdef SAMBA4_USES_HEIMDAL
2146 /**
2147  * @brief Simulate a kinit by putting the tgt in the given credential cache.
2148  *
2149  * @param[in]  ctx      The library context
2150  *
2151  * @param[in]  cc       The credential cache to store the tgt in.
2152  *
2153  * @param[in]  principal The initial client princial.
2154  *
2155  * @param[in]  password  The password (or NULL).
2156  *
2157  * @param[in]  impersonate_principal The impersonatiion principal (or NULL).
2158  *
2159  * @param[in]  self_service The local service for S4U2Self if
2160  *                          impersonate_principal is specified).
2161  *
2162  * @param[in]  target_service The service name of the initial credentials
2163  *                            (kpasswd/REALM or a remote service). It defaults
2164  *                            to the krbtgt if NULL.
2165  *
2166  * @param[in]  krb_options Initial credential options.
2167  *
2168  * @param[in]  expire_time    A pointer to store the experation time of the
2169  *                            credentials (or NULL).
2170  *
2171  * @param[in]  kdc_time       A pointer to store the time when the ticket becomes
2172  *                            valid (or NULL).
2173  *
2174  * @return 0 on success, a Kerberos error code otherwise.
2175  */
2176 krb5_error_code smb_krb5_kinit_s4u2_ccache(krb5_context ctx,
2177                                            krb5_ccache store_cc,
2178                                            krb5_principal init_principal,
2179                                            const char *init_password,
2180                                            krb5_principal impersonate_principal,
2181                                            const char *self_service,
2182                                            const char *target_service,
2183                                            krb5_get_init_creds_opt *krb_options,
2184                                            time_t *expire_time,
2185                                            time_t *kdc_time)
2186 {
2187         krb5_error_code code = 0;
2188         krb5_get_creds_opt options;
2189         krb5_principal store_principal;
2190         krb5_creds store_creds;
2191         krb5_creds *s4u2self_creds;
2192         Ticket s4u2self_ticket;
2193         size_t s4u2self_ticketlen;
2194         krb5_creds *s4u2proxy_creds;
2195         krb5_principal self_princ;
2196         bool s4u2proxy;
2197         krb5_principal target_princ;
2198         krb5_ccache tmp_cc;
2199         const char *self_realm;
2200         const char *client_realm = NULL;
2201         krb5_principal blacklist_principal = NULL;
2202         krb5_principal whitelist_principal = NULL;
2203
2204         code = krb5_get_init_creds_password(ctx, &store_creds,
2205                                             init_principal,
2206                                             init_password,
2207                                             NULL, NULL,
2208                                             0,
2209                                             NULL,
2210                                             krb_options);
2211         if (code != 0) {
2212                 return code;
2213         }
2214
2215         store_principal = init_principal;
2216
2217         /*
2218          * We are trying S4U2Self now:
2219          *
2220          * As we do not want to expose our TGT in the
2221          * krb5_ccache, which is also holds the impersonated creds.
2222          *
2223          * Some low level krb5/gssapi function might use the TGT
2224          * identity and let the client act as our machine account.
2225          *
2226          * We need to avoid that and use a temporary krb5_ccache
2227          * in order to pass our TGT to the krb5_get_creds() function.
2228          */
2229         code = krb5_cc_new_unique(ctx, NULL, NULL, &tmp_cc);
2230         if (code != 0) {
2231                 krb5_free_cred_contents(ctx, &store_creds);
2232                 return code;
2233         }
2234
2235         code = krb5_cc_initialize(ctx, tmp_cc, store_creds.client);
2236         if (code != 0) {
2237                 krb5_cc_destroy(ctx, tmp_cc);
2238                 krb5_free_cred_contents(ctx, &store_creds);
2239                 return code;
2240         }
2241
2242         code = krb5_cc_store_cred(ctx, tmp_cc, &store_creds);
2243         if (code != 0) {
2244                 krb5_free_cred_contents(ctx, &store_creds);
2245                 krb5_cc_destroy(ctx, tmp_cc);
2246                 return code;
2247         }
2248
2249         /*
2250          * we need to remember the client principal of our
2251          * TGT and make sure the KDC does not return this
2252          * in the impersonated tickets. This can happen
2253          * if the KDC does not support S4U2Self and S4U2Proxy.
2254          */
2255         blacklist_principal = store_creds.client;
2256         store_creds.client = NULL;
2257         krb5_free_cred_contents(ctx, &store_creds);
2258
2259         /*
2260          * Check if we also need S4U2Proxy or if S4U2Self is
2261          * enough in order to get a ticket for the target.
2262          */
2263         if (target_service == NULL) {
2264                 s4u2proxy = false;
2265         } else if (strcmp(target_service, self_service) == 0) {
2266                 s4u2proxy = false;
2267         } else {
2268                 s4u2proxy = true;
2269         }
2270
2271         /*
2272          * For S4U2Self we need our own service principal,
2273          * which belongs to our own realm (available on
2274          * our client principal).
2275          */
2276         self_realm = krb5_principal_get_realm(ctx, init_principal);
2277
2278         code = krb5_parse_name(ctx, self_service, &self_princ);
2279         if (code != 0) {
2280                 krb5_free_principal(ctx, blacklist_principal);
2281                 krb5_cc_destroy(ctx, tmp_cc);
2282                 return code;
2283         }
2284
2285         code = krb5_principal_set_realm(ctx, self_princ, self_realm);
2286         if (code != 0) {
2287                 krb5_free_principal(ctx, blacklist_principal);
2288                 krb5_free_principal(ctx, self_princ);
2289                 krb5_cc_destroy(ctx, tmp_cc);
2290                 return code;
2291         }
2292
2293         code = krb5_get_creds_opt_alloc(ctx, &options);
2294         if (code != 0) {
2295                 krb5_free_principal(ctx, blacklist_principal);
2296                 krb5_free_principal(ctx, self_princ);
2297                 krb5_cc_destroy(ctx, tmp_cc);
2298                 return code;
2299         }
2300
2301         if (s4u2proxy) {
2302                 /*
2303                  * If we want S4U2Proxy, we need the forwardable flag
2304                  * on the S4U2Self ticket.
2305                  */
2306                 krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2307         }
2308
2309         code = krb5_get_creds_opt_set_impersonate(ctx, options,
2310                                                   impersonate_principal);
2311         if (code != 0) {
2312                 krb5_get_creds_opt_free(ctx, options);
2313                 krb5_free_principal(ctx, blacklist_principal);
2314                 krb5_free_principal(ctx, self_princ);
2315                 krb5_cc_destroy(ctx, tmp_cc);
2316                 return code;
2317         }
2318
2319         code = krb5_get_creds(ctx, options, tmp_cc,
2320                               self_princ, &s4u2self_creds);
2321         krb5_get_creds_opt_free(ctx, options);
2322         krb5_free_principal(ctx, self_princ);
2323         if (code != 0) {
2324                 krb5_free_principal(ctx, blacklist_principal);
2325                 krb5_cc_destroy(ctx, tmp_cc);
2326                 return code;
2327         }
2328
2329         if (!s4u2proxy) {
2330                 krb5_cc_destroy(ctx, tmp_cc);
2331
2332                 /*
2333                  * Now make sure we store the impersonated principal
2334                  * and creds instead of the TGT related stuff
2335                  * in the krb5_ccache of the caller.
2336                  */
2337                 code = krb5_copy_creds_contents(ctx, s4u2self_creds,
2338                                                 &store_creds);
2339                 krb5_free_creds(ctx, s4u2self_creds);
2340                 if (code != 0) {
2341                         return code;
2342                 }
2343
2344                 /*
2345                  * It's important to store the principal the KDC
2346                  * returned, as otherwise the caller would not find
2347                  * the S4U2Self ticket in the krb5_ccache lookup.
2348                  */
2349                 store_principal = store_creds.client;
2350                 goto store;
2351         }
2352
2353         /*
2354          * We are trying S4U2Proxy:
2355          *
2356          * We need the ticket from the S4U2Self step
2357          * and our TGT in order to get the delegated ticket.
2358          */
2359         code = decode_Ticket((const uint8_t *)s4u2self_creds->ticket.data,
2360                              s4u2self_creds->ticket.length,
2361                              &s4u2self_ticket,
2362                              &s4u2self_ticketlen);
2363         if (code != 0) {
2364                 krb5_free_creds(ctx, s4u2self_creds);
2365                 krb5_free_principal(ctx, blacklist_principal);
2366                 krb5_cc_destroy(ctx, tmp_cc);
2367                 return code;
2368         }
2369
2370         /*
2371          * we need to remember the client principal of the
2372          * S4U2Self stage and as it needs to match the one we
2373          * will get for the S4U2Proxy stage. We need this
2374          * in order to detect KDCs which does not support S4U2Proxy.
2375          */
2376         whitelist_principal = s4u2self_creds->client;
2377         s4u2self_creds->client = NULL;
2378         krb5_free_creds(ctx, s4u2self_creds);
2379
2380         /*
2381          * For S4U2Proxy we also got a target service principal,
2382          * which also belongs to our own realm (available on
2383          * our client principal).
2384          */
2385         code = krb5_parse_name(ctx, target_service, &target_princ);
2386         if (code != 0) {
2387                 free_Ticket(&s4u2self_ticket);
2388                 krb5_free_principal(ctx, whitelist_principal);
2389                 krb5_free_principal(ctx, blacklist_principal);
2390                 krb5_cc_destroy(ctx, tmp_cc);
2391                 return code;
2392         }
2393
2394         code = krb5_principal_set_realm(ctx, target_princ, self_realm);
2395         if (code != 0) {
2396                 free_Ticket(&s4u2self_ticket);
2397                 krb5_free_principal(ctx, target_princ);
2398                 krb5_free_principal(ctx, whitelist_principal);
2399                 krb5_free_principal(ctx, blacklist_principal);
2400                 krb5_cc_destroy(ctx, tmp_cc);
2401                 return code;
2402         }
2403
2404         code = krb5_get_creds_opt_alloc(ctx, &options);
2405         if (code != 0) {
2406                 free_Ticket(&s4u2self_ticket);
2407                 krb5_free_principal(ctx, target_princ);
2408                 krb5_free_principal(ctx, whitelist_principal);
2409                 krb5_free_principal(ctx, blacklist_principal);
2410                 krb5_cc_destroy(ctx, tmp_cc);
2411                 return code;
2412         }
2413
2414         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_FORWARDABLE);
2415         krb5_get_creds_opt_set_options(ctx, options, KRB5_GC_CONSTRAINED_DELEGATION);
2416
2417         code = krb5_get_creds_opt_set_ticket(ctx, options, &s4u2self_ticket);
2418         free_Ticket(&s4u2self_ticket);
2419         if (code != 0) {
2420                 krb5_get_creds_opt_free(ctx, options);
2421                 krb5_free_principal(ctx, target_princ);
2422                 krb5_free_principal(ctx, whitelist_principal);
2423                 krb5_free_principal(ctx, blacklist_principal);
2424                 krb5_cc_destroy(ctx, tmp_cc);
2425                 return code;
2426         }
2427
2428         code = krb5_get_creds(ctx, options, tmp_cc,
2429                               target_princ, &s4u2proxy_creds);
2430         krb5_get_creds_opt_free(ctx, options);
2431         krb5_free_principal(ctx, target_princ);
2432         krb5_cc_destroy(ctx, tmp_cc);
2433         if (code != 0) {
2434                 krb5_free_principal(ctx, whitelist_principal);
2435                 krb5_free_principal(ctx, blacklist_principal);
2436                 return code;
2437         }
2438
2439         /*
2440          * Now make sure we store the impersonated principal
2441          * and creds instead of the TGT related stuff
2442          * in the krb5_ccache of the caller.
2443          */
2444         code = krb5_copy_creds_contents(ctx, s4u2proxy_creds,
2445                                         &store_creds);
2446         krb5_free_creds(ctx, s4u2proxy_creds);
2447         if (code != 0) {
2448                 krb5_free_principal(ctx, whitelist_principal);
2449                 krb5_free_principal(ctx, blacklist_principal);
2450                 return code;
2451         }
2452
2453         /*
2454          * It's important to store the principal the KDC
2455          * returned, as otherwise the caller would not find
2456          * the S4U2Self ticket in the krb5_ccache lookup.
2457          */
2458         store_principal = store_creds.client;
2459
2460  store:
2461         if (blacklist_principal &&
2462             krb5_principal_compare(ctx, store_creds.client, blacklist_principal)) {
2463                 char *sp = NULL;
2464                 char *ip = NULL;
2465
2466                 code = krb5_unparse_name(ctx, blacklist_principal, &sp);
2467                 if (code != 0) {
2468                         sp = NULL;
2469                 }
2470                 code = krb5_unparse_name(ctx, impersonate_principal, &ip);
2471                 if (code != 0) {
2472                         ip = NULL;
2473                 }
2474                 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2475                           "KDC returned self principal[%s] while impersonating [%s]\n",
2476                           sp?sp:"<no memory>",
2477                           ip?ip:"<no memory>"));
2478
2479                 SAFE_FREE(sp);
2480                 SAFE_FREE(ip);
2481
2482                 krb5_free_principal(ctx, whitelist_principal);
2483                 krb5_free_principal(ctx, blacklist_principal);
2484                 krb5_free_cred_contents(ctx, &store_creds);
2485                 return KRB5_FWD_BAD_PRINCIPAL;
2486         }
2487         if (blacklist_principal) {
2488                 krb5_free_principal(ctx, blacklist_principal);
2489         }
2490
2491         if (whitelist_principal &&
2492             !krb5_principal_compare(ctx, store_creds.client, whitelist_principal)) {
2493                 char *sp = NULL;
2494                 char *ep = NULL;
2495
2496                 code = krb5_unparse_name(ctx, store_creds.client, &sp);
2497                 if (code != 0) {
2498                         sp = NULL;
2499                 }
2500                 code = krb5_unparse_name(ctx, whitelist_principal, &ep);
2501                 if (code != 0) {
2502                         ep = NULL;
2503                 }
2504                 DEBUG(1, ("smb_krb5_kinit_password_cache: "
2505                           "KDC returned wrong principal[%s] we expected [%s]\n",
2506                           sp?sp:"<no memory>",
2507                           ep?ep:"<no memory>"));
2508
2509                 SAFE_FREE(sp);
2510                 SAFE_FREE(ep);
2511
2512                 krb5_free_principal(ctx, whitelist_principal);
2513                 krb5_free_cred_contents(ctx, &store_creds);
2514                 return KRB5_FWD_BAD_PRINCIPAL;
2515         }
2516         if (whitelist_principal) {
2517                 krb5_free_principal(ctx, whitelist_principal);
2518         }
2519
2520         code = krb5_cc_initialize(ctx, store_cc, store_principal);
2521         if (code != 0) {
2522                 krb5_free_cred_contents(ctx, &store_creds);
2523                 return code;
2524         }
2525
2526         code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2527         if (code != 0) {
2528                 krb5_free_cred_contents(ctx, &store_creds);
2529                 return code;
2530         }
2531
2532         client_realm = krb5_principal_get_realm(ctx, store_creds.client);
2533         if (client_realm != NULL) {
2534                 /*
2535                  * Because the CANON flag doesn't have any impact
2536                  * on the impersonate_principal => store_creds.client
2537                  * realm mapping. We need to store the credentials twice,
2538                  * once with the returned realm and once with the
2539                  * realm of impersonate_principal.
2540                  */
2541                 code = krb5_principal_set_realm(ctx, store_creds.server,
2542                                                 client_realm);
2543                 if (code != 0) {
2544                         krb5_free_cred_contents(ctx, &store_creds);
2545                         return code;
2546                 }
2547
2548                 code = krb5_cc_store_cred(ctx, store_cc, &store_creds);
2549                 if (code != 0) {
2550                         krb5_free_cred_contents(ctx, &store_creds);
2551                         return code;
2552                 }
2553         }
2554
2555         if (expire_time) {
2556                 *expire_time = (time_t) store_creds.times.endtime;
2557         }
2558
2559         if (kdc_time) {
2560                 *kdc_time = (time_t) store_creds.times.starttime;
2561         }
2562
2563         krb5_free_cred_contents(ctx, &store_creds);
2564
2565         return 0;
2566 }
2567 #endif
2568
2569 #if !defined(HAVE_KRB5_MAKE_PRINCIPAL) && defined(HAVE_KRB5_BUILD_PRINCIPAL_ALLOC_VA)
2570 /**
2571  * @brief Create a principal name using a variable argument list.
2572  *
2573  * @param[in]  context  The library context.
2574  *
2575  * @param[inout]  principal A pointer to the principal structure.
2576  *
2577  * @param[in]  _realm    The realm to use. If NULL then the function will
2578  *                       get the default realm name.
2579  *
2580  * @param[in]  ...       A list of 'char *' components, ending with NULL.
2581  *
2582  * Use krb5_free_principal() to free the principal when it is no longer needed.
2583  *
2584  * @return 0 on success, a Kerberos error code otherwise.
2585  */
2586 krb5_error_code smb_krb5_make_principal(krb5_context context,
2587                                         krb5_principal *principal,
2588                                         const char *_realm, ...)
2589 {
2590         krb5_error_code code;
2591         bool free_realm;
2592         char *realm;
2593         va_list ap;
2594
2595         if (_realm) {
2596                 realm = discard_const_p(char, _realm);
2597                 free_realm = false;
2598         } else {
2599                 code = krb5_get_default_realm(context, &realm);
2600                 if (code) {
2601                         return code;
2602                 }
2603                 free_realm = true;
2604         }
2605
2606         va_start(ap, _realm);
2607         code = krb5_build_principal_alloc_va(context, principal,
2608                                              strlen(realm), realm,
2609                                              ap);
2610         va_end(ap);
2611
2612         if (free_realm) {
2613                 krb5_free_default_realm(context, realm);
2614         }
2615
2616         return code;
2617 }
2618 #endif
2619
2620 #if !defined(HAVE_KRB5_CC_GET_LIFETIME) && defined(HAVE_KRB5_CC_RETRIEVE_CRED)
2621 /**
2622  * @brief Get the lifetime of the initial ticket in the cache.
2623  *
2624  * @param[in]  context  The kerberos context.
2625  *
2626  * @param[in]  id       The credential cache to get the ticket lifetime.
2627  *
2628  * @param[out] t        A pointer to a time value to store the lifetime.
2629  *
2630  * @return              0 on success, a krb5_error_code on error.
2631  */
2632 krb5_error_code smb_krb5_cc_get_lifetime(krb5_context context,
2633                                          krb5_ccache id,
2634                                          time_t *t)
2635 {
2636         krb5_cc_cursor cursor;
2637         krb5_error_code kerr;
2638         krb5_creds cred;
2639         krb5_timestamp now;
2640
2641         *t = 0;
2642
2643         kerr = krb5_timeofday(context, &now);
2644         if (kerr) {
2645                 return kerr;
2646         }
2647
2648         kerr = krb5_cc_start_seq_get(context, id, &cursor);
2649         if (kerr) {
2650                 return kerr;
2651         }
2652
2653         while ((kerr = krb5_cc_next_cred(context, id, &cursor, &cred)) == 0) {
2654 #ifndef HAVE_FLAGS_IN_KRB5_CREDS
2655                 if (cred.ticket_flags & TKT_FLG_INITIAL) {
2656 #else
2657                 if (cred.flags.b.initial) {
2658 #endif
2659                         if (now < cred.times.endtime) {
2660                                 *t = (time_t) (cred.times.endtime - now);
2661                         }
2662                         krb5_free_cred_contents(context, &cred);
2663                         break;
2664                 }
2665                 krb5_free_cred_contents(context, &cred);
2666         }
2667
2668         krb5_cc_end_seq_get(context, id, &cursor);
2669
2670         return kerr;
2671 }
2672 #endif /* HAVE_KRB5_CC_GET_LIFETIME */
2673
2674 #if !defined(HAVE_KRB5_FREE_CHECKSUM_CONTENTS) && defined(HAVE_FREE_CHECKSUM)
2675 void smb_krb5_free_checksum_contents(krb5_context ctx, krb5_checksum *cksum)
2676 {
2677         free_Checksum(cksum);
2678 }
2679 #endif
2680
2681 /**
2682  * @brief Compute a checksum operating on a keyblock.
2683  *
2684  * This function computes a checksum over a PAC using the keyblock for a keyed
2685  * checksum.
2686  *
2687  * @param[in]  mem_ctx A talloc context to alocate the signature on.
2688  *
2689  * @param[in]  pac_data The PAC as input.
2690  *
2691  * @param[in]  context  The library context.
2692  *
2693  * @param[in]  keyblock Encryption key for a keyed checksum.
2694  *
2695  * @param[out] sig_type The checksum type
2696  *
2697  * @param[out] sig_blob The talloc'ed checksum
2698  *
2699  * The caller must free the sig_blob with talloc_free() when it is not needed
2700  * anymore.
2701  *
2702  * @return 0 on success, a Kerberos error code otherwise.
2703  */
2704 krb5_error_code smb_krb5_make_pac_checksum(TALLOC_CTX *mem_ctx,
2705                                            DATA_BLOB *pac_data,
2706                                            krb5_context context,
2707                                            const krb5_keyblock *keyblock,
2708                                            uint32_t *sig_type,
2709                                            DATA_BLOB *sig_blob)
2710 {
2711         krb5_error_code ret;
2712         krb5_checksum cksum;
2713 #if defined(HAVE_KRB5_CRYPTO_INIT) && defined(HAVE_KRB5_CREATE_CHECKSUM)
2714         krb5_crypto crypto;
2715
2716
2717         ret = krb5_crypto_init(context,
2718                                keyblock,
2719                                0,
2720                                &crypto);
2721         if (ret) {
2722                 DEBUG(0,("krb5_crypto_init() failed: %s\n",
2723                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2724                 return ret;
2725         }
2726         ret = krb5_create_checksum(context,
2727                                    crypto,
2728                                    KRB5_KU_OTHER_CKSUM,
2729                                    0,
2730                                    pac_data->data,
2731                                    pac_data->length,
2732                                    &cksum);
2733         if (ret) {
2734                 DEBUG(2, ("PAC Verification failed: %s\n",
2735                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2736         }
2737
2738         krb5_crypto_destroy(context, crypto);
2739
2740         if (ret) {
2741                 return ret;
2742         }
2743
2744         *sig_type = cksum.cksumtype;
2745         *sig_blob = data_blob_talloc(mem_ctx,
2746                                         cksum.checksum.data,
2747                                         cksum.checksum.length);
2748 #elif defined(HAVE_KRB5_C_MAKE_CHECKSUM)
2749         krb5_data input;
2750
2751         input.data = (char *)pac_data->data;
2752         input.length = pac_data->length;
2753
2754         ret = krb5_c_make_checksum(context,
2755                                    0,
2756                                    keyblock,
2757                                    KRB5_KEYUSAGE_APP_DATA_CKSUM,
2758                                    &input,
2759                                    &cksum);
2760         if (ret) {
2761                 DEBUG(2, ("PAC Verification failed: %s\n",
2762                           smb_get_krb5_error_message(context, ret, mem_ctx)));
2763                 return ret;
2764         }
2765
2766         *sig_type = cksum.checksum_type;
2767         *sig_blob = data_blob_talloc(mem_ctx,
2768                                         cksum.contents,
2769                                         cksum.length);
2770
2771 #else
2772 #error krb5_create_checksum or krb5_c_make_checksum not available
2773 #endif /* HAVE_KRB5_C_MAKE_CHECKSUM */
2774         smb_krb5_free_checksum_contents(context, &cksum);
2775
2776         return 0;
2777 }
2778
2779
2780 /**
2781  * @brief Get realm of a principal
2782  *
2783  * @param[in] mem_ctx   The talloc ctx to put the result on
2784  *
2785  * @param[in] context   The library context
2786  *
2787  * @param[in] principal The principal to get the realm from.
2788  *
2789  * @return A talloced string with the realm or NULL if an error occurred.
2790  */
2791 char *smb_krb5_principal_get_realm(TALLOC_CTX *mem_ctx,
2792                                    krb5_context context,
2793                                    krb5_const_principal principal)
2794 {
2795 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
2796         return talloc_strdup(mem_ctx,
2797                              krb5_principal_get_realm(context, principal));
2798 #elif defined(krb5_princ_realm) /* MIT */
2799         const krb5_data *realm;
2800         realm = krb5_princ_realm(context, principal);
2801         return talloc_strndup(mem_ctx, realm->data, realm->length);
2802 #else
2803 #error UNKNOWN_GET_PRINC_REALM_FUNCTIONS
2804 #endif
2805 }
2806
2807 /**
2808  * @brief Get realm of a principal
2809  *
2810  * @param[in] context   The library context
2811  *
2812  * @param[in] principal The principal to set the realm
2813  *
2814  * @param[in] realm     The realm as a string to set.
2815  *
2816  * @retur 0 on success, a Kerberos error code otherwise.
2817  */
2818 krb5_error_code smb_krb5_principal_set_realm(krb5_context context,
2819                                              krb5_principal principal,
2820                                              const char *realm)
2821 {
2822 #ifdef HAVE_KRB5_PRINCIPAL_SET_REALM /* Heimdal */
2823         return krb5_principal_set_realm(context, principal, realm);
2824 #elif defined(krb5_princ_realm) && defined(krb5_princ_set_realm) /* MIT */
2825         krb5_error_code ret;
2826         krb5_data data;
2827         krb5_data *old_data;
2828
2829         old_data = krb5_princ_realm(context, principal);
2830
2831         ret = smb_krb5_copy_data_contents(&data,
2832                                           realm,
2833                                           strlen(realm));
2834         if (ret) {
2835                 return ret;
2836         }
2837
2838         /* free realm before setting */
2839         free(old_data->data);
2840
2841         krb5_princ_set_realm(context, principal, &data);
2842
2843         return ret;
2844 #else
2845 #error UNKNOWN_PRINC_SET_REALM_FUNCTION
2846 #endif
2847 }
2848
2849
2850 /**
2851  * @brief Get the realm from the service hostname.
2852  *
2853  * This function will look for a domain realm mapping in the [domain_realm]
2854  * section of the krb5.conf first and fallback to extract the realm from
2855  * the provided service hostname. As a last resort it will return the
2856  * provided client_realm.
2857  *
2858  * @param[in]  mem_ctx     The talloc context
2859  *
2860  * @param[in]  hostname    The service hostname
2861  *
2862  * @param[in]  client_realm  If we can not find a mapping, fall back to
2863  *                           this realm.
2864  *
2865  * @return The realm to use for the service hostname, NULL if a fatal error
2866  *         occured.
2867  */
2868 char *smb_krb5_get_realm_from_hostname(TALLOC_CTX *mem_ctx,
2869                                        const char *hostname,
2870                                        const char *client_realm)
2871 {
2872 #if defined(HAVE_KRB5_REALM_TYPE)
2873         /* Heimdal. */
2874         krb5_realm *realm_list = NULL;
2875 #else
2876         /* MIT */
2877         char **realm_list = NULL;
2878 #endif
2879         char *realm = NULL;
2880         krb5_error_code kerr;
2881         krb5_context ctx = NULL;
2882
2883         initialize_krb5_error_table();
2884         if (krb5_init_context(&ctx)) {
2885                 return NULL;
2886         }
2887
2888         kerr = krb5_get_host_realm(ctx, hostname, &realm_list);
2889         if (kerr == KRB5_ERR_HOST_REALM_UNKNOWN) {
2890                 realm_list = NULL;
2891                 kerr = 0;
2892         }
2893         if (kerr != 0) {
2894                 DEBUG(3,("kerberos_get_realm_from_hostname %s: "
2895                         "failed %s\n",
2896                         hostname ? hostname : "(NULL)",
2897                         error_message(kerr) ));
2898                 goto out;
2899         }
2900
2901         if (realm_list != NULL &&
2902             realm_list[0] != NULL &&
2903             realm_list[0][0] != '\0') {
2904                 realm = talloc_strdup(mem_ctx, realm_list[0]);
2905                 if (realm == NULL) {
2906                         goto out;
2907                 }
2908         } else {
2909                 const char *p = NULL;
2910
2911                 /*
2912                  * "dc6.samba2003.example.com"
2913                  * returns a realm of "SAMBA2003.EXAMPLE.COM"
2914                  *
2915                  * "dc6." returns realm as NULL
2916                  */
2917                 p = strchr_m(hostname, '.');
2918                 if (p != NULL && p[1] != '\0') {
2919                         realm = talloc_strdup_upper(mem_ctx, p + 1);
2920                         if (realm == NULL) {
2921                                 goto out;
2922                         }
2923                 }
2924         }
2925
2926         if (realm == NULL) {
2927                 realm = talloc_strdup(mem_ctx, client_realm);
2928         }
2929
2930   out:
2931
2932         if (ctx) {
2933                 if (realm_list) {
2934                         krb5_free_host_realm(ctx, realm_list);
2935                         realm_list = NULL;
2936                 }
2937                 krb5_free_context(ctx);
2938                 ctx = NULL;
2939         }
2940         return realm;
2941 }
2942
2943 /**
2944  * @brief Get an error string from a Kerberos error code.
2945  *
2946  * @param[in]  context  The library context.
2947  *
2948  * @param[in]  code     The Kerberos error code.
2949  *
2950  * @param[in]  mem_ctx  The talloc context to allocate the error string on.
2951  *
2952  * @return A talloc'ed error string or NULL if an error occurred.
2953  *
2954  * The caller must free the returned error string with talloc_free() if not
2955  * needed anymore
2956  */
2957 char *smb_get_krb5_error_message(krb5_context context,
2958                                  krb5_error_code code,
2959                                  TALLOC_CTX *mem_ctx)
2960 {
2961         char *ret;
2962
2963 #if defined(HAVE_KRB5_GET_ERROR_MESSAGE) && defined(HAVE_KRB5_FREE_ERROR_MESSAGE)
2964         const char *context_error = krb5_get_error_message(context, code);
2965         if (context_error) {
2966                 ret = talloc_asprintf(mem_ctx, "%s: %s",
2967                                         error_message(code), context_error);
2968                 krb5_free_error_message(context, context_error);
2969                 return ret;
2970         }
2971 #endif
2972         ret = talloc_strdup(mem_ctx, error_message(code));
2973         return ret;
2974 }
2975
2976
2977 /**
2978  * @brief Return the kerberos library setting for: libdefaults:allow_weak_crypto
2979  *
2980  * @param[in]  context  The library context
2981  *
2982  * @return True if weak crypto is allowed, false if not.
2983  */
2984 krb5_boolean smb_krb5_get_allowed_weak_crypto(krb5_context context)
2985 #if defined(HAVE_KRB5_CONFIG_GET_BOOL_DEFAULT)
2986 {
2987         return krb5_config_get_bool_default(context,
2988                                             NULL,
2989                                             FALSE,
2990                                             "libdefaults",
2991                                             "allow_weak_crypto",
2992                                             NULL);
2993 }
2994 #elif defined(HAVE_PROFILE_H) && defined(HAVE_KRB5_GET_PROFILE)
2995 {
2996 #include <profile.h>
2997         krb5_error_code ret;
2998         krb5_boolean ret_default = false;
2999         profile_t profile;
3000         int ret_profile;
3001
3002         ret = krb5_get_profile(context,
3003                                &profile);
3004         if (ret) {
3005                 return ret_default;
3006         }
3007
3008         ret = profile_get_boolean(profile,
3009                                   "libdefaults",
3010                                   "allow_weak_crypto",
3011                                   NULL, /* subsubname */
3012                                   ret_default, /* def_val */
3013                                   &ret_profile /* *ret_default */);
3014         if (ret) {
3015                 return ret_default;
3016         }
3017
3018         profile_release(profile);
3019
3020         return ret_profile;
3021 }
3022 #else
3023 #error UNKNOWN_KRB5_CONFIG_ROUTINES
3024 #endif
3025
3026 /**
3027  * @brief Return the type of a krb5_principal
3028  *
3029  * @param[in]  context  The library context.
3030  *
3031  * @param[in]  principal The principal to get the type from.
3032  *
3033  * @return The integer type of the principal.
3034  */
3035 int smb_krb5_principal_get_type(krb5_context context,
3036                                 krb5_const_principal principal)
3037 {
3038 #ifdef HAVE_KRB5_PRINCIPAL_GET_TYPE /* Heimdal */
3039         return krb5_principal_get_type(context, principal);
3040 #elif defined(krb5_princ_type) /* MIT */
3041         return krb5_princ_type(context, principal);
3042 #else
3043 #error  UNKNOWN_PRINC_GET_TYPE_FUNCTION
3044 #endif
3045 }
3046
3047 /**
3048  * @brief Set the type of a principal
3049  *
3050  * @param[in]  context  The library context
3051  *
3052  * @param[inout] principal The principal to set the type for.
3053  *
3054  * @param[in]  type     The principal type to set.
3055  */
3056 void smb_krb5_principal_set_type(krb5_context context,
3057                                  krb5_principal principal,
3058                                  int type)
3059 {
3060 #ifdef HAVE_KRB5_PRINCIPAL_SET_TYPE /* Heimdal */
3061         krb5_principal_set_type(context, principal, type);
3062 #elif defined(krb5_princ_type) /* MIT */
3063         krb5_princ_type(context, principal) = type;
3064 #else
3065 #error  UNKNOWN_PRINC_SET_TYPE_FUNCTION
3066 #endif
3067 }
3068
3069 #if !defined(HAVE_KRB5_WARNX)
3070 /**
3071  * @brief Log a Kerberos message
3072  *
3073  * It sends the message to com_err.
3074  *
3075  * @param[in]  context  The library context
3076  *
3077  * @param[in]  fmt      The message format
3078  *
3079  * @param[in]  ...      The message arguments
3080  *
3081  * @return 0 on success.
3082  */
3083 krb5_error_code krb5_warnx(krb5_context context, const char *fmt, ...)
3084 {
3085         va_list args;
3086
3087         va_start(args, fmt);
3088         com_err_va("samba-kdc", errno, fmt, args);
3089         va_end(args);
3090
3091         return 0;
3092 }
3093 #endif
3094
3095 /**
3096  * @brief Copy a credential cache.
3097  *
3098  * @param[in]  context  The library context.
3099  *
3100  * @param[in]  incc     Credential cache to be copied.
3101  *
3102  * @param[inout] outcc  Copy of credential cache to be filled in.
3103  *
3104  * @return 0 on success, a Kerberos error code otherwise.
3105  */
3106 krb5_error_code smb_krb5_cc_copy_creds(krb5_context context,
3107                                        krb5_ccache incc, krb5_ccache outcc)
3108 {
3109 #ifdef HAVE_KRB5_CC_COPY_CACHE /* Heimdal */
3110         return krb5_cc_copy_cache(context, incc, outcc);
3111 #elif defined(HAVE_KRB5_CC_COPY_CREDS)
3112         krb5_error_code ret;
3113         krb5_principal princ = NULL;
3114
3115         ret = krb5_cc_get_principal(context, incc, &princ);
3116         if (ret != 0) {
3117                 return ret;
3118         }
3119         ret = krb5_cc_initialize(context, outcc, princ);
3120         krb5_free_principal(context, princ);
3121         if (ret != 0) {
3122                 return ret;
3123         }
3124         return krb5_cc_copy_creds(context, incc, outcc);
3125 #else
3126 #error UNKNOWN_KRB5_CC_COPY_CACHE_OR_CREDS_FUNCTION
3127 #endif
3128 }
3129
3130 /**********************************************************
3131  * ADS KRB5 CALLS
3132  **********************************************************/
3133
3134 static bool ads_cleanup_expired_creds(krb5_context context,
3135                                       krb5_ccache  ccache,
3136                                       krb5_creds  *credsp)
3137 {
3138         krb5_error_code retval;
3139         const char *cc_type = krb5_cc_get_type(context, ccache);
3140
3141         DEBUG(3, ("ads_cleanup_expired_creds: Ticket in ccache[%s:%s] expiration %s\n",
3142                   cc_type, krb5_cc_get_name(context, ccache),
3143                   http_timestring(talloc_tos(), credsp->times.endtime)));
3144
3145         /* we will probably need new tickets if the current ones
3146            will expire within 10 seconds.
3147         */
3148         if (credsp->times.endtime >= (time(NULL) + 10))
3149                 return false;
3150
3151         /* heimdal won't remove creds from a file ccache, and
3152            perhaps we shouldn't anyway, since internally we
3153            use memory ccaches, and a FILE one probably means that
3154            we're using creds obtained outside of our exectuable
3155         */
3156         if (strequal(cc_type, "FILE")) {
3157                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a %s ccache\n", cc_type));
3158                 return false;
3159         }
3160
3161         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
3162         if (retval) {
3163                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
3164                           error_message(retval)));
3165                 /* If we have an error in this, we want to display it,
3166                    but continue as though we deleted it */
3167         }
3168         return true;
3169 }
3170
3171 /* Allocate and setup the auth context into the state we need. */
3172
3173 static krb5_error_code ads_setup_auth_context(krb5_context context,
3174                                               krb5_auth_context *auth_context)
3175 {
3176         krb5_error_code retval;
3177
3178         retval = krb5_auth_con_init(context, auth_context );
3179         if (retval) {
3180                 DEBUG(1,("krb5_auth_con_init failed (%s)\n",
3181                         error_message(retval)));
3182                 return retval;
3183         }
3184
3185         /* Ensure this is an addressless ticket. */
3186         retval = krb5_auth_con_setaddrs(context, *auth_context, NULL, NULL);
3187         if (retval) {
3188                 DEBUG(1,("krb5_auth_con_setaddrs failed (%s)\n",
3189                         error_message(retval)));
3190         }
3191
3192         return retval;
3193 }
3194
3195 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
3196 static krb5_error_code ads_create_gss_checksum(krb5_data *in_data, /* [inout] */
3197                                                uint32_t gss_flags)
3198 {
3199         unsigned int orig_length = in_data->length;
3200         unsigned int base_cksum_size = GSSAPI_CHECKSUM_SIZE;
3201         char *gss_cksum = NULL;
3202
3203         if (orig_length) {
3204                 /* Extra length field for delgated ticket. */
3205                 base_cksum_size += 4;
3206         }
3207
3208         if ((unsigned int)base_cksum_size + orig_length <
3209                         (unsigned int)base_cksum_size) {
3210                 return EINVAL;
3211         }
3212
3213         gss_cksum = (char *)SMB_MALLOC(base_cksum_size + orig_length);
3214         if (gss_cksum == NULL) {
3215                 return ENOMEM;
3216         }
3217
3218         memset(gss_cksum, '\0', base_cksum_size + orig_length);
3219         SIVAL(gss_cksum, 0, GSSAPI_BNDLENGTH);
3220
3221         /*
3222          * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes.
3223          * This matches the behavior of heimdal and mit.
3224          *
3225          * And it is needed to work against some closed source
3226          * SMB servers.
3227          *
3228          * See bug #7883
3229          */
3230         memset(&gss_cksum[4], 0x00, GSSAPI_BNDLENGTH);
3231
3232         SIVAL(gss_cksum, 20, gss_flags);
3233
3234         if (orig_length) {
3235                 SSVAL(gss_cksum, 24, 1); /* The Delegation Option identifier */
3236                 SSVAL(gss_cksum, 26, orig_length);
3237                 /* Copy the kerberos KRB_CRED data */
3238                 memcpy(gss_cksum + 28, in_data->data, orig_length);
3239                 free(in_data->data);
3240                 in_data->data = NULL;
3241                 in_data->length = 0;
3242         }
3243         in_data->data = gss_cksum;
3244         in_data->length = base_cksum_size + orig_length;
3245         return 0;
3246 }
3247 #endif
3248
3249 /*
3250  * We can't use krb5_mk_req because w2k wants the service to be in a particular
3251  * format.
3252  */
3253 static krb5_error_code ads_krb5_mk_req(krb5_context context,
3254                                        krb5_auth_context *auth_context,
3255                                        const krb5_flags ap_req_options,
3256                                        const char *principal,
3257                                        krb5_ccache ccache,
3258                                        krb5_data *outbuf,
3259                                        time_t *expire_time,
3260                                        const char *impersonate_princ_s)
3261 {
3262         krb5_error_code retval;
3263         krb5_principal server;
3264         krb5_principal impersonate_princ = NULL;
3265         krb5_creds *credsp;
3266         krb5_creds creds;
3267         krb5_data in_data;
3268         bool creds_ready = false;
3269         int i = 0, maxtries = 3;
3270         bool ok;
3271
3272         ZERO_STRUCT(in_data);
3273
3274         retval = smb_krb5_parse_name(context, principal, &server);
3275         if (retval != 0) {
3276                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
3277                 return retval;
3278         }
3279
3280         if (impersonate_princ_s) {
3281                 retval = smb_krb5_parse_name(context, impersonate_princ_s,
3282                                              &impersonate_princ);
3283                 if (retval) {
3284                         DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", impersonate_princ_s));
3285                         goto cleanup_princ;
3286                 }
3287         }
3288
3289         /* obtain ticket & session key */
3290         ZERO_STRUCT(creds);
3291         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
3292                 DEBUG(1,("ads_krb5_mk_req: krb5_copy_principal failed (%s)\n",
3293                          error_message(retval)));
3294                 goto cleanup_princ;
3295         }
3296
3297         retval = krb5_cc_get_principal(context, ccache, &creds.client);
3298         if (retval != 0) {
3299                 /* This can commonly fail on smbd startup with no ticket in the cache.
3300                  * Report at higher level than 1. */
3301                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n",
3302                          error_message(retval)));
3303                 goto cleanup_creds;
3304         }
3305
3306         while (!creds_ready && (i < maxtries)) {
3307
3308                 retval = smb_krb5_get_credentials(context,
3309                                                   ccache,
3310                                                   creds.client,
3311                                                   creds.server,
3312                                                   impersonate_princ,
3313                                                   &credsp);
3314                 if (retval != 0) {
3315                         DBG_WARNING("smb_krb5_get_credentials failed for %s "
3316                                     "(%s)\n",
3317                                     principal,
3318                                     error_message(retval));
3319                         goto cleanup_creds;
3320                 }
3321
3322                 /* cope with ticket being in the future due to clock skew */
3323                 if ((unsigned)credsp->times.starttime > time(NULL)) {
3324                         time_t t = time(NULL);
3325                         int time_offset =(int)((unsigned)credsp->times.starttime-t);
3326                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
3327                         krb5_set_real_time(context, t + time_offset + 1, 0);
3328                 }
3329
3330                 ok = ads_cleanup_expired_creds(context, ccache, credsp);
3331                 if (!ok) {
3332                         creds_ready = true;
3333                 }
3334
3335                 i++;
3336         }
3337
3338         DBG_DEBUG("Ticket (%s) in ccache (%s:%s) is valid until: (%s - %u)\n",
3339                   principal,
3340                   krb5_cc_get_type(context, ccache),
3341                   krb5_cc_get_name(context, ccache),
3342                   http_timestring(talloc_tos(),
3343                                   (unsigned)credsp->times.endtime),
3344                   (unsigned)credsp->times.endtime);
3345
3346         if (expire_time) {
3347                 *expire_time = (time_t)credsp->times.endtime;
3348         }
3349
3350         /* Allocate the auth_context. */
3351         retval = ads_setup_auth_context(context, auth_context);
3352         if (retval != 0) {
3353                 DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3354                             error_message(retval));
3355                 goto cleanup_creds;
3356         }
3357
3358 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
3359         {
3360                 uint32_t gss_flags = 0;
3361
3362                 if (credsp->ticket_flags & TKT_FLG_OK_AS_DELEGATE) {
3363                         /*
3364                          * Fetch a forwarded TGT from the KDC so that we can
3365                          * hand off a 2nd ticket as part of the kerberos
3366                          * exchange.
3367                          */
3368
3369                         DBG_INFO("Server marked as OK to delegate to, building "
3370                                  "forwardable TGT\n");
3371
3372                         retval = krb5_auth_con_setuseruserkey(context,
3373                                         *auth_context,
3374                                         &credsp->keyblock );
3375                         if (retval != 0) {
3376                                 DBG_WARNING("krb5_auth_con_setuseruserkey "
3377                                             "failed (%s)\n",
3378                                             error_message(retval));
3379                                 goto cleanup_creds;
3380                         }
3381
3382                         /* Must use a subkey for forwarded tickets. */
3383                         retval = krb5_auth_con_setflags(context,
3384                                                         *auth_context,
3385                                                         KRB5_AUTH_CONTEXT_USE_SUBKEY);
3386                         if (retval != 0) {
3387                                 DBG_WARNING("krb5_auth_con_setflags failed (%s)\n",
3388                                             error_message(retval));
3389                                 goto cleanup_creds;
3390                         }
3391
3392                         retval = krb5_fwd_tgt_creds(context,/* Krb5 context [in] */
3393                                 *auth_context,  /* Authentication context [in] */
3394                                 discard_const_p(char, KRB5_TGS_NAME),  /* Ticket service name ("krbtgt") [in] */
3395                                 credsp->client, /* Client principal for the tgt [in] */
3396                                 credsp->server, /* Server principal for the tgt [in] */
3397                                 ccache,         /* Credential cache to use for storage [in] */
3398                                 1,              /* Turn on for "Forwardable ticket" [in] */
3399                                 &in_data );     /* Resulting response [out] */
3400
3401                         if (retval) {
3402                                 DBG_INFO("krb5_fwd_tgt_creds failed (%s)\n",
3403                                          error_message(retval));
3404
3405                                 /*
3406                                  * This is not fatal. Delete the *auth_context and continue
3407                                  * with krb5_mk_req_extended to get a non-forwardable ticket.
3408                                  */
3409
3410                                 if (in_data.data) {
3411                                         free( in_data.data );
3412                                         in_data.data = NULL;
3413                                         in_data.length = 0;
3414                                 }
3415                                 krb5_auth_con_free(context, *auth_context);
3416                                 *auth_context = NULL;
3417                                 retval = ads_setup_auth_context(context, auth_context);
3418                                 if (retval != 0) {
3419                                         DBG_WARNING("ads_setup_auth_context failed (%s)\n",
3420                                                     error_message(retval));
3421                                         goto cleanup_creds;
3422                                 }
3423                         } else {
3424                                 /* We got a delegated ticket. */
3425                                 gss_flags |= GSS_C_DELEG_FLAG;
3426                         }
3427                 }
3428
3429                 /* Frees and reallocates in_data into a GSS checksum blob. */
3430                 retval = ads_create_gss_checksum(&in_data, gss_flags);
3431                 if (retval != 0) {
3432                         goto cleanup_data;
3433                 }
3434
3435                 /* We always want GSS-checksum types. */
3436                 retval = krb5_auth_con_set_req_cksumtype(context, *auth_context, GSSAPI_CHECKSUM );
3437                 if (retval != 0) {
3438                         DEBUG(1,("krb5_auth_con_set_req_cksumtype failed (%s)\n",
3439                                 error_message(retval)));
3440                         goto cleanup_data;
3441                 }
3442         }
3443 #endif
3444
3445         retval = krb5_mk_req_extended(context, auth_context, ap_req_options,
3446                                       &in_data, credsp, outbuf);
3447         if (retval != 0) {
3448                 DBG_WARNING("krb5_mk_req_extended failed (%s)\n",
3449                             error_message(retval));
3450         }
3451
3452 #if defined(TKT_FLG_OK_AS_DELEGATE ) && defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY) && defined(KRB5_AUTH_CONTEXT_USE_SUBKEY) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
3453 cleanup_data:
3454 #endif
3455
3456         if (in_data.data) {
3457                 free( in_data.data );
3458                 in_data.length = 0;
3459         }
3460
3461         krb5_free_creds(context, credsp);
3462
3463 cleanup_creds:
3464         krb5_free_cred_contents(context, &creds);
3465
3466 cleanup_princ:
3467         krb5_free_principal(context, server);
3468         if (impersonate_princ) {
3469                 krb5_free_principal(context, impersonate_princ);
3470         }
3471
3472         return retval;
3473 }
3474
3475 /*
3476   get a kerberos5 ticket for the given service
3477 */
3478 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3479                             const char *principal,
3480                             time_t time_offset,
3481                             DATA_BLOB *ticket,
3482                             DATA_BLOB *session_key_krb5,
3483                             uint32_t extra_ap_opts, const char *ccname,
3484                             time_t *tgs_expire,
3485                             const char *impersonate_princ_s)
3486 {
3487         krb5_error_code retval;
3488         krb5_data packet;
3489         krb5_context context = NULL;
3490         krb5_ccache ccdef = NULL;
3491         krb5_auth_context auth_context = NULL;
3492         krb5_enctype enc_types[] = {
3493 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
3494                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
3495 #endif
3496 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
3497                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
3498 #endif
3499                 ENCTYPE_ARCFOUR_HMAC,
3500                 ENCTYPE_DES_CBC_MD5,
3501                 ENCTYPE_DES_CBC_CRC,
3502                 ENCTYPE_NULL};
3503         bool ok;
3504
3505         initialize_krb5_error_table();
3506         retval = krb5_init_context(&context);
3507         if (retval != 0) {
3508                 DBG_WARNING("krb5_init_context failed (%s)\n",
3509                             error_message(retval));
3510                 goto failed;
3511         }
3512
3513         if (time_offset != 0) {
3514                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
3515         }
3516
3517         retval = krb5_cc_resolve(context,
3518                                  ccname ? ccname : krb5_cc_default_name(context),
3519                                  &ccdef);
3520         if (retval != 0) {
3521                 DBG_WARNING("krb5_cc_default failed (%s)\n",
3522                             error_message(retval));
3523                 goto failed;
3524         }
3525
3526         retval = krb5_set_default_tgs_ktypes(context, enc_types);
3527         if (retval != 0) {
3528                 DBG_WARNING("krb5_set_default_tgs_ktypes failed (%s)\n",
3529                             error_message(retval));
3530                 goto failed;
3531         }
3532
3533         retval = ads_krb5_mk_req(context,
3534                                  &auth_context,
3535                                  AP_OPTS_USE_SUBKEY | (krb5_flags)extra_ap_opts,
3536                                  principal,
3537                                  ccdef,
3538                                  &packet,
3539                                  tgs_expire,
3540                                  impersonate_princ_s);
3541         if (retval != 0) {
3542                 goto failed;
3543         }
3544
3545         ok = smb_krb5_get_smb_session_key(mem_ctx,
3546                                           context,
3547                                           auth_context,
3548                                           session_key_krb5,
3549                                           false);
3550         if (!ok) {
3551                 retval = ENOMEM;
3552                 goto failed;
3553         }
3554
3555         *ticket = data_blob_talloc(mem_ctx, packet.data, packet.length);
3556
3557         smb_krb5_free_data_contents(context, &packet);
3558
3559 failed:
3560
3561         if (context) {
3562                 if (ccdef) {
3563                         krb5_cc_close(context, ccdef);
3564                 }
3565                 if (auth_context) {
3566                         krb5_auth_con_free(context, auth_context);
3567                 }
3568                 krb5_free_context(context);
3569         }
3570
3571         return retval;
3572 }
3573
3574 #ifndef SAMBA4_USES_HEIMDAL /* MITKRB5 tracing callback */
3575 static void smb_krb5_trace_cb(krb5_context ctx,
3576                               const krb5_trace_info *info,
3577                               void *data)
3578 {
3579         if (info != NULL) {
3580                 DBGC_DEBUG(DBGC_KERBEROS, "%s", info->message);
3581         }
3582 }
3583 #endif
3584
3585 krb5_error_code smb_krb5_init_context_common(krb5_context *_krb5_context)
3586 {
3587         krb5_error_code ret;
3588         krb5_context krb5_ctx;
3589
3590         initialize_krb5_error_table();
3591
3592         ret = krb5_init_context(&krb5_ctx);
3593         if (ret) {
3594                 DBG_ERR("Krb5 context initialization failed (%s)\n",
3595                          error_message(ret));
3596                 return ret;
3597         }
3598
3599         /* The MIT Kerberos build relies on using the system krb5.conf file.
3600          * If you really want to use another file please set KRB5_CONFIG
3601          * accordingly. */
3602 #ifndef SAMBA4_USES_HEIMDAL
3603         ret = krb5_set_trace_callback(krb5_ctx, smb_krb5_trace_cb, NULL);
3604         if (ret) {
3605                 DBG_ERR("Failed to set MIT kerberos trace callback! (%s)\n",
3606                         error_message(ret));
3607         }
3608 #endif
3609         *_krb5_context = krb5_ctx;
3610         return 0;
3611 }
3612
3613 #else /* HAVE_KRB5 */
3614 /* This saves a few linking headaches */
3615 int ads_krb5_cli_get_ticket(TALLOC_CTX *mem_ctx,
3616                             const char *principal,
3617                             time_t time_offset,
3618                             DATA_BLOB *ticket,
3619                             DATA_BLOB *session_key_krb5,
3620                             uint32_t extra_ap_opts, const char *ccname,
3621                             time_t *tgs_expire,
3622                             const char *impersonate_princ_s)
3623 {
3624          DEBUG(0,("NO KERBEROS SUPPORT\n"));
3625          return 1;
3626 }
3627
3628 #endif /* HAVE_KRB5 */