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