r21557: indent only fix. No code change.
[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         while (!auth_ok && (krb5_kt_next_entry(context, keytab, &kt_entry, &kt_cursor) == 0)) {
92                 ret = smb_krb5_unparse_name(context, kt_entry.principal, &entry_princ_s);
93                 if (ret) {
94                         DEBUG(1, ("ads_keytab_verify_ticket: smb_krb5_unparse_name failed (%s)\n",
95                                 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 = (char *)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
115                                         /* workaround for MIT: 
116                                          * as krb5_ktfile_get_entry will
117                                          * explicitly close the
118                                          * krb5_keytab as soon as
119                                          * krb5_rd_req has sucessfully
120                                          * decrypted the ticket but the
121                                          * ticket is not valid yet (due
122                                          * to clockskew) there is no
123                                          * point in querying more
124                                          * keytab entries - Guenther */
125                                                 
126                                         if (ret == KRB5KRB_AP_ERR_TKT_NYV || 
127                                             ret == KRB5KRB_AP_ERR_TKT_EXPIRED) {
128                                                 break;
129                                         }
130                                 } else {
131                                         DEBUG(3,("ads_keytab_verify_ticket: "
132                                                 "krb5_rd_req_return_keyblock_from_keytab succeeded for principal %s\n",
133                                                 entry_princ_s));
134                                         auth_ok = True;
135                                         break;
136                                 }
137                         }
138                 }
139
140                 /* Free the name we parsed. */
141                 SAFE_FREE(entry_princ_s);
142
143                 /* Free the entry we just read. */
144                 smb_krb5_kt_free_entry(context, &kt_entry);
145                 ZERO_STRUCT(kt_entry);
146         }
147         krb5_kt_end_seq_get(context, keytab, &kt_cursor);
148
149         ZERO_STRUCT(kt_cursor);
150
151   out:
152         
153         for (i = 0; i < sizeof(valid_princ_formats) / sizeof(valid_princ_formats[0]); i++) {
154                 SAFE_FREE(valid_princ_formats[i]);
155         }
156         
157         if (!auth_ok) {
158                 if (!number_matched_principals) {
159                         DEBUG(3, ("ads_keytab_verify_ticket: no keytab principals matched expected file service name.\n"));
160                 } else {
161                         DEBUG(3, ("ads_keytab_verify_ticket: krb5_rd_req failed for all %d matched keytab principals\n",
162                                 number_matched_principals));
163                 }
164         }
165
166         SAFE_FREE(entry_princ_s);
167
168         {
169                 krb5_keytab_entry zero_kt_entry;
170                 ZERO_STRUCT(zero_kt_entry);
171                 if (memcmp(&zero_kt_entry, &kt_entry, sizeof(krb5_keytab_entry))) {
172                         smb_krb5_kt_free_entry(context, &kt_entry);
173                 }
174         }
175
176         {
177                 krb5_kt_cursor zero_csr;
178                 ZERO_STRUCT(zero_csr);
179                 if ((memcmp(&kt_cursor, &zero_csr, sizeof(krb5_kt_cursor)) != 0) && keytab) {
180                         krb5_kt_end_seq_get(context, keytab, &kt_cursor);
181                 }
182         }
183
184         if (keytab) {
185                 krb5_kt_close(context, keytab);
186         }
187         return auth_ok;
188 }
189
190 /**********************************************************************************
191  Try to verify a ticket using the secrets.tdb.
192 ***********************************************************************************/
193
194 static BOOL ads_secrets_verify_ticket(krb5_context context, krb5_auth_context auth_context,
195                                       krb5_principal host_princ,
196                                       const DATA_BLOB *ticket, krb5_data *p_packet, krb5_ticket **pp_tkt,
197                                       krb5_keyblock **keyblock)
198 {
199         krb5_error_code ret = 0;
200         BOOL auth_ok = False;
201         char *password_s = NULL;
202         krb5_data password;
203         krb5_enctype enctypes[4] = { ENCTYPE_DES_CBC_CRC, ENCTYPE_DES_CBC_MD5, 0, 0 };
204         int i;
205
206 #if defined(ENCTYPE_ARCFOUR_HMAC)
207         enctypes[2] = ENCTYPE_ARCFOUR_HMAC;
208 #endif
209
210         ZERO_STRUCTP(keyblock);
211
212         if (!secrets_init()) {
213                 DEBUG(1,("ads_secrets_verify_ticket: secrets_init failed\n"));
214                 return False;
215         }
216
217         password_s = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
218         if (!password_s) {
219                 DEBUG(1,("ads_secrets_verify_ticket: failed to fetch machine password\n"));
220                 return False;
221         }
222
223         password.data = password_s;
224         password.length = strlen(password_s);
225
226         /* CIFS doesn't use addresses in tickets. This would break NAT. JRA */
227
228         p_packet->length = ticket->length;
229         p_packet->data = (char *)ticket->data;
230
231         /* We need to setup a auth context with each possible encoding type in turn. */
232         for (i=0;enctypes[i];i++) {
233                 krb5_keyblock *key = NULL;
234
235                 if (!(key = SMB_MALLOC_P(krb5_keyblock))) {
236                         goto out;
237                 }
238         
239                 if (create_kerberos_key_from_string(context, host_princ, &password, key, enctypes[i])) {
240                         SAFE_FREE(key);
241                         continue;
242                 }
243
244                 krb5_auth_con_setuseruserkey(context, auth_context, key);
245
246                 if (!(ret = krb5_rd_req(context, &auth_context, p_packet, 
247                                         NULL,
248                                         NULL, NULL, pp_tkt))) {
249                         DEBUG(10,("ads_secrets_verify_ticket: enc type [%u] decrypted message !\n",
250                                 (unsigned int)enctypes[i] ));
251                         auth_ok = True;
252                         krb5_copy_keyblock(context, key, keyblock);
253                         krb5_free_keyblock(context, key);
254                         break;
255                 }
256
257                 DEBUG((ret != KRB5_BAD_ENCTYPE) ? 3 : 10,
258                                 ("ads_secrets_verify_ticket: enc type [%u] failed to decrypt with error %s\n",
259                                 (unsigned int)enctypes[i], error_message(ret)));
260
261                 /* successfully decrypted but ticket is just not valid at the moment */
262                 if (ret == KRB5KRB_AP_ERR_TKT_NYV || 
263                     ret == KRB5KRB_AP_ERR_TKT_EXPIRED) {
264                         break;
265                 }
266
267                 krb5_free_keyblock(context, key);
268
269         }
270
271  out:
272         SAFE_FREE(password_s);
273
274         return auth_ok;
275 }
276
277 /**********************************************************************************
278  Verify an incoming ticket and parse out the principal name and 
279  authorization_data if available.
280 ***********************************************************************************/
281
282 NTSTATUS ads_verify_ticket(TALLOC_CTX *mem_ctx,
283                            const char *realm, time_t time_offset,
284                            const DATA_BLOB *ticket, 
285                            char **principal, PAC_DATA **pac_data,
286                            DATA_BLOB *ap_rep,
287                            DATA_BLOB *session_key)
288 {
289         NTSTATUS sret = NT_STATUS_LOGON_FAILURE;
290         NTSTATUS pac_ret;
291         DATA_BLOB auth_data;
292         krb5_context context = NULL;
293         krb5_auth_context auth_context = NULL;
294         krb5_data packet;
295         krb5_ticket *tkt = NULL;
296         krb5_rcache rcache = NULL;
297         krb5_keyblock *keyblock = NULL;
298         time_t authtime;
299         int ret;
300
301         krb5_principal host_princ = NULL;
302         krb5_const_principal client_principal = NULL;
303         char *host_princ_s = NULL;
304         BOOL got_replay_mutex = False;
305
306         BOOL auth_ok = False;
307         BOOL got_auth_data = False;
308
309         ZERO_STRUCT(packet);
310         ZERO_STRUCT(auth_data);
311         ZERO_STRUCTP(ap_rep);
312         ZERO_STRUCTP(session_key);
313
314         initialize_krb5_error_table();
315         ret = krb5_init_context(&context);
316         if (ret) {
317                 DEBUG(1,("ads_verify_ticket: krb5_init_context failed (%s)\n", error_message(ret)));
318                 return NT_STATUS_LOGON_FAILURE;
319         }
320
321         if (time_offset != 0) {
322                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
323         }
324
325         ret = krb5_set_default_realm(context, realm);
326         if (ret) {
327                 DEBUG(1,("ads_verify_ticket: krb5_set_default_realm failed (%s)\n", error_message(ret)));
328                 goto out;
329         }
330
331         /* This whole process is far more complex than I would
332            like. We have to go through all this to allow us to store
333            the secret internally, instead of using /etc/krb5.keytab */
334
335         ret = krb5_auth_con_init(context, &auth_context);
336         if (ret) {
337                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_init failed (%s)\n", error_message(ret)));
338                 goto out;
339         }
340
341         asprintf(&host_princ_s, "%s$", global_myname());
342         strlower_m(host_princ_s);
343         ret = smb_krb5_parse_name(context, host_princ_s, &host_princ);
344         if (ret) {
345                 DEBUG(1,("ads_verify_ticket: smb_krb5_parse_name(%s) failed (%s)\n",
346                                         host_princ_s, error_message(ret)));
347                 goto out;
348         }
349
350
351         /* Lock a mutex surrounding the replay as there is no locking in the MIT krb5
352          * code surrounding the replay cache... */
353
354         if (!grab_server_mutex("replay cache mutex")) {
355                 DEBUG(1,("ads_verify_ticket: unable to protect replay cache with mutex.\n"));
356                 goto out;
357         }
358
359         got_replay_mutex = True;
360
361         /*
362          * JRA. We must set the rcache here. This will prevent replay attacks.
363          */
364
365         ret = krb5_get_server_rcache(context, krb5_princ_component(context, host_princ, 0), &rcache);
366         if (ret) {
367                 DEBUG(1,("ads_verify_ticket: krb5_get_server_rcache failed (%s)\n", error_message(ret)));
368                 goto out;
369         }
370
371         ret = krb5_auth_con_setrcache(context, auth_context, rcache);
372         if (ret) {
373                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_setrcache failed (%s)\n", error_message(ret)));
374                 goto out;
375         }
376
377         if (lp_use_kerberos_keytab()) {
378                 auth_ok = ads_keytab_verify_ticket(context, auth_context, ticket, &packet, &tkt, &keyblock);
379         }
380         if (!auth_ok) {
381                 auth_ok = ads_secrets_verify_ticket(context, auth_context, host_princ,
382                                                     ticket, &packet, &tkt, &keyblock);
383         }
384
385         release_server_mutex();
386         got_replay_mutex = False;
387
388 #if 0
389         /* Heimdal leaks here, if we fix the leak, MIT crashes */
390         if (rcache) {
391                 krb5_rc_close(context, rcache);
392         }
393 #endif
394
395         if (!auth_ok) {
396                 DEBUG(3,("ads_verify_ticket: krb5_rd_req with auth failed (%s)\n", 
397                          error_message(ret)));
398                 goto out;
399         } 
400         
401         authtime = get_authtime_from_tkt(tkt);
402         client_principal = get_principal_from_tkt(tkt);
403
404         ret = krb5_mk_rep(context, auth_context, &packet);
405         if (ret) {
406                 DEBUG(3,("ads_verify_ticket: Failed to generate mutual authentication reply (%s)\n",
407                         error_message(ret)));
408                 goto out;
409         }
410
411         *ap_rep = data_blob(packet.data, packet.length);
412         SAFE_FREE(packet.data);
413         packet.length = 0;
414
415         get_krb5_smb_session_key(context, auth_context, session_key, True);
416         dump_data_pw("SMB session key (from ticket)\n", session_key->data, session_key->length);
417
418 #if 0
419         file_save("/tmp/ticket.dat", ticket->data, ticket->length);
420 #endif
421
422         /* continue when no PAC is retrieved or we couldn't decode the PAC 
423            (like accounts that have the UF_NO_AUTH_DATA_REQUIRED flag set, or
424            Kerberos tickets encrypted using a DES key) - Guenther */
425
426         got_auth_data = get_auth_data_from_tkt(mem_ctx, &auth_data, tkt);
427         if (!got_auth_data) {
428                 DEBUG(3,("ads_verify_ticket: did not retrieve auth data. continuing without PAC\n"));
429         }
430
431         if (got_auth_data && pac_data != NULL) {
432
433                 pac_ret = decode_pac_data(mem_ctx, &auth_data, context, keyblock, client_principal, authtime, pac_data);
434                 if (!NT_STATUS_IS_OK(pac_ret)) {
435                         DEBUG(3,("ads_verify_ticket: failed to decode PAC_DATA: %s\n", nt_errstr(pac_ret)));
436                         *pac_data = NULL;
437                 }
438                 data_blob_free(&auth_data);
439         }
440
441 #if 0
442 #if defined(HAVE_KRB5_TKT_ENC_PART2)
443         /* MIT */
444         if (tkt->enc_part2) {
445                 file_save("/tmp/authdata.dat",
446                           tkt->enc_part2->authorization_data[0]->contents,
447                           tkt->enc_part2->authorization_data[0]->length);
448         }
449 #else
450         /* Heimdal */
451         if (tkt->ticket.authorization_data) {
452                 file_save("/tmp/authdata.dat",
453                           tkt->ticket.authorization_data->val->ad_data.data,
454                           tkt->ticket.authorization_data->val->ad_data.length);
455         }
456 #endif
457 #endif
458
459         if ((ret = smb_krb5_unparse_name(context, client_principal, principal))) {
460                 DEBUG(3,("ads_verify_ticket: smb_krb5_unparse_name failed (%s)\n", 
461                          error_message(ret)));
462                 sret = NT_STATUS_LOGON_FAILURE;
463                 goto out;
464         }
465
466         sret = NT_STATUS_OK;
467
468  out:
469
470         if (got_replay_mutex) {
471                 release_server_mutex();
472         }
473
474         if (!NT_STATUS_IS_OK(sret)) {
475                 data_blob_free(&auth_data);
476         }
477
478         if (!NT_STATUS_IS_OK(sret)) {
479                 data_blob_free(ap_rep);
480         }
481
482         if (host_princ) {
483                 krb5_free_principal(context, host_princ);
484         }
485
486         if (keyblock) {
487                 krb5_free_keyblock(context, keyblock);
488         }
489
490         if (tkt != NULL) {
491                 krb5_free_ticket(context, tkt);
492         }
493
494         SAFE_FREE(host_princ_s);
495
496         if (auth_context) {
497                 krb5_auth_con_free(context, auth_context);
498         }
499
500         if (context) {
501                 krb5_free_context(context);
502         }
503
504         return sret;
505 }
506
507 #endif /* HAVE_KRB5 */