disable OID check to get IAKERB to work
[cyrus-sasl.git] / plugins / gs2.c
1 /*
2  * Copyright (c) 2010 PADL Software Pty Ltd.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Redistributions in any form must be accompanied by information on
17  *    how to obtain complete source code for the GS2 software and any
18  *    accompanying software that uses the GS2 software. The source code
19  *    must either be included in the distribution or be available for no
20  *    more than the cost of distribution plus a nominal fee, and must be
21  *    freely redistributable under reasonable conditions. For an
22  *    executable file, complete source code means the source code for all
23  *    modules it contains. It does not include source code for modules or
24  *    files that typically accompany the major components of the operating
25  *    system on which the executable file runs.
26  *
27  * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE ``AS IS'' AND ANY EXPRESS
28  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29  * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
30  * NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
37  * THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 /*
40  * Copyright (c) 1998-2003 Carnegie Mellon University.
41  * All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  *
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  *
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in
52  *    the documentation and/or other materials provided with the
53  *    distribution.
54  *
55  * 3. The name "Carnegie Mellon University" must not be used to
56  *    endorse or promote products derived from this software without
57  *    prior written permission. For permission or any other legal
58  *    details, please contact
59  *      Office of Technology Transfer
60  *      Carnegie Mellon University
61  *      5000 Forbes Avenue
62  *      Pittsburgh, PA  15213-3890
63  *      (412) 268-4387, fax: (412) 268-7395
64  *      tech-transfer@andrew.cmu.edu
65  *
66  * 4. Redistributions of any form whatsoever must retain the following
67  *    acknowledgment:
68  *    "This product includes software developed by Computing Services
69  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
70  *
71  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
72  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
73  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
74  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
75  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
76  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
77  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
78  */
79
80 #include <config.h>
81 #include <gssapi/gssapi.h>
82 #include <gssapi/gssapi_ext.h>
83 #include <fcntl.h>
84 #include <stdio.h>
85 #include <sasl.h>
86 #include <saslutil.h>
87 #include <saslplug.h>
88
89 #include "plugin_common.h"
90
91 #ifdef HAVE_UNISTD_H
92 #include <unistd.h>
93 #endif
94
95 #include <errno.h>
96 #include <assert.h>
97 #include "gs2_token.h"
98
99 #define GS2_CB_FLAG_MASK    0x0F
100 #define GS2_CB_FLAG_N       0x00
101 #define GS2_CB_FLAG_P       0x01
102 #define GS2_CB_FLAG_Y       0x02
103 #define GS2_NONSTD_FLAG     0x10
104
105 typedef struct context {
106     gss_ctx_id_t gss_ctx;
107     gss_name_t client_name;
108     gss_name_t server_name;
109     gss_cred_id_t server_creds;
110     gss_cred_id_t client_creds;
111     char *out_buf;
112     unsigned out_buf_len;
113     const sasl_utils_t *utils;
114     char *authid;
115     char *authzid;
116     union {
117         sasl_client_plug_t *client;
118         sasl_server_plug_t *server;
119     } plug;
120     gss_OID mechanism;
121     int gs2_flags;
122     char *cbindingname;
123     struct gss_channel_bindings_struct gss_cbindings;
124     sasl_secret_t *password;
125     unsigned int free_password;
126     OM_uint32 lifetime;
127 } context_t;
128
129 static gss_OID_set gs2_mechs = GSS_C_NO_OID_SET;
130
131 static int gs2_ask_user_info(context_t *context,
132                              sasl_client_params_t *params,
133                              char **realms, int nrealm,
134                              sasl_interact_t **prompt_need,
135                              sasl_out_params_t *oparams);
136
137 static int gs2_verify_initial_message(context_t *text,
138                                       sasl_server_params_t *sparams,
139                                       const char *in,
140                                       unsigned inlen,
141                                       gss_buffer_t token);
142
143 static int gs2_make_header(context_t *text,
144                            sasl_client_params_t *cparams,
145                            const char *authzid,
146                            char **out,
147                            unsigned *outlen);
148
149 static int gs2_make_message(context_t *text,
150                             sasl_client_params_t *cparams,
151                             int initialContextToken,
152                             gss_buffer_t token,
153                             char **out,
154                             unsigned *outlen);
155
156 static int gs2_get_mech_attrs(const sasl_utils_t *utils,
157                               const gss_OID mech,
158                               unsigned int *security_flags,
159                               unsigned int *features,
160                               const unsigned long **prompts);
161
162 static int gs2_indicate_mechs(const sasl_utils_t *utils);
163
164 static int gs2_map_sasl_name(const sasl_utils_t *utils,
165                              const char *mech,
166                              gss_OID *oid);
167
168 static int gs2_duplicate_buffer(const sasl_utils_t *utils,
169                                 const gss_buffer_t src,
170                                 gss_buffer_t dst);
171
172 static int gs2_unescape_authzid(const sasl_utils_t *utils,
173                                 char **in,
174                                 unsigned *inlen,
175                                 char **authzid);
176
177 static int gs2_escape_authzid(const sasl_utils_t *utils,
178                               const char *in,
179                               unsigned inlen,
180                               char **authzid);
181
182 /* sasl_gs_log: only logs status string returned from gss_display_status() */
183 #define sasl_gs2_log(x,y,z) sasl_gs2_seterror_(x,y,z,1)
184 #define sasl_gs2_seterror(x,y,z) sasl_gs2_seterror_(x,y,z,0)
185
186 static int
187 sasl_gs2_seterror_(const sasl_utils_t *utils, OM_uint32 maj, OM_uint32 min,
188                    int logonly);
189
190 static context_t *
191 sasl_gs2_new_context(const sasl_utils_t *utils)
192 {
193     context_t *ret;
194
195     ret = utils->malloc(sizeof(context_t));
196     if (!ret)
197         return NULL;
198
199     memset(ret, 0, sizeof(context_t));
200     ret->utils = utils;
201
202     return ret;
203 }
204
205 static int
206 sasl_gs2_free_context_contents(context_t *text)
207 {
208     OM_uint32 min_stat;
209
210     if (text == NULL)
211         return SASL_OK;
212
213     if (text->gss_ctx != GSS_C_NO_CONTEXT) {
214         gss_delete_sec_context(&min_stat,&text->gss_ctx,
215                                GSS_C_NO_BUFFER);
216         text->gss_ctx = GSS_C_NO_CONTEXT;
217     }
218
219     if (text->client_name != GSS_C_NO_NAME) {
220         gss_release_name(&min_stat,&text->client_name);
221         text->client_name = GSS_C_NO_NAME;
222     }
223
224     if (text->server_name != GSS_C_NO_NAME) {
225         gss_release_name(&min_stat,&text->server_name);
226         text->server_name = GSS_C_NO_NAME;
227     }
228
229     if (text->server_creds != GSS_C_NO_CREDENTIAL) {
230         gss_release_cred(&min_stat, &text->server_creds);
231         text->server_creds = GSS_C_NO_CREDENTIAL;
232     }
233
234     if (text->client_creds != GSS_C_NO_CREDENTIAL) {
235         gss_release_cred(&min_stat, &text->client_creds);
236         text->client_creds = GSS_C_NO_CREDENTIAL;
237     }
238
239     if (text->authid != NULL) {
240         text->utils->free(text->authid);
241         text->authid = NULL;
242     }
243
244     if (text->authzid != NULL) {
245         text->utils->free(text->authzid);
246         text->authzid = NULL;
247     }
248
249     gss_release_buffer(&min_stat, &text->gss_cbindings.application_data);
250
251     if (text->out_buf != NULL) {
252         text->utils->free(text->out_buf);
253         text->out_buf = NULL;
254     }
255
256     text->out_buf_len = 0;
257
258     if (text->cbindingname != NULL) {
259         text->utils->free(text->cbindingname);
260         text->cbindingname = NULL;
261     }
262
263     if (text->free_password)
264         _plug_free_secret(text->utils, &text->password);
265
266     memset(text, 0, sizeof(*text));
267
268     return SASL_OK;
269 }
270
271 static void
272 gs2_common_mech_dispose(void *conn_context, const sasl_utils_t *utils)
273 {
274     sasl_gs2_free_context_contents((context_t *)(conn_context));
275     utils->free(conn_context);
276 }
277
278 static void
279 gs2_common_mech_free(void *global_context __attribute__((unused)),
280                      const sasl_utils_t *utils)
281 {
282     OM_uint32 minor;
283
284     if (gs2_mechs != GSS_C_NO_OID_SET) {
285         gss_release_oid_set(&minor, &gs2_mechs);
286         gs2_mechs = GSS_C_NO_OID_SET;
287     }
288 }
289
290 /*****************************  Server Section  *****************************/
291
292 static int
293 gs2_server_mech_new(void *glob_context,
294                     sasl_server_params_t *params,
295                     const char *challenge __attribute__((unused)),
296                     unsigned challen __attribute__((unused)),
297                     void **conn_context)
298 {
299     context_t *text;
300     int ret;
301
302     text = sasl_gs2_new_context(params->utils);
303     if (text == NULL) {
304         MEMERROR(params->utils);
305         return SASL_NOMEM;
306     }
307
308     text->gss_ctx = GSS_C_NO_CONTEXT;
309     text->client_name = GSS_C_NO_NAME;
310     text->server_name = GSS_C_NO_NAME;
311     text->server_creds = GSS_C_NO_CREDENTIAL;
312     text->client_creds = GSS_C_NO_CREDENTIAL;
313     text->plug.server = glob_context;
314
315     ret = gs2_map_sasl_name(params->utils, text->plug.server->mech_name,
316                             &text->mechanism);
317     if (ret != SASL_OK) {
318         gs2_common_mech_dispose(text, params->utils);
319         return ret;
320     }
321
322     *conn_context = text;
323
324     return SASL_OK;
325 }
326
327 static int
328 gs2_server_mech_step(void *conn_context,
329                      sasl_server_params_t *params,
330                      const char *clientin,
331                      unsigned clientinlen,
332                      const char **serverout,
333                      unsigned *serveroutlen,
334                      sasl_out_params_t *oparams)
335 {
336     context_t *text = (context_t *)conn_context;
337     gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
338     gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
339     OM_uint32 maj_stat = GSS_S_FAILURE, min_stat = 0;
340     gss_buffer_desc name_buf = GSS_C_EMPTY_BUFFER;
341     gss_buffer_desc short_name_buf = GSS_C_EMPTY_BUFFER;
342     gss_name_t without = GSS_C_NO_NAME;
343     gss_OID_set_desc mechs;
344     gss_OID actual_mech = GSS_C_NO_OID;
345     OM_uint32 out_flags = 0;
346     int ret = 0, equal = 0;
347     int initialContextToken = (text->gss_ctx == GSS_C_NO_CONTEXT);
348     char *p;
349
350     if (serverout == NULL) {
351         PARAMERROR(text->utils);
352         return SASL_BADPARAM;
353     }
354
355     *serverout = NULL;
356     *serveroutlen = 0;
357
358     if (initialContextToken) {
359         name_buf.length = strlen(params->service) + 1 + strlen(params->serverFQDN);
360         name_buf.value = params->utils->malloc(name_buf.length + 1);
361         if (name_buf.value == NULL) {
362             MEMERROR(text->utils);
363             ret = SASL_NOMEM;
364             goto cleanup;
365         }
366         snprintf(name_buf.value, name_buf.length + 1,
367                  "%s@%s", params->service, params->serverFQDN);
368         maj_stat = gss_import_name(&min_stat,
369                                    &name_buf,
370                                    GSS_C_NT_HOSTBASED_SERVICE,
371                                    &text->server_name);
372         params->utils->free(name_buf.value);
373         name_buf.value = NULL;
374
375         if (GSS_ERROR(maj_stat))
376             goto cleanup;
377
378         assert(text->server_creds == GSS_C_NO_CREDENTIAL);
379
380         mechs.count = 1;
381         mechs.elements = (gss_OID)text->mechanism;
382
383         if (params->gss_creds == GSS_C_NO_CREDENTIAL) {
384             maj_stat = gss_acquire_cred(&min_stat,
385                                         text->server_name,
386                                         GSS_C_INDEFINITE,
387                                         &mechs,
388                                         GSS_C_ACCEPT,
389                                         &text->server_creds,
390                                         NULL,
391                                         &text->lifetime);
392             if (GSS_ERROR(maj_stat))
393                 goto cleanup;
394         }
395
396         ret = gs2_verify_initial_message(text,
397                                          params,
398                                          clientin,
399                                          clientinlen,
400                                          &input_token);
401         if (ret != SASL_OK)
402             goto cleanup;
403     } else {
404         input_token.value = (void *)clientin;
405         input_token.length = clientinlen;
406     }
407
408     maj_stat = gss_accept_sec_context(&min_stat,
409                                       &text->gss_ctx,
410                                       (params->gss_creds != GSS_C_NO_CREDENTIAL)
411                                         ? (gss_cred_id_t)params->gss_creds
412                                         : text->server_creds,
413                                       &input_token,
414                                       &text->gss_cbindings,
415                                       &text->client_name,
416                                       &actual_mech,
417                                       &output_token,
418                                       &out_flags,
419                                       &text->lifetime,
420                                       &text->client_creds);
421     if (GSS_ERROR(maj_stat)) {
422         sasl_gs2_log(text->utils, maj_stat, min_stat);
423         text->utils->seterror(text->utils->conn, SASL_NOLOG,
424                               "GS2 Failure: gss_accept_sec_context");
425         ret = (maj_stat == GSS_S_BAD_BINDINGS) ? SASL_BADBINDING : SASL_BADAUTH;
426         goto cleanup;
427     }
428
429     *serveroutlen = output_token.length;
430     if (output_token.value != NULL) {
431         ret = _plug_buf_alloc(text->utils, &text->out_buf,
432                               &text->out_buf_len, *serveroutlen);
433         if (ret != SASL_OK)
434             goto cleanup;
435         memcpy(text->out_buf, output_token.value, *serveroutlen);
436         *serverout = text->out_buf;
437     } else {
438         /* No output token, send an empty string */
439         *serverout = "";
440         serveroutlen = 0;
441     }
442
443     if (maj_stat == GSS_S_CONTINUE_NEEDED) {
444         ret = SASL_CONTINUE;
445         goto cleanup;
446     }
447
448     assert(maj_stat == GSS_S_COMPLETE);
449
450 #if 0
451     if (!g_OID_equal(text->mechanism, actual_mech)) {
452         ret = SASL_WRONGMECH;
453         goto cleanup;
454     }
455 #endif
456     if ((out_flags & GSS_C_SEQUENCE_FLAG) == 0)  {
457         ret = SASL_BADAUTH;
458         goto cleanup;
459     }
460
461     maj_stat = gss_display_name(&min_stat, text->client_name,
462                                 &name_buf, NULL);
463     if (GSS_ERROR(maj_stat))
464         goto cleanup;
465
466     ret = gs2_duplicate_buffer(params->utils, &name_buf, &short_name_buf);
467     if (ret != 0)
468         goto cleanup;
469
470     p = (char *)memchr(name_buf.value, '@', name_buf.length);
471     if (p != NULL) {
472         short_name_buf.length = (p - (char *)name_buf.value);
473
474         maj_stat = gss_import_name(&min_stat,
475                                    &short_name_buf,
476                                    GSS_C_NT_USER_NAME,
477                                    &without);
478         if (GSS_ERROR(maj_stat)) {
479             ret = SASL_FAIL;
480             goto cleanup;
481         }
482
483         maj_stat = gss_compare_name(&min_stat, text->client_name,
484                                     without, &equal);
485         if (GSS_ERROR(maj_stat)) {
486             ret = SASL_FAIL;
487             goto cleanup;
488         }
489
490         if (equal)
491             ((char *)short_name_buf.value)[short_name_buf.length] = '\0';
492     }
493
494     text->authid = (char *)short_name_buf.value;
495     short_name_buf.value = NULL;
496     short_name_buf.length = 0;
497
498     if (text->authzid != NULL) {
499         ret = params->canon_user(params->utils->conn,
500                                  text->authzid, 0,
501                                  SASL_CU_AUTHZID, oparams);
502         if (ret != SASL_OK)
503             goto cleanup;
504     }
505
506     ret = params->canon_user(params->utils->conn,
507                              text->authid, 0,
508                              text->authzid == NULL
509                                 ? (SASL_CU_AUTHZID | SASL_CU_AUTHID)
510                                 : SASL_CU_AUTHID,
511                              oparams);
512     if (ret != SASL_OK)
513         goto cleanup;
514
515     switch (text->gs2_flags & GS2_CB_FLAG_MASK) {
516     case GS2_CB_FLAG_N:
517         oparams->cbindingdisp = SASL_CB_DISP_NONE;
518         break;
519     case GS2_CB_FLAG_P:
520         oparams->cbindingdisp = SASL_CB_DISP_USED;
521         oparams->cbindingname = text->cbindingname;
522         break;
523     case GS2_CB_FLAG_Y:
524         oparams->cbindingdisp = SASL_CB_DISP_WANT;
525         break;
526     }
527
528     if (text->client_creds != GSS_C_NO_CREDENTIAL)
529         oparams->client_creds = &text->client_creds;
530     else
531         oparams->client_creds = NULL;
532
533     oparams->gss_peer_name = text->client_name;
534     oparams->gss_local_name = text->server_name;
535     oparams->maxoutbuf = 0xFFFFFF;
536     oparams->encode = NULL;
537     oparams->decode = NULL;
538     oparams->mech_ssf = 0;
539     oparams->doneflag = 1;
540
541     ret = SASL_OK;
542
543 cleanup:
544     if (initialContextToken)
545         gss_release_buffer(&min_stat, &input_token);
546     gss_release_buffer(&min_stat, &name_buf);
547     gss_release_buffer(&min_stat, &short_name_buf);
548     gss_release_buffer(&min_stat, &output_token);
549     gss_release_name(&min_stat, &without);
550
551     if (ret == SASL_OK && maj_stat != GSS_S_COMPLETE) {
552         sasl_gs2_seterror(text->utils, maj_stat, min_stat);
553         ret = SASL_FAIL;
554     }
555     if (ret != SASL_OK && ret != SASL_CONTINUE)
556         sasl_gs2_free_context_contents(text);
557
558     return ret;
559 }
560
561 static int
562 gs2_common_plug_init(const sasl_utils_t *utils,
563                      size_t plugsize,
564                      int (*plug_alloc)(const sasl_utils_t *,
565                                        void *,
566                                        const gss_buffer_t,
567                                        const gss_OID),
568                      void **pluglist,
569                      int *plugcount)
570 {
571     OM_uint32 major, minor;
572     size_t i, count = 0;
573     void *plugs = NULL;
574
575     *pluglist = NULL;
576     *plugcount = 0;
577
578     if (gs2_indicate_mechs(utils) != SASL_OK) {
579         return SASL_NOMECH;
580     }
581
582     plugs = utils->malloc(2 * gs2_mechs->count * plugsize);
583     if (plugs == NULL) {
584         MEMERROR(utils);
585         return SASL_NOMEM;
586     }
587     memset(plugs, 0, 2 * gs2_mechs->count * plugsize);
588
589     for (i = 0; i < gs2_mechs->count; i++) {
590         gss_buffer_desc sasl_mech_name = GSS_C_EMPTY_BUFFER;
591
592         major = gss_inquire_saslname_for_mech(&minor,
593                                               &gs2_mechs->elements[i],
594                                               &sasl_mech_name,
595                                               GSS_C_NO_BUFFER,
596                                               GSS_C_NO_BUFFER);
597         if (GSS_ERROR(major))
598             continue;
599
600 #define PLUG_AT(index)      (void *)((unsigned char *)plugs + (count * plugsize))
601
602         if (plug_alloc(utils, PLUG_AT(count), &sasl_mech_name,
603                        &gs2_mechs->elements[i]) == SASL_OK)
604             count++;
605
606         gss_release_buffer(&minor, &sasl_mech_name);
607     }
608
609     if (count == 0) {
610         utils->free(plugs);
611         return SASL_NOMECH;
612     }
613
614     *pluglist = plugs;
615     *plugcount = count;
616
617     return SASL_OK;
618 }
619
620 static int
621 gs2_server_plug_alloc(const sasl_utils_t *utils,
622                       void *plug,
623                       gss_buffer_t sasl_name,
624                       gss_OID mech)
625 {
626     int ret;
627     sasl_server_plug_t *splug = (sasl_server_plug_t *)plug;
628     gss_buffer_desc buf;
629
630     memset(splug, 0, sizeof(*splug));
631
632     ret = gs2_get_mech_attrs(utils, mech,
633                              &splug->security_flags,
634                              &splug->features,
635                              NULL);
636     if (ret != SASL_OK)
637         return ret;
638
639     ret = gs2_duplicate_buffer(utils, sasl_name, &buf);
640     if (ret != SASL_OK)
641         return ret;
642
643     splug->mech_name = (char *)buf.value;
644     splug->glob_context = plug;
645     splug->mech_new = gs2_server_mech_new;
646     splug->mech_step = gs2_server_mech_step;
647     splug->mech_dispose = gs2_common_mech_dispose;
648     splug->mech_free = gs2_common_mech_free;
649
650     return SASL_OK;
651 }
652
653 static sasl_server_plug_t *gs2_server_plugins;
654 static int gs2_server_plugcount;
655
656 int
657 gs2_server_plug_init(const sasl_utils_t *utils,
658                      int maxversion,
659                      int *outversion,
660                      sasl_server_plug_t **pluglist,
661                      int *plugcount)
662 {
663     int ret;
664
665     *pluglist = NULL;
666     *plugcount = 0;
667
668     if (maxversion < SASL_SERVER_PLUG_VERSION)
669         return SASL_BADVERS;
670
671     *outversion = SASL_SERVER_PLUG_VERSION;
672
673     if (gs2_server_plugins == NULL) {
674         ret = gs2_common_plug_init(utils,
675                                    sizeof(sasl_server_plug_t),
676                                    gs2_server_plug_alloc,
677                                    (void **)&gs2_server_plugins,
678                                    &gs2_server_plugcount);
679         if (ret != SASL_OK)
680             return ret;
681     }
682
683     *pluglist = gs2_server_plugins;
684     *plugcount = gs2_server_plugcount;
685
686     return SASL_OK;
687 }
688
689 /*****************************  Client Section  *****************************/
690
691 static int gs2_client_mech_step(void *conn_context,
692                                 sasl_client_params_t *params,
693                                 const char *serverin,
694                                 unsigned serverinlen,
695                                 sasl_interact_t **prompt_need,
696                                 const char **clientout,
697                                 unsigned *clientoutlen,
698                                 sasl_out_params_t *oparams)
699 {
700     context_t *text = (context_t *)conn_context;
701     gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
702     gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
703     gss_buffer_desc name_buf = GSS_C_EMPTY_BUFFER;
704     OM_uint32 maj_stat = GSS_S_FAILURE, min_stat = 0;
705     OM_uint32 req_flags, ret_flags;
706     gss_OID actual_mech = GSS_C_NO_OID;
707     int ret = SASL_FAIL;
708     int initialContextToken;
709
710     *clientout = NULL;
711     *clientoutlen = 0;
712
713     if (text->gss_ctx == GSS_C_NO_CONTEXT) {
714         ret = gs2_ask_user_info(text, params, NULL, 0, prompt_need, oparams);
715         if (ret != SASL_OK)
716             goto cleanup;
717
718         if (params->gss_creds == GSS_C_NO_CREDENTIAL &&
719             text->password != NULL && text->password->len != 0) {
720             gss_buffer_desc password_buf;
721             gss_buffer_desc name_buf;
722             gss_OID_set_desc mechs;
723
724             name_buf.length = strlen(oparams->authid);
725             name_buf.value = (void *)oparams->authid;
726
727             password_buf.length = text->password->len;
728             password_buf.value = text->password->data;
729
730             mechs.count = 1;
731             mechs.elements = (gss_OID)text->mechanism;
732
733             maj_stat = gss_import_name(&min_stat,
734                                        &name_buf,
735                                        GSS_C_NT_USER_NAME,
736                                        &text->client_name);
737             if (GSS_ERROR(maj_stat))
738                 goto cleanup;
739
740             maj_stat = gss_acquire_cred_with_password(&min_stat,
741                                                       text->client_name,
742                                                       &password_buf,
743                                                       GSS_C_INDEFINITE,
744                                                       &mechs,
745                                                       GSS_C_INITIATE,
746                                                       &text->client_creds,
747                                                       NULL,
748                                                       &text->lifetime);
749             if (GSS_ERROR(maj_stat))
750                 goto cleanup;
751         }
752
753         initialContextToken = 1;
754     } else
755         initialContextToken = 0;
756
757     if (text->server_name == GSS_C_NO_NAME) { /* only once */
758         name_buf.length = strlen(params->service) + 1 + strlen(params->serverFQDN);
759         name_buf.value = params->utils->malloc(name_buf.length + 1);
760         if (name_buf.value == NULL) {
761             ret = SASL_NOMEM;
762             goto cleanup;
763         }
764         if (params->serverFQDN == NULL ||
765             strlen(params->serverFQDN) == 0) {
766             SETERROR(text->utils, "GS2 Failure: no serverFQDN");
767             ret = SASL_FAIL;
768             goto cleanup;
769         }
770
771         snprintf(name_buf.value, name_buf.length + 1,
772                  "%s@%s", params->service, params->serverFQDN);
773
774         maj_stat = gss_import_name (&min_stat,
775                                     &name_buf,
776                                     GSS_C_NT_HOSTBASED_SERVICE,
777                                     &text->server_name);
778         params->utils->free(name_buf.value);
779         name_buf.value = NULL;
780
781         if (GSS_ERROR(maj_stat))
782             goto cleanup;
783     }
784
785     /* From GSSAPI plugin: apparently this is for some IMAP bug workaround */
786     if (serverinlen == 0 && text->gss_ctx != GSS_C_NO_CONTEXT) {
787         gss_delete_sec_context(&min_stat, &text->gss_ctx, GSS_C_NO_BUFFER);
788         text->gss_ctx = GSS_C_NO_CONTEXT;
789     }
790
791     input_token.value = (void *)serverin;
792     input_token.length = serverinlen;
793
794     if (initialContextToken) {
795         if ((text->plug.client->features & SASL_FEAT_GSS_FRAMING) == 0)
796             text->gs2_flags |= GS2_NONSTD_FLAG;
797
798         switch (params->cbindingdisp) {
799         case SASL_CB_DISP_NONE:
800             text->gs2_flags |= GS2_CB_FLAG_N;
801             break;
802         case SASL_CB_DISP_USED:
803             text->gs2_flags |= GS2_CB_FLAG_P;
804             break;
805         case SASL_CB_DISP_WANT:
806             text->gs2_flags |= GS2_CB_FLAG_Y;
807             break;
808         }
809
810         ret = gs2_make_header(text, params,
811                               strcmp(oparams->user, oparams->authid) ?
812                                      (char *) oparams->user : NULL,
813                               &text->out_buf, &text->out_buf_len);
814         if (ret != 0)
815             goto cleanup;
816     }
817
818     req_flags = GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG;
819
820     maj_stat = gss_init_sec_context(&min_stat,
821                                     (params->gss_creds != GSS_C_NO_CREDENTIAL)
822                                         ? (gss_cred_id_t)params->gss_creds
823                                         : text->client_creds,
824                                     &text->gss_ctx,
825                                     text->server_name,
826                                     (gss_OID)text->mechanism,
827                                     req_flags,
828                                     GSS_C_INDEFINITE,
829                                     &text->gss_cbindings,
830                                     serverinlen ? &input_token : GSS_C_NO_BUFFER,
831                                     NULL,
832                                     &output_token,
833                                     &ret_flags,
834                                     &text->lifetime);
835     if (GSS_ERROR(maj_stat))
836         goto cleanup;
837
838     ret = gs2_make_message(text, params, initialContextToken, &output_token,
839                            &text->out_buf, &text->out_buf_len);
840     if (ret != 0)
841         goto cleanup;
842
843     *clientout = text->out_buf;
844     *clientoutlen = text->out_buf_len;
845
846     if (maj_stat == GSS_S_CONTINUE_NEEDED) {
847         ret = SASL_CONTINUE;
848         goto cleanup;
849     }
850
851     if (text->client_name != GSS_C_NO_NAME)
852         gss_release_name(&min_stat, &text->client_name);
853
854     maj_stat = gss_inquire_context(&min_stat,
855                                    text->gss_ctx,
856                                    &text->client_name,
857                                    NULL,
858                                    &text->lifetime,
859                                    &actual_mech,
860                                    &ret_flags, /* flags */
861                                    NULL,
862                                    NULL);
863     if (GSS_ERROR(maj_stat))
864         goto cleanup;
865
866     if (!g_OID_equal(text->mechanism, actual_mech)) {
867         ret = SASL_WRONGMECH;
868         goto cleanup;
869     }
870     if ((ret_flags & req_flags) != req_flags) {
871         maj_stat = SASL_BADAUTH;
872         goto cleanup;
873     }
874
875     maj_stat = gss_display_name(&min_stat,
876                                 text->client_name,
877                                 &name_buf,
878                                 NULL);
879     if (GSS_ERROR(maj_stat))
880         goto cleanup;
881
882     oparams->gss_peer_name = text->server_name;
883     oparams->gss_local_name = text->client_name;
884     oparams->encode = NULL;
885     oparams->decode = NULL;
886     oparams->mech_ssf = 0;
887     oparams->maxoutbuf = 0xFFFFFF;
888     oparams->doneflag = 1;
889
890 cleanup:
891     gss_release_buffer(&min_stat, &output_token);
892     gss_release_buffer(&min_stat, &name_buf);
893
894     if (ret == SASL_OK && maj_stat != GSS_S_COMPLETE) {
895         sasl_gs2_seterror(text->utils, maj_stat, min_stat);
896         ret = SASL_FAIL;
897     }
898     if (ret != SASL_OK && ret != SASL_CONTINUE)
899         sasl_gs2_free_context_contents(text);
900
901     return ret;
902 }
903
904 static int gs2_client_mech_new(void *glob_context,
905                                sasl_client_params_t *params,
906                                void **conn_context)
907 {
908     context_t *text;
909     int ret;
910
911     text = sasl_gs2_new_context(params->utils);
912     if (text == NULL) {
913         MEMERROR(params->utils);
914         return SASL_NOMEM;
915     }
916
917     text->gss_ctx = GSS_C_NO_CONTEXT;
918     text->client_name = GSS_C_NO_NAME;
919     text->server_creds = GSS_C_NO_CREDENTIAL;
920     text->client_creds  = GSS_C_NO_CREDENTIAL;
921     text->plug.client = glob_context;
922
923     ret = gs2_map_sasl_name(params->utils, text->plug.client->mech_name,
924                             &text->mechanism);
925     if (ret != SASL_OK) {
926         gs2_common_mech_dispose(text, params->utils);
927         return ret;
928     }
929
930     *conn_context = text;
931
932     return SASL_OK;
933 }
934
935 static int
936 gs2_client_plug_alloc(const sasl_utils_t *utils,
937                       void *plug,
938                       gss_buffer_t sasl_name,
939                       gss_OID mech)
940 {
941     int ret;
942     sasl_client_plug_t *cplug = (sasl_client_plug_t *)plug;
943     gss_buffer_desc buf;
944
945     memset(cplug, 0, sizeof(*cplug));
946
947     ret = gs2_get_mech_attrs(utils, mech,
948                              &cplug->security_flags,
949                              &cplug->features,
950                              &cplug->required_prompts);
951     if (ret != SASL_OK)
952         return ret;
953
954     ret = gs2_duplicate_buffer(utils, sasl_name, &buf);
955     if (ret != SASL_OK)
956         return ret;
957
958     cplug->mech_name = (char *)buf.value;
959     cplug->features |= SASL_FEAT_NEEDSERVERFQDN;
960     cplug->glob_context = plug;
961     cplug->mech_new = gs2_client_mech_new;
962     cplug->mech_step = gs2_client_mech_step;
963     cplug->mech_dispose = gs2_common_mech_dispose;
964     cplug->mech_free = gs2_common_mech_free;
965
966     return SASL_OK;
967 }
968
969 static sasl_client_plug_t *gs2_client_plugins;
970 static int gs2_client_plugcount;
971
972 int
973 gs2_client_plug_init(const sasl_utils_t *utils,
974                      int maxversion,
975                      int *outversion,
976                      sasl_client_plug_t **pluglist,
977                      int *plugcount)
978 {
979     int ret;
980
981     *pluglist = NULL;
982     *plugcount = 0;
983
984     if (maxversion < SASL_CLIENT_PLUG_VERSION)
985         return SASL_BADVERS;
986
987     *outversion = SASL_CLIENT_PLUG_VERSION;
988
989     if (gs2_client_plugins == NULL) {
990         ret = gs2_common_plug_init(utils,
991                                    sizeof(sasl_client_plug_t),
992                                    gs2_client_plug_alloc,
993                                    (void **)&gs2_client_plugins,
994                                    &gs2_client_plugcount);
995         if (ret != SASL_OK)
996             return ret;
997     }
998
999     *pluglist = gs2_client_plugins;
1000     *plugcount = gs2_client_plugcount;
1001
1002     return SASL_OK;
1003 }
1004
1005 /*
1006  * Copy header and application channel bindings to GSS channel bindings
1007  * structure in context.
1008  */
1009 static int
1010 gs2_save_cbindings(context_t *text,
1011                    gss_buffer_t header,
1012                    const sasl_channel_binding_t *cbinding)
1013 {
1014     gss_buffer_t gss_cbindings = &text->gss_cbindings.application_data;
1015     size_t len;
1016     unsigned char *p;
1017
1018     assert(gss_cbindings->value == NULL);
1019
1020     /*
1021      * The application-data field MUST be set to the gs2-header, excluding
1022      * the initial [gs2-nonstd-flag ","] part, concatenated with, when a
1023      * gs2-cb-flag of "p" is used, the application's channel binding data.
1024      */
1025     len = header->length;
1026     if (text->gs2_flags & GS2_NONSTD_FLAG) {
1027         assert(len > 2);
1028         len -= 2;
1029     }
1030     if ((text->gs2_flags & GS2_CB_FLAG_MASK) == GS2_CB_FLAG_P &&
1031         cbinding != NULL) {
1032         len += cbinding->len;
1033     }
1034
1035     gss_cbindings->length = len;
1036     gss_cbindings->value = text->utils->malloc(len);
1037     if (gss_cbindings->value == NULL)
1038         return SASL_NOMEM;
1039
1040     p = (unsigned char *)gss_cbindings->value;
1041     if (text->gs2_flags & GS2_NONSTD_FLAG) {
1042         memcpy(p, (unsigned char *)header->value + 2, header->length - 2);
1043         p += header->length - 2;
1044     } else {
1045         memcpy(p, header->value, header->length);
1046         p += header->length;
1047     }
1048
1049     if ((text->gs2_flags & GS2_CB_FLAG_MASK) == GS2_CB_FLAG_P &&
1050         cbinding != NULL) {
1051         memcpy(p, cbinding->data, cbinding->len);
1052     }
1053
1054     return SASL_OK;
1055 }
1056
1057 #define CHECK_REMAIN(n)     do { if (remain < (n)) return SASL_BADPROT; } while (0)
1058
1059 /*
1060  * Verify gs2-header, save authzid and channel bindings to context.
1061  */
1062 static int
1063 gs2_verify_initial_message(context_t *text,
1064                            sasl_server_params_t *sparams,
1065                            const char *in,
1066                            unsigned inlen,
1067                            gss_buffer_t token)
1068 {
1069     char *p = (char *)in;
1070     unsigned remain = inlen;
1071     int ret;
1072     gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
1073
1074     assert(text->cbindingname == NULL);
1075     assert(text->authzid == NULL);
1076
1077     token->length = 0;
1078     token->value = NULL;
1079
1080     /* minimum header includes CB flag and non-zero GSS token */
1081     CHECK_REMAIN(4); /* [pny],,. */
1082
1083     /* non-standard GSS framing flag */
1084     if (remain > 1 && memcmp(p, "F,", 2) == 0) {
1085         text->gs2_flags |= GS2_NONSTD_FLAG;
1086         remain -= 2;
1087         p += 2;
1088     }
1089
1090     /* SASL channel bindings */
1091     CHECK_REMAIN(1); /* [pny] */
1092     remain--;
1093     switch (*p++) {
1094     case 'p':
1095         CHECK_REMAIN(1); /* = */
1096         remain--;
1097         if (*p++ != '=')
1098             return SASL_BADPROT;
1099
1100         ret = gs2_unescape_authzid(text->utils, &p, &remain, &text->cbindingname);
1101         if (ret != SASL_OK)
1102             return ret;
1103
1104         text->gs2_flags |= GS2_CB_FLAG_P;
1105         break;
1106     case 'n':
1107         text->gs2_flags |= GS2_CB_FLAG_N;
1108         break;
1109     case 'y':
1110         text->gs2_flags |= GS2_CB_FLAG_Y;
1111         break;
1112     }
1113
1114     CHECK_REMAIN(1); /* , */
1115     remain--;
1116     if (*p++ != ',')
1117         return SASL_BADPROT;
1118
1119     /* authorization identity */
1120     if (remain > 1 && memcmp(p, "a=", 2) == 0) {
1121         CHECK_REMAIN(2);
1122         remain -= 2;
1123         p += 2;
1124
1125         ret = gs2_unescape_authzid(text->utils, &p, &remain, &text->authzid);
1126         if (ret != SASL_OK)
1127             return ret;
1128     }
1129
1130     /* end of header */
1131     CHECK_REMAIN(1); /* , */
1132     remain--;
1133     if (*p++ != ',')
1134         return SASL_BADPROT;
1135
1136     buf.length = inlen - remain;
1137     buf.value = (void *)in;
1138
1139     /* stash channel bindings to pass into gss_accept_sec_context() */
1140     ret = gs2_save_cbindings(text, &buf, sparams->cbinding);
1141     if (ret != SASL_OK)
1142         return ret;
1143
1144     buf.length = remain;
1145     buf.value = p;
1146
1147     if (text->gs2_flags & GS2_NONSTD_FLAG) {
1148         token->value = text->utils->malloc(buf.length);
1149         if (token->value == NULL)
1150             return SASL_NOMEM;
1151
1152         token->length = buf.length;
1153         memcpy(token->value, buf.value, buf.length);
1154     } else {
1155         unsigned int token_size;
1156
1157         /* create a properly formed GSS token */
1158         token_size = gs2_token_size(text->mechanism, buf.length);
1159         token->value = text->utils->malloc(token_size);
1160         if (token->value == NULL)
1161             return SASL_NOMEM;
1162
1163         token->length = token_size;
1164
1165         p = (char *)token->value;
1166         gs2_make_token_header(text->mechanism, buf.length,
1167                               (unsigned char **)&p);
1168         memcpy(p, buf.value, buf.length);
1169     }
1170
1171     return SASL_OK;
1172 }
1173
1174 /*
1175  * Create gs2-header, save channel bindings to context.
1176  */
1177 static int
1178 gs2_make_header(context_t *text,
1179                 sasl_client_params_t *cparams,
1180                 const char *authzid,
1181                 char **out,
1182                 unsigned *outlen)
1183 {
1184     size_t required = 0;
1185     size_t wire_authzid_len = 0, cbnamelen = 0;
1186     char *wire_authzid = NULL;
1187     char *p;
1188     int ret;
1189     gss_buffer_desc buf;
1190
1191     *out = NULL;
1192     *outlen = 0;
1193
1194     /* non-standard GSS framing flag */
1195     if (text->gs2_flags & GS2_NONSTD_FLAG)
1196         required += 2; /* F, */
1197
1198     /* SASL channel bindings */
1199     switch (text->gs2_flags & GS2_CB_FLAG_MASK) {
1200     case GS2_CB_FLAG_P:
1201         if (!SASL_CB_PRESENT(cparams))
1202             return SASL_BADPARAM;
1203         cbnamelen = strlen(cparams->cbinding->name);
1204         required += 1 /*=*/ + cbnamelen;
1205         /* fallthrough */
1206     case GS2_CB_FLAG_N:
1207     case GS2_CB_FLAG_Y:
1208         required += 2; /* [pny], */
1209         break;
1210     default:
1211         return SASL_BADPARAM;
1212     }
1213
1214     /* authorization identity */
1215     if (authzid != NULL) {
1216         ret = gs2_escape_authzid(text->utils, authzid,
1217                                  strlen(authzid), &wire_authzid);
1218         if (ret != SASL_OK)
1219             return ret;
1220
1221         wire_authzid_len = strlen(wire_authzid);
1222         required += 2 /* a= */ + wire_authzid_len;
1223     }
1224
1225     required += 1; /* trailing comma */
1226
1227     ret = _plug_buf_alloc(text->utils, out, outlen, required);
1228     if (ret != SASL_OK) {
1229         text->utils->free(wire_authzid);
1230         return ret;
1231     }
1232
1233     *out = text->out_buf;
1234     *outlen = required;
1235
1236     p = (char *)text->out_buf;
1237     if (text->gs2_flags & GS2_NONSTD_FLAG) {
1238         *p++ = 'F';
1239         *p++ = ',';
1240     }
1241     switch (text->gs2_flags & GS2_CB_FLAG_MASK) {
1242     case GS2_CB_FLAG_P:
1243         memcpy(p, "p=", 2);
1244         memcpy(p + 2, cparams->cbinding->name, cbnamelen);
1245         p += 2 + cbnamelen;
1246         break;
1247     case GS2_CB_FLAG_N:
1248         *p++ = 'n';
1249         break;
1250     case GS2_CB_FLAG_Y:
1251         *p++ = 'y';
1252         break;
1253     }
1254     *p++ = ',';
1255     if (wire_authzid != NULL) {
1256         memcpy(p, "a=", 2);
1257         memcpy(p + 2, wire_authzid, wire_authzid_len);
1258         text->utils->free(wire_authzid);
1259         p += 2 + wire_authzid_len;
1260     }
1261     *p++ = ',';
1262
1263     assert(p == (char *)text->out_buf + required);
1264
1265     buf.length = required;
1266     buf.value = *out;
1267
1268     ret = gs2_save_cbindings(text, &buf, cparams->cbinding);
1269     if (ret != SASL_OK)
1270         return ret;
1271
1272     return SASL_OK;
1273 }
1274
1275 /*
1276  * Convert a GSS token to a GS2 one
1277  */
1278 static int
1279 gs2_make_message(context_t *text,
1280                  sasl_client_params_t *cparams __attribute__((unused)),
1281                  int initialContextToken,
1282                  gss_buffer_t token,
1283                  char **out,
1284                  unsigned *outlen)
1285 {
1286     OM_uint32 major, minor;
1287     unsigned char *mech_token_data;
1288     size_t mech_token_size;
1289     char *p;
1290     unsigned header_len = 0;
1291     int ret;
1292
1293     mech_token_size = token->length;
1294     mech_token_data = (unsigned char *)token->value;
1295
1296     if (initialContextToken) {
1297         header_len = *outlen;
1298
1299         major = gs2_verify_token_header(&minor, text->mechanism,
1300                                         &mech_token_size, &mech_token_data,
1301                                         token->length);
1302         if ((major == GSS_S_DEFECTIVE_TOKEN &&
1303              (text->plug.client->features & SASL_FEAT_GSS_FRAMING)) ||
1304             GSS_ERROR(major))
1305             return SASL_FAIL;
1306     }
1307
1308     ret = _plug_buf_alloc(text->utils, out, outlen,
1309                           header_len + mech_token_size);
1310     if (ret != 0)
1311         return ret;
1312
1313     p = *out + header_len;
1314     memcpy(p, mech_token_data, mech_token_size);
1315
1316     *outlen = header_len + mech_token_size;
1317
1318     return SASL_OK;
1319 }
1320
1321 static const unsigned long gs2_required_prompts[] = {
1322     SASL_CB_LIST_END
1323 };
1324
1325 /*
1326  * Map GSS mechanism attributes to SASL ones
1327  */
1328 static int
1329 gs2_get_mech_attrs(const sasl_utils_t *utils,
1330                    const gss_OID mech,
1331                    unsigned int *security_flags,
1332                    unsigned int *features,
1333                    const unsigned long **prompts)
1334 {
1335     OM_uint32 major, minor;
1336     int present;
1337     gss_OID_set attrs = GSS_C_NO_OID_SET;
1338
1339     major = gss_inquire_attrs_for_mech(&minor, mech, &attrs, NULL);
1340     if (GSS_ERROR(major)) {
1341         utils->seterror(utils->conn, SASL_NOLOG,
1342                         "GS2 Failure: gss_inquire_attrs_for_mech");
1343         return SASL_FAIL;
1344     }
1345
1346     *security_flags = SASL_SEC_NOPLAINTEXT | SASL_SEC_NOACTIVE;
1347     *features = SASL_FEAT_WANT_CLIENT_FIRST | SASL_FEAT_CHANNEL_BINDING;
1348     if (prompts != NULL)
1349         *prompts = gs2_required_prompts;
1350
1351 #define MA_PRESENT(a)   (gss_test_oid_set_member(&minor, (gss_OID)(a), \
1352                                                  attrs, &present) == GSS_S_COMPLETE && \
1353                          present)
1354
1355     if (MA_PRESENT(GSS_C_MA_PFS))
1356         *security_flags |= SASL_SEC_FORWARD_SECRECY;
1357     if (!MA_PRESENT(GSS_C_MA_AUTH_INIT_ANON))
1358         *security_flags |= SASL_SEC_NOANONYMOUS;
1359     if (MA_PRESENT(GSS_C_MA_DELEG_CRED))
1360         *security_flags |= SASL_SEC_PASS_CREDENTIALS;
1361     if (MA_PRESENT(GSS_C_MA_AUTH_TARG))
1362         *security_flags |= SASL_SEC_MUTUAL_AUTH;
1363     if (MA_PRESENT(GSS_C_MA_AUTH_INIT_INIT) && prompts != NULL)
1364         *prompts = NULL;
1365     if (MA_PRESENT(GSS_C_MA_ITOK_FRAMED))
1366         *features |= SASL_FEAT_GSS_FRAMING;
1367
1368     gss_release_oid_set(&minor, &attrs);
1369
1370     return SASL_OK;
1371 }
1372
1373 /*
1374  * Enumerate GSS mechanisms that can be used for GS2
1375  */
1376 static int gs2_indicate_mechs(const sasl_utils_t *utils)
1377 {
1378     OM_uint32 major, minor;
1379     gss_OID_desc desired_oids[3];
1380     gss_OID_set_desc desired_attrs;
1381     gss_OID_desc except_oids[3];
1382     gss_OID_set_desc except_attrs;
1383
1384     if (gs2_mechs != GSS_C_NO_OID_SET)
1385         return SASL_OK;
1386
1387     desired_oids[0] = *GSS_C_MA_AUTH_INIT;
1388     desired_oids[1] = *GSS_C_MA_AUTH_TARG;
1389     desired_oids[2] = *GSS_C_MA_CBINDINGS;
1390     desired_attrs.count = sizeof(desired_oids)/sizeof(desired_oids[0]);
1391     desired_attrs.elements = desired_oids;
1392
1393     except_oids[0] = *GSS_C_MA_MECH_NEGO;
1394     except_oids[1] = *GSS_C_MA_NOT_MECH;
1395     except_oids[2] = *GSS_C_MA_DEPRECATED;
1396
1397     except_attrs.count = sizeof(except_oids)/sizeof(except_oids[0]);
1398     except_attrs.elements = except_oids;
1399
1400     major = gss_indicate_mechs_by_attrs(&minor,
1401                                         &desired_attrs,
1402                                         &except_attrs,
1403                                         GSS_C_NO_OID_SET,
1404                                         &gs2_mechs);
1405     if (GSS_ERROR(major)) {
1406         utils->seterror(utils->conn, SASL_NOLOG,
1407                         "GS2 Failure: gss_indicate_mechs_by_attrs");
1408         return SASL_FAIL;
1409     }
1410
1411     return (gs2_mechs->count > 0) ? SASL_OK : SASL_NOMECH;
1412 }
1413
1414 /*
1415  * Map SASL mechanism name to OID
1416  */
1417 static int
1418 gs2_map_sasl_name(const sasl_utils_t *utils,
1419                   const char *mech,
1420                   gss_OID *oid)
1421 {
1422     OM_uint32 major, minor;
1423     gss_buffer_desc buf;
1424
1425     buf.length = strlen(mech);
1426     buf.value = (void *)mech;
1427
1428     major = gss_inquire_mech_for_saslname(&minor, &buf, oid);
1429     if (GSS_ERROR(major)) {
1430         utils->seterror(utils->conn, SASL_NOLOG,
1431                         "GS2 Failure: gss_inquire_mech_for_saslname");
1432         return SASL_FAIL;
1433     }
1434
1435     return SASL_OK;
1436 }
1437
1438 static int
1439 gs2_duplicate_buffer(const sasl_utils_t *utils,
1440                      const gss_buffer_t src,
1441                      gss_buffer_t dst)
1442 {
1443     dst->value = utils->malloc(src->length + 1);
1444     if (dst->value == NULL)
1445         return SASL_NOMEM;
1446
1447     memcpy(dst->value, src->value, src->length);
1448     ((char *)dst->value)[src->length] = '\0';
1449     dst->length = src->length;
1450
1451     return SASL_OK;
1452 }
1453
1454 static int
1455 gs2_unescape_authzid(const sasl_utils_t *utils,
1456                      char **endp,
1457                      unsigned *remain,
1458                      char **authzid)
1459 {
1460     char *in = *endp;
1461     size_t i, len, inlen = *remain;
1462     char *p;
1463
1464     *endp = NULL;
1465
1466     for (i = 0, len = 0; i < inlen; i++) {
1467         if (in[i] == ',') {
1468             *endp = &in[i];
1469             *remain -= i;
1470             break;
1471         } else if (in[i] == '=') {
1472             if (inlen <= i + 2)
1473                 return SASL_BADPROT;
1474             i += 2;
1475         }
1476         len++;
1477     }
1478
1479     if (len == 0 || *endp == NULL)
1480         return SASL_BADPROT;
1481
1482     p = *authzid = utils->malloc(len + 1);
1483     if (*authzid == NULL)
1484         return SASL_NOMEM;
1485
1486     for (i = 0; i < inlen; i++) {
1487         if (in[i] == ',')
1488             break;
1489         else if (in[i] == '=') {
1490             if (memcmp(&in[i + 1], "2C", 2) == 0)
1491                 *p++ = ',';
1492             else if (memcmp(&in[i + 1], "3D", 2) == 0)
1493                 *p++ = '=';
1494             else {
1495                 utils->free(*authzid);
1496                 *authzid = NULL;
1497                 return SASL_BADPROT;
1498             }
1499             i += 2;
1500         } else
1501             *p++ = in[i];
1502     }
1503
1504     *p = '\0';
1505
1506     return SASL_OK;
1507 }
1508
1509 static int
1510 gs2_escape_authzid(const sasl_utils_t *utils,
1511                    const char *in,
1512                    unsigned inlen,
1513                    char **authzid)
1514 {
1515     size_t i;
1516     char *p;
1517
1518     p = *authzid = utils->malloc((inlen * 3) + 1);
1519     if (*authzid == NULL)
1520         return SASL_NOMEM;
1521
1522     for (i = 0; i < inlen; i++) {
1523         if (in[i] == ',') {
1524             memcpy(p, "=2C", 3);
1525             p += 3;
1526         } else if (in[i] == '=') {
1527             memcpy(p, "=3D", 3);
1528             p += 3;
1529         } else {
1530             *p++ = in[i];
1531         }
1532     }
1533
1534     *p = '\0';
1535
1536     return SASL_OK;
1537 }
1538
1539 static int
1540 gs2_ask_user_info(context_t *text,
1541                   sasl_client_params_t *params,
1542                   char **realms __attribute__((unused)),
1543                   int nrealm __attribute__((unused)),
1544                   sasl_interact_t **prompt_need,
1545                   sasl_out_params_t *oparams)
1546 {
1547     int result = SASL_OK;
1548     const char *authid = NULL, *userid = NULL;
1549     int user_result = SASL_OK;
1550     int auth_result = SASL_OK;
1551     int pass_result = SASL_OK;
1552
1553     /* try to get the authid */
1554     if (oparams->authid == NULL) {
1555         auth_result = _plug_get_authid(params->utils, &authid, prompt_need);
1556
1557         if (auth_result != SASL_OK && auth_result != SASL_INTERACT) {
1558             return auth_result;
1559         }
1560     }
1561
1562     /* try to get the userid */
1563     if (oparams->user == NULL) {
1564         user_result = _plug_get_userid(params->utils, &userid, prompt_need);
1565
1566         if (user_result != SASL_OK && user_result != SASL_INTERACT) {
1567             return user_result;
1568         }
1569     }
1570
1571     /* try to get the password */
1572     if (text->password == NULL) {
1573         pass_result = _plug_get_password(params->utils, &text->password,
1574                                          &text->free_password, prompt_need);
1575         if (pass_result != SASL_OK && pass_result != SASL_INTERACT) {
1576             return pass_result;
1577         }
1578     }
1579
1580     /* free prompts we got */
1581     if (prompt_need && *prompt_need) {
1582         params->utils->free(*prompt_need);
1583         *prompt_need = NULL;
1584     }
1585
1586     /* if there are prompts not filled in */
1587     if (user_result == SASL_INTERACT || auth_result == SASL_INTERACT ||
1588         pass_result == SASL_INTERACT) {
1589
1590         /* make the prompt list */
1591         result =
1592             _plug_make_prompts(params->utils, prompt_need,
1593                                user_result == SASL_INTERACT ?
1594                                "Please enter your authorization name" : NULL,
1595                                NULL,
1596                                auth_result == SASL_INTERACT ?
1597                                "Please enter your authentication name" : NULL,
1598                                NULL,
1599                                pass_result == SASL_INTERACT ?
1600                                "Please enter your password" : NULL, NULL,
1601                                NULL, NULL, NULL,
1602                                NULL,
1603                                NULL, NULL);
1604         if (result == SASL_OK) return SASL_INTERACT;
1605
1606         return result;
1607     }
1608
1609     if (oparams->authid == NULL) {
1610         if (userid == NULL || userid[0] == '\0') {
1611             result = params->canon_user(params->utils->conn, authid, 0,
1612                                         SASL_CU_AUTHID | SASL_CU_AUTHZID,
1613                                         oparams);
1614         } else {
1615             result = params->canon_user(params->utils->conn,
1616                                         authid, 0, SASL_CU_AUTHID, oparams);
1617             if (result != SASL_OK) return result;
1618
1619             result = params->canon_user(params->utils->conn,
1620                                         userid, 0, SASL_CU_AUTHZID, oparams);
1621         }
1622         if (result != SASL_OK)
1623             return result;
1624     }
1625
1626     return result;
1627 }
1628
1629 static int
1630 sasl_gs2_seterror_(const sasl_utils_t *utils, OM_uint32 maj, OM_uint32 min,
1631                    int logonly)
1632 {
1633     OM_uint32 maj_stat, min_stat;
1634     gss_buffer_desc msg;
1635     OM_uint32 msg_ctx;
1636     int ret;
1637     char *out = NULL;
1638     unsigned int len, curlen = 0;
1639     const char prefix[] = "GSSAPI Error: ";
1640
1641     len = sizeof(prefix);
1642     ret = _plug_buf_alloc(utils, &out, &curlen, 256);
1643     if (ret != SASL_OK)
1644         return SASL_OK;
1645
1646     strcpy(out, prefix);
1647
1648     msg_ctx = 0;
1649     while (1) {
1650         maj_stat = gss_display_status(&min_stat, maj,
1651                                       GSS_C_GSS_CODE, GSS_C_NULL_OID,
1652                                       &msg_ctx, &msg);
1653
1654         if (GSS_ERROR(maj_stat)) {
1655             if (logonly) {
1656                 utils->log(utils->conn, SASL_LOG_FAIL,
1657                         "GS2 Failure: (could not get major error message)");
1658             } else {
1659                 utils->seterror(utils->conn, 0,
1660                                 "GS2 Failure "
1661                                 "(could not get major error message)");
1662             }
1663             utils->free(out);
1664             return SASL_OK;
1665         }
1666
1667         len += len + msg.length;
1668         ret = _plug_buf_alloc(utils, &out, &curlen, len);
1669         if (ret != SASL_OK) {
1670             utils->free(out);
1671             return SASL_OK;
1672         }
1673
1674         strcat(out, msg.value);
1675
1676         gss_release_buffer(&min_stat, &msg);
1677
1678         if (!msg_ctx)
1679             break;
1680     }
1681
1682     /* Now get the minor status */
1683
1684     len += 2;
1685     ret = _plug_buf_alloc(utils, &out, &curlen, len);
1686     if (ret != SASL_OK) {
1687         utils->free(out);
1688         return SASL_NOMEM;
1689     }
1690
1691     strcat(out, " (");
1692
1693     msg_ctx = 0;
1694     while (1) {
1695         maj_stat = gss_display_status(&min_stat, min,
1696                                       GSS_C_MECH_CODE, GSS_C_NULL_OID,
1697                                       &msg_ctx, &msg);
1698
1699         if (GSS_ERROR(maj_stat)) {
1700             if (logonly) {
1701                 utils->log(utils->conn, SASL_LOG_FAIL,
1702                         "GS2 Failure: (could not get minor error message)");
1703             } else {
1704                 utils->seterror(utils->conn, 0,
1705                                 "GS2 Failure "
1706                                 "(could not get minor error message)");
1707             }
1708             utils->free(out);
1709             return SASL_OK;
1710         }
1711
1712         len += len + msg.length;
1713
1714         ret = _plug_buf_alloc(utils, &out, &curlen, len);
1715         if (ret != SASL_OK) {
1716             utils->free(out);
1717             return SASL_NOMEM;
1718         }
1719
1720         strcat(out, msg.value);
1721
1722         gss_release_buffer(&min_stat, &msg);
1723
1724         if (!msg_ctx)
1725             break;
1726     }
1727
1728     len += 1;
1729     ret = _plug_buf_alloc(utils, &out, &curlen, len);
1730     if (ret != SASL_OK) {
1731         utils->free(out);
1732         return SASL_NOMEM;
1733     }
1734
1735     strcat(out, ")");
1736
1737     if (logonly) {
1738         utils->log(utils->conn, SASL_LOG_FAIL, out);
1739     } else {
1740         utils->seterror(utils->conn, 0, out);
1741     }
1742     utils->free(out);
1743
1744     return SASL_OK;
1745 }