s4-auth-krb: smb_rd_req_return_stuff is used only in gensec_krb5
[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 /* Taken from  accept_sec_context.c,v 1.65 */
468 static
469 krb5_error_code smb_rd_req_return_stuff(krb5_context context, 
470                                         krb5_auth_context *auth_context,
471                                         const krb5_data *inbuf,
472                                         krb5_keytab keytab, 
473                                         krb5_principal acceptor_principal,
474                                         krb5_data *outbuf, 
475                                         krb5_ticket **ticket, 
476                                         krb5_keyblock **keyblock)
477 {
478         krb5_rd_req_in_ctx in = NULL;
479         krb5_rd_req_out_ctx out = NULL;
480         krb5_error_code kret;
481
482         *keyblock = NULL;
483         *ticket = NULL;
484         outbuf->length = 0;
485         outbuf->data = NULL;
486
487         kret = krb5_rd_req_in_ctx_alloc(context, &in);
488         if (kret == 0)
489             kret = krb5_rd_req_in_set_keytab(context, in, keytab);
490         if (kret) {
491             if (in)
492                 krb5_rd_req_in_ctx_free(context, in);
493             return kret;
494         }
495
496         kret = krb5_rd_req_ctx(context,
497                                auth_context,
498                                inbuf,
499                                acceptor_principal,
500                                in, &out);
501         krb5_rd_req_in_ctx_free(context, in);
502         if (kret) {
503             return kret;
504         }
505
506         /*
507          * We need to remember some data on the context_handle.
508          */
509         kret = krb5_rd_req_out_get_ticket(context, out, 
510                                           ticket);
511         if (kret == 0) {
512             kret = krb5_rd_req_out_get_keyblock(context, out,
513                                                 keyblock);
514         }
515         krb5_rd_req_out_ctx_free(context, out);
516
517         if (kret == 0) {
518                 kret = krb5_mk_rep(context, *auth_context, outbuf);
519         }
520
521         if (kret) {
522                 krb5_free_ticket(context, *ticket);
523                 krb5_free_keyblock(context, *keyblock);
524                 krb5_data_free(outbuf);
525         }
526
527         return kret;
528 }
529 /**
530  * Next state function for the Krb5 GENSEC mechanism
531  * 
532  * @param gensec_krb5_state KRB5 State
533  * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on
534  * @param in The request, as a DATA_BLOB
535  * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx
536  * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, 
537  *                or NT_STATUS_OK if the user is authenticated. 
538  */
539
540 static NTSTATUS gensec_krb5_update(struct gensec_security *gensec_security, 
541                                    TALLOC_CTX *out_mem_ctx, 
542                                    struct tevent_context *ev,
543                                    const DATA_BLOB in, DATA_BLOB *out) 
544 {
545         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
546         krb5_error_code ret = 0;
547         NTSTATUS nt_status;
548
549         switch (gensec_krb5_state->state_position) {
550         case GENSEC_KRB5_CLIENT_START:
551         {
552                 DATA_BLOB unwrapped_out;
553                 
554                 nt_status = gensec_krb5_common_client_creds(gensec_security, ev, gensec_krb5_state->gssapi);
555                 if (!NT_STATUS_IS_OK(nt_status)) {
556                         return nt_status;
557                 }
558
559                 if (gensec_krb5_state->gssapi) {
560                         unwrapped_out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length);
561                         
562                         /* wrap that up in a nice GSS-API wrapping */
563                         *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REQ);
564                 } else {
565                         *out = data_blob_talloc(out_mem_ctx, gensec_krb5_state->enc_ticket.data, gensec_krb5_state->enc_ticket.length);
566                 }
567                 if (gensec_krb5_state->ap_req_options & AP_OPTS_MUTUAL_REQUIRED) {
568                         gensec_krb5_state->state_position = GENSEC_KRB5_CLIENT_MUTUAL_AUTH;
569                         nt_status = NT_STATUS_MORE_PROCESSING_REQUIRED;
570                 } else {
571                         gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
572                         nt_status = NT_STATUS_OK;
573                 }
574                 return nt_status;
575         }
576                 
577         case GENSEC_KRB5_CLIENT_MUTUAL_AUTH:
578         {
579                 DATA_BLOB unwrapped_in;
580                 krb5_data inbuf;
581                 krb5_ap_rep_enc_part *repl = NULL;
582                 uint8_t tok_id[2];
583
584                 if (gensec_krb5_state->gssapi) {
585                         if (!gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) {
586                                 DEBUG(1,("gensec_gssapi_parse_krb5_wrap(mutual authentication) failed to parse\n"));
587                                 dump_data_pw("Mutual authentication message:\n", in.data, in.length);
588                                 return NT_STATUS_INVALID_PARAMETER;
589                         }
590                 } else {
591                         unwrapped_in = in;
592                 }
593                 /* TODO: check the tok_id */
594
595                 inbuf.data = unwrapped_in.data;
596                 inbuf.length = unwrapped_in.length;
597                 ret = krb5_rd_rep(gensec_krb5_state->smb_krb5_context->krb5_context, 
598                                   gensec_krb5_state->auth_context,
599                                   &inbuf, &repl);
600                 if (ret) {
601                         DEBUG(1,("krb5_rd_rep (mutual authentication) failed (%s)\n",
602                                  smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, ret, out_mem_ctx)));
603                         dump_data_pw("Mutual authentication message:\n", (uint8_t *)inbuf.data, inbuf.length);
604                         nt_status = NT_STATUS_ACCESS_DENIED;
605                 } else {
606                         *out = data_blob(NULL, 0);
607                         nt_status = NT_STATUS_OK;
608                         gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
609                 }
610                 if (repl) {
611                         krb5_free_ap_rep_enc_part(gensec_krb5_state->smb_krb5_context->krb5_context, repl);
612                 }
613                 return nt_status;
614         }
615
616         case GENSEC_KRB5_SERVER_START:
617         {
618                 DATA_BLOB unwrapped_in;
619                 DATA_BLOB unwrapped_out = data_blob(NULL, 0);
620                 krb5_data inbuf, outbuf;
621                 uint8_t tok_id[2];
622                 struct keytab_container *keytab;
623                 krb5_principal server_in_keytab;
624                 const char *error_string;
625                 enum credentials_obtained obtained;
626
627                 if (!in.data) {
628                         return NT_STATUS_INVALID_PARAMETER;
629                 }       
630
631                 /* Grab the keytab, however generated */
632                 ret = cli_credentials_get_keytab(gensec_get_credentials(gensec_security), 
633                                                  gensec_security->settings->lp_ctx, &keytab);
634                 if (ret) {
635                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
636                 }
637                 
638                 /* This ensures we lookup the correct entry in that
639                  * keytab.  A NULL principal is acceptable, and means
640                  * that the krb5 libs should search the keytab at
641                  * accept time for any matching key */
642                 ret = principal_from_credentials(out_mem_ctx, gensec_get_credentials(gensec_security), 
643                                                  gensec_krb5_state->smb_krb5_context, 
644                                                  &server_in_keytab, &obtained, &error_string);
645
646                 if (ret) {
647                         DEBUG(2,("Failed to make credentials from principal: %s\n", error_string));
648                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
649                 }
650
651                 /* Parse the GSSAPI wrapping, if it's there... (win2k3 allows it to be omited) */
652                 if (gensec_krb5_state->gssapi
653                     && gensec_gssapi_parse_krb5_wrap(out_mem_ctx, &in, &unwrapped_in, tok_id)) {
654                         inbuf.data = unwrapped_in.data;
655                         inbuf.length = unwrapped_in.length;
656                 } else {
657                         inbuf.data = in.data;
658                         inbuf.length = in.length;
659                 }
660
661                 ret = smb_rd_req_return_stuff(gensec_krb5_state->smb_krb5_context->krb5_context,
662                                               &gensec_krb5_state->auth_context, 
663                                               &inbuf, keytab->keytab, server_in_keytab,  
664                                               &outbuf, 
665                                               &gensec_krb5_state->ticket, 
666                                               &gensec_krb5_state->keyblock);
667
668                 if (ret) {
669                         return NT_STATUS_LOGON_FAILURE;
670                 }
671                 unwrapped_out.data = (uint8_t *)outbuf.data;
672                 unwrapped_out.length = outbuf.length;
673                 gensec_krb5_state->state_position = GENSEC_KRB5_DONE;
674                 /* wrap that up in a nice GSS-API wrapping */
675                 if (gensec_krb5_state->gssapi) {
676                         *out = gensec_gssapi_gen_krb5_wrap(out_mem_ctx, &unwrapped_out, TOK_ID_KRB_AP_REP);
677                 } else {
678                         *out = data_blob_talloc(out_mem_ctx, outbuf.data, outbuf.length);
679                 }
680                 krb5_data_free(&outbuf);
681                 return NT_STATUS_OK;
682         }
683
684         case GENSEC_KRB5_DONE:
685         default:
686                 /* Asking too many times... */
687                 return NT_STATUS_INVALID_PARAMETER;
688         }
689 }
690
691 static NTSTATUS gensec_krb5_session_key(struct gensec_security *gensec_security, 
692                                         TALLOC_CTX *mem_ctx,
693                                         DATA_BLOB *session_key) 
694 {
695         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
696         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
697         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
698         krb5_keyblock *skey;
699         krb5_error_code err = -1;
700
701         if (gensec_krb5_state->state_position != GENSEC_KRB5_DONE) {
702                 return NT_STATUS_NO_USER_SESSION_KEY;
703         }
704
705         switch (gensec_security->gensec_role) {
706         case GENSEC_CLIENT:
707                 err = krb5_auth_con_getlocalsubkey(context, auth_context, &skey);
708                 break;
709         case GENSEC_SERVER:
710                 err = krb5_auth_con_getremotesubkey(context, auth_context, &skey);
711                 break;
712         }
713         if (err == 0 && skey != NULL) {
714                 DEBUG(10, ("Got KRB5 session key of length %d\n",  
715                            (int)KRB5_KEY_LENGTH(skey)));
716                 *session_key = data_blob_talloc(mem_ctx,
717                                                KRB5_KEY_DATA(skey), KRB5_KEY_LENGTH(skey));
718                 dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length);
719
720                 krb5_free_keyblock(context, skey);
721                 return NT_STATUS_OK;
722         } else {
723                 DEBUG(10, ("KRB5 error getting session key %d\n", err));
724                 return NT_STATUS_NO_USER_SESSION_KEY;
725         }
726 }
727
728 static NTSTATUS gensec_krb5_session_info(struct gensec_security *gensec_security,
729                                          TALLOC_CTX *mem_ctx,
730                                          struct auth_session_info **_session_info) 
731 {
732         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
733         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
734         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
735         struct auth_session_info *session_info = NULL;
736
737         krb5_principal client_principal;
738         char *principal_string;
739         
740         DATA_BLOB pac_blob, *pac_blob_ptr = NULL;
741         krb5_data pac_data;
742
743         krb5_error_code ret;
744
745         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
746         if (!tmp_ctx) {
747                 return NT_STATUS_NO_MEMORY;
748         }
749         
750         ret = krb5_ticket_get_client(context, gensec_krb5_state->ticket, &client_principal);
751         if (ret) {
752                 DEBUG(5, ("krb5_ticket_get_client failed to get cleint principal: %s\n", 
753                           smb_get_krb5_error_message(context, 
754                                                      ret, tmp_ctx)));
755                 talloc_free(tmp_ctx);
756                 return NT_STATUS_NO_MEMORY;
757         }
758         
759         ret = krb5_unparse_name(gensec_krb5_state->smb_krb5_context->krb5_context, 
760                                 client_principal, &principal_string);
761         if (ret) {
762                 DEBUG(1, ("Unable to parse client principal: %s\n",
763                           smb_get_krb5_error_message(context, 
764                                                      ret, tmp_ctx)));
765                 krb5_free_principal(context, client_principal);
766                 talloc_free(tmp_ctx);
767                 return NT_STATUS_NO_MEMORY;
768         }
769
770         ret = krb5_ticket_get_authorization_data_type(context, gensec_krb5_state->ticket, 
771                                                       KRB5_AUTHDATA_WIN2K_PAC, 
772                                                       &pac_data);
773         
774         if (ret) {
775                 /* NO pac */
776                 DEBUG(5, ("krb5_ticket_get_authorization_data_type failed to find PAC: %s\n", 
777                           smb_get_krb5_error_message(context, 
778                                                      ret, tmp_ctx)));
779         } else {
780                 /* Found pac */
781                 pac_blob = data_blob_talloc(tmp_ctx, pac_data.data, pac_data.length);
782                 if (!pac_blob.data) {
783                         free(principal_string);
784                         krb5_free_principal(context, client_principal);
785                         talloc_free(tmp_ctx);
786                         return NT_STATUS_NO_MEMORY;
787                 }
788
789                 /* decode and verify the pac */
790                 nt_status = kerberos_decode_pac(gensec_krb5_state,
791                                                 pac_blob,
792                                                 gensec_krb5_state->smb_krb5_context->krb5_context,
793                                                 NULL, gensec_krb5_state->keyblock,
794                                                 client_principal,
795                                                 gensec_krb5_state->ticket->ticket.authtime, NULL);
796
797                 if (!NT_STATUS_IS_OK(nt_status)) {
798                         free(principal_string);
799                         krb5_free_principal(context, client_principal);
800                         talloc_free(tmp_ctx);
801                         return nt_status;
802                 }
803
804                 pac_blob_ptr = &pac_blob;
805         }
806
807         nt_status = gensec_generate_session_info_pac(tmp_ctx,
808                                                      gensec_security,
809                                                      gensec_krb5_state->smb_krb5_context,
810                                                      pac_blob_ptr, principal_string,
811                                                      gensec_get_remote_address(gensec_security),
812                                                      &session_info);
813
814         free(principal_string);
815         krb5_free_principal(context, client_principal);
816
817         if (!NT_STATUS_IS_OK(nt_status)) {
818                 talloc_free(tmp_ctx);
819                 return nt_status;
820         }
821
822         nt_status = gensec_krb5_session_key(gensec_security, session_info, &session_info->session_key);
823
824         if (!NT_STATUS_IS_OK(nt_status)) {
825                 talloc_free(tmp_ctx);
826                 return nt_status;
827         }
828
829         *_session_info = talloc_steal(mem_ctx, session_info);
830
831         talloc_free(tmp_ctx);
832         return NT_STATUS_OK;
833 }
834
835 static NTSTATUS gensec_krb5_wrap(struct gensec_security *gensec_security, 
836                                    TALLOC_CTX *mem_ctx, 
837                                    const DATA_BLOB *in, 
838                                    DATA_BLOB *out)
839 {
840         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
841         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
842         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
843         krb5_error_code ret;
844         krb5_data input, output;
845         input.length = in->length;
846         input.data = in->data;
847         
848         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
849                 ret = krb5_mk_priv(context, auth_context, &input, &output, NULL);
850                 if (ret) {
851                         DEBUG(1, ("krb5_mk_priv failed: %s\n", 
852                                   smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
853                                                              ret, mem_ctx)));
854                         return NT_STATUS_ACCESS_DENIED;
855                 }
856                 *out = data_blob_talloc(mem_ctx, output.data, output.length);
857                 
858                 krb5_data_free(&output);
859         } else {
860                 return NT_STATUS_ACCESS_DENIED;
861         }
862         return NT_STATUS_OK;
863 }
864
865 static NTSTATUS gensec_krb5_unwrap(struct gensec_security *gensec_security, 
866                                      TALLOC_CTX *mem_ctx, 
867                                      const DATA_BLOB *in, 
868                                      DATA_BLOB *out)
869 {
870         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
871         krb5_context context = gensec_krb5_state->smb_krb5_context->krb5_context;
872         krb5_auth_context auth_context = gensec_krb5_state->auth_context;
873         krb5_error_code ret;
874         krb5_data input, output;
875         krb5_replay_data replay;
876         input.length = in->length;
877         input.data = in->data;
878         
879         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
880                 ret = krb5_rd_priv(context, auth_context, &input, &output, &replay);
881                 if (ret) {
882                         DEBUG(1, ("krb5_rd_priv failed: %s\n", 
883                                   smb_get_krb5_error_message(gensec_krb5_state->smb_krb5_context->krb5_context, 
884                                                              ret, mem_ctx)));
885                         return NT_STATUS_ACCESS_DENIED;
886                 }
887                 *out = data_blob_talloc(mem_ctx, output.data, output.length);
888                 
889                 krb5_data_free(&output);
890         } else {
891                 return NT_STATUS_ACCESS_DENIED;
892         }
893         return NT_STATUS_OK;
894 }
895
896 static bool gensec_krb5_have_feature(struct gensec_security *gensec_security,
897                                      uint32_t feature)
898 {
899         struct gensec_krb5_state *gensec_krb5_state = (struct gensec_krb5_state *)gensec_security->private_data;
900         if (feature & GENSEC_FEATURE_SESSION_KEY) {
901                 return true;
902         } 
903         if (!gensec_krb5_state->gssapi && 
904             (feature & GENSEC_FEATURE_SEAL)) {
905                 return true;
906         } 
907         
908         return false;
909 }
910
911 static const char *gensec_krb5_oids[] = { 
912         GENSEC_OID_KERBEROS5,
913         GENSEC_OID_KERBEROS5_OLD,
914         NULL 
915 };
916
917 static const struct gensec_security_ops gensec_fake_gssapi_krb5_security_ops = {
918         .name           = "fake_gssapi_krb5",
919         .auth_type      = DCERPC_AUTH_TYPE_KRB5,
920         .oid            = gensec_krb5_oids,
921         .client_start   = gensec_fake_gssapi_krb5_client_start,
922         .server_start   = gensec_fake_gssapi_krb5_server_start,
923         .update         = gensec_krb5_update,
924         .magic          = gensec_magic_check_krb5_oid,
925         .session_key    = gensec_krb5_session_key,
926         .session_info   = gensec_krb5_session_info,
927         .have_feature   = gensec_krb5_have_feature,
928         .enabled        = false,
929         .kerberos       = true,
930         .priority       = GENSEC_KRB5
931 };
932
933 static const struct gensec_security_ops gensec_krb5_security_ops = {
934         .name           = "krb5",
935         .client_start   = gensec_krb5_client_start,
936         .server_start   = gensec_krb5_server_start,
937         .update         = gensec_krb5_update,
938         .session_key    = gensec_krb5_session_key,
939         .session_info   = gensec_krb5_session_info,
940         .have_feature   = gensec_krb5_have_feature,
941         .wrap           = gensec_krb5_wrap,
942         .unwrap         = gensec_krb5_unwrap,
943         .enabled        = true,
944         .kerberos       = true,
945         .priority       = GENSEC_KRB5
946 };
947
948 _PUBLIC_ NTSTATUS gensec_krb5_init(void)
949 {
950         NTSTATUS ret;
951
952         ret = gensec_register(&gensec_krb5_security_ops);
953         if (!NT_STATUS_IS_OK(ret)) {
954                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
955                         gensec_krb5_security_ops.name));
956                 return ret;
957         }
958
959         ret = gensec_register(&gensec_fake_gssapi_krb5_security_ops);
960         if (!NT_STATUS_IS_OK(ret)) {
961                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
962                         gensec_krb5_security_ops.name));
963                 return ret;
964         }
965
966         return ret;
967 }