r9693: Move the smb_krb5_context setup code to use the new pattern of
[ira/wip.git] / source4 / auth / kerberos / clikrb5.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    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "system/network.h"
25 #include "system/kerberos.h"
26 #include "system/time.h"
27 #include "auth/kerberos/kerberos.h"
28
29 #ifdef HAVE_KRB5
30
31 #ifndef HAVE_KRB5_SET_REAL_TIME
32 /*
33  * This function is not in the Heimdal mainline.
34  */
35  krb5_error_code krb5_set_real_time(krb5_context context, int32_t seconds, int32_t microseconds)
36 {
37         krb5_error_code ret;
38         int32_t sec, usec;
39
40         ret = krb5_us_timeofday(context, &sec, &usec);
41         if (ret)
42                 return ret;
43
44         context->kdc_sec_offset = seconds - sec;
45         context->kdc_usec_offset = microseconds - usec;
46
47         return 0;
48 }
49 #endif
50
51 #if defined(HAVE_KRB5_SET_DEFAULT_IN_TKT_ETYPES) && !defined(HAVE_KRB5_SET_DEFAULT_TGS_KTYPES)
52  krb5_error_code krb5_set_default_tgs_ktypes(krb5_context ctx, const krb5_enctype *enc)
53 {
54         return krb5_set_default_in_tkt_etypes(ctx, enc);
55 }
56 #endif
57
58 #if defined(HAVE_ADDR_TYPE_IN_KRB5_ADDRESS)
59 /* HEIMDAL */
60  void setup_kaddr( krb5_address *pkaddr, struct sockaddr *paddr)
61 {
62         pkaddr->addr_type = KRB5_ADDRESS_INET;
63         pkaddr->address.length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
64         pkaddr->address.data = (char *)&(((struct sockaddr_in *)paddr)->sin_addr);
65 }
66 #elif defined(HAVE_ADDRTYPE_IN_KRB5_ADDRESS)
67 /* MIT */
68  void setup_kaddr( krb5_address *pkaddr, struct sockaddr *paddr)
69 {
70         pkaddr->addrtype = ADDRTYPE_INET;
71         pkaddr->length = sizeof(((struct sockaddr_in *)paddr)->sin_addr);
72         pkaddr->contents = (krb5_octet *)&(((struct sockaddr_in *)paddr)->sin_addr);
73 }
74 #else
75 #error UNKNOWN_ADDRTYPE
76 #endif
77
78 #if defined(HAVE_KRB5_PRINCIPAL2SALT) && defined(HAVE_KRB5_USE_ENCTYPE) && defined(HAVE_KRB5_STRING_TO_KEY) && defined(HAVE_KRB5_ENCRYPT_BLOCK)
79  int create_kerberos_key_from_string(krb5_context context,
80                                         krb5_principal host_princ,
81                                         krb5_data *password,
82                                         krb5_keyblock *key,
83                                         krb5_enctype enctype)
84 {
85         int ret;
86         krb5_data salt;
87         krb5_encrypt_block eblock;
88
89         ret = krb5_principal2salt(context, host_princ, &salt);
90         if (ret) {
91                 DEBUG(1,("krb5_principal2salt failed (%s)\n", error_message(ret)));
92                 return ret;
93         }
94         krb5_use_enctype(context, &eblock, enctype);
95         ret = krb5_string_to_key(context, &eblock, key, password, &salt);
96         SAFE_FREE(salt.data);
97         return ret;
98 }
99 #elif defined(HAVE_KRB5_GET_PW_SALT) && defined(HAVE_KRB5_STRING_TO_KEY_SALT)
100  int create_kerberos_key_from_string(krb5_context context,
101                                         krb5_principal host_princ,
102                                         krb5_data *password,
103                                         krb5_keyblock *key,
104                                         krb5_enctype enctype)
105 {
106         int ret;
107         krb5_salt salt;
108
109         ret = krb5_get_pw_salt(context, host_princ, &salt);
110         if (ret) {
111                 DEBUG(1,("krb5_get_pw_salt failed (%s)\n", error_message(ret)));
112                 return ret;
113         }
114         return krb5_string_to_key_salt(context, enctype, password->data,
115                 salt, key);
116 }
117 #else
118 #error UNKNOWN_CREATE_KEY_FUNCTIONS
119 #endif
120
121 #if defined(HAVE_KRB5_GET_PERMITTED_ENCTYPES)
122  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
123                                             krb5_enctype **enctypes)
124 {
125         return krb5_get_permitted_enctypes(context, enctypes);
126 }
127 #elif defined(HAVE_KRB5_GET_DEFAULT_IN_TKT_ETYPES)
128  krb5_error_code get_kerberos_allowed_etypes(krb5_context context, 
129                                             krb5_enctype **enctypes)
130 {
131         return krb5_get_default_in_tkt_etypes(context, enctypes);
132 }
133 #else
134 #error UNKNOWN_GET_ENCTYPES_FUNCTIONS
135 #endif
136
137  void free_kerberos_etypes(krb5_context context, 
138                            krb5_enctype *enctypes)
139 {
140 #if defined(HAVE_KRB5_FREE_KTYPES)
141         krb5_free_ktypes(context, enctypes);
142         return;
143 #else
144         SAFE_FREE(enctypes);
145         return;
146 #endif
147 }
148
149 #if defined(HAVE_KRB5_AUTH_CON_SETKEY) && !defined(HAVE_KRB5_AUTH_CON_SETUSERUSERKEY)
150  krb5_error_code krb5_auth_con_setuseruserkey(krb5_context context,
151                                         krb5_auth_context auth_context,
152                                         krb5_keyblock *keyblock)
153 {
154         return krb5_auth_con_setkey(context, auth_context, keyblock);
155 }
156 #endif
157
158  DATA_BLOB get_auth_data_from_tkt(TALLOC_CTX *mem_ctx, 
159                             krb5_ticket *tkt)
160 {
161         DATA_BLOB auth_data = data_blob(NULL, 0); 
162 #if defined(HAVE_KRB5_TKT_ENC_PART2)
163         if (tkt && tkt->enc_part2 
164             && tkt->enc_part2->authorization_data
165             && tkt->enc_part2->authorization_data[0]
166             && tkt->enc_part2->authorization_data[0]->length)
167                 auth_data = data_blob(tkt->enc_part2->authorization_data[0]->contents,
168                         tkt->enc_part2->authorization_data[0]->length);
169 #else
170         if (tkt && tkt->ticket.authorization_data && tkt->ticket.authorization_data->len)
171                 auth_data = data_blob(tkt->ticket.authorization_data->val->ad_data.data,
172                         tkt->ticket.authorization_data->val->ad_data.length);
173 #endif
174         return auth_data;
175 }
176
177  krb5_const_principal get_principal_from_tkt(krb5_ticket *tkt)
178 {
179 #if defined(HAVE_KRB5_TKT_ENC_PART2)
180         return tkt->enc_part2->client;
181 #else
182         return tkt->client;
183 #endif
184 }
185
186 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
187  void krb5_free_unparsed_name(krb5_context context, char *val)
188 {
189         SAFE_FREE(val);
190 }
191 #endif
192
193  void kerberos_free_data_contents(krb5_context context, krb5_data *pdata)
194 {
195 #if defined(HAVE_KRB5_FREE_DATA_CONTENTS)
196         if (pdata->data) {
197                 krb5_free_data_contents(context, pdata);
198         }
199 #else
200         SAFE_FREE(pdata->data);
201 #endif
202 }
203
204  void kerberos_set_creds_enctype(krb5_creds *pcreds, int enctype)
205 {
206 #if defined(HAVE_KRB5_KEYBLOCK_IN_CREDS)
207         KRB5_KEY_TYPE((&pcreds->keyblock)) = enctype;
208 #elif defined(HAVE_KRB5_SESSION_IN_CREDS)
209         KRB5_KEY_TYPE((&pcreds->session)) = enctype;
210 #else
211 #error UNKNOWN_KEYBLOCK_MEMBER_IN_KRB5_CREDS_STRUCT
212 #endif
213 }
214
215  BOOL kerberos_compatible_enctypes(krb5_context context,
216                                   krb5_enctype enctype1,
217                                   krb5_enctype enctype2)
218 {
219 #if defined(HAVE_KRB5_C_ENCTYPE_COMPARE)
220         krb5_boolean similar = 0;
221
222         krb5_c_enctype_compare(context, enctype1, enctype2, &similar);
223         return similar ? True : False;
224 #elif defined(HAVE_KRB5_ENCTYPES_COMPATIBLE_KEYS)
225         return krb5_enctypes_compatible_keys(context, enctype1, enctype2) ? True : False;
226 #endif
227 }
228
229 static BOOL ads_cleanup_expired_creds(krb5_context context, 
230                                       krb5_ccache  ccache,
231                                       krb5_creds  *credsp)
232 {
233         krb5_error_code retval;
234         TALLOC_CTX *mem_ctx = talloc_init("ticket expied time");
235         if (!mem_ctx) {
236                 return False;
237         }
238
239         DEBUG(3, ("Ticket in ccache[%s] expiration %s\n",
240                   krb5_cc_default_name(context),
241                   http_timestring(mem_ctx, credsp->times.endtime)));
242
243         talloc_free(mem_ctx);
244
245         /* we will probably need new tickets if the current ones
246            will expire within 10 seconds.
247         */
248         if (credsp->times.endtime >= (time(NULL) + 10))
249                 return False;
250
251         /* heimdal won't remove creds from a file ccache, and 
252            perhaps we shouldn't anyway, since internally we 
253            use memory ccaches, and a FILE one probably means that
254            we're using creds obtained outside of our exectuable
255         */
256         if (StrCaseCmp(krb5_cc_get_type(context, ccache), "FILE") == 0) {
257                 DEBUG(5, ("ads_cleanup_expired_creds: We do not remove creds from a FILE ccache\n"));
258                 return False;
259         }
260         
261         retval = krb5_cc_remove_cred(context, ccache, 0, credsp);
262         if (retval) {
263                 DEBUG(1, ("ads_cleanup_expired_creds: krb5_cc_remove_cred failed, err %s\n",
264                           error_message(retval)));
265                 /* If we have an error in this, we want to display it,
266                    but continue as though we deleted it */
267         }
268         return True;
269 }
270
271 /*
272   we can't use krb5_mk_req because w2k wants the service to be in a particular format
273 */
274 krb5_error_code ads_krb5_mk_req(krb5_context context, 
275                                 krb5_auth_context *auth_context, 
276                                 const krb5_flags ap_req_options,
277                                 const char *principal,
278                                 krb5_ccache ccache, 
279                                 krb5_data *outbuf)
280 {
281         krb5_error_code           retval;
282         krb5_principal    server;
283         krb5_creds              * credsp;
284         krb5_creds                creds;
285         krb5_data in_data;
286         BOOL creds_ready = False;
287         
288         TALLOC_CTX *mem_ctx = NULL;
289
290         retval = krb5_parse_name(context, principal, &server);
291         if (retval) {
292                 DEBUG(1,("ads_krb5_mk_req: Failed to parse principal %s\n", principal));
293                 return retval;
294         }
295         
296         /* obtain ticket & session key */
297         ZERO_STRUCT(creds);
298         if ((retval = krb5_copy_principal(context, server, &creds.server))) {
299                 DEBUG(1,("krb5_copy_principal failed (%s)\n", 
300                          error_message(retval)));
301                 goto cleanup_princ;
302         }
303         
304         if ((retval = krb5_cc_get_principal(context, ccache, &creds.client))) {
305                 /* This can commonly fail on smbd startup with no ticket in the cache.
306                  * Report at higher level than 1. */
307                 DEBUG(3,("ads_krb5_mk_req: krb5_cc_get_principal failed (%s)\n", 
308                          error_message(retval)));
309                 goto cleanup_creds;
310         }
311
312         while(!creds_ready) {
313                 if ((retval = krb5_get_credentials(context, 0, ccache, 
314                                                    &creds, &credsp))) {
315                         DEBUG(1,("ads_krb5_mk_req: krb5_get_credentials failed for %s (%s)\n",
316                                  principal, error_message(retval)));
317                         goto cleanup_creds;
318                 }
319
320                 /* cope with ticket being in the future due to clock skew */
321                 if ((unsigned)credsp->times.starttime > time(NULL)) {
322                         time_t t = time(NULL);
323                         int time_offset =(unsigned)credsp->times.starttime-t;
324                         DEBUG(4,("ads_krb5_mk_req: Advancing clock by %d seconds to cope with clock skew\n", time_offset));
325                         krb5_set_real_time(context, t + time_offset + 1, 0);
326                 }
327
328                 if (!ads_cleanup_expired_creds(context, ccache, credsp))
329                         creds_ready = True;
330         }
331
332         mem_ctx = talloc_init("ticket expied time");
333         if (!mem_ctx) {
334                 retval = ENOMEM;
335                 goto cleanup_creds;
336         }
337         DEBUG(10,("Ticket (%s) in ccache (%s) is valid until: (%s - %d)\n",
338                   principal, krb5_cc_default_name(context),
339                   http_timestring(mem_ctx, (unsigned)credsp->times.endtime), 
340                   (unsigned)credsp->times.endtime));
341         
342         in_data.length = 0;
343         retval = krb5_mk_req_extended(context, auth_context, ap_req_options, 
344                                       &in_data, credsp, outbuf);
345         if (retval) {
346                 DEBUG(1,("ads_krb5_mk_req: krb5_mk_req_extended failed (%s)\n", 
347                          error_message(retval)));
348         }
349         
350         krb5_free_creds(context, credsp);
351
352 cleanup_creds:
353         krb5_free_cred_contents(context, &creds);
354
355 cleanup_princ:
356         krb5_free_principal(context, server);
357
358         return retval;
359 }
360
361  krb5_error_code smb_krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *kt_entry)
362 {
363 #if defined(HAVE_KRB5_KT_FREE_ENTRY)
364         return krb5_kt_free_entry(context, kt_entry);
365 #elif defined(HAVE_KRB5_FREE_KEYTAB_ENTRY_CONTENTS)
366         return krb5_free_keytab_entry_contents(context, kt_entry);
367 #else
368 #error UNKNOWN_KT_FREE_FUNCTION
369 #endif
370 }
371
372  char *smb_get_krb5_error_message(krb5_context context, krb5_error_code code, TALLOC_CTX *mem_ctx) 
373 {
374         char *ret;
375         
376 #if defined(HAVE_KRB5_GET_ERROR_STRING) && defined(HAVE_KRB5_FREE_ERROR_STRING)         
377         char *context_error = krb5_get_error_string(context);
378         ret = talloc_asprintf(mem_ctx, "%s: %s", error_message(code), context_error);
379         krb5_free_error_string(context, context_error);
380 #else 
381         ret = talloc_strdup(mem_ctx, error_message(code));
382 #endif
383         return ret;
384 }
385
386
387 static int smb_krb5_context_destory_1(void *ptr) 
388 {
389         struct smb_krb5_context *ctx = ptr;
390         krb5_free_context(ctx->krb5_context); 
391         return 0;
392 }
393
394 #ifdef HAVE_KRB5_LOG_CONTROL
395 static int smb_krb5_context_destory_2(void *ptr) 
396 {
397         struct smb_krb5_context *ctx = ptr;
398
399         /* Otherwise krb5_free_context will try and close what we have already free()ed */
400         krb5_set_warn_dest(ctx->krb5_context, NULL);
401         krb5_closelog(ctx->krb5_context, ctx->logf);
402         smb_krb5_context_destory_1(ptr);
403         return 0;
404 }
405
406 /* We never close down the DEBUG system, and no need to unreference the use */
407 static void smb_krb5_debug_close(void *private) {
408         return;
409 }
410
411 static void smb_krb5_debug_wrapper(const char *timestr, const char *msg, void *private) 
412 {
413         DEBUG(3, ("Kerberos: %s\n", msg));
414 }
415
416 #endif
417
418  krb5_error_code smb_krb5_init_context(TALLOC_CTX *parent_ctx, 
419                                        struct smb_krb5_context **smb_krb5_context) 
420 {
421         krb5_error_code ret;
422         TALLOC_CTX *tmp_ctx;
423         
424         initialize_krb5_error_table();
425         
426         tmp_ctx = talloc_new(parent_ctx);
427         *smb_krb5_context = talloc(tmp_ctx, struct smb_krb5_context);
428
429         if (!*smb_krb5_context || !tmp_ctx) {
430                 talloc_free(*smb_krb5_context);
431                 talloc_free(tmp_ctx);
432                 return ENOMEM;
433         }
434
435         ret = krb5_init_context(&(*smb_krb5_context)->krb5_context);
436         if (ret) {
437                 DEBUG(1,("krb5_init_context failed (%s)\n", 
438                          error_message(ret)));
439                 return ret;
440         }
441
442         talloc_set_destructor(*smb_krb5_context, smb_krb5_context_destory_1);
443
444         if (lp_realm() && *lp_realm()) {
445                 char *upper_realm = strupper_talloc(tmp_ctx, lp_realm());
446                 if (!upper_realm) {
447                         DEBUG(1,("gensec_krb5_start: could not uppercase realm: %s\n", lp_realm()));
448                         talloc_free(tmp_ctx);
449                         return ENOMEM;
450                 }
451                 ret = krb5_set_default_realm((*smb_krb5_context)->krb5_context, lp_realm());
452                 if (ret) {
453                         DEBUG(1,("krb5_set_default_realm failed (%s)\n", 
454                                  smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx)));
455                         talloc_free(tmp_ctx);
456                         return ret;
457                 }
458         }
459
460 #ifdef HAVE_KRB5_LOG_CONTROL
461         /* TODO: Should we have a different name here? */
462         ret = krb5_initlog((*smb_krb5_context)->krb5_context, "Samba", &(*smb_krb5_context)->logf);
463         
464         if (ret) {
465                 DEBUG(1,("krb5_initlog failed (%s)\n", 
466                          smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx)));
467                 talloc_free(tmp_ctx);
468                 return ret;
469         }
470
471         talloc_set_destructor(*smb_krb5_context, smb_krb5_context_destory_2);
472
473         ret = krb5_addlog_func((*smb_krb5_context)->krb5_context, (*smb_krb5_context)->logf, 0 /* min */, -1 /* max */, 
474                                smb_krb5_debug_wrapper, smb_krb5_debug_close, NULL);
475         if (ret) {
476                 DEBUG(1,("krb5_addlog_func failed (%s)\n", 
477                          smb_get_krb5_error_message((*smb_krb5_context)->krb5_context, ret, tmp_ctx)));
478                 talloc_free(tmp_ctx);
479                 return ret;
480         }
481         krb5_set_warn_dest((*smb_krb5_context)->krb5_context, (*smb_krb5_context)->logf);
482
483 #endif  
484         talloc_steal(parent_ctx, *smb_krb5_context);
485         talloc_free(tmp_ctx);
486         return 0;
487 }
488
489 #endif