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