GSS_S_PROMPTING_NEEDED is a bit
[cyrus-sasl.git] / plugins / cram.c
1 /* CRAM-MD5 SASL plugin
2  * Rob Siemborski
3  * Tim Martin 
4  * $Id: cram.c,v 1.85 2004/09/08 10:57:56 mel Exp $
5  */
6 /* 
7  * Copyright (c) 1998-2003 Carnegie Mellon University.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. The name "Carnegie Mellon University" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For permission or any other legal
24  *    details, please contact  
25  *      Office of Technology Transfer
26  *      Carnegie Mellon University
27  *      5000 Forbes Avenue
28  *      Pittsburgh, PA  15213-3890
29  *      (412) 268-4387, fax: (412) 268-7395
30  *      tech-transfer@andrew.cmu.edu
31  *
32  * 4. Redistributions of any form whatsoever must retain the following
33  *    acknowledgment:
34  *    "This product includes software developed by Computing Services
35  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
36  *
37  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
38  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
39  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
40  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
42  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
43  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
44  */
45
46 #include <config.h>
47
48 #include <string.h>
49 #include <stdlib.h>
50 #include <stdio.h>
51 #ifndef macintosh
52 #include <sys/stat.h>
53 #endif
54 #include <fcntl.h>
55
56 #include <sasl.h>
57 #include <saslplug.h>
58 #include <saslutil.h>
59
60 #include "plugin_common.h"
61
62 #ifdef macintosh
63 #include <sasl_cram_plugin_decl.h>
64 #endif
65
66 /*****************************  Common Section  *****************************/
67
68 static const char plugin_id[] = "$Id: cram.c,v 1.85 2004/09/08 10:57:56 mel Exp $";
69
70 /* convert a string of 8bit chars to it's representation in hex
71  * using lowercase letters
72  */
73 static char *convert16(unsigned char *in, int inlen, const sasl_utils_t *utils)
74 {
75     static char hex[]="0123456789abcdef";
76     int lup;
77     char *out;
78
79     out = utils->malloc(inlen*2+1);
80     if (out == NULL) return NULL;
81     
82     for (lup=0; lup < inlen; lup++) {
83         out[lup*2] = hex[in[lup] >> 4];
84         out[lup*2+1] = hex[in[lup] & 15];
85     }
86
87     out[lup*2] = 0;
88     return out;
89 }
90
91
92 /*****************************  Server Section  *****************************/
93
94 typedef struct server_context {
95     int state;
96
97     char *challenge;
98 } server_context_t;
99
100 static int
101 crammd5_server_mech_new(void *glob_context __attribute__((unused)),
102                         sasl_server_params_t *sparams,
103                         const char *challenge __attribute__((unused)),
104                         unsigned challen __attribute__((unused)),
105                         void **conn_context)
106 {
107     server_context_t *text;
108     
109     /* holds state are in */
110     text = sparams->utils->malloc(sizeof(server_context_t));
111     if (text == NULL) {
112         MEMERROR( sparams->utils );
113         return SASL_NOMEM;
114     }
115     
116     memset(text, 0, sizeof(server_context_t));
117     
118     text->state = 1;
119     
120     *conn_context = text;
121     
122     return SASL_OK;
123 }
124
125 /*
126  * Returns the current time (or part of it) in string form
127  *  maximum length=15
128  */
129 static char *gettime(sasl_server_params_t *sparams)
130 {
131     char *ret;
132     time_t t;
133     
134     t=time(NULL);
135     ret= sparams->utils->malloc(15);
136     if (ret==NULL) return NULL;
137     
138     /* the bottom bits are really the only random ones so if
139        we overflow we don't want to loose them */
140     snprintf(ret,15,"%lu",t%(0xFFFFFF));
141     
142     return ret;
143 }
144
145 static char *randomdigits(sasl_server_params_t *sparams)
146 {
147     unsigned int num;
148     char *ret;
149     unsigned char temp[5]; /* random 32-bit number */
150     
151     sparams->utils->rand(sparams->utils->rpool,(char *) temp,4);
152     num=(temp[0] * 256 * 256 * 256) +
153         (temp[1] * 256 * 256) +
154         (temp[2] * 256) +
155         (temp[3] );
156     
157     ret = sparams->utils->malloc(15); /* there's no way an unsigned can be longer than this right? */
158     if (ret == NULL) return NULL;
159     sprintf(ret, "%u", num);
160     
161     return ret;
162 }
163
164 static int
165 crammd5_server_mech_step1(server_context_t *text,
166                           sasl_server_params_t *sparams,
167                           const char *clientin __attribute__((unused)),
168                           unsigned clientinlen,
169                           const char **serverout,
170                           unsigned *serveroutlen,
171                           sasl_out_params_t *oparams __attribute__((unused)))
172 {
173     char *time, *randdigits;
174             
175     /* we shouldn't have received anything */
176     if (clientinlen != 0) {
177         SETERROR(sparams->utils, "CRAM-MD5 does not accpet inital data");
178         return SASL_BADPROT;
179     }
180     
181     /* get time and a random number for the nonce */
182     time = gettime(sparams);
183     randdigits = randomdigits(sparams);
184     if ((time == NULL) || (randdigits == NULL)) {
185         MEMERROR( sparams->utils );
186         return SASL_NOMEM;
187     }
188     
189     /* allocate some space for the challenge */
190     text->challenge = sparams->utils->malloc(200 + 1);
191     if (text->challenge == NULL) {
192         MEMERROR(sparams->utils);
193         return SASL_NOMEM;
194     }
195     
196     /* create the challenge */
197     snprintf(text->challenge, 200, "<%s.%s@%s>", randdigits, time,
198              sparams->serverFQDN);
199     
200     *serverout = text->challenge;
201     *serveroutlen = (unsigned) strlen(text->challenge);
202     
203     /* free stuff */
204     sparams->utils->free(time);    
205     sparams->utils->free(randdigits);    
206     
207     text->state = 2;
208     
209     return SASL_CONTINUE;
210 }
211     
212 static int
213 crammd5_server_mech_step2(server_context_t *text,
214                           sasl_server_params_t *sparams,
215                           const char *clientin,
216                           unsigned clientinlen,
217                           const char **serverout __attribute__((unused)),
218                           unsigned *serveroutlen __attribute__((unused)),
219                           sasl_out_params_t *oparams)
220 {
221     char *userid = NULL;
222     sasl_secret_t *sec = NULL;
223     int pos;
224     size_t len;
225     int result = SASL_FAIL;
226     const char *password_request[] = { SASL_AUX_PASSWORD,
227                                        "*cmusaslsecretCRAM-MD5",
228                                        NULL };
229     struct propval auxprop_values[3];
230     HMAC_MD5_CTX tmphmac;
231     HMAC_MD5_STATE md5state;
232     int clear_md5state = 0;
233     char *digest_str = NULL;
234     UINT4 digest[4];
235     
236     /* extract userid; everything before last space */
237     pos = clientinlen-1;
238     while ((pos > 0) && (clientin[pos] != ' ')) pos--;
239     
240     if (pos <= 0) {
241         SETERROR( sparams->utils,"need authentication name");
242         return SASL_BADPROT;
243     }
244     
245     userid = (char *) sparams->utils->malloc(pos+1);
246     if (userid == NULL) {
247         MEMERROR( sparams->utils);
248         return SASL_NOMEM;
249     }
250     
251     /* copy authstr out */
252     memcpy(userid, clientin, pos);
253     userid[pos] = '\0';
254     
255     result = sparams->utils->prop_request(sparams->propctx, password_request);
256     if (result != SASL_OK) goto done;
257     
258     /* this will trigger the getting of the aux properties */
259     result = sparams->canon_user(sparams->utils->conn,
260                                  userid, 0, SASL_CU_AUTHID | SASL_CU_AUTHZID,
261                                  oparams);
262     if (result != SASL_OK) goto done;
263     
264     result = sparams->utils->prop_getnames(sparams->propctx,
265                                            password_request,
266                                            auxprop_values);
267     if (result < 0 ||
268         ((!auxprop_values[0].name || !auxprop_values[0].values) &&
269          (!auxprop_values[1].name || !auxprop_values[1].values))) {
270         /* We didn't find this username */
271         sparams->utils->seterror(sparams->utils->conn,0,
272                                  "no secret in database");
273         result = sparams->transition ? SASL_TRANS : SASL_NOUSER;
274         goto done;
275     }
276     
277     if (auxprop_values[0].name && auxprop_values[0].values) {
278         len = strlen(auxprop_values[0].values[0]);
279         if (len == 0) {
280             sparams->utils->seterror(sparams->utils->conn,0,
281                                      "empty secret");
282             result = SASL_FAIL;
283             goto done;
284         }
285         
286         sec = sparams->utils->malloc(sizeof(sasl_secret_t) + len);
287         if (!sec) goto done;
288         
289         sec->len = (unsigned) len;
290         strncpy((char *)sec->data, auxprop_values[0].values[0], len + 1);   
291         
292         clear_md5state = 1;
293         /* Do precalculation on plaintext secret */
294         sparams->utils->hmac_md5_precalc(&md5state, /* OUT */
295                                          sec->data,
296                                          sec->len);
297     } else if (auxprop_values[1].name && auxprop_values[1].values) {
298         /* We have a precomputed secret */
299         memcpy(&md5state, auxprop_values[1].values[0],
300                sizeof(HMAC_MD5_STATE));
301     } else {
302         sparams->utils->seterror(sparams->utils->conn, 0,
303                                  "Have neither type of secret");
304         return SASL_FAIL;
305     }
306     
307     /* erase the plaintext password */
308     sparams->utils->prop_erase(sparams->propctx, password_request[0]);
309
310     /* ok this is annoying:
311        so we have this half-way hmac transform instead of the plaintext
312        that means we half to:
313        -import it back into a md5 context
314        -do an md5update with the nonce 
315        -finalize it
316     */
317     sparams->utils->hmac_md5_import(&tmphmac, (HMAC_MD5_STATE *) &md5state);
318     sparams->utils->MD5Update(&(tmphmac.ictx),
319                               (const unsigned char *) text->challenge,
320                               (unsigned) strlen(text->challenge));
321     sparams->utils->hmac_md5_final((unsigned char *) &digest, &tmphmac);
322     
323     /* convert to base 16 with lower case letters */
324     digest_str = convert16((unsigned char *) digest, 16, sparams->utils);
325     
326     /* if same then verified 
327      *  - we know digest_str is null terminated but clientin might not be
328      *  - verify the length of clientin anyway!
329      */
330     len = strlen(digest_str);
331     if (clientinlen-pos-1 < len ||
332         strncmp(digest_str, clientin+pos+1, len) != 0) {
333         sparams->utils->seterror(sparams->utils->conn, 0,
334                                  "incorrect digest response");
335         result = SASL_BADAUTH;
336         goto done;
337     }
338     
339     /* set oparams */
340     oparams->doneflag = 1;
341     oparams->mech_ssf = 0;
342     oparams->maxoutbuf = 0;
343     oparams->encode_context = NULL;
344     oparams->encode = NULL;
345     oparams->decode_context = NULL;
346     oparams->decode = NULL;
347     oparams->param_version = 0;
348     
349     result = SASL_OK;
350     
351   done:
352     if (userid) sparams->utils->free(userid);
353     if (sec) _plug_free_secret(sparams->utils, &sec);
354
355     if (digest_str) sparams->utils->free(digest_str);
356     if (clear_md5state) memset(&md5state, 0, sizeof(md5state));
357     
358     return result;
359 }
360
361 static int crammd5_server_mech_step(void *conn_context,
362                                     sasl_server_params_t *sparams,
363                                     const char *clientin,
364                                     unsigned clientinlen,
365                                     const char **serverout,
366                                     unsigned *serveroutlen,
367                                     sasl_out_params_t *oparams)
368 {
369     server_context_t *text = (server_context_t *) conn_context;
370     
371     *serverout = NULL;
372     *serveroutlen = 0;
373     
374     /* this should be well more than is ever needed */
375     if (clientinlen > 1024) {
376         SETERROR(sparams->utils, "CRAM-MD5 input longer than 1024 bytes");
377         return SASL_BADPROT;
378     }
379     
380     switch (text->state) {
381
382     case 1:
383         return crammd5_server_mech_step1(text, sparams,
384                                          clientin, clientinlen,
385                                          serverout, serveroutlen,
386                                          oparams);
387
388     case 2:
389         return crammd5_server_mech_step2(text, sparams,
390                                          clientin, clientinlen,
391                                          serverout, serveroutlen,
392                                          oparams);
393
394     default: /* should never get here */
395         sparams->utils->log(NULL, SASL_LOG_ERR,
396                            "Invalid CRAM-MD5 server step %d\n", text->state);
397         return SASL_FAIL;
398     }
399     
400     return SASL_FAIL; /* should never get here */
401 }
402
403 static void crammd5_server_mech_dispose(void *conn_context,
404                                         const sasl_utils_t *utils)
405 {
406     server_context_t *text = (server_context_t *) conn_context;
407     
408     if (!text) return;
409     
410     if (text->challenge) _plug_free_string(utils,&(text->challenge));
411     
412     utils->free(text);
413 }
414
415 static sasl_server_plug_t crammd5_server_plugins[] = 
416 {
417     {
418         "CRAM-MD5",                     /* mech_name */
419         0,                              /* max_ssf */
420         SASL_SEC_NOPLAINTEXT
421         | SASL_SEC_NOANONYMOUS,         /* security_flags */
422         SASL_FEAT_SERVER_FIRST,         /* features */
423         NULL,                           /* glob_context */
424         &crammd5_server_mech_new,       /* mech_new */
425         &crammd5_server_mech_step,      /* mech_step */
426         &crammd5_server_mech_dispose,   /* mech_dispose */
427         NULL,                           /* mech_free */
428         NULL,                           /* setpass */
429         NULL,                           /* user_query */
430         NULL,                           /* idle */
431         NULL,                           /* mech avail */
432         NULL                            /* spare */
433     }
434 };
435
436 int crammd5_server_plug_init(const sasl_utils_t *utils,
437                              int maxversion,
438                              int *out_version,
439                              sasl_server_plug_t **pluglist,
440                              int *plugcount)
441 {
442     if (maxversion < SASL_SERVER_PLUG_VERSION) {
443         SETERROR( utils, "CRAM version mismatch");
444         return SASL_BADVERS;
445     }
446     
447     *out_version = SASL_SERVER_PLUG_VERSION;
448     *pluglist = crammd5_server_plugins;
449     *plugcount = 1;  
450     
451     return SASL_OK;
452 }
453
454 /*****************************  Client Section  *****************************/
455
456 typedef struct client_context {
457     char *out_buf;
458     unsigned out_buf_len;
459 } client_context_t;
460
461 static int crammd5_client_mech_new(void *glob_context __attribute__((unused)), 
462                                    sasl_client_params_t *params,
463                                    void **conn_context)
464 {
465     client_context_t *text;
466     
467     /* holds state are in */
468     text = params->utils->malloc(sizeof(client_context_t));
469     if (text == NULL) {
470         MEMERROR(params->utils);
471         return SASL_NOMEM;
472     }
473     
474     memset(text, 0, sizeof(client_context_t));
475
476     *conn_context = text;
477     
478     return SASL_OK;
479 }
480
481 static char *make_hashed(sasl_secret_t *sec, char *nonce, int noncelen, 
482                          const sasl_utils_t *utils)
483 {
484     unsigned char digest[24];  
485     char *in16;
486     
487     if (sec == NULL) return NULL;
488     
489     /* do the hmac md5 hash output 128 bits */
490     utils->hmac_md5((unsigned char *) nonce, noncelen,
491                     sec->data, sec->len, digest);
492     
493     /* convert that to hex form */
494     in16 = convert16(digest, 16, utils);
495     if (in16 == NULL) return NULL;
496     
497     return in16;
498 }
499
500 static int crammd5_client_mech_step(void *conn_context,
501                                     sasl_client_params_t *params,
502                                     const char *serverin,
503                                     unsigned serverinlen,
504                                     sasl_interact_t **prompt_need,
505                                     const char **clientout,
506                                     unsigned *clientoutlen,
507                                     sasl_out_params_t *oparams)
508 {
509     client_context_t *text = (client_context_t *) conn_context;
510     const char *authid = NULL;
511     sasl_secret_t *password = NULL;
512     unsigned int free_password = 0; /* set if we need to free password */
513     int auth_result = SASL_OK;
514     int pass_result = SASL_OK;
515     int result;
516     size_t maxsize;
517     char *in16 = NULL;
518
519     *clientout = NULL;
520     *clientoutlen = 0;
521     
522     /* First check for absurd lengths */
523     if (serverinlen > 1024) {
524         params->utils->seterror(params->utils->conn, 0,
525                                 "CRAM-MD5 input longer than 1024 bytes");
526         return SASL_BADPROT;
527     }
528     
529     /* check if sec layer strong enough */
530     if (params->props.min_ssf > params->external_ssf) {
531         SETERROR( params->utils, "SSF requested of CRAM-MD5 plugin");
532         return SASL_TOOWEAK;
533     }
534     
535     /* try to get the userid */
536     if (oparams->authid == NULL) {
537         auth_result=_plug_get_authid(params->utils, &authid, prompt_need);
538         
539         if ((auth_result != SASL_OK) && (auth_result != SASL_INTERACT))
540             return auth_result;
541     }
542     
543     /* try to get the password */
544     if (password == NULL) {
545         pass_result=_plug_get_password(params->utils, &password,
546                                        &free_password, prompt_need);
547         
548         if ((pass_result != SASL_OK) && (pass_result != SASL_INTERACT))
549             return pass_result;
550     }
551     
552     /* free prompts we got */
553     if (prompt_need && *prompt_need) {
554         params->utils->free(*prompt_need);
555         *prompt_need = NULL;
556     }
557     
558     /* if there are prompts not filled in */
559     if ((auth_result == SASL_INTERACT) || (pass_result == SASL_INTERACT)) {
560         /* make the prompt list */
561         result =
562             _plug_make_prompts(params->utils, prompt_need,
563                                NULL, NULL,
564                                auth_result == SASL_INTERACT ?
565                                "Please enter your authentication name" : NULL,
566                                NULL,
567                                pass_result == SASL_INTERACT ?
568                                "Please enter your password" : NULL, NULL,
569                                NULL, NULL, NULL,
570                                NULL, NULL, NULL);
571         if (result != SASL_OK) goto cleanup;
572         
573         return SASL_INTERACT;
574     }
575     
576     if (!password) {
577         PARAMERROR(params->utils);
578         return SASL_BADPARAM;
579     }
580     
581     result = params->canon_user(params->utils->conn, authid, 0,
582                                 SASL_CU_AUTHID | SASL_CU_AUTHZID, oparams);
583     if (result != SASL_OK) goto cleanup;
584     
585     /*
586      * username SP digest (keyed md5 where key is passwd)
587      */
588     
589     in16 = make_hashed(password, (char *) serverin, serverinlen,
590                        params->utils);
591     
592     if (in16 == NULL) {
593         SETERROR(params->utils, "whoops, make_hashed failed us this time");
594         result = SASL_FAIL;
595         goto cleanup;
596     }
597     
598     maxsize = 32+1+strlen(oparams->authid)+30;
599     result = _plug_buf_alloc(params->utils, &(text->out_buf),
600                              &(text->out_buf_len), (unsigned) maxsize);
601     if (result != SASL_OK) goto cleanup;
602     
603     snprintf(text->out_buf, maxsize, "%s %s", oparams->authid, in16);
604     
605     *clientout = text->out_buf;
606     *clientoutlen = (unsigned) strlen(*clientout);
607     
608     /* set oparams */
609     oparams->doneflag = 1;
610     oparams->mech_ssf = 0;
611     oparams->maxoutbuf = 0;
612     oparams->encode_context = NULL;
613     oparams->encode = NULL;
614     oparams->decode_context = NULL;
615     oparams->decode = NULL;
616     oparams->param_version = 0;
617     
618     result = SASL_OK;
619
620   cleanup:
621     /* get rid of private information */
622     if (in16) _plug_free_string(params->utils, &in16);
623     
624     /* get rid of all sensitive info */
625     if (free_password) _plug_free_secret(params-> utils, &password);
626
627     return result;
628 }
629
630 static void crammd5_client_mech_dispose(void *conn_context,
631                                         const sasl_utils_t *utils)
632 {
633     client_context_t *text = (client_context_t *) conn_context;
634     
635     if (!text) return;
636     
637     if (text->out_buf) utils->free(text->out_buf);
638     
639     utils->free(text);
640 }
641
642 static sasl_client_plug_t crammd5_client_plugins[] = 
643 {
644     {
645         "CRAM-MD5",                     /* mech_name */
646         0,                              /* max_ssf */
647         SASL_SEC_NOPLAINTEXT
648         | SASL_SEC_NOANONYMOUS,         /* security_flags */
649         SASL_FEAT_SERVER_FIRST,         /* features */
650         NULL,                           /* required_prompts */
651         NULL,                           /* glob_context */
652         &crammd5_client_mech_new,       /* mech_new */
653         &crammd5_client_mech_step,      /* mech_step */
654         &crammd5_client_mech_dispose,   /* mech_dispose */
655         NULL,                           /* mech_free */
656         NULL,                           /* idle */
657         NULL,                           /* spare */
658         NULL                            /* spare */
659     }
660 };
661
662 int crammd5_client_plug_init(const sasl_utils_t *utils,
663                              int maxversion,
664                              int *out_version,
665                              sasl_client_plug_t **pluglist,
666                              int *plugcount)
667 {
668     if (maxversion < SASL_CLIENT_PLUG_VERSION) {
669         SETERROR( utils, "CRAM version mismatch");
670         return SASL_BADVERS;
671     }
672     
673     *out_version = SASL_CLIENT_PLUG_VERSION;
674     *pluglist = crammd5_client_plugins;
675     *plugcount = 1;
676     
677     return SASL_OK;
678 }