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