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