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