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