r26233: Pass loadparm context when creating krb5 contexts.
[jelmer/samba4-debian.git] / source / auth / gensec / gensec_gssapi.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Kerberos backend for GENSEC
5    
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
7    Copyright (C) Stefan Metzmacher <metze@samba.org> 2004-2005
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "lib/events/events.h"
26 #include "system/kerberos.h"
27 #include "heimdal/lib/gssapi/gssapi/gssapi.h"
28 #include "auth/kerberos/kerberos.h"
29 #include "librpc/gen_ndr/krb5pac.h"
30 #include "auth/auth.h"
31 #include "lib/ldb/include/ldb.h"
32 #include "auth/auth_sam.h"
33 #include "librpc/rpc/dcerpc.h"
34 #include "auth/credentials/credentials.h"
35 #include "auth/credentials/credentials_krb5.h"
36 #include "auth/gensec/gensec.h"
37 #include "param/param.h"
38
39 enum gensec_gssapi_sasl_state 
40 {
41         STAGE_GSS_NEG,
42         STAGE_SASL_SSF_NEG,
43         STAGE_SASL_SSF_ACCEPT,
44         STAGE_DONE
45 };
46
47 #define NEG_SEAL 0x4
48 #define NEG_SIGN 0x2
49 #define NEG_NONE 0x1
50
51 struct gensec_gssapi_state {
52         gss_ctx_id_t gssapi_context;
53         struct gss_channel_bindings_struct *input_chan_bindings;
54         gss_name_t server_name;
55         gss_name_t client_name;
56         OM_uint32 want_flags, got_flags;
57         const gss_OID_desc *gss_oid;
58
59         DATA_BLOB session_key;
60         DATA_BLOB pac;
61
62         struct smb_krb5_context *smb_krb5_context;
63         struct gssapi_creds_container *client_cred;
64         struct gssapi_creds_container *server_cred;
65
66         gss_cred_id_t delegated_cred_handle;
67
68         bool sasl; /* We have two different mechs in this file: One
69                     * for SASL wrapped GSSAPI and another for normal
70                     * GSSAPI */
71         enum gensec_gssapi_sasl_state sasl_state;
72         uint8_t sasl_protection; /* What was negotiated at the SASL
73                                   * layer, independent of the GSSAPI
74                                   * layer... */
75
76         size_t max_wrap_buf_size;
77         int gss_exchange_count;
78 };
79
80 static size_t gensec_gssapi_max_input_size(struct gensec_security *gensec_security);
81 static size_t gensec_gssapi_max_wrapped_size(struct gensec_security *gensec_security);
82
83 static char *gssapi_error_string(TALLOC_CTX *mem_ctx, 
84                                  OM_uint32 maj_stat, OM_uint32 min_stat, 
85                                  const gss_OID_desc *mech)
86 {
87         OM_uint32 disp_min_stat, disp_maj_stat;
88         gss_buffer_desc maj_error_message;
89         gss_buffer_desc min_error_message;
90         char *maj_error_string, *min_error_string;
91         OM_uint32 msg_ctx = 0;
92
93         char *ret;
94
95         maj_error_message.value = NULL;
96         min_error_message.value = NULL;
97         maj_error_message.length = 0;
98         min_error_message.length = 0;
99         
100         disp_maj_stat = gss_display_status(&disp_min_stat, maj_stat, GSS_C_GSS_CODE,
101                            mech, &msg_ctx, &maj_error_message);
102         disp_maj_stat = gss_display_status(&disp_min_stat, min_stat, GSS_C_MECH_CODE,
103                            mech, &msg_ctx, &min_error_message);
104         
105         maj_error_string = talloc_strndup(mem_ctx, (char *)maj_error_message.value, maj_error_message.length);
106
107         min_error_string = talloc_strndup(mem_ctx, (char *)min_error_message.value, min_error_message.length);
108
109         ret = talloc_asprintf(mem_ctx, "%s: %s", maj_error_string, min_error_string);
110
111         talloc_free(maj_error_string);
112         talloc_free(min_error_string);
113
114         gss_release_buffer(&disp_min_stat, &maj_error_message);
115         gss_release_buffer(&disp_min_stat, &min_error_message);
116
117         return ret;
118 }
119
120
121 static int gensec_gssapi_destructor(struct gensec_gssapi_state *gensec_gssapi_state)
122 {
123         OM_uint32 maj_stat, min_stat;
124         
125         if (gensec_gssapi_state->delegated_cred_handle != GSS_C_NO_CREDENTIAL) {
126                 maj_stat = gss_release_cred(&min_stat, 
127                                             &gensec_gssapi_state->delegated_cred_handle);
128         }
129
130         if (gensec_gssapi_state->gssapi_context != GSS_C_NO_CONTEXT) {
131                 maj_stat = gss_delete_sec_context (&min_stat,
132                                                    &gensec_gssapi_state->gssapi_context,
133                                                    GSS_C_NO_BUFFER);
134         }
135
136         if (gensec_gssapi_state->server_name != GSS_C_NO_NAME) {
137                 maj_stat = gss_release_name(&min_stat, &gensec_gssapi_state->server_name);
138         }
139         if (gensec_gssapi_state->client_name != GSS_C_NO_NAME) {
140                 maj_stat = gss_release_name(&min_stat, &gensec_gssapi_state->client_name);
141         }
142         return 0;
143 }
144
145 static NTSTATUS gensec_gssapi_start(struct gensec_security *gensec_security)
146 {
147         struct gensec_gssapi_state *gensec_gssapi_state;
148         krb5_error_code ret;
149         struct gsskrb5_send_to_kdc send_to_kdc;
150
151         gensec_gssapi_state = talloc(gensec_security, struct gensec_gssapi_state);
152         if (!gensec_gssapi_state) {
153                 return NT_STATUS_NO_MEMORY;
154         }
155         
156         gensec_gssapi_state->gss_exchange_count = 0;
157         gensec_gssapi_state->max_wrap_buf_size
158                 = lp_parm_int(global_loadparm, NULL, "gensec_gssapi", "max wrap buf size", 65536);
159                 
160         gensec_gssapi_state->sasl = false;
161         gensec_gssapi_state->sasl_state = STAGE_GSS_NEG;
162
163         gensec_security->private_data = gensec_gssapi_state;
164
165         gensec_gssapi_state->gssapi_context = GSS_C_NO_CONTEXT;
166         gensec_gssapi_state->server_name = GSS_C_NO_NAME;
167         gensec_gssapi_state->client_name = GSS_C_NO_NAME;
168
169         /* TODO: Fill in channel bindings */
170         gensec_gssapi_state->input_chan_bindings = GSS_C_NO_CHANNEL_BINDINGS;
171         
172         gensec_gssapi_state->want_flags = 0;
173         if (lp_parm_bool(global_loadparm, NULL, "gensec_gssapi", "mutual", true)) {
174                 gensec_gssapi_state->want_flags |= GSS_C_MUTUAL_FLAG;
175         }
176         if (lp_parm_bool(global_loadparm, NULL, "gensec_gssapi", "delegation", true)) {
177                 gensec_gssapi_state->want_flags |= GSS_C_DELEG_FLAG;
178         }
179         if (lp_parm_bool(global_loadparm, NULL, "gensec_gssapi", "replay", true)) {
180                 gensec_gssapi_state->want_flags |= GSS_C_REPLAY_FLAG;
181         }
182         if (lp_parm_bool(global_loadparm, NULL, "gensec_gssapi", "sequence", true)) {
183                 gensec_gssapi_state->want_flags |= GSS_C_SEQUENCE_FLAG;
184         }
185
186         gensec_gssapi_state->got_flags = 0;
187
188         gensec_gssapi_state->session_key = data_blob(NULL, 0);
189         gensec_gssapi_state->pac = data_blob(NULL, 0);
190
191         gensec_gssapi_state->delegated_cred_handle = GSS_C_NO_CREDENTIAL;
192
193         talloc_set_destructor(gensec_gssapi_state, gensec_gssapi_destructor);
194
195         if (gensec_security->want_features & GENSEC_FEATURE_SIGN) {
196                 gensec_gssapi_state->want_flags |= GSS_C_INTEG_FLAG;
197         }
198         if (gensec_security->want_features & GENSEC_FEATURE_SEAL) {
199                 gensec_gssapi_state->want_flags |= GSS_C_CONF_FLAG;
200         }
201         if (gensec_security->want_features & GENSEC_FEATURE_DCE_STYLE) {
202                 gensec_gssapi_state->want_flags |= GSS_C_DCE_STYLE;
203         }
204
205         gensec_gssapi_state->gss_oid = GSS_C_NULL_OID;
206         
207         send_to_kdc.func = smb_krb5_send_and_recv_func;
208         send_to_kdc.ptr = gensec_security->event_ctx;
209
210         ret = gsskrb5_set_send_to_kdc(&send_to_kdc);
211         if (ret) {
212                 DEBUG(1,("gensec_krb5_start: gsskrb5_set_send_to_kdc failed\n"));
213                 talloc_free(gensec_gssapi_state);
214                 return NT_STATUS_INTERNAL_ERROR;
215         }
216         if (lp_realm(global_loadparm) && *lp_realm(global_loadparm)) {
217                 char *upper_realm = strupper_talloc(gensec_gssapi_state, lp_realm(global_loadparm));
218                 if (!upper_realm) {
219                         DEBUG(1,("gensec_krb5_start: could not uppercase realm: %s\n", lp_realm(global_loadparm)));
220                         talloc_free(gensec_gssapi_state);
221                         return NT_STATUS_NO_MEMORY;
222                 }
223                 ret = gsskrb5_set_default_realm(upper_realm);
224                 talloc_free(upper_realm);
225                 if (ret) {
226                         DEBUG(1,("gensec_krb5_start: gsskrb5_set_default_realm failed\n"));
227                         talloc_free(gensec_gssapi_state);
228                         return NT_STATUS_INTERNAL_ERROR;
229                 }
230         }
231
232         /* don't do DNS lookups of any kind, it might/will fail for a netbios name */
233         ret = gsskrb5_set_dns_canonicalize(lp_parm_bool(global_loadparm, NULL, "krb5", "set_dns_canonicalize", false));
234         if (ret) {
235                 DEBUG(1,("gensec_krb5_start: gsskrb5_set_dns_canonicalize failed\n"));
236                 talloc_free(gensec_gssapi_state);
237                 return NT_STATUS_INTERNAL_ERROR;
238         }
239
240         ret = smb_krb5_init_context(gensec_gssapi_state, 
241                                     gensec_security->event_ctx,
242                                     global_loadparm,
243                                     &gensec_gssapi_state->smb_krb5_context);
244         if (ret) {
245                 DEBUG(1,("gensec_krb5_start: krb5_init_context failed (%s)\n",
246                          error_message(ret)));
247                 talloc_free(gensec_gssapi_state);
248                 return NT_STATUS_INTERNAL_ERROR;
249         }
250         return NT_STATUS_OK;
251 }
252
253 static NTSTATUS gensec_gssapi_server_start(struct gensec_security *gensec_security)
254 {
255         NTSTATUS nt_status;
256         int ret;
257         struct gensec_gssapi_state *gensec_gssapi_state;
258         struct cli_credentials *machine_account;
259         struct gssapi_creds_container *gcc;
260
261         nt_status = gensec_gssapi_start(gensec_security);
262         if (!NT_STATUS_IS_OK(nt_status)) {
263                 return nt_status;
264         }
265
266         gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
267
268         machine_account = gensec_get_credentials(gensec_security);
269         
270         if (!machine_account) {
271                 DEBUG(3, ("No machine account credentials specified\n"));
272                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
273         } else {
274                 ret = cli_credentials_get_server_gss_creds(machine_account, &gcc);
275                 if (ret) {
276                         DEBUG(1, ("Aquiring acceptor credentials failed: %s\n", 
277                                   error_message(ret)));
278                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
279                 }
280         }
281
282         gensec_gssapi_state->server_cred = gcc;
283         return NT_STATUS_OK;
284
285 }
286
287 static NTSTATUS gensec_gssapi_sasl_server_start(struct gensec_security *gensec_security)
288 {
289         NTSTATUS nt_status;
290         struct gensec_gssapi_state *gensec_gssapi_state;
291         nt_status = gensec_gssapi_server_start(gensec_security);
292
293         if (NT_STATUS_IS_OK(nt_status)) {
294                 gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
295                 gensec_gssapi_state->sasl = true;
296         }
297         return nt_status;
298 }
299
300 static NTSTATUS gensec_gssapi_client_start(struct gensec_security *gensec_security)
301 {
302         struct gensec_gssapi_state *gensec_gssapi_state;
303         struct cli_credentials *creds = gensec_get_credentials(gensec_security);
304         krb5_error_code ret;
305         NTSTATUS nt_status;
306         gss_buffer_desc name_token;
307         gss_OID name_type;
308         OM_uint32 maj_stat, min_stat;
309         const char *hostname = gensec_get_target_hostname(gensec_security);
310         const char *principal;
311         struct gssapi_creds_container *gcc;
312
313         if (!hostname) {
314                 DEBUG(1, ("Could not determine hostname for target computer, cannot use kerberos\n"));
315                 return NT_STATUS_INVALID_PARAMETER;
316         }
317         if (is_ipaddress(hostname)) {
318                 DEBUG(2, ("Cannot do GSSAPI to an IP address\n"));
319                 return NT_STATUS_INVALID_PARAMETER;
320         }
321         if (strcmp(hostname, "localhost") == 0) {
322                 DEBUG(2, ("GSSAPI to 'localhost' does not make sense\n"));
323                 return NT_STATUS_INVALID_PARAMETER;
324         }
325
326         nt_status = gensec_gssapi_start(gensec_security);
327         if (!NT_STATUS_IS_OK(nt_status)) {
328                 return nt_status;
329         }
330
331         gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
332
333         gensec_gssapi_state->gss_oid = gss_mech_krb5;
334
335         principal = gensec_get_target_principal(gensec_security);
336         if (principal && lp_client_use_spnego_principal(global_loadparm)) {
337                 name_type = GSS_C_NULL_OID;
338         } else {
339                 principal = talloc_asprintf(gensec_gssapi_state, "%s@%s", 
340                                             gensec_get_target_service(gensec_security), 
341                                             hostname);
342
343                 name_type = GSS_C_NT_HOSTBASED_SERVICE;
344         }               
345         name_token.value  = discard_const_p(uint8_t, principal);
346         name_token.length = strlen(principal);
347
348
349         maj_stat = gss_import_name (&min_stat,
350                                     &name_token,
351                                     name_type,
352                                     &gensec_gssapi_state->server_name);
353         if (maj_stat) {
354                 DEBUG(2, ("GSS Import name of %s failed: %s\n",
355                           (char *)name_token.value,
356                           gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
357                 return NT_STATUS_INVALID_PARAMETER;
358         }
359
360         ret = cli_credentials_get_client_gss_creds(creds, &gcc);
361         switch (ret) {
362         case 0:
363                 break;
364         case KRB5KDC_ERR_PREAUTH_FAILED:
365                 return NT_STATUS_LOGON_FAILURE;
366         case KRB5_KDC_UNREACH:
367                 DEBUG(3, ("Cannot reach a KDC we require to contact %s\n", principal));
368                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
369         default:
370                 DEBUG(1, ("Aquiring initiator credentials failed\n"));
371                 return NT_STATUS_UNSUCCESSFUL;
372         }
373
374         gensec_gssapi_state->client_cred = gcc;
375         if (!talloc_reference(gensec_gssapi_state, gcc)) {
376                 return NT_STATUS_NO_MEMORY;
377         }
378         
379         return NT_STATUS_OK;
380 }
381
382 static NTSTATUS gensec_gssapi_sasl_client_start(struct gensec_security *gensec_security)
383 {
384         NTSTATUS nt_status;
385         struct gensec_gssapi_state *gensec_gssapi_state;
386         nt_status = gensec_gssapi_client_start(gensec_security);
387
388         if (NT_STATUS_IS_OK(nt_status)) {
389                 gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
390                 gensec_gssapi_state->sasl = true;
391         }
392         return nt_status;
393 }
394
395
396 /**
397  * Check if the packet is one for this mechansim
398  * 
399  * @param gensec_security GENSEC state
400  * @param in The request, as a DATA_BLOB
401  * @return Error, INVALID_PARAMETER if it's not a packet for us
402  *                or NT_STATUS_OK if the packet is ok. 
403  */
404
405 static NTSTATUS gensec_gssapi_magic(struct gensec_security *gensec_security, 
406                                     const DATA_BLOB *in) 
407 {
408         if (gensec_gssapi_check_oid(in, GENSEC_OID_KERBEROS5)) {
409                 return NT_STATUS_OK;
410         } else {
411                 return NT_STATUS_INVALID_PARAMETER;
412         }
413 }
414
415
416 /**
417  * Next state function for the GSSAPI GENSEC mechanism
418  * 
419  * @param gensec_gssapi_state GSSAPI State
420  * @param out_mem_ctx The TALLOC_CTX for *out to be allocated on
421  * @param in The request, as a DATA_BLOB
422  * @param out The reply, as an talloc()ed DATA_BLOB, on *out_mem_ctx
423  * @return Error, MORE_PROCESSING_REQUIRED if a reply is sent, 
424  *                or NT_STATUS_OK if the user is authenticated. 
425  */
426
427 static NTSTATUS gensec_gssapi_update(struct gensec_security *gensec_security, 
428                                    TALLOC_CTX *out_mem_ctx, 
429                                    const DATA_BLOB in, DATA_BLOB *out) 
430 {
431         struct gensec_gssapi_state *gensec_gssapi_state
432                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
433         NTSTATUS nt_status = NT_STATUS_LOGON_FAILURE;
434         OM_uint32 maj_stat, min_stat;
435         OM_uint32 min_stat2;
436         gss_buffer_desc input_token, output_token;
437         gss_OID gss_oid_p = NULL;
438         input_token.length = in.length;
439         input_token.value = in.data;
440
441         switch (gensec_gssapi_state->sasl_state) {
442         case STAGE_GSS_NEG:
443         {
444                 switch (gensec_security->gensec_role) {
445                 case GENSEC_CLIENT:
446                 {
447                         maj_stat = gss_init_sec_context(&min_stat, 
448                                                         gensec_gssapi_state->client_cred->creds,
449                                                         &gensec_gssapi_state->gssapi_context, 
450                                                         gensec_gssapi_state->server_name, 
451                                                         discard_const_p(gss_OID_desc, gensec_gssapi_state->gss_oid),
452                                                         gensec_gssapi_state->want_flags, 
453                                                         0, 
454                                                         gensec_gssapi_state->input_chan_bindings,
455                                                         &input_token, 
456                                                         &gss_oid_p,
457                                                         &output_token, 
458                                                         &gensec_gssapi_state->got_flags, /* ret flags */
459                                                         NULL);
460                         if (gss_oid_p) {
461                                 gensec_gssapi_state->gss_oid = gss_oid_p;
462                         }
463                         break;
464                 }
465                 case GENSEC_SERVER:
466                 {
467                         maj_stat = gss_accept_sec_context(&min_stat, 
468                                                           &gensec_gssapi_state->gssapi_context, 
469                                                           gensec_gssapi_state->server_cred->creds,
470                                                           &input_token, 
471                                                           gensec_gssapi_state->input_chan_bindings,
472                                                           &gensec_gssapi_state->client_name, 
473                                                           &gss_oid_p,
474                                                           &output_token, 
475                                                           &gensec_gssapi_state->got_flags, 
476                                                           NULL, 
477                                                           &gensec_gssapi_state->delegated_cred_handle);
478                         if (gss_oid_p) {
479                                 gensec_gssapi_state->gss_oid = gss_oid_p;
480                         }
481                         break;
482                 }
483                 default:
484                         return NT_STATUS_INVALID_PARAMETER;
485                         
486                 }
487
488                 gensec_gssapi_state->gss_exchange_count++;
489
490                 if (maj_stat == GSS_S_COMPLETE) {
491                         *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length);
492                         gss_release_buffer(&min_stat2, &output_token);
493                         
494                         if (gensec_gssapi_state->got_flags & GSS_C_DELEG_FLAG) {
495                                 DEBUG(5, ("gensec_gssapi: credentials were delegated\n"));
496                         } else {
497                                 DEBUG(5, ("gensec_gssapi: NO credentials were delegated\n"));
498                         }
499
500                         /* We may have been invoked as SASL, so there
501                          * is more work to do */
502                         if (gensec_gssapi_state->sasl) {
503                                 /* Due to a very subtle interaction
504                                  * with SASL and the LDAP libs, we
505                                  * must ensure the data pointer is 
506                                  * != NULL, but the length is 0.  
507                                  *
508                                  * This ensures we send a 'zero
509                                  * length' (rather than NULL) response 
510                                  */
511                                 
512                                 if (!out->data) {
513                                         out->data = (uint8_t *)talloc_strdup(out_mem_ctx, "\0");
514                                 }
515
516                                 gensec_gssapi_state->sasl_state = STAGE_SASL_SSF_NEG;
517                                 return NT_STATUS_MORE_PROCESSING_REQUIRED;
518                         } else {
519                                 gensec_gssapi_state->sasl_state = STAGE_DONE;
520
521                                 if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
522                                         DEBUG(5, ("GSSAPI Connection will be cryptographicly sealed\n"));
523                                 } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
524                                         DEBUG(5, ("GSSAPI Connection will be cryptographicly signed\n"));
525                                 } else {
526                                         DEBUG(5, ("GSSAPI Connection will have no cryptographic protection\n"));
527                                 }
528
529                                 return NT_STATUS_OK;
530                         }
531                 } else if (maj_stat == GSS_S_CONTINUE_NEEDED) {
532                         *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length);
533                         gss_release_buffer(&min_stat2, &output_token);
534                         
535                         return NT_STATUS_MORE_PROCESSING_REQUIRED;
536                 } else if (gss_oid_equal(gensec_gssapi_state->gss_oid, gss_mech_krb5)) {
537                         switch (min_stat) {
538                         case KRB5_KDC_UNREACH:
539                                 DEBUG(3, ("Cannot reach a KDC we require: %s\n",
540                                           gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
541                                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
542                         case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN:
543                                 DEBUG(3, ("Server is not registered with our KDC: %s\n", 
544                                           gssapi_error_string(gensec_gssapi_state, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
545                                 return NT_STATUS_INVALID_PARAMETER; /* Make SPNEGO ignore us, we can't go any further here */
546                         case KRB5KRB_AP_ERR_MSG_TYPE:
547                                 /* garbage input, possibly from the auto-mech detection */
548                                 return NT_STATUS_INVALID_PARAMETER;
549                         default:
550                                 DEBUG(1, ("GSS Update(krb5)(%d) Update failed: %s\n", 
551                                           gensec_gssapi_state->gss_exchange_count,
552                                           gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
553                                 return nt_status;
554                         }
555                 } else {
556                         DEBUG(1, ("GSS Update(%d) failed: %s\n", 
557                                   gensec_gssapi_state->gss_exchange_count,
558                                   gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
559                         return nt_status;
560                 }
561                 break;
562         }
563
564         /* These last two stages are only done if we were invoked as SASL */
565         case STAGE_SASL_SSF_NEG:
566         {
567                 switch (gensec_security->gensec_role) {
568                 case GENSEC_CLIENT:
569                 {
570                         uint8_t maxlength_proposed[4]; 
571                         uint8_t maxlength_accepted[4]; 
572                         uint8_t security_supported;
573                         int conf_state;
574                         gss_qop_t qop_state;
575                         input_token.length = in.length;
576                         input_token.value = in.data;
577
578                         /* As a client, we have just send a
579                          * zero-length blob to the server (after the
580                          * normal GSSAPI exchange), and it has replied
581                          * with it's SASL negotiation */
582                         
583                         maj_stat = gss_unwrap(&min_stat, 
584                                               gensec_gssapi_state->gssapi_context, 
585                                               &input_token,
586                                               &output_token, 
587                                               &conf_state,
588                                               &qop_state);
589                         if (GSS_ERROR(maj_stat)) {
590                                 DEBUG(1, ("gensec_gssapi_update: GSS UnWrap of SASL protection negotiation failed: %s\n", 
591                                           gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
592                                 return NT_STATUS_ACCESS_DENIED;
593                         }
594                         
595                         if (output_token.length < 4) {
596                                 return NT_STATUS_INVALID_PARAMETER;
597                         }
598
599                         memcpy(maxlength_proposed, output_token.value, 4);
600                         gss_release_buffer(&min_stat, &output_token);
601
602                         /* first byte is the proposed security */
603                         security_supported = maxlength_proposed[0];
604                         maxlength_proposed[0] = '\0';
605                         
606                         /* Rest is the proposed max wrap length */
607                         gensec_gssapi_state->max_wrap_buf_size = MIN(RIVAL(maxlength_proposed, 0), 
608                                                                      gensec_gssapi_state->max_wrap_buf_size);
609                         gensec_gssapi_state->sasl_protection = 0;
610                         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
611                                 if (security_supported & NEG_SEAL) {
612                                         gensec_gssapi_state->sasl_protection |= NEG_SEAL;
613                                 }
614                         } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
615                                 if (security_supported & NEG_SIGN) {
616                                         gensec_gssapi_state->sasl_protection |= NEG_SIGN;
617                                 }
618                         } else if (security_supported & NEG_NONE) {
619                                 gensec_gssapi_state->sasl_protection |= NEG_NONE;
620                         } else {
621                                 DEBUG(1, ("Remote server does not support unprotected connections"));
622                                 return NT_STATUS_ACCESS_DENIED;
623                         }
624
625                         /* Send back the negotiated max length */
626
627                         RSIVAL(maxlength_accepted, 0, gensec_gssapi_state->max_wrap_buf_size);
628
629                         maxlength_accepted[0] = gensec_gssapi_state->sasl_protection;
630                         
631                         input_token.value = maxlength_accepted;
632                         input_token.length = sizeof(maxlength_accepted);
633
634                         maj_stat = gss_wrap(&min_stat, 
635                                             gensec_gssapi_state->gssapi_context, 
636                                             false,
637                                             GSS_C_QOP_DEFAULT,
638                                             &input_token,
639                                             &conf_state,
640                                             &output_token);
641                         if (GSS_ERROR(maj_stat)) {
642                                 DEBUG(1, ("GSS Update(SSF_NEG): GSS Wrap failed: %s\n", 
643                                           gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
644                                 return NT_STATUS_ACCESS_DENIED;
645                         }
646                         
647                         *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length);
648                         gss_release_buffer(&min_stat, &output_token);
649
650                         /* quirk:  This changes the value that gensec_have_feature returns, to be that after SASL negotiation */
651                         gensec_gssapi_state->sasl_state = STAGE_DONE;
652
653                         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
654                                 DEBUG(3, ("SASL/GSSAPI Connection to server will be cryptographicly sealed\n"));
655                         } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
656                                 DEBUG(3, ("SASL/GSSAPI Connection to server will be cryptographicly signed\n"));
657                         } else {
658                                 DEBUG(3, ("SASL/GSSAPI Connection to server will have no cryptographicly protection\n"));
659                         }
660
661                         return NT_STATUS_OK;
662                 }
663                 case GENSEC_SERVER:
664                 {
665                         uint8_t maxlength_proposed[4]; 
666                         uint8_t security_supported = 0x0;
667                         int conf_state;
668
669                         /* As a server, we have just been sent a zero-length blob (note this, but it isn't fatal) */
670                         if (in.length != 0) {
671                                 DEBUG(1, ("SASL/GSSAPI: client sent non-zero length starting SASL negotiation!\n"));
672                         }
673                         
674                         /* Give the client some idea what we will support */
675                           
676                         RSIVAL(maxlength_proposed, 0, gensec_gssapi_state->max_wrap_buf_size);
677                         /* first byte is the proposed security */
678                         maxlength_proposed[0] = '\0';
679                         
680                         gensec_gssapi_state->sasl_protection = 0;
681                         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
682                                 security_supported |= NEG_SEAL;
683                         } 
684                         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
685                                 security_supported |= NEG_SIGN;
686                         }
687                         if (security_supported == 0) {
688                                 /* If we don't support anything, this must be 0 */
689                                 RSIVAL(maxlength_proposed, 0, 0x0);
690                         }
691
692                         /* TODO:  We may not wish to support this */
693                         security_supported |= NEG_NONE;
694                         maxlength_proposed[0] = security_supported;
695                         
696                         input_token.value = maxlength_proposed;
697                         input_token.length = sizeof(maxlength_proposed);
698
699                         maj_stat = gss_wrap(&min_stat, 
700                                             gensec_gssapi_state->gssapi_context, 
701                                             false,
702                                             GSS_C_QOP_DEFAULT,
703                                             &input_token,
704                                             &conf_state,
705                                             &output_token);
706                         if (GSS_ERROR(maj_stat)) {
707                                 DEBUG(1, ("GSS Update(SSF_NEG): GSS Wrap failed: %s\n", 
708                                           gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
709                                 return NT_STATUS_ACCESS_DENIED;
710                         }
711                         
712                         *out = data_blob_talloc(out_mem_ctx, output_token.value, output_token.length);
713                         gss_release_buffer(&min_stat, &output_token);
714
715                         gensec_gssapi_state->sasl_state = STAGE_SASL_SSF_ACCEPT;
716                         return NT_STATUS_MORE_PROCESSING_REQUIRED;
717                 }
718                 default:
719                         return NT_STATUS_INVALID_PARAMETER;
720                         
721                 }
722         }
723         /* This is s server-only stage */
724         case STAGE_SASL_SSF_ACCEPT:
725         {
726                 uint8_t maxlength_accepted[4]; 
727                 uint8_t security_accepted;
728                 int conf_state;
729                 gss_qop_t qop_state;
730                 input_token.length = in.length;
731                 input_token.value = in.data;
732                         
733                 maj_stat = gss_unwrap(&min_stat, 
734                                       gensec_gssapi_state->gssapi_context, 
735                                       &input_token,
736                                       &output_token, 
737                                       &conf_state,
738                                       &qop_state);
739                 if (GSS_ERROR(maj_stat)) {
740                         DEBUG(1, ("gensec_gssapi_update: GSS UnWrap of SASL protection negotiation failed: %s\n", 
741                                   gssapi_error_string(out_mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
742                         return NT_STATUS_ACCESS_DENIED;
743                 }
744                         
745                 if (output_token.length < 4) {
746                         return NT_STATUS_INVALID_PARAMETER;
747                 }
748
749                 memcpy(maxlength_accepted, output_token.value, 4);
750                 gss_release_buffer(&min_stat, &output_token);
751                 
752                 /* first byte is the proposed security */
753                 security_accepted = maxlength_accepted[0];
754                 maxlength_accepted[0] = '\0';
755                 
756                 /* Rest is the proposed max wrap length */
757                 gensec_gssapi_state->max_wrap_buf_size = MIN(RIVAL(maxlength_accepted, 0), 
758                                                              gensec_gssapi_state->max_wrap_buf_size);
759
760                 gensec_gssapi_state->sasl_protection = 0;
761                 if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
762                         if (security_accepted & NEG_SEAL) {
763                                 gensec_gssapi_state->sasl_protection |= NEG_SEAL;
764                         }
765                 } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
766                         if (security_accepted & NEG_SIGN) {
767                                 gensec_gssapi_state->sasl_protection |= NEG_SIGN;
768                         }
769                 } else if (security_accepted & NEG_NONE) {
770                         gensec_gssapi_state->sasl_protection |= NEG_NONE;
771                 } else {
772                         DEBUG(1, ("Remote client does not support unprotected connections, but we failed to negotiate anything better"));
773                         return NT_STATUS_ACCESS_DENIED;
774                 }
775
776                 /* quirk:  This changes the value that gensec_have_feature returns, to be that after SASL negotiation */
777                 gensec_gssapi_state->sasl_state = STAGE_DONE;
778                 if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)) {
779                         DEBUG(5, ("SASL/GSSAPI Connection from client will be cryptographicly sealed\n"));
780                 } else if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SIGN)) {
781                         DEBUG(5, ("SASL/GSSAPI Connection from client will be cryptographicly signed\n"));
782                 } else {
783                         DEBUG(5, ("SASL/GSSAPI Connection from client will have no cryptographic protection\n"));
784                 }
785
786                 *out = data_blob(NULL, 0);
787                 return NT_STATUS_OK;    
788         }
789         default:
790                 return NT_STATUS_INVALID_PARAMETER;
791         }
792 }
793
794 static NTSTATUS gensec_gssapi_wrap(struct gensec_security *gensec_security, 
795                                    TALLOC_CTX *mem_ctx, 
796                                    const DATA_BLOB *in, 
797                                    DATA_BLOB *out)
798 {
799         struct gensec_gssapi_state *gensec_gssapi_state
800                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
801         OM_uint32 maj_stat, min_stat;
802         gss_buffer_desc input_token, output_token;
803         int conf_state;
804         input_token.length = in->length;
805         input_token.value = in->data;
806
807         maj_stat = gss_wrap(&min_stat, 
808                             gensec_gssapi_state->gssapi_context, 
809                             gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL),
810                             GSS_C_QOP_DEFAULT,
811                             &input_token,
812                             &conf_state,
813                             &output_token);
814         if (GSS_ERROR(maj_stat)) {
815                 DEBUG(1, ("gensec_gssapi_wrap: GSS Wrap failed: %s\n", 
816                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
817                 return NT_STATUS_ACCESS_DENIED;
818         }
819
820         *out = data_blob_talloc(mem_ctx, output_token.value, output_token.length);
821         gss_release_buffer(&min_stat, &output_token);
822
823         if (gensec_gssapi_state->sasl) {
824                 size_t max_wrapped_size = gensec_gssapi_max_wrapped_size(gensec_security);
825                 if (max_wrapped_size < out->length) {
826                         DEBUG(1, ("gensec_gssapi_wrap: when wrapped, INPUT data (%u) is grew to be larger than SASL negotiated maximum output size (%u > %u)\n",
827                                   (unsigned)in->length, 
828                                   (unsigned)out->length, 
829                                   (unsigned int)max_wrapped_size));
830                         return NT_STATUS_INVALID_PARAMETER;
831                 }
832         }
833         
834         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)
835             && !conf_state) {
836                 return NT_STATUS_ACCESS_DENIED;
837         }
838         return NT_STATUS_OK;
839 }
840
841 static NTSTATUS gensec_gssapi_unwrap(struct gensec_security *gensec_security, 
842                                      TALLOC_CTX *mem_ctx, 
843                                      const DATA_BLOB *in, 
844                                      DATA_BLOB *out)
845 {
846         struct gensec_gssapi_state *gensec_gssapi_state
847                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
848         OM_uint32 maj_stat, min_stat;
849         gss_buffer_desc input_token, output_token;
850         int conf_state;
851         gss_qop_t qop_state;
852         input_token.length = in->length;
853         input_token.value = in->data;
854         
855         if (gensec_gssapi_state->sasl) {
856                 size_t max_wrapped_size = gensec_gssapi_max_wrapped_size(gensec_security);
857                 if (max_wrapped_size < in->length) {
858                         DEBUG(1, ("gensec_gssapi_unwrap: WRAPPED data is larger than SASL negotiated maximum size\n"));
859                         return NT_STATUS_INVALID_PARAMETER;
860                 }
861         }
862         
863         maj_stat = gss_unwrap(&min_stat, 
864                               gensec_gssapi_state->gssapi_context, 
865                               &input_token,
866                               &output_token, 
867                               &conf_state,
868                               &qop_state);
869         if (GSS_ERROR(maj_stat)) {
870                 DEBUG(1, ("gensec_gssapi_unwrap: GSS UnWrap failed: %s\n", 
871                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
872                 return NT_STATUS_ACCESS_DENIED;
873         }
874
875         *out = data_blob_talloc(mem_ctx, output_token.value, output_token.length);
876         gss_release_buffer(&min_stat, &output_token);
877         
878         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)
879             && !conf_state) {
880                 return NT_STATUS_ACCESS_DENIED;
881         }
882         return NT_STATUS_OK;
883 }
884
885 /* Find out the maximum input size negotiated on this connection */
886
887 static size_t gensec_gssapi_max_input_size(struct gensec_security *gensec_security) 
888 {
889         struct gensec_gssapi_state *gensec_gssapi_state
890                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
891         OM_uint32 maj_stat, min_stat;
892         OM_uint32 max_input_size;
893
894         maj_stat = gss_wrap_size_limit(&min_stat, 
895                                        gensec_gssapi_state->gssapi_context,
896                                        gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL),
897                                        GSS_C_QOP_DEFAULT,
898                                        gensec_gssapi_state->max_wrap_buf_size,
899                                        &max_input_size);
900         if (GSS_ERROR(maj_stat)) {
901                 TALLOC_CTX *mem_ctx = talloc_new(NULL); 
902                 DEBUG(1, ("gensec_gssapi_max_input_size: determinaing signature size with gss_wrap_size_limit failed: %s\n", 
903                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
904                 talloc_free(mem_ctx);
905                 return 0;
906         }
907
908         return max_input_size;
909 }
910
911 /* Find out the maximum output size negotiated on this connection */
912 static size_t gensec_gssapi_max_wrapped_size(struct gensec_security *gensec_security) 
913 {
914         struct gensec_gssapi_state *gensec_gssapi_state = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);;
915         return gensec_gssapi_state->max_wrap_buf_size;
916 }
917
918 static NTSTATUS gensec_gssapi_seal_packet(struct gensec_security *gensec_security, 
919                                           TALLOC_CTX *mem_ctx, 
920                                           uint8_t *data, size_t length, 
921                                           const uint8_t *whole_pdu, size_t pdu_length, 
922                                           DATA_BLOB *sig)
923 {
924         struct gensec_gssapi_state *gensec_gssapi_state
925                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
926         OM_uint32 maj_stat, min_stat;
927         gss_buffer_desc input_token, output_token;
928         int conf_state;
929         ssize_t sig_length;
930
931         input_token.length = length;
932         input_token.value = data;
933         
934         maj_stat = gss_wrap(&min_stat, 
935                             gensec_gssapi_state->gssapi_context,
936                             gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL),
937                             GSS_C_QOP_DEFAULT,
938                             &input_token,
939                             &conf_state,
940                             &output_token);
941         if (GSS_ERROR(maj_stat)) {
942                 DEBUG(1, ("gensec_gssapi_seal_packet: GSS Wrap failed: %s\n", 
943                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
944                 return NT_STATUS_ACCESS_DENIED;
945         }
946
947         if (output_token.length < input_token.length) {
948                 DEBUG(1, ("gensec_gssapi_seal_packet: GSS Wrap length [%ld] *less* than caller length [%ld]\n", 
949                           (long)output_token.length, (long)length));
950                 return NT_STATUS_INTERNAL_ERROR;
951         }
952         sig_length = output_token.length - input_token.length;
953
954         memcpy(data, ((uint8_t *)output_token.value) + sig_length, length);
955         *sig = data_blob_talloc(mem_ctx, (uint8_t *)output_token.value, sig_length);
956
957         dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length);
958         dump_data_pw("gensec_gssapi_seal_packet: clear\n", data, length);
959         dump_data_pw("gensec_gssapi_seal_packet: sealed\n", ((uint8_t *)output_token.value) + sig_length, output_token.length - sig_length);
960
961         gss_release_buffer(&min_stat, &output_token);
962
963         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)
964             && !conf_state) {
965                 return NT_STATUS_ACCESS_DENIED;
966         }
967         return NT_STATUS_OK;
968 }
969
970 static NTSTATUS gensec_gssapi_unseal_packet(struct gensec_security *gensec_security, 
971                                             TALLOC_CTX *mem_ctx, 
972                                             uint8_t *data, size_t length, 
973                                             const uint8_t *whole_pdu, size_t pdu_length,
974                                             const DATA_BLOB *sig)
975 {
976         struct gensec_gssapi_state *gensec_gssapi_state
977                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
978         OM_uint32 maj_stat, min_stat;
979         gss_buffer_desc input_token, output_token;
980         int conf_state;
981         gss_qop_t qop_state;
982         DATA_BLOB in;
983
984         dump_data_pw("gensec_gssapi_unseal_packet: sig\n", sig->data, sig->length);
985
986         in = data_blob_talloc(mem_ctx, NULL, sig->length + length);
987
988         memcpy(in.data, sig->data, sig->length);
989         memcpy(in.data + sig->length, data, length);
990
991         input_token.length = in.length;
992         input_token.value = in.data;
993         
994         maj_stat = gss_unwrap(&min_stat, 
995                               gensec_gssapi_state->gssapi_context, 
996                               &input_token,
997                               &output_token, 
998                               &conf_state,
999                               &qop_state);
1000         if (GSS_ERROR(maj_stat)) {
1001                 DEBUG(1, ("gensec_gssapi_unseal_packet: GSS UnWrap failed: %s\n", 
1002                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1003                 return NT_STATUS_ACCESS_DENIED;
1004         }
1005
1006         if (output_token.length != length) {
1007                 return NT_STATUS_INTERNAL_ERROR;
1008         }
1009
1010         memcpy(data, output_token.value, length);
1011
1012         gss_release_buffer(&min_stat, &output_token);
1013         
1014         if (gensec_have_feature(gensec_security, GENSEC_FEATURE_SEAL)
1015             && !conf_state) {
1016                 return NT_STATUS_ACCESS_DENIED;
1017         }
1018         return NT_STATUS_OK;
1019 }
1020
1021 static NTSTATUS gensec_gssapi_sign_packet(struct gensec_security *gensec_security, 
1022                                           TALLOC_CTX *mem_ctx, 
1023                                           const uint8_t *data, size_t length, 
1024                                           const uint8_t *whole_pdu, size_t pdu_length, 
1025                                           DATA_BLOB *sig)
1026 {
1027         struct gensec_gssapi_state *gensec_gssapi_state
1028                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
1029         OM_uint32 maj_stat, min_stat;
1030         gss_buffer_desc input_token, output_token;
1031         int conf_state;
1032         ssize_t sig_length = 0;
1033
1034         input_token.length = length;
1035         input_token.value = discard_const_p(uint8_t *, data);
1036
1037         maj_stat = gss_wrap(&min_stat, 
1038                             gensec_gssapi_state->gssapi_context,
1039                             0,
1040                             GSS_C_QOP_DEFAULT,
1041                             &input_token,
1042                             &conf_state,
1043                             &output_token);
1044         if (GSS_ERROR(maj_stat)) {
1045                 DEBUG(1, ("GSS Wrap failed: %s\n", 
1046                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1047                 return NT_STATUS_ACCESS_DENIED;
1048         }
1049
1050         if (output_token.length < input_token.length) {
1051                 DEBUG(1, ("gensec_gssapi_sign_packet: GSS Wrap length [%ld] *less* than caller length [%ld]\n", 
1052                           (long)output_token.length, (long)length));
1053                 return NT_STATUS_INTERNAL_ERROR;
1054         }
1055
1056         /* Caller must pad to right boundary */
1057         sig_length = output_token.length - input_token.length;
1058
1059         *sig = data_blob_talloc(mem_ctx, (uint8_t *)output_token.value, sig_length);
1060
1061         dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length);
1062
1063         gss_release_buffer(&min_stat, &output_token);
1064
1065         return NT_STATUS_OK;
1066 }
1067
1068 static NTSTATUS gensec_gssapi_check_packet(struct gensec_security *gensec_security, 
1069                                            TALLOC_CTX *mem_ctx, 
1070                                            const uint8_t *data, size_t length, 
1071                                            const uint8_t *whole_pdu, size_t pdu_length, 
1072                                            const DATA_BLOB *sig)
1073 {
1074         struct gensec_gssapi_state *gensec_gssapi_state
1075                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
1076         OM_uint32 maj_stat, min_stat;
1077         gss_buffer_desc input_token, output_token;
1078         int conf_state;
1079         gss_qop_t qop_state;
1080         DATA_BLOB in;
1081
1082         dump_data_pw("gensec_gssapi_seal_packet: sig\n", sig->data, sig->length);
1083
1084         in = data_blob_talloc(mem_ctx, NULL, sig->length + length);
1085
1086         memcpy(in.data, sig->data, sig->length);
1087         memcpy(in.data + sig->length, data, length);
1088
1089         input_token.length = in.length;
1090         input_token.value = in.data;
1091         
1092         maj_stat = gss_unwrap(&min_stat, 
1093                               gensec_gssapi_state->gssapi_context, 
1094                               &input_token,
1095                               &output_token, 
1096                               &conf_state,
1097                               &qop_state);
1098         if (GSS_ERROR(maj_stat)) {
1099                 DEBUG(1, ("GSS UnWrap failed: %s\n", 
1100                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1101                 return NT_STATUS_ACCESS_DENIED;
1102         }
1103
1104         if (output_token.length != length) {
1105                 return NT_STATUS_INTERNAL_ERROR;
1106         }
1107
1108         gss_release_buffer(&min_stat, &output_token);
1109
1110         return NT_STATUS_OK;
1111 }
1112
1113 /* Try to figure out what features we actually got on the connection */
1114 static bool gensec_gssapi_have_feature(struct gensec_security *gensec_security, 
1115                                        uint32_t feature) 
1116 {
1117         struct gensec_gssapi_state *gensec_gssapi_state
1118                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
1119         if (feature & GENSEC_FEATURE_SIGN) {
1120                 /* If we are going GSSAPI SASL, then we honour the second negotiation */
1121                 if (gensec_gssapi_state->sasl 
1122                     && gensec_gssapi_state->sasl_state == STAGE_DONE) {
1123                         return ((gensec_gssapi_state->sasl_protection & NEG_SIGN) 
1124                                 && (gensec_gssapi_state->got_flags & GSS_C_INTEG_FLAG));
1125                 }
1126                 return gensec_gssapi_state->got_flags & GSS_C_INTEG_FLAG;
1127         }
1128         if (feature & GENSEC_FEATURE_SEAL) {
1129                 /* If we are going GSSAPI SASL, then we honour the second negotiation */
1130                 if (gensec_gssapi_state->sasl 
1131                     && gensec_gssapi_state->sasl_state == STAGE_DONE) {
1132                         return ((gensec_gssapi_state->sasl_protection & NEG_SEAL) 
1133                                  && (gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG));
1134                 }
1135                 return gensec_gssapi_state->got_flags & GSS_C_CONF_FLAG;
1136         }
1137         if (feature & GENSEC_FEATURE_SESSION_KEY) {
1138                 /* Only for GSSAPI/Krb5 */
1139                 if (gss_oid_equal(gensec_gssapi_state->gss_oid, gss_mech_krb5)) {
1140                         return true;
1141                 }
1142         }
1143         if (feature & GENSEC_FEATURE_DCE_STYLE) {
1144                 return gensec_gssapi_state->got_flags & GSS_C_DCE_STYLE;
1145         }
1146         /* We can always do async (rather than strict request/reply) packets.  */
1147         if (feature & GENSEC_FEATURE_ASYNC_REPLIES) {
1148                 return true;
1149         }
1150         return false;
1151 }
1152
1153 /*
1154  * Extract the 'sesssion key' needed by SMB signing and ncacn_np 
1155  * (for encrypting some passwords).
1156  * 
1157  * This breaks all the abstractions, but what do you expect...
1158  */
1159 static NTSTATUS gensec_gssapi_session_key(struct gensec_security *gensec_security, 
1160                                           DATA_BLOB *session_key) 
1161 {
1162         struct gensec_gssapi_state *gensec_gssapi_state
1163                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
1164         OM_uint32 maj_stat, min_stat;
1165         krb5_keyblock *subkey;
1166
1167         if (gensec_gssapi_state->session_key.data) {
1168                 *session_key = gensec_gssapi_state->session_key;
1169                 return NT_STATUS_OK;
1170         }
1171
1172         maj_stat = gsskrb5_get_initiator_subkey(&min_stat, 
1173                                                 gensec_gssapi_state->gssapi_context,
1174                                                 &subkey);
1175         if (maj_stat != 0) {
1176                 DEBUG(1, ("NO session key for this mech\n"));
1177                 return NT_STATUS_NO_USER_SESSION_KEY;
1178         }
1179         
1180         DEBUG(10, ("Got KRB5 session key of length %d\n",  
1181                    (int)KRB5_KEY_LENGTH(subkey)));
1182         gensec_gssapi_state->session_key = data_blob_talloc(gensec_gssapi_state, 
1183                                                             KRB5_KEY_DATA(subkey), KRB5_KEY_LENGTH(subkey));
1184         krb5_free_keyblock(gensec_gssapi_state->smb_krb5_context->krb5_context, subkey);
1185         *session_key = gensec_gssapi_state->session_key;
1186         dump_data_pw("KRB5 Session Key:\n", session_key->data, session_key->length);
1187
1188         return NT_STATUS_OK;
1189 }
1190
1191 /* Get some basic (and authorization) information about the user on
1192  * this session.  This uses either the PAC (if present) or a local
1193  * database lookup */
1194 static NTSTATUS gensec_gssapi_session_info(struct gensec_security *gensec_security,
1195                                            struct auth_session_info **_session_info) 
1196 {
1197         NTSTATUS nt_status;
1198         TALLOC_CTX *mem_ctx;
1199         struct gensec_gssapi_state *gensec_gssapi_state
1200                 = talloc_get_type(gensec_security->private_data, struct gensec_gssapi_state);
1201         struct auth_serversupplied_info *server_info = NULL;
1202         struct auth_session_info *session_info = NULL;
1203         struct PAC_LOGON_INFO *logon_info;
1204         OM_uint32 maj_stat, min_stat;
1205         gss_buffer_desc name_token;
1206         gss_buffer_desc pac;
1207         krb5_keyblock *keyblock;
1208         time_t authtime;
1209         krb5_principal principal;
1210         char *principal_string;
1211         DATA_BLOB pac_blob;
1212         
1213         if ((gensec_gssapi_state->gss_oid->length != gss_mech_krb5->length)
1214             || (memcmp(gensec_gssapi_state->gss_oid->elements, gss_mech_krb5->elements, 
1215                        gensec_gssapi_state->gss_oid->length) != 0)) {
1216                 DEBUG(1, ("NO session info available for this mech\n"));
1217                 return NT_STATUS_INVALID_PARAMETER;
1218         }
1219                 
1220         mem_ctx = talloc_named(gensec_gssapi_state, 0, "gensec_gssapi_session_info context"); 
1221         NT_STATUS_HAVE_NO_MEMORY(mem_ctx);
1222
1223         maj_stat = gss_display_name (&min_stat,
1224                                      gensec_gssapi_state->client_name,
1225                                      &name_token,
1226                                      NULL);
1227         if (GSS_ERROR(maj_stat)) {
1228                 DEBUG(1, ("GSS display_name failed: %s\n", 
1229                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1230                 talloc_free(mem_ctx);
1231                 return NT_STATUS_FOOBAR;
1232         }
1233
1234         principal_string = talloc_strndup(mem_ctx, 
1235                                           (const char *)name_token.value, 
1236                                           name_token.length);
1237
1238         gss_release_buffer(&min_stat, &name_token);
1239
1240         if (!principal_string) {
1241                 talloc_free(mem_ctx);
1242                 return NT_STATUS_NO_MEMORY;
1243         }
1244
1245         maj_stat = gsskrb5_extract_authz_data_from_sec_context(&min_stat, 
1246                                                                gensec_gssapi_state->gssapi_context, 
1247                                                                KRB5_AUTHDATA_WIN2K_PAC,
1248                                                                &pac);
1249         
1250         
1251         if (maj_stat == 0) {
1252                 pac_blob = data_blob_talloc(mem_ctx, pac.value, pac.length);
1253                 gss_release_buffer(&min_stat, &pac);
1254
1255         } else {
1256                 pac_blob = data_blob(NULL, 0);
1257         }
1258         
1259         /* IF we have the PAC - otherwise we need to get this
1260          * data from elsewere - local ldb, or (TODO) lookup of some
1261          * kind... 
1262          */
1263         if (pac_blob.length) {
1264                 krb5_error_code ret;
1265                 union netr_Validation validation;
1266
1267                 maj_stat = gsskrb5_extract_authtime_from_sec_context(&min_stat,
1268                                                                      gensec_gssapi_state->gssapi_context, 
1269                                                                      &authtime);
1270                 
1271                 if (GSS_ERROR(maj_stat)) {
1272                         DEBUG(1, ("gsskrb5_extract_authtime_from_sec_context: %s\n", 
1273                                   gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1274                         talloc_free(mem_ctx);
1275                         return NT_STATUS_FOOBAR;
1276                 }
1277
1278                 maj_stat = gsskrb5_extract_service_keyblock(&min_stat, 
1279                                                             gensec_gssapi_state->gssapi_context, 
1280                                                             &keyblock);
1281                 
1282                 if (GSS_ERROR(maj_stat)) {
1283                         DEBUG(1, ("gsskrb5_copy_service_keyblock failed: %s\n", 
1284                                   gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1285                         talloc_free(mem_ctx);
1286                         return NT_STATUS_FOOBAR;
1287                 } 
1288
1289                 ret = krb5_parse_name_flags(gensec_gssapi_state->smb_krb5_context->krb5_context,
1290                                             principal_string, 
1291                                             KRB5_PRINCIPAL_PARSE_MUST_REALM,
1292                                             &principal);
1293                 if (ret) {
1294                         krb5_free_keyblock(gensec_gssapi_state->smb_krb5_context->krb5_context,
1295                                            keyblock);
1296                         talloc_free(mem_ctx);
1297                         return NT_STATUS_INVALID_PARAMETER;
1298                 }
1299                 
1300                 /* decode and verify the pac */
1301                 nt_status = kerberos_pac_logon_info(mem_ctx, &logon_info, pac_blob,
1302                                                     gensec_gssapi_state->smb_krb5_context->krb5_context,
1303                                                     NULL, keyblock, principal, authtime, NULL);
1304                 krb5_free_principal(gensec_gssapi_state->smb_krb5_context->krb5_context, principal);
1305                 krb5_free_keyblock(gensec_gssapi_state->smb_krb5_context->krb5_context,
1306                                    keyblock);
1307
1308                 if (!NT_STATUS_IS_OK(nt_status)) {
1309                         talloc_free(mem_ctx);
1310                         return nt_status;
1311                 }
1312                 validation.sam3 = &logon_info->info3;
1313                 nt_status = make_server_info_netlogon_validation(gensec_gssapi_state, 
1314                                                                  NULL,
1315                                                                  3, &validation,
1316                                                                  &server_info); 
1317                 if (!NT_STATUS_IS_OK(nt_status)) {
1318                         talloc_free(mem_ctx);
1319                         return nt_status;
1320                 }
1321         } else if (!lp_parm_bool(global_loadparm, NULL, "gensec", "require_pac", false)) {
1322                 DEBUG(1, ("Unable to find PAC, resorting to local user lookup: %s\n",
1323                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1324                 nt_status = sam_get_server_info_principal(mem_ctx, principal_string,
1325                                                           &server_info);
1326
1327                 if (!NT_STATUS_IS_OK(nt_status)) {
1328                         talloc_free(mem_ctx);
1329                         return nt_status;
1330                 }
1331         } else {
1332                 DEBUG(1, ("Unable to find PAC in ticket from %s, failing to allow access: %s\n",
1333                           principal_string,
1334                           gssapi_error_string(mem_ctx, maj_stat, min_stat, gensec_gssapi_state->gss_oid)));
1335                 return NT_STATUS_ACCESS_DENIED;
1336         }
1337
1338         /* references the server_info into the session_info */
1339         nt_status = auth_generate_session_info(mem_ctx, server_info, &session_info);
1340         if (!NT_STATUS_IS_OK(nt_status)) {
1341                 talloc_free(mem_ctx);
1342                 return nt_status;
1343         }
1344
1345         nt_status = gensec_gssapi_session_key(gensec_security, &session_info->session_key);
1346         if (!NT_STATUS_IS_OK(nt_status)) {
1347                 talloc_free(mem_ctx);
1348                 return nt_status;
1349         }
1350
1351         if (!(gensec_gssapi_state->got_flags & GSS_C_DELEG_FLAG)) {
1352                 DEBUG(10, ("gensec_gssapi: NO delegated credentials supplied by client\n"));
1353         } else {
1354                 krb5_error_code ret;
1355                 DEBUG(10, ("gensec_gssapi: delegated credentials supplied by client\n"));
1356                 session_info->credentials = cli_credentials_init(session_info);
1357                 if (!session_info->credentials) {
1358                         talloc_free(mem_ctx);
1359                         return NT_STATUS_NO_MEMORY;
1360                 }
1361
1362                 cli_credentials_set_event_context(session_info->credentials, gensec_security->event_ctx);
1363                 cli_credentials_set_conf(session_info->credentials, global_loadparm);
1364                 /* Just so we don't segfault trying to get at a username */
1365                 cli_credentials_set_anonymous(session_info->credentials);
1366                 
1367                 ret = cli_credentials_set_client_gss_creds(session_info->credentials, 
1368                                                            gensec_gssapi_state->delegated_cred_handle,
1369                                                            CRED_SPECIFIED);
1370                 if (ret) {
1371                         talloc_free(mem_ctx);
1372                         return NT_STATUS_NO_MEMORY;
1373                 }
1374                 
1375                 /* This credential handle isn't useful for password authentication, so ensure nobody tries to do that */
1376                 cli_credentials_set_kerberos_state(session_info->credentials, CRED_MUST_USE_KERBEROS);
1377
1378                 /* It has been taken from this place... */
1379                 gensec_gssapi_state->delegated_cred_handle = GSS_C_NO_CREDENTIAL;
1380         }
1381         talloc_steal(gensec_gssapi_state, session_info);
1382         talloc_free(mem_ctx);
1383         *_session_info = session_info;
1384
1385         return NT_STATUS_OK;
1386 }
1387
1388 static const char *gensec_gssapi_krb5_oids[] = { 
1389         GENSEC_OID_KERBEROS5_OLD,
1390         GENSEC_OID_KERBEROS5,
1391         NULL 
1392 };
1393
1394 static const char *gensec_gssapi_spnego_oids[] = { 
1395         GENSEC_OID_SPNEGO,
1396         NULL 
1397 };
1398
1399 /* As a server, this could in theory accept any GSSAPI mech */
1400 static const struct gensec_security_ops gensec_gssapi_spnego_security_ops = {
1401         .name           = "gssapi_spnego",
1402         .sasl_name      = "GSS-SPNEGO",
1403         .auth_type      = DCERPC_AUTH_TYPE_SPNEGO,
1404         .oid            = gensec_gssapi_spnego_oids,
1405         .client_start   = gensec_gssapi_client_start,
1406         .server_start   = gensec_gssapi_server_start,
1407         .magic          = gensec_gssapi_magic,
1408         .update         = gensec_gssapi_update,
1409         .session_key    = gensec_gssapi_session_key,
1410         .session_info   = gensec_gssapi_session_info,
1411         .sign_packet    = gensec_gssapi_sign_packet,
1412         .check_packet   = gensec_gssapi_check_packet,
1413         .seal_packet    = gensec_gssapi_seal_packet,
1414         .unseal_packet  = gensec_gssapi_unseal_packet,
1415         .wrap           = gensec_gssapi_wrap,
1416         .unwrap         = gensec_gssapi_unwrap,
1417         .have_feature   = gensec_gssapi_have_feature,
1418         .enabled        = false,
1419         .kerberos       = true,
1420         .priority       = GENSEC_GSSAPI
1421 };
1422
1423 /* As a server, this could in theory accept any GSSAPI mech */
1424 static const struct gensec_security_ops gensec_gssapi_krb5_security_ops = {
1425         .name           = "gssapi_krb5",
1426         .auth_type      = DCERPC_AUTH_TYPE_KRB5,
1427         .oid            = gensec_gssapi_krb5_oids,
1428         .client_start   = gensec_gssapi_client_start,
1429         .server_start   = gensec_gssapi_server_start,
1430         .magic          = gensec_gssapi_magic,
1431         .update         = gensec_gssapi_update,
1432         .session_key    = gensec_gssapi_session_key,
1433         .session_info   = gensec_gssapi_session_info,
1434         .sign_packet    = gensec_gssapi_sign_packet,
1435         .check_packet   = gensec_gssapi_check_packet,
1436         .seal_packet    = gensec_gssapi_seal_packet,
1437         .unseal_packet  = gensec_gssapi_unseal_packet,
1438         .wrap           = gensec_gssapi_wrap,
1439         .unwrap         = gensec_gssapi_unwrap,
1440         .have_feature   = gensec_gssapi_have_feature,
1441         .enabled        = true,
1442         .kerberos       = true,
1443         .priority       = GENSEC_GSSAPI
1444 };
1445
1446 /* As a server, this could in theory accept any GSSAPI mech */
1447 static const struct gensec_security_ops gensec_gssapi_sasl_krb5_security_ops = {
1448         .name             = "gssapi_krb5_sasl",
1449         .sasl_name        = "GSSAPI",
1450         .client_start     = gensec_gssapi_sasl_client_start,
1451         .server_start     = gensec_gssapi_sasl_server_start,
1452         .update           = gensec_gssapi_update,
1453         .session_key      = gensec_gssapi_session_key,
1454         .session_info     = gensec_gssapi_session_info,
1455         .max_input_size   = gensec_gssapi_max_input_size,
1456         .max_wrapped_size = gensec_gssapi_max_wrapped_size,
1457         .wrap             = gensec_gssapi_wrap,
1458         .unwrap           = gensec_gssapi_unwrap,
1459         .have_feature     = gensec_gssapi_have_feature,
1460         .enabled          = true,
1461         .kerberos         = true,
1462         .priority         = GENSEC_GSSAPI
1463 };
1464
1465 NTSTATUS gensec_gssapi_init(void)
1466 {
1467         NTSTATUS ret;
1468
1469         ret = gensec_register(&gensec_gssapi_spnego_security_ops);
1470         if (!NT_STATUS_IS_OK(ret)) {
1471                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
1472                         gensec_gssapi_spnego_security_ops.name));
1473                 return ret;
1474         }
1475
1476         ret = gensec_register(&gensec_gssapi_krb5_security_ops);
1477         if (!NT_STATUS_IS_OK(ret)) {
1478                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
1479                         gensec_gssapi_krb5_security_ops.name));
1480                 return ret;
1481         }
1482
1483         ret = gensec_register(&gensec_gssapi_sasl_krb5_security_ops);
1484         if (!NT_STATUS_IS_OK(ret)) {
1485                 DEBUG(0,("Failed to register '%s' gensec backend!\n",
1486                         gensec_gssapi_sasl_krb5_security_ops.name));
1487                 return ret;
1488         }
1489
1490         return ret;
1491 }