r10656: BIG merge from trunk. Features not copied over
[samba.git] / source / libads / kerberos_verify.c
1 /* 
2    Unix SMB/CIFS implementation.
3    kerberos utility library
4    Copyright (C) Andrew Tridgell 2001
5    Copyright (C) Remus Koos 2001
6    Copyright (C) Luke Howard 2003   
7    Copyright (C) Guenther Deschner 2003, 2005
8    Copyright (C) Jim McDonough (jmcd@us.ibm.com) 2003
9    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26 #include "includes.h"
27
28 #ifdef HAVE_KRB5
29
30 #if !defined(HAVE_KRB5_PRINC_COMPONENT)
31 const krb5_data *krb5_princ_component(krb5_context, krb5_principal, int );
32 #endif
33
34 /**********************************************************************************
35  Try to verify a ticket using the system keytab... the system keytab has kvno -1 entries, so
36  it's more like what microsoft does... see comment in utils/net_ads.c in the
37  ads_keytab_add_entry function for details.
38 ***********************************************************************************/
39
40 static BOOL ads_keytab_verify_ticket(krb5_context context, krb5_auth_context auth_context,
41                         const DATA_BLOB *ticket, krb5_data *p_packet, krb5_ticket **pp_tkt, 
42                         krb5_keyblock **keyblock)
43 {
44         krb5_error_code ret = 0;
45         BOOL auth_ok = False;
46         krb5_keytab keytab = NULL;
47         krb5_kt_cursor kt_cursor;
48         krb5_keytab_entry kt_entry;
49         char *valid_princ_formats[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
50         char *entry_princ_s = NULL;
51         fstring my_name, my_fqdn;
52         int i;
53         int number_matched_principals = 0;
54
55         /* Generate the list of principal names which we expect
56          * clients might want to use for authenticating to the file
57          * service.  We allow name$,{host,cifs}/{name,fqdn,name.REALM}. */
58
59         fstrcpy(my_name, global_myname());
60
61         my_fqdn[0] = '\0';
62         name_to_fqdn(my_fqdn, global_myname());
63
64         asprintf(&valid_princ_formats[0], "%s$@%s", my_name, lp_realm());
65         asprintf(&valid_princ_formats[1], "host/%s@%s", my_name, lp_realm());
66         asprintf(&valid_princ_formats[2], "host/%s@%s", my_fqdn, lp_realm());
67         asprintf(&valid_princ_formats[3], "host/%s.%s@%s", my_name, lp_realm(), lp_realm());
68         asprintf(&valid_princ_formats[4], "cifs/%s@%s", my_name, lp_realm());
69         asprintf(&valid_princ_formats[5], "cifs/%s@%s", my_fqdn, lp_realm());
70         asprintf(&valid_princ_formats[6], "cifs/%s.%s@%s", my_name, lp_realm(), lp_realm());
71
72         ZERO_STRUCT(kt_entry);
73         ZERO_STRUCT(kt_cursor);
74
75         ret = krb5_kt_default(context, &keytab);
76         if (ret) {
77                 DEBUG(1, ("ads_keytab_verify_ticket: krb5_kt_default failed (%s)\n", error_message(ret)));
78                 goto out;
79         }
80
81         /* Iterate through the keytab.  For each key, if the principal
82          * name case-insensitively matches one of the allowed formats,
83          * try verifying the ticket using that principal. */
84
85         ret = krb5_kt_start_seq_get(context, keytab, &kt_cursor);
86         if (ret) {
87                 DEBUG(1, ("ads_keytab_verify_ticket: krb5_kt_start_seq_get failed (%s)\n", error_message(ret)));
88                 goto out;
89         }
90   
91         if (ret != KRB5_KT_END && ret != ENOENT ) {
92                 while (!auth_ok && (krb5_kt_next_entry(context, keytab, &kt_entry, &kt_cursor) == 0)) {
93                         ret = krb5_unparse_name(context, kt_entry.principal, &entry_princ_s);
94                         if (ret) {
95                                 DEBUG(1, ("ads_keytab_verify_ticket: krb5_unparse_name failed (%s)\n", error_message(ret)));
96                                 goto out;
97                         }
98
99                         for (i = 0; i < sizeof(valid_princ_formats) / sizeof(valid_princ_formats[0]); i++) {
100                                 if (strequal(entry_princ_s, valid_princ_formats[i])) {
101                                         number_matched_principals++;
102                                         p_packet->length = ticket->length;
103                                         p_packet->data = (krb5_pointer)ticket->data;
104                                         *pp_tkt = NULL;
105
106                                         ret = krb5_rd_req_return_keyblock_from_keytab(context, &auth_context, p_packet,
107                                                                                       kt_entry.principal, keytab,
108                                                                                       NULL, pp_tkt, keyblock);
109
110                                         if (ret) {
111                                                 DEBUG(10,("ads_keytab_verify_ticket: "
112                                                         "krb5_rd_req_return_keyblock_from_keytab(%s) failed: %s\n",
113                                                         entry_princ_s, error_message(ret)));
114                                         } else {
115                                                 DEBUG(3,("ads_keytab_verify_ticket: "
116                                                         "krb5_rd_req_return_keyblock_from_keytab succeeded for principal %s\n",
117                                                         entry_princ_s));
118                                                 auth_ok = True;
119                                                 break;
120                                         }
121                                 }
122                         }
123
124                         /* Free the name we parsed. */
125                         krb5_free_unparsed_name(context, entry_princ_s);
126                         entry_princ_s = NULL;
127
128                         /* Free the entry we just read. */
129                         smb_krb5_kt_free_entry(context, &kt_entry);
130                         ZERO_STRUCT(kt_entry);
131                 }
132                 krb5_kt_end_seq_get(context, keytab, &kt_cursor);
133         }
134
135         ZERO_STRUCT(kt_cursor);
136
137   out:
138         
139         for (i = 0; i < sizeof(valid_princ_formats) / sizeof(valid_princ_formats[0]); i++) {
140                 SAFE_FREE(valid_princ_formats[i]);
141         }
142         
143         if (!auth_ok) {
144                 if (!number_matched_principals) {
145                         DEBUG(3, ("ads_keytab_verify_ticket: no keytab principals matched expected file service name.\n"));
146                 } else {
147                         DEBUG(3, ("ads_keytab_verify_ticket: krb5_rd_req failed for all %d matched keytab principals\n",
148                                 number_matched_principals));
149                 }
150         }
151
152         if (entry_princ_s) {
153                 krb5_free_unparsed_name(context, entry_princ_s);
154         }
155
156         {
157                 krb5_keytab_entry zero_kt_entry;
158                 ZERO_STRUCT(zero_kt_entry);
159                 if (memcmp(&zero_kt_entry, &kt_entry, sizeof(krb5_keytab_entry))) {
160                         smb_krb5_kt_free_entry(context, &kt_entry);
161                 }
162         }
163
164         {
165                 krb5_kt_cursor zero_csr;
166                 ZERO_STRUCT(zero_csr);
167                 if ((memcmp(&kt_cursor, &zero_csr, sizeof(krb5_kt_cursor)) != 0) && keytab) {
168                         krb5_kt_end_seq_get(context, keytab, &kt_cursor);
169                 }
170         }
171
172         if (keytab) {
173                 krb5_kt_close(context, keytab);
174         }
175         return auth_ok;
176 }
177
178 /**********************************************************************************
179  Try to verify a ticket using the secrets.tdb.
180 ***********************************************************************************/
181
182 static BOOL ads_secrets_verify_ticket(krb5_context context, krb5_auth_context auth_context,
183                                       krb5_principal host_princ,
184                                       const DATA_BLOB *ticket, krb5_data *p_packet, krb5_ticket **pp_tkt,
185                                       krb5_keyblock **keyblock)
186 {
187         krb5_error_code ret = 0;
188         BOOL auth_ok = False;
189         char *password_s = NULL;
190         krb5_data password;
191         krb5_enctype *enctypes = NULL;
192         int i;
193
194         ZERO_STRUCTP(keyblock);
195
196         if (!secrets_init()) {
197                 DEBUG(1,("ads_secrets_verify_ticket: secrets_init failed\n"));
198                 return False;
199         }
200
201         password_s = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
202         if (!password_s) {
203                 DEBUG(1,("ads_secrets_verify_ticket: failed to fetch machine password\n"));
204                 return False;
205         }
206
207         password.data = password_s;
208         password.length = strlen(password_s);
209
210         /* CIFS doesn't use addresses in tickets. This would break NAT. JRA */
211
212         if ((ret = get_kerberos_allowed_etypes(context, &enctypes))) {
213                 DEBUG(1,("ads_secrets_verify_ticket: krb5_get_permitted_enctypes failed (%s)\n", 
214                          error_message(ret)));
215                 goto out;
216         }
217
218         p_packet->length = ticket->length;
219         p_packet->data = (krb5_pointer)ticket->data;
220
221         /* We need to setup a auth context with each possible encoding type in turn. */
222         for (i=0;enctypes[i];i++) {
223                 krb5_keyblock *key = NULL;
224
225                 if (!(key = SMB_MALLOC_P(krb5_keyblock))) {
226                         goto out;
227                 }
228         
229                 if (create_kerberos_key_from_string(context, host_princ, &password, key, enctypes[i])) {
230                         SAFE_FREE(key);
231                         continue;
232                 }
233
234                 krb5_auth_con_setuseruserkey(context, auth_context, key);
235
236                 if (!(ret = krb5_rd_req(context, &auth_context, p_packet, 
237                                         NULL,
238                                         NULL, NULL, pp_tkt))) {
239                         DEBUG(10,("ads_secrets_verify_ticket: enc type [%u] decrypted message !\n",
240                                 (unsigned int)enctypes[i] ));
241                         auth_ok = True;
242                         krb5_copy_keyblock(context, key, keyblock);
243                         krb5_free_keyblock(context, key);
244                         break;
245                 }
246         
247                 DEBUG((ret != KRB5_BAD_ENCTYPE) ? 3 : 10,
248                                 ("ads_secrets_verify_ticket: enc type [%u] failed to decrypt with error %s\n",
249                                 (unsigned int)enctypes[i], error_message(ret)));
250
251                 krb5_free_keyblock(context, key);
252
253         }
254
255  out:
256
257         free_kerberos_etypes(context, enctypes);
258         SAFE_FREE(password_s);
259
260         return auth_ok;
261 }
262
263 /**********************************************************************************
264  Verify an incoming ticket and parse out the principal name and 
265  authorization_data if available.
266 ***********************************************************************************/
267
268 NTSTATUS ads_verify_ticket(TALLOC_CTX *mem_ctx,
269                            const char *realm, const DATA_BLOB *ticket, 
270                            char **principal, PAC_DATA **pac_data,
271                            DATA_BLOB *ap_rep,
272                            DATA_BLOB *session_key)
273 {
274         NTSTATUS sret = NT_STATUS_LOGON_FAILURE;
275         DATA_BLOB auth_data;
276         krb5_context context = NULL;
277         krb5_auth_context auth_context = NULL;
278         krb5_data packet;
279         krb5_ticket *tkt = NULL;
280         krb5_rcache rcache = NULL;
281         krb5_keyblock *keyblock = NULL;
282         time_t authtime;
283         int ret;
284
285         krb5_principal host_princ = NULL;
286         krb5_const_principal client_principal = NULL;
287         char *host_princ_s = NULL;
288         BOOL got_replay_mutex = False;
289
290         BOOL auth_ok = False;
291         BOOL got_auth_data = False;
292
293         ZERO_STRUCT(packet);
294         ZERO_STRUCT(auth_data);
295         ZERO_STRUCTP(ap_rep);
296         ZERO_STRUCTP(session_key);
297
298         initialize_krb5_error_table();
299         ret = krb5_init_context(&context);
300         if (ret) {
301                 DEBUG(1,("ads_verify_ticket: krb5_init_context failed (%s)\n", error_message(ret)));
302                 return NT_STATUS_LOGON_FAILURE;
303         }
304
305         ret = krb5_set_default_realm(context, realm);
306         if (ret) {
307                 DEBUG(1,("ads_verify_ticket: krb5_set_default_realm failed (%s)\n", error_message(ret)));
308                 goto out;
309         }
310
311         /* This whole process is far more complex than I would
312            like. We have to go through all this to allow us to store
313            the secret internally, instead of using /etc/krb5.keytab */
314
315         ret = krb5_auth_con_init(context, &auth_context);
316         if (ret) {
317                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_init failed (%s)\n", error_message(ret)));
318                 goto out;
319         }
320
321         asprintf(&host_princ_s, "%s$", global_myname());
322         strlower_m(host_princ_s);
323         ret = krb5_parse_name(context, host_princ_s, &host_princ);
324         if (ret) {
325                 DEBUG(1,("ads_verify_ticket: krb5_parse_name(%s) failed (%s)\n",
326                                         host_princ_s, error_message(ret)));
327                 goto out;
328         }
329
330
331         /* Lock a mutex surrounding the replay as there is no locking in the MIT krb5
332          * code surrounding the replay cache... */
333
334         if (!grab_server_mutex("replay cache mutex")) {
335                 DEBUG(1,("ads_verify_ticket: unable to protect replay cache with mutex.\n"));
336                 goto out;
337         }
338
339         got_replay_mutex = True;
340
341         /*
342          * JRA. We must set the rcache here. This will prevent replay attacks.
343          */
344
345         ret = krb5_get_server_rcache(context, krb5_princ_component(context, host_princ, 0), &rcache);
346         if (ret) {
347                 DEBUG(1,("ads_verify_ticket: krb5_get_server_rcache failed (%s)\n", error_message(ret)));
348                 goto out;
349         }
350
351         ret = krb5_auth_con_setrcache(context, auth_context, rcache);
352         if (ret) {
353                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_setrcache failed (%s)\n", error_message(ret)));
354                 goto out;
355         }
356
357         if (lp_use_kerberos_keytab()) {
358                 auth_ok = ads_keytab_verify_ticket(context, auth_context, ticket, &packet, &tkt, &keyblock);
359         }
360         if (!auth_ok) {
361                 auth_ok = ads_secrets_verify_ticket(context, auth_context, host_princ,
362                                                     ticket, &packet, &tkt, &keyblock);
363         }
364
365         release_server_mutex();
366         got_replay_mutex = False;
367
368 #if 0
369         /* Heimdal leaks here, if we fix the leak, MIT crashes */
370         if (rcache) {
371                 krb5_rc_close(context, rcache);
372         }
373 #endif
374
375         if (!auth_ok) {
376                 DEBUG(3,("ads_verify_ticket: krb5_rd_req with auth failed (%s)\n", 
377                          error_message(ret)));
378                 goto out;
379         } else {
380                 authtime = get_authtime_from_tkt(tkt);
381                 client_principal = get_principal_from_tkt(tkt);
382         }
383
384         ret = krb5_mk_rep(context, auth_context, &packet);
385         if (ret) {
386                 DEBUG(3,("ads_verify_ticket: Failed to generate mutual authentication reply (%s)\n",
387                         error_message(ret)));
388                 goto out;
389         }
390
391         *ap_rep = data_blob(packet.data, packet.length);
392         SAFE_FREE(packet.data);
393         packet.length = 0;
394
395         get_krb5_smb_session_key(context, auth_context, session_key, True);
396         dump_data_pw("SMB session key (from ticket)\n", session_key->data, session_key->length);
397
398 #if 0
399         file_save("/tmp/ticket.dat", ticket->data, ticket->length);
400 #endif
401
402         /* continue when no PAC is retrieved 
403            (like accounts that have the UF_NO_AUTH_DATA_REQUIRED flag set) */
404
405         got_auth_data = get_auth_data_from_tkt(mem_ctx, &auth_data, tkt);
406         if (!got_auth_data) {
407                 DEBUG(3,("ads_verify_ticket: did not retrieve auth data. continuing without PAC\n"));
408         }
409
410         if (got_auth_data && pac_data != NULL) {
411
412                 sret = decode_pac_data(mem_ctx, &auth_data, context, keyblock, client_principal, authtime, pac_data);
413                 if (!NT_STATUS_IS_OK(sret)) {
414                         DEBUG(0,("ads_verify_ticket: failed to decode PAC_DATA: %s\n", nt_errstr(sret)));
415                         goto out;
416                 }
417                 data_blob_free(&auth_data);
418         }
419
420 #if 0
421 #if defined(HAVE_KRB5_TKT_ENC_PART2)
422         /* MIT */
423         if (tkt->enc_part2) {
424                 file_save("/tmp/authdata.dat",
425                           tkt->enc_part2->authorization_data[0]->contents,
426                           tkt->enc_part2->authorization_data[0]->length);
427         }
428 #else
429         /* Heimdal */
430         if (tkt->ticket.authorization_data) {
431                 file_save("/tmp/authdata.dat",
432                           tkt->ticket.authorization_data->val->ad_data.data,
433                           tkt->ticket.authorization_data->val->ad_data.length);
434         }
435 #endif
436 #endif
437
438         if ((ret = krb5_unparse_name(context, get_principal_from_tkt(tkt),
439                                      principal))) {
440                 DEBUG(3,("ads_verify_ticket: krb5_unparse_name failed (%s)\n", 
441                          error_message(ret)));
442                 sret = NT_STATUS_LOGON_FAILURE;
443                 goto out;
444         }
445
446         sret = NT_STATUS_OK;
447
448  out:
449
450         if (got_replay_mutex) {
451                 release_server_mutex();
452         }
453
454         if (!NT_STATUS_IS_OK(sret)) {
455                 data_blob_free(&auth_data);
456         }
457
458         if (!NT_STATUS_IS_OK(sret)) {
459                 data_blob_free(ap_rep);
460         }
461
462         if (host_princ) {
463                 krb5_free_principal(context, host_princ);
464         }
465
466         if (keyblock) {
467                 krb5_free_keyblock(context, keyblock);
468         }
469
470         if (tkt != NULL) {
471                 krb5_free_ticket(context, tkt);
472         }
473
474         SAFE_FREE(host_princ_s);
475
476         if (auth_context) {
477                 krb5_auth_con_free(context, auth_context);
478         }
479
480         if (context) {
481                 krb5_free_context(context);
482         }
483
484         return sret;
485 }
486
487 #endif /* HAVE_KRB5 */