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