r16952: New derive DES salt code and Krb5 keytab generation
[samba.git] / source3 / 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[4] = { ENCTYPE_DES_CBC_CRC, ENCTYPE_DES_CBC_MD5, 0, 0 };
206         int i;
207
208 #if defined(ENCTYPE_ARCFOUR_HMAC)
209         enctypes[2] = ENCTYPE_ARCFOUR_HMAC;
210 #endif
211
212         ZERO_STRUCTP(keyblock);
213
214         if (!secrets_init()) {
215                 DEBUG(1,("ads_secrets_verify_ticket: secrets_init failed\n"));
216                 return False;
217         }
218
219         password_s = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
220         if (!password_s) {
221                 DEBUG(1,("ads_secrets_verify_ticket: failed to fetch machine password\n"));
222                 return False;
223         }
224
225         password.data = password_s;
226         password.length = strlen(password_s);
227
228         /* CIFS doesn't use addresses in tickets. This would break NAT. JRA */
229
230         p_packet->length = ticket->length;
231         p_packet->data = (krb5_pointer)ticket->data;
232
233         /* We need to setup a auth context with each possible encoding type in turn. */
234         for (i=0;enctypes[i];i++) {
235                 krb5_keyblock *key = NULL;
236
237                 if (!(key = SMB_MALLOC_P(krb5_keyblock))) {
238                         goto out;
239                 }
240         
241                 if (create_kerberos_key_from_string(context, host_princ, &password, key, enctypes[i])) {
242                         SAFE_FREE(key);
243                         continue;
244                 }
245
246                 krb5_auth_con_setuseruserkey(context, auth_context, key);
247
248                 if (!(ret = krb5_rd_req(context, &auth_context, p_packet, 
249                                         NULL,
250                                         NULL, NULL, pp_tkt))) {
251                         DEBUG(10,("ads_secrets_verify_ticket: enc type [%u] decrypted message !\n",
252                                 (unsigned int)enctypes[i] ));
253                         auth_ok = True;
254                         krb5_copy_keyblock(context, key, keyblock);
255                         krb5_free_keyblock(context, key);
256                         break;
257                 }
258
259                 DEBUG((ret != KRB5_BAD_ENCTYPE) ? 3 : 10,
260                                 ("ads_secrets_verify_ticket: enc type [%u] failed to decrypt with error %s\n",
261                                 (unsigned int)enctypes[i], error_message(ret)));
262
263                 /* successfully decrypted but ticket is just not valid at the moment */
264                 if (ret == KRB5KRB_AP_ERR_TKT_NYV || 
265                     ret == KRB5KRB_AP_ERR_TKT_EXPIRED) {
266                         break;
267                 }
268
269                 krb5_free_keyblock(context, key);
270
271         }
272
273  out:
274         SAFE_FREE(password_s);
275
276         return auth_ok;
277 }
278
279 /**********************************************************************************
280  Verify an incoming ticket and parse out the principal name and 
281  authorization_data if available.
282 ***********************************************************************************/
283
284 NTSTATUS ads_verify_ticket(TALLOC_CTX *mem_ctx,
285                            const char *realm, time_t time_offset,
286                            const DATA_BLOB *ticket, 
287                            char **principal, PAC_DATA **pac_data,
288                            DATA_BLOB *ap_rep,
289                            DATA_BLOB *session_key)
290 {
291         NTSTATUS sret = NT_STATUS_LOGON_FAILURE;
292         NTSTATUS pac_ret;
293         DATA_BLOB auth_data;
294         krb5_context context = NULL;
295         krb5_auth_context auth_context = NULL;
296         krb5_data packet;
297         krb5_ticket *tkt = NULL;
298         krb5_rcache rcache = NULL;
299         krb5_keyblock *keyblock = NULL;
300         time_t authtime;
301         int ret;
302
303         krb5_principal host_princ = NULL;
304         krb5_const_principal client_principal = NULL;
305         char *host_princ_s = NULL;
306         BOOL got_replay_mutex = False;
307
308         BOOL auth_ok = False;
309         BOOL got_auth_data = False;
310
311         ZERO_STRUCT(packet);
312         ZERO_STRUCT(auth_data);
313         ZERO_STRUCTP(ap_rep);
314         ZERO_STRUCTP(session_key);
315
316         initialize_krb5_error_table();
317         ret = krb5_init_context(&context);
318         if (ret) {
319                 DEBUG(1,("ads_verify_ticket: krb5_init_context failed (%s)\n", error_message(ret)));
320                 return NT_STATUS_LOGON_FAILURE;
321         }
322
323         if (time_offset != 0) {
324                 krb5_set_real_time(context, time(NULL) + time_offset, 0);
325         }
326
327         ret = krb5_set_default_realm(context, realm);
328         if (ret) {
329                 DEBUG(1,("ads_verify_ticket: krb5_set_default_realm failed (%s)\n", error_message(ret)));
330                 goto out;
331         }
332
333         /* This whole process is far more complex than I would
334            like. We have to go through all this to allow us to store
335            the secret internally, instead of using /etc/krb5.keytab */
336
337         ret = krb5_auth_con_init(context, &auth_context);
338         if (ret) {
339                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_init failed (%s)\n", error_message(ret)));
340                 goto out;
341         }
342
343         asprintf(&host_princ_s, "%s$", global_myname());
344         strlower_m(host_princ_s);
345         ret = smb_krb5_parse_name(context, host_princ_s, &host_princ);
346         if (ret) {
347                 DEBUG(1,("ads_verify_ticket: smb_krb5_parse_name(%s) failed (%s)\n",
348                                         host_princ_s, error_message(ret)));
349                 goto out;
350         }
351
352
353         /* Lock a mutex surrounding the replay as there is no locking in the MIT krb5
354          * code surrounding the replay cache... */
355
356         if (!grab_server_mutex("replay cache mutex")) {
357                 DEBUG(1,("ads_verify_ticket: unable to protect replay cache with mutex.\n"));
358                 goto out;
359         }
360
361         got_replay_mutex = True;
362
363         /*
364          * JRA. We must set the rcache here. This will prevent replay attacks.
365          */
366
367         ret = krb5_get_server_rcache(context, krb5_princ_component(context, host_princ, 0), &rcache);
368         if (ret) {
369                 DEBUG(1,("ads_verify_ticket: krb5_get_server_rcache failed (%s)\n", error_message(ret)));
370                 goto out;
371         }
372
373         ret = krb5_auth_con_setrcache(context, auth_context, rcache);
374         if (ret) {
375                 DEBUG(1,("ads_verify_ticket: krb5_auth_con_setrcache failed (%s)\n", error_message(ret)));
376                 goto out;
377         }
378
379         if (lp_use_kerberos_keytab()) {
380                 auth_ok = ads_keytab_verify_ticket(context, auth_context, ticket, &packet, &tkt, &keyblock);
381         }
382         if (!auth_ok) {
383                 auth_ok = ads_secrets_verify_ticket(context, auth_context, host_princ,
384                                                     ticket, &packet, &tkt, &keyblock);
385         }
386
387         release_server_mutex();
388         got_replay_mutex = False;
389
390 #if 0
391         /* Heimdal leaks here, if we fix the leak, MIT crashes */
392         if (rcache) {
393                 krb5_rc_close(context, rcache);
394         }
395 #endif
396
397         if (!auth_ok) {
398                 DEBUG(3,("ads_verify_ticket: krb5_rd_req with auth failed (%s)\n", 
399                          error_message(ret)));
400                 goto out;
401         } 
402         
403         authtime = get_authtime_from_tkt(tkt);
404         client_principal = get_principal_from_tkt(tkt);
405
406         ret = krb5_mk_rep(context, auth_context, &packet);
407         if (ret) {
408                 DEBUG(3,("ads_verify_ticket: Failed to generate mutual authentication reply (%s)\n",
409                         error_message(ret)));
410                 goto out;
411         }
412
413         *ap_rep = data_blob(packet.data, packet.length);
414         SAFE_FREE(packet.data);
415         packet.length = 0;
416
417         get_krb5_smb_session_key(context, auth_context, session_key, True);
418         dump_data_pw("SMB session key (from ticket)\n", session_key->data, session_key->length);
419
420 #if 0
421         file_save("/tmp/ticket.dat", ticket->data, ticket->length);
422 #endif
423
424         /* continue when no PAC is retrieved or we couldn't decode the PAC 
425            (like accounts that have the UF_NO_AUTH_DATA_REQUIRED flag set, or
426            Kerberos tickets encrypted using a DES key) - Guenther */
427
428         got_auth_data = get_auth_data_from_tkt(mem_ctx, &auth_data, tkt);
429         if (!got_auth_data) {
430                 DEBUG(3,("ads_verify_ticket: did not retrieve auth data. continuing without PAC\n"));
431         }
432
433         if (got_auth_data && pac_data != NULL) {
434
435                 pac_ret = decode_pac_data(mem_ctx, &auth_data, context, keyblock, client_principal, authtime, pac_data);
436                 if (!NT_STATUS_IS_OK(pac_ret)) {
437                         DEBUG(3,("ads_verify_ticket: failed to decode PAC_DATA: %s\n", nt_errstr(pac_ret)));
438                         *pac_data = NULL;
439                 }
440                 data_blob_free(&auth_data);
441         }
442
443 #if 0
444 #if defined(HAVE_KRB5_TKT_ENC_PART2)
445         /* MIT */
446         if (tkt->enc_part2) {
447                 file_save("/tmp/authdata.dat",
448                           tkt->enc_part2->authorization_data[0]->contents,
449                           tkt->enc_part2->authorization_data[0]->length);
450         }
451 #else
452         /* Heimdal */
453         if (tkt->ticket.authorization_data) {
454                 file_save("/tmp/authdata.dat",
455                           tkt->ticket.authorization_data->val->ad_data.data,
456                           tkt->ticket.authorization_data->val->ad_data.length);
457         }
458 #endif
459 #endif
460
461         if ((ret = smb_krb5_unparse_name(context, client_principal, principal))) {
462                 DEBUG(3,("ads_verify_ticket: smb_krb5_unparse_name failed (%s)\n", 
463                          error_message(ret)));
464                 sret = NT_STATUS_LOGON_FAILURE;
465                 goto out;
466         }
467
468         sret = NT_STATUS_OK;
469
470  out:
471
472         if (got_replay_mutex) {
473                 release_server_mutex();
474         }
475
476         if (!NT_STATUS_IS_OK(sret)) {
477                 data_blob_free(&auth_data);
478         }
479
480         if (!NT_STATUS_IS_OK(sret)) {
481                 data_blob_free(ap_rep);
482         }
483
484         if (host_princ) {
485                 krb5_free_principal(context, host_princ);
486         }
487
488         if (keyblock) {
489                 krb5_free_keyblock(context, keyblock);
490         }
491
492         if (tkt != NULL) {
493                 krb5_free_ticket(context, tkt);
494         }
495
496         SAFE_FREE(host_princ_s);
497
498         if (auth_context) {
499                 krb5_auth_con_free(context, auth_context);
500         }
501
502         if (context) {
503                 krb5_free_context(context);
504         }
505
506         return sret;
507 }
508
509 #endif /* HAVE_KRB5 */