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