8dde8373a8e45cbc850b1da78f74cd501aa0a04c
[idra/samba.git] / source4 / auth / gensec / gensec_krb5.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Kerberos backend for GENSEC
5    
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004
7    Copyright (C) Andrew Tridgell 2001
8    Copyright (C) Luke Howard 2002-2003
9    Copyright (C) Stefan Metzmacher 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 3 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    
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "system/kerberos.h"
28 #include "auth/kerberos/kerberos.h"
29 #include "auth/auth.h"
30 #include "lib/socket/socket.h"
31 #include "lib/tsocket/tsocket.h"
32 #include "librpc/rpc/dcerpc.h"
33 #include "auth/credentials/credentials.h"
34 #include "auth/credentials/credentials_krb5.h"
35 #include "auth/kerberos/kerberos_credentials.h"
36 #include "auth/gensec/gensec.h"
37 #include "auth/gensec/gensec_proto.h"
38 #include "auth/gensec/gensec_toplevel_proto.h"
39 #include "param/param.h"
40 #include "auth/auth_sam_reply.h"
41 #include "lib/util/util_net.h"
42 #include "../lib/util/asn1.h"
43 #include "auth/kerberos/pac_utils.h"
44
45 _PUBLIC_ NTSTATUS gensec_krb5_init(void);
46
47 enum GENSEC_KRB5_STATE {
48         GENSEC_KRB5_SERVER_START,
49         GENSEC_KRB5_CLIENT_START,
50         GENSEC_KRB5_CLIENT_MUTUAL_AUTH,
51         GENSEC_KRB5_DONE
52 };
53
54 struct gensec_krb5_state {
55         enum GENSEC_KRB5_STATE state_position;
56         struct smb_krb5_context *smb_krb5_context;
57         krb5_auth_context auth_context;
58         krb5_data enc_ticket;
59         krb5_keyblock *keyblock;
60         krb5_ticket *ticket;
61         bool gssapi;
62         krb5_flags ap_req_options;
63 };
64
65 static int gensec_krb5_destroy(struct gensec_krb5_state *gensec_krb5_state)
66 {
67         if (!gensec_krb5_state->smb_krb5_context) {
68                 /* We can't clean anything else up unless we started up this far */
69                 return 0;
70         }
71         if (gensec_krb5_state->enc_ticket.length) { 
72                 kerberos_free_data_contents(gensec_krb5_state->smb_krb5_context->krb5_context, 
73                                             &gensec_krb5_state->enc_ticket); 
74         }
75
76         if (gensec_krb5_state->ticket) {
77                 krb5_free_ticket(gensec_krb5_state->smb_krb5_context->krb5_context, 
78                                  gensec_krb5_state->ticket);
79         }
80
81         /* ccache freed in a child destructor */
82
83         krb5_free_keyblock(gensec_krb5_state->smb_krb5_context->krb5_context, 
84                            gensec_krb5_state->keyblock);
85                 
86         if (gensec_krb5_state->auth_context) {
87                 krb5_auth_con_free(gensec_krb5_state->smb_krb5_context->krb5_context, 
88                                    gensec_krb5_state->auth_context);
89         }
90
91         return 0;
92 }
93
94 static NTSTATUS gensec_krb5_start(struct gensec_security *gensec_security, bool gssapi)
95 {
96         krb5_error_code ret;
97         struct gensec_krb5_state *gensec_krb5_state;
98         struct cli_credentials *creds;
99         const struct tsocket_address *tlocal_addr, *tremote_addr;
100         krb5_address my_krb5_addr, peer_krb5_addr;
101         
102         creds = gensec_get_credentials(gensec_security);
103         if (!creds) {
104                 return NT_STATUS_INVALID_PARAMETER;
105         }
106
107         gensec_krb5_state = talloc(gensec_security, struct gensec_krb5_state);
108         if (!gensec_krb5_state) {
109                 return NT_STATUS_NO_MEMORY;
110         }
111
112         gensec_security->private_data = gensec_krb5_state;
113         gensec_krb5_state->smb_krb5_context = NULL;
114         gensec_krb5_state->auth_context = NULL;
115         gensec_krb5_state->ticket = NULL;
116         ZERO_STRUCT(gensec_krb5_state->enc_ticket);
117         gensec_krb5_state->keyblock = NULL;
118         gensec_krb5_state->gssapi = gssapi;
119
120         talloc_set_destructor(gensec_krb5_state, gensec_krb5_destroy); 
121
122         if (cli_credentials_get_krb5_context(creds, 
123                                              gensec_security->settings->lp_ctx, &gensec_krb5_state->smb_krb5_context)) {
124                 talloc_free(gensec_krb5_state);
125                 return NT_STATUS_INTERNAL_ERROR;
126         }
127
128         ret = krb5_auth_con_init(gensec_krb5_state->smb_krb5_context->krb5_context, &gensec_krb5_state->auth_context);
129         if (ret) {
130                 DEBUG(1,("gensec_krb5_start: krb5_auth_con_init failed (%s)\n", 
131                          smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
132                                                     ret, gensec_krb5_state)));
133                 talloc_free(gensec_krb5_state);
134                 return NT_STATUS_INTERNAL_ERROR;
135         }
136
137         ret = krb5_auth_con_setflags(gensec_krb5_state->smb_krb5_context->krb5_context, 
138                                      gensec_krb5_state->auth_context,
139                                      KRB5_AUTH_CONTEXT_DO_SEQUENCE);
140         if (ret) {
141                 DEBUG(1,("gensec_krb5_start: krb5_auth_con_setflags failed (%s)\n", 
142                          smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
143                                                     ret, gensec_krb5_state)));
144                 talloc_free(gensec_krb5_state);
145                 return NT_STATUS_INTERNAL_ERROR;
146         }
147
148         tlocal_addr = gensec_get_local_address(gensec_security);
149         if (tlocal_addr) {
150                 ssize_t socklen;
151                 struct sockaddr_storage ss;
152
153                 socklen = tsocket_address_bsd_sockaddr(tlocal_addr,
154                                 (struct sockaddr *) &ss,
155                                 sizeof(struct sockaddr_storage));
156                 if (socklen < 0) {
157                         talloc_free(gensec_krb5_state);
158                         return NT_STATUS_INTERNAL_ERROR;
159                 }
160                 ret = krb5_sockaddr2address(gensec_krb5_state->smb_krb5_context->krb5_context,
161                                 (const struct sockaddr *) &ss, &my_krb5_addr);
162                 if (ret) {
163                         DEBUG(1,("gensec_krb5_start: krb5_sockaddr2address (local) failed (%s)\n", 
164                                  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
165                                                             ret, gensec_krb5_state)));
166                         talloc_free(gensec_krb5_state);
167                         return NT_STATUS_INTERNAL_ERROR;
168                 }
169         }
170
171         tremote_addr = gensec_get_remote_address(gensec_security);
172         if (tremote_addr) {
173                 ssize_t socklen;
174                 struct sockaddr_storage ss;
175
176                 socklen = tsocket_address_bsd_sockaddr(tremote_addr,
177                                 (struct sockaddr *) &ss,
178                                 sizeof(struct sockaddr_storage));
179                 if (socklen < 0) {
180                         talloc_free(gensec_krb5_state);
181                         return NT_STATUS_INTERNAL_ERROR;
182                 }
183                 ret = krb5_sockaddr2address(gensec_krb5_state->smb_krb5_context->krb5_context,
184                                 (const struct sockaddr *) &ss, &peer_krb5_addr);
185                 if (ret) {
186                         DEBUG(1,("gensec_krb5_start: krb5_sockaddr2address (local) failed (%s)\n", 
187                                  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
188                                                             ret, gensec_krb5_state)));
189                         talloc_free(gensec_krb5_state);
190                         return NT_STATUS_INTERNAL_ERROR;
191                 }
192         }
193
194         ret = krb5_auth_con_setaddrs(gensec_krb5_state->smb_krb5_context->krb5_context, 
195                                      gensec_krb5_state->auth_context,
196                                      tlocal_addr ? &my_krb5_addr : NULL,
197                                      tremote_addr ? &peer_krb5_addr : NULL);
198         if (ret) {
199                 DEBUG(1,("gensec_krb5_start: krb5_auth_con_setaddrs failed (%s)\n", 
200                          smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
201                                                     ret, gensec_krb5_state)));
202                 talloc_free(gensec_krb5_state);
203                 return NT_STATUS_INTERNAL_ERROR;
204         }
205
206         return NT_STATUS_OK;
207 }
208
209 static NTSTATUS gensec_krb5_common_server_start(struct gensec_security *gensec_security, bool gssapi)
210 {
211         NTSTATUS nt_status;
212         struct gensec_krb5_state *gensec_krb5_state;
213
214         nt_status = gensec_krb5_start(gensec_security, gssapi);
215         if (!NT_STATUS_IS_OK(nt_status)) {
216                 return nt_status;
217         }
218         
219         gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
220         gensec_krb5_state->state_position = GENSEC_KRB5_SERVER_START;
221
222         return NT_STATUS_OK;
223 }
224
225 static NTSTATUS gensec_krb5_server_start(struct gensec_security *gensec_security)
226 {
227         return gensec_krb5_common_server_start(gensec_security, false);
228 }
229
230 static NTSTATUS gensec_fake_gssapi_krb5_server_start(struct gensec_security *gensec_security)
231 {
232         return gensec_krb5_common_server_start(gensec_security, true);
233 }
234
235 static NTSTATUS gensec_krb5_common_client_start(struct gensec_security *gensec_security, bool gssapi)
236 {
237         const char *hostname;
238         struct gensec_krb5_state *gensec_krb5_state;
239         NTSTATUS nt_status;
240         hostname = gensec_get_target_hostname(gensec_security);
241         if (!hostname) {
242                 DEBUG(1, ("Could not determine hostname for target computer, cannot use kerberos\n"));
243                 return NT_STATUS_INVALID_PARAMETER;
244         }
245         if (is_ipaddress(hostname)) {
246                 DEBUG(2, ("Cannot do krb5 to an IP address"));
247                 return NT_STATUS_INVALID_PARAMETER;
248         }
249         if (strcmp(hostname, "localhost") == 0) {
250                 DEBUG(2, ("krb5 to 'localhost' does not make sense"));
251                 return NT_STATUS_INVALID_PARAMETER;
252         }
253                         
254         nt_status = gensec_krb5_start(gensec_security, gssapi);
255         if (!NT_STATUS_IS_OK(nt_status)) {
256                 return nt_status;
257         }
258
259         gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
260         gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_START;
261         gensec_krb5_state->ap_req_options = AP_OPTS_USE_SUBKEY;
262
263         if (gensec_krb5_state->gssapi) {
264                 /* The Fake GSSAPI modal emulates Samba3, which does not do mutual authentication */
265                 if (gensec_setting_bool(gensec_security->settings, "gensec_fake_gssapi_krb5", "mutual", false)) {
266                         gensec_krb5_state->ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
267                 }
268         } else {
269                 /* The wrapping for KPASSWD (a user of the raw KRB5 API) should be mutually authenticated */
270                 if (gensec_setting_bool(gensec_security->settings, "gensec_krb5", "mutual", true)) {
271                         gensec_krb5_state->ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
272                 }
273         }
274         return NT_STATUS_OK;
275 }
276
277 static NTSTATUS gensec_krb5_common_client_creds(struct gensec_security *gensec_security,
278                                                 struct tevent_context *ev,
279                                                 bool gssapi)
280 {
281         struct gensec_krb5_state *gensec_krb5_state;
282         krb5_error_code ret;
283         struct ccache_container *ccache_container;
284         const char *error_string;
285         const char *principal;
286         const char *hostname;
287         krb5_data in_data;
288         struct tevent_context *previous_ev;
289
290         gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
291
292         principal = gensec_get_target_principal(gensec_security);
293         hostname = gensec_get_target_hostname(gensec_security);
294
295         ret = cli_credentials_get_ccache(gensec_get_credentials(gensec_security), 
296                                          ev,
297                                          gensec_security->settings->lp_ctx, &ccache_container, &error_string);
298         switch (ret) {
299         case 0:
300                 break;
301         case KRB5KDC_ERR_PREAUTH_FAILED:
302         case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN:
303                 return NT_STATUS_LOGON_FAILURE;
304         case KRB5_KDC_UNREACH:
305                 DEBUG(3, ("Cannot reach a KDC we require to contact %s: %s\n", principal, error_string));
306                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
307         case KRB5_CC_NOTFOUND:
308         case KRB5_CC_END:
309                 DEBUG(3, ("Error preparing credentials we require to contact %s : %s\n", principal, error_string));
310                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
311         default:
312                 DEBUG(1, ("gensec_krb5_start: Aquiring initiator credentials failed: %s\n", error_string));
313                 return NT_STATUS_UNSUCCESSFUL;
314         }
315         in_data.length = 0;
316         
317         /* Do this every time, in case we have weird recursive issues here */
318         ret = smb_krb5_context_set_event_ctx(gensec_krb5_state->smb_krb5_context, ev, &previous_ev);
319         if (ret != 0) {
320                 DEBUG(1, ("gensec_krb5_start: Setting event context failed\n"));
321                 return NT_STATUS_NO_MEMORY;
322         }
323         if (principal) {
324                 krb5_principal target_principal;
325                 ret = krb5_parse_name(gensec_krb5_state->smb_krb5_context->krb5_context, principal,
326                                       &target_principal);
327                 if (ret == 0) {
328                         ret = krb5_mk_req_exact(gensec_krb5_state->smb_krb5_context->krb5_context, 
329                                                 &gensec_krb5_state->auth_context,
330                                                 gensec_krb5_state->ap_req_options, 
331                                                 target_principal,
332                                                 &in_data, ccache_container->ccache, 
333                                                 &gensec_krb5_state->enc_ticket);
334                         krb5_free_principal(gensec_krb5_state->smb_krb5_context->krb5_context, 
335                                             target_principal);
336                 }
337         } else {
338                 ret = krb5_mk_req(gensec_krb5_state->smb_krb5_context->krb5_context, 
339                                   &gensec_krb5_state->auth_context,
340                                   gensec_krb5_state->ap_req_options,
341                                   gensec_get_target_service(gensec_security),
342                                   hostname,
343                                   &in_data, ccache_container->ccache, 
344                                   &gensec_krb5_state->enc_ticket);
345         }
346
347         smb_krb5_context_remove_event_ctx(gensec_krb5_state->smb_krb5_context, previous_ev, ev);
348
349         switch (ret) {
350         case 0:
351                 return NT_STATUS_OK;
352         case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN:
353                 DEBUG(3, ("Server [%s] is not registered with our KDC: %s\n", 
354                           hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
355                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
356         case KRB5_KDC_UNREACH:
357                 DEBUG(3, ("Cannot reach a KDC we require to contact host [%s]: %s\n",
358                           hostname, smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
359                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
360         case KRB5KDC_ERR_PREAUTH_FAILED:
361         case KRB5KRB_AP_ERR_TKT_EXPIRED:
362         case KRB5_CC_END:
363                 /* Too much clock skew - we will need to kinit to re-skew the clock */
364         case KRB5KRB_AP_ERR_SKEW:
365         case KRB5_KDCREP_SKEW:
366         {
367                 DEBUG(3, ("kerberos (mk_req) failed: %s\n", 
368                           smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
369                 /*fall through*/
370         }
371         
372         /* just don't print a message for these really ordinary messages */
373         case KRB5_FCC_NOFILE:
374         case KRB5_CC_NOTFOUND:
375         case ENOENT:
376                 
377                 return NT_STATUS_UNSUCCESSFUL;
378                 break;
379                 
380         default:
381                 DEBUG(0, ("kerberos: %s\n", 
382                           smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, gensec_krb5_state)));
383                 return NT_STATUS_UNSUCCESSFUL;
384         }
385 }
386
387 static NTSTATUS gensec_krb5_client_start(struct gensec_security *gensec_security)
388 {
389         return gensec_krb5_common_client_start(gensec_security, false);
390 }
391
392 static NTSTATUS gensec_fake_gssapi_krb5_client_start(struct gensec_security *gensec_security)
393 {
394         return gensec_krb5_common_client_start(gensec_security, true);
395 }
396
397
398 /*
399   generate a krb5 GSS-API wrapper packet given a ticket
400 */
401 static DATA_BLOB gensec_gssapi_gen_krb5_wrap(TALLOC_CTX *mem_ctx, const DATA_BLOB *ticket, const uint8_t tok_id[2])
402 {
403         struct asn1_data *data;
404         DATA_BLOB ret;
405
406         data = asn1_init(mem_ctx);
407         if (!data || !ticket->data) {
408                 return data_blob(NULL,0);
409         }
410
411         asn1_push_tag(data, ASN1_APPLICATION(0));
412         asn1_write_OID(data, GENSEC_OID_KERBEROS5);
413
414         asn1_write(data, tok_id, 2);
415         asn1_write(data, ticket->data, ticket->length);
416         asn1_pop_tag(data);
417
418         if (data->has_error) {
419                 DEBUG(1,("Failed to build krb5 wrapper at offset %d\n", (int)data->ofs));
420                 asn1_free(data);
421                 return data_blob(NULL,0);
422         }
423
424         ret = data_blob_talloc(mem_ctx, data->data, data->length);
425         asn1_free(data);
426
427         return ret;
428 }
429
430 /*
431   parse a krb5 GSS-API wrapper packet giving a ticket
432 */
433 static bool gensec_gssapi_parse_krb5_wrap(TALLOC_CTX *mem_ctx, const DATA_BLOB *blob, DATA_BLOB *ticket, uint8_t tok_id[2])
434 {
435         bool ret;
436         struct asn1_data *data = asn1_init(mem_ctx);
437         int data_remaining;
438
439         if (!data) {
440                 return false;
441         }
442
443         asn1_load(data, *blob);
444         asn1_start_tag(data, ASN1_APPLICATION(0));
445         asn1_check_OID(data, GENSEC_OID_KERBEROS5);
446
447         data_remaining = asn1_tag_remaining(data);
448
449         if (data_remaining < 3) {
450                 data->has_error = true;
451         } else {
452                 asn1_read(data, tok_id, 2);
453                 data_remaining -= 2;
454                 *ticket = data_blob_talloc(mem_ctx, NULL, data_remaining);
455                 asn1_read(data, ticket->data, ticket->length);
456         }
457
458         asn1_end_tag(data);
459
460         ret = !data->has_error;
461
462         asn1_free(data);
463
464         return ret;
465 }
466
467 /**
468  * Next state function for the Krb5 GENSEC mechanism
469  * 
470  * @param gensec_krb5_state KRB5 State
471  * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on
472  * @param in The request, as a DATA_BLOB
473  * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx
474  * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, 
475  *                or NT_STATUS_OK if the user is authenticated. 
476  */
477
478 static NTSTATUS gensec_krb5_update(struct gensec_security *gensec_security, 
479                                    TALLOC_CTX *out_mem_ctx, 
480                                    struct tevent_context *ev,
481                                    const DATA_BLOB in, DATA_BLOB *out) 
482 {
483         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
484         krb5_error_code ret = 0;
485         NTSTATUS nt_status;
486
487         switch (gensec_krb5_state->state_position) {
488         case GENSEC_KRB5_CLIENT_START:
489         {
490                 DATA_BLOB unwrapped_out;
491                 
492                 nt_status = gensec_krb5_common_client_creds(gensec_security, ev, gensec_krb5_state->gssapi);
493                 if (!NT_STATUS_IS_OK(nt_status)) {
494                         return nt_status;
495                 }
496
497                 if (gensec_krb5_state->gssapi) {
498                         unwrapped_out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length);
499                         
500                         /* wrap that up in a nice GSS-API wrapping */
501                         *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REQ);
502                 } else {
503                         *out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length);
504                 }
505                 if (gensec_krb5_state->ap_req_options & AP_OPTS_MUTUAL_REQUIRED) {
506                         gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_MUTUAL_AUTH;
507                         nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED;
508                 } else {
509                         gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
510                         nt_status = NT_STATUS_OK;
511                 }
512                 return nt_status;
513         }
514                 
515         case GENSEC_KRB5_CLIENT_MUTUAL_AUTH:
516         {
517                 DATA_BLOB unwrapped_in;
518                 krb5_data inbuf;
519                 krb5_ap_rep_enc_part *repl = NULL;
520                 uint8_t tok_id[2];
521
522                 if (gensec_krb5_state->gssapi) {
523                         if (!gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) {
524                                 DEBUG(1,("gensec_gssapi_parse_krb5_wrap(mutual authentication) failed to parse\n"));
525                                 dump_data_pw("Mutual authentication message:\n", in.data, in.length);
526                                 return NT_STATUS_INVALID_PARAMETER;
527                         }
528                 } else {
529                         unwrapped_in = in;
530                 }
531                 /* TODO: check the tok_id */
532
533                 inbuf.data = unwrapped_in.data;
534                 inbuf.length = unwrapped_in.length;
535                 ret = krb5_rd_rep(gensec_krb5_state->smb_krb5_context->krb5_context, 
536                                   gensec_krb5_state->auth_context,
537                                   &inbuf, &repl);
538                 if (ret) {
539                         DEBUG(1,("krb5_rd_rep (mutual authentication) failed (%s)\n",
540                                  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, out_mem_ctx)));
541                         dump_data_pw("Mutual authentication message:\n", (uint8_t *)inbuf.data, inbuf.length);
542                         nt_status = NT_STATUS_ACCESS_DENIED;
543                 } else {
544                         *out = data_blob(NULL, 0);
545                         nt_status = NT_STATUS_OK;
546                         gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
547                 }
548                 if (repl) {
549                         krb5_free_ap_rep_enc_part(gensec_krb5_state->smb_krb5_context->krb5_context, repl);
550                 }
551                 return nt_status;
552         }
553
554         case GENSEC_KRB5_SERVER_START:
555         {
556                 DATA_BLOB unwrapped_in;
557                 DATA_BLOB unwrapped_out = data_blob(NULL, 0);
558                 krb5_data inbuf, outbuf;
559                 uint8_t tok_id[2];
560                 struct keytab_container *keytab;
561                 krb5_principal server_in_keytab;
562                 const char *error_string;
563                 enum credentials_obtained obtained;
564
565                 if (!in.data) {
566                         return NT_STATUS_INVALID_PARAMETER;
567                 }       
568
569                 /* Grab the keytab, however generated */
570                 ret = cli_credentials_get_keytab(gensec_get_credentials(gensec_security), 
571                                                  gensec_security->settings->lp_ctx, &keytab);
572                 if (ret) {
573                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
574                 }
575                 
576                 /* This ensures we lookup the correct entry in that
577                  * keytab.  A NULL principal is acceptable, and means
578                  * that the krb5 libs should search the keytab at
579                  * accept time for any matching key */
580                 ret = principal_from_credentials(out_mem_ctx, gensec_get_credentials(gensec_security), 
581                                                  gensec_krb5_state->smb_krb5_context, 
582                                                  &server_in_keytab, &obtained, &error_string);
583
584                 if (ret) {
585                         DEBUG(2,("Failed to make credentials from principal: %s\n", error_string));
586                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
587                 }
588
589                 /* Parse the GSSAPI wrapping, if it's there... (win2k3 allows it to be omited) */
590                 if (gensec_krb5_state->gssapi
591                     && gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) {
592                         inbuf.data = unwrapped_in.data;
593                         inbuf.length = unwrapped_in.length;
594                 } else {
595                         inbuf.data = in.data;
596                         inbuf.length = in.length;
597                 }
598
599                 ret = smb_rd_req_return_stuff(gensec_krb5_state->smb_krb5_context->krb5_context,
600                                               &gensec_krb5_state->auth_context, 
601                                               &inbuf, keytab->keytab, server_in_keytab,  
602                                               &outbuf, 
603                                               &gensec_krb5_state->ticket, 
604                                               &gensec_krb5_state->keyblock);
605
606                 if (ret) {
607                         return NT_STATUS_LOGON_FAILURE;
608                 }
609                 unwrapped_out.data = (uint8_t *)outbuf.data;
610                 unwrapped_out.length = outbuf.length;
611                 gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
612                 /* wrap that up in a nice GSS-API wrapping */
613                 if (gensec_krb5_state->gssapi) {
614                         *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REP);
615                 } else {
616                         *out = data_blob_talloc(out_mem_ctx, outbuf.data, outbuf.length);
617                 }
618                 krb5_data_free(&outbuf);
619                 return NT_STATUS_OK;
620         }
621
622         case GENSEC_KRB5_DONE:
623         default:
624                 /* Asking too many times... */
625                 return NT_STATUS_INVALID_PARAMETER;
626         }
627 }
628
629 static NTSTATUS gensec_krb5_session_key(struct gensec_security *gensec_security, 
630                                         TALLOC_CTX *mem_ctx,
631                                         DATA_BLOB *session_key) 
632 {
633         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
634         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
635         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
636         krb5_keyblock *skey;
637         krb5_error_code err = -1;
638
639         if (gensec_krb5_state->state_position != GENSEC_KRB5_DONE) {
640                 return NT_STATUS_NO_USER_SESSION_KEY;
641         }
642
643         switch (gensec_security->gensec_role) {
644         case GENSEC_CLIENT:
645                 err = krb5_auth_con_getlocalsubkey(context, auth_context, &skey);
646                 break;
647         case GENSEC_SERVER:
648                 err = krb5_auth_con_getremotesubkey(context, auth_context, &skey);
649                 break;
650         }
651         if (err == 0 && skey != NULL) {
652                 DEBUG(10, ("Got KRB5 session key of length %d\n",  
653                            (int)KRB5_KEY_LENGTH(skey)));
654                 *session_key = data_blob_talloc(mem_ctx,
655                                                KRB5_KEY_DATA(skey), KRB5_KEY_LENGTH(skey));
656                 dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length);
657
658                 krb5_free_keyblock(context, skey);
659                 return NT_STATUS_OK;
660         } else {
661                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
662                 return NT_STATUS_NO_USER_SESSION_KEY;
663         }
664 }
665
666 static NTSTATUS gensec_krb5_session_info(struct gensec_security *gensec_security,
667                                          TALLOC_CTX *mem_ctx,
668                                          struct auth_session_info **_session_info) 
669 {
670         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
671         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
672         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
673         struct auth_session_info *session_info = NULL;
674
675         krb5_principal client_principal;
676         char *principal_string;
677         
678         DATA_BLOB pac_blob, *pac_blob_ptr = NULL;
679         krb5_data pac_data;
680
681         krb5_error_code ret;
682
683         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
684         if (!tmp_ctx) {
685                 return NT_STATUS_NO_MEMORY;
686         }
687         
688         ret = krb5_ticket_get_client(context, gensec_krb5_state->ticket, &client_principal);
689         if (ret) {
690                 DEBUG(5, ("krb5_ticket_get_client failed to get cleint principal: %s\n", 
691                           smb_get_krb5_error_message(context, 
692                                                      ret, tmp_ctx)));
693                 talloc_free(tmp_ctx);
694                 return NT_STATUS_NO_MEMORY;
695         }
696         
697         ret = krb5_unparse_name(gensec_krb5_state->smb_krb5_context->krb5_context, 
698                                 client_principal, &principal_string);
699         if (ret) {
700                 DEBUG(1, ("Unable to parse client principal: %s\n",
701                           smb_get_krb5_error_message(context, 
702                                                      ret, tmp_ctx)));
703                 krb5_free_principal(context, client_principal);
704                 talloc_free(tmp_ctx);
705                 return NT_STATUS_NO_MEMORY;
706         }
707
708         ret = krb5_ticket_get_authorization_data_type(context, gensec_krb5_state->ticket, 
709                                                       KRB5_AUTHDATA_WIN2K_PAC, 
710                                                       &pac_data);
711         
712         if (ret) {
713                 /* NO pac */
714                 DEBUG(5, ("krb5_ticket_get_authorization_data_type failed to find PAC: %s\n", 
715                           smb_get_krb5_error_message(context, 
716                                                      ret, tmp_ctx)));
717         } else {
718                 /* Found pac */
719                 pac_blob = data_blob_talloc(tmp_ctx, pac_data.data, pac_data.length);
720                 if (!pac_blob.data) {
721                         free(principal_string);
722                         krb5_free_principal(context, client_principal);
723                         talloc_free(tmp_ctx);
724                         return NT_STATUS_NO_MEMORY;
725                 }
726
727                 /* decode and verify the pac */
728                 nt_status = kerberos_decode_pac(gensec_krb5_state,
729                                                 pac_blob,
730                                                 gensec_krb5_state->smb_krb5_context->krb5_context,
731                                                 NULL, gensec_krb5_state->keyblock,
732                                                 client_principal,
733                                                 gensec_krb5_state->ticket->ticket.authtime, NULL);
734
735                 if (!NT_STATUS_IS_OK(nt_status)) {
736                         free(principal_string);
737                         krb5_free_principal(context, client_principal);
738                         talloc_free(tmp_ctx);
739                         return nt_status;
740                 }
741
742                 pac_blob_ptr = &pac_blob;
743         }
744
745         nt_status = gensec_generate_session_info_pac(tmp_ctx,
746                                                      gensec_security,
747                                                      gensec_krb5_state->smb_krb5_context,
748                                                      pac_blob_ptr, principal_string,
749                                                      gensec_get_remote_address(gensec_security),
750                                                      &session_info);
751
752         free(principal_string);
753         krb5_free_principal(context, client_principal);
754
755         if (!NT_STATUS_IS_OK(nt_status)) {
756                 talloc_free(tmp_ctx);
757                 return nt_status;
758         }
759
760         nt_status = gensec_krb5_session_key(gensec_security, session_info, &session_info->session_key);
761
762         if (!NT_STATUS_IS_OK(nt_status)) {
763                 talloc_free(tmp_ctx);
764                 return nt_status;
765         }
766
767         *_session_info = talloc_steal(mem_ctx, session_info);
768
769         talloc_free(tmp_ctx);
770         return NT_STATUS_OK;
771 }
772
773 static NTSTATUS gensec_krb5_wrap(struct gensec_security *gensec_security, 
774                                    TALLOC_CTX *mem_ctx, 
775                                    const DATA_BLOB *in, 
776                                    DATA_BLOB *out)
777 {
778         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
779         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
780         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
781         krb5_error_code ret;
782         krb5_data input, output;
783         input.length = in->length;
784         input.data = in->data;
785         
786         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
787                 ret = krb5_mk_priv(context, auth_context, &input, &output, NULL);
788                 if (ret) {
789                         DEBUG(1, ("krb5_mk_priv failed: %s\n", 
790                                   smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
791                                                              ret, mem_ctx)));
792                         return NT_STATUS_ACCESS_DENIED;
793                 }
794                 *out = data_blob_talloc(mem_ctx, output.data, output.length);
795                 
796                 krb5_data_free(&output);
797         } else {
798                 return NT_STATUS_ACCESS_DENIED;
799         }
800         return NT_STATUS_OK;
801 }
802
803 static NTSTATUS gensec_krb5_unwrap(struct gensec_security *gensec_security, 
804                                      TALLOC_CTX *mem_ctx, 
805                                      const DATA_BLOB *in, 
806                                      DATA_BLOB *out)
807 {
808         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
809         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
810         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
811         krb5_error_code ret;
812         krb5_data input, output;
813         krb5_replay_data replay;
814         input.length = in->length;
815         input.data = in->data;
816         
817         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
818                 ret = krb5_rd_priv(context, auth_context, &input, &output, &replay);
819                 if (ret) {
820                         DEBUG(1, ("krb5_rd_priv failed: %s\n", 
821                                   smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
822                                                              ret, mem_ctx)));
823                         return NT_STATUS_ACCESS_DENIED;
824                 }
825                 *out = data_blob_talloc(mem_ctx, output.data, output.length);
826                 
827                 krb5_data_free(&output);
828         } else {
829                 return NT_STATUS_ACCESS_DENIED;
830         }
831         return NT_STATUS_OK;
832 }
833
834 static bool gensec_krb5_have_feature(struct gensec_security *gensec_security,
835                                      uint32_t feature)
836 {
837         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
838         if (feature & GENSEC_FEATURE_SESSION_KEY) {
839                 return true;
840         } 
841         if (!gensec_krb5_state->gssapi && 
842             (feature & GENSEC_FEATURE_SEAL)) {
843                 return true;
844         } 
845         
846         return false;
847 }
848
849 static const char *gensec_krb5_oids[] = { 
850         GENSEC_OID_KERBEROS5,
851         GENSEC_OID_KERBEROS5_OLD,
852         NULL 
853 };
854
855 static const struct gensec_security_ops gensec_fake_gssapi_krb5_security_ops = {
856         .name           = "fake_gssapi_krb5",
857         .auth_type      = DCERPC_AUTH_TYPE_KRB5,
858         .oid            = gensec_krb5_oids,
859         .client_start   = gensec_fake_gssapi_krb5_client_start,
860         .server_start   = gensec_fake_gssapi_krb5_server_start,
861         .update         = gensec_krb5_update,
862         .magic          = gensec_magic_check_krb5_oid,
863         .session_key    = gensec_krb5_session_key,
864         .session_info   = gensec_krb5_session_info,
865         .have_feature   = gensec_krb5_have_feature,
866         .enabled        = false,
867         .kerberos       = true,
868         .priority       = GENSEC_KRB5
869 };
870
871 static const struct gensec_security_ops gensec_krb5_security_ops = {
872         .name           = "krb5",
873         .client_start   = gensec_krb5_client_start,
874         .server_start   = gensec_krb5_server_start,
875         .update         = gensec_krb5_update,
876         .session_key    = gensec_krb5_session_key,
877         .session_info   = gensec_krb5_session_info,
878         .have_feature   = gensec_krb5_have_feature,
879         .wrap           = gensec_krb5_wrap,
880         .unwrap         = gensec_krb5_unwrap,
881         .enabled        = true,
882         .kerberos       = true,
883         .priority       = GENSEC_KRB5
884 };
885
886 _PUBLIC_ NTSTATUS gensec_krb5_init(void)
887 {
888         NTSTATUS ret;
889
890         ret = gensec_register(&gensec_krb5_security_ops);
891         if (!NT_STATUS_IS_OK(ret)) {
892                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
893                         gensec_krb5_security_ops.name));
894                 return ret;
895         }
896
897         ret = gensec_register(&gensec_fake_gssapi_krb5_security_ops);
898         if (!NT_STATUS_IS_OK(ret)) {
899                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
900                         gensec_krb5_security_ops.name));
901                 return ret;
902         }
903
904         return ret;
905 }