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